Small bug fixes.
[org-mode/org-tableheadings.git] / lisp / org.el
blobd38cbda441b2bbc2ad13fe7b5778d9d72bbf64f3
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.00pre-1
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, or (at your option)
15 ;; 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; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (make-variable-buffer-local 'org-table-formula-constants-local)
72 ;;;; Require other packages
74 (eval-when-compile
75 (require 'cl)
76 (require 'gnus-sum)
77 (require 'calendar))
78 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
79 ;; the file noutline.el being loaded.
80 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
81 ;; We require noutline, which might be provided in outline.el
82 (require 'outline) (require 'noutline)
83 ;; Other stuff we need.
84 (require 'time-date)
85 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
86 (require 'easymenu)
88 (require 'org-macs)
89 (require 'org-compat)
91 ;;;; Customization variables
93 ;;; Version
95 (defconst org-version "6.00pre-1"
96 "The version number of the file org.el.")
98 (defun org-version (&optional here)
99 "Show the org-mode version in the echo area.
100 With prefix arg HERE, insert it at point."
101 (interactive "P")
102 (let ((version (format "Org-mode version %s" org-version)))
103 (message version)
104 (if here
105 (insert version))))
107 ;;; Compatibility constants
109 ;;; The custom variables
111 (defgroup org nil
112 "Outline-based notes management and organizer."
113 :tag "Org"
114 :group 'outlines
115 :group 'hypermedia
116 :group 'calendar)
118 (defcustom org-load-hook nil
119 "Hook that is run after org.el has been loaded."
120 :group 'org
121 :type 'hook)
123 (defvar org-modules) ; defined below
124 (defvar org-modules-loaded nil
125 "Have the modules been loaded already?")
127 (defun org-load-modules-maybe (&optional force)
128 "Load all extensions listed in `org-default-extensions'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
142 (defcustom org-modules '(org-bbdb org-gnus org-info org-irc org-mhe org-rmail org-vm org-wl)
143 "Modules that should always be loaded together with org.el.
144 If the description starts with <A>, this means the extension
145 will be autoloaded when needed, preloading is not necessary.
146 If a description starts with <C>, the file is not part of emacs
147 and loading it will require that you have downloaded and properly installed
148 the org-mode distribution."
149 :group 'org
150 :set 'org-set-modules
151 :type
152 '(set :greedy t
153 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
154 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
155 (const :tag " info: Links to Info nodes" org-info)
156 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
157 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
158 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
159 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
160 (const :tag " vm: Links to VM folders/messages" org-vm)
161 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
162 (const :tag " mouse: Additional mouse support" org-mouse)
163 ; (const :tag "A export-latex: LaTeX export" org-export-latex)
164 ; (const :tag "A publish: Publishing" org-publish)
166 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
167 (const :tag "C bibtex: Org links to BibTeX entries" org-bibtex)
168 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
169 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
170 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
171 (const :tag "C id: Global id's for identifying entries" org-id)
172 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
173 (const :tag "C iswitchb: Use iswitchb to select Org buffer" org-iswitchb)
174 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
175 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
176 (const :tag "C mew: Support for links to messages in Mew" org-mew)
177 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
178 (const :tag "C registry: A registry for Org links" org-registry)
179 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
180 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
181 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)))
183 ;; FIXME: Needs a separate group...
184 (defcustom org-completion-fallback-command 'hippie-expand
185 "The expansion command called by \\[org-complete] in normal context.
186 Normal means, no org-mode-specific context."
187 :group 'org
188 :type 'function)
190 (defgroup org-startup nil
191 "Options concerning startup of Org-mode."
192 :tag "Org Startup"
193 :group 'org)
195 (defcustom org-startup-folded t
196 "Non-nil means, entering Org-mode will switch to OVERVIEW.
197 This can also be configured on a per-file basis by adding one of
198 the following lines anywhere in the buffer:
200 #+STARTUP: fold
201 #+STARTUP: nofold
202 #+STARTUP: content"
203 :group 'org-startup
204 :type '(choice
205 (const :tag "nofold: show all" nil)
206 (const :tag "fold: overview" t)
207 (const :tag "content: all headlines" content)))
209 (defcustom org-startup-truncated t
210 "Non-nil means, entering Org-mode will set `truncate-lines'.
211 This is useful since some lines containing links can be very long and
212 uninteresting. Also tables look terrible when wrapped."
213 :group 'org-startup
214 :type 'boolean)
216 (defcustom org-startup-align-all-tables nil
217 "Non-nil means, align all tables when visiting a file.
218 This is useful when the column width in tables is forced with <N> cookies
219 in table fields. Such tables will look correct only after the first re-align.
220 This can also be configured on a per-file basis by adding one of
221 the following lines anywhere in the buffer:
222 #+STARTUP: align
223 #+STARTUP: noalign"
224 :group 'org-startup
225 :type 'boolean)
227 (defcustom org-insert-mode-line-in-empty-file nil
228 "Non-nil means insert the first line setting Org-mode in empty files.
229 When the function `org-mode' is called interactively in an empty file, this
230 normally means that the file name does not automatically trigger Org-mode.
231 To ensure that the file will always be in Org-mode in the future, a
232 line enforcing Org-mode will be inserted into the buffer, if this option
233 has been set."
234 :group 'org-startup
235 :type 'boolean)
237 (defcustom org-replace-disputed-keys nil
238 "Non-nil means use alternative key bindings for some keys.
239 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
240 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
241 If you want to use Org-mode together with one of these other modes,
242 or more generally if you would like to move some Org-mode commands to
243 other keys, set this variable and configure the keys with the variable
244 `org-disputed-keys'.
246 This option is only relevant at load-time of Org-mode, and must be set
247 *before* org.el is loaded. Changing it requires a restart of Emacs to
248 become effective."
249 :group 'org-startup
250 :type 'boolean)
252 (if (fboundp 'defvaralias)
253 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
255 (defcustom org-disputed-keys
256 '(([(shift up)] . [(meta p)])
257 ([(shift down)] . [(meta n)])
258 ([(shift left)] . [(meta -)])
259 ([(shift right)] . [(meta +)])
260 ([(control shift right)] . [(meta shift +)])
261 ([(control shift left)] . [(meta shift -)]))
262 "Keys for which Org-mode and other modes compete.
263 This is an alist, cars are the default keys, second element specifies
264 the alternative to use when `org-replace-disputed-keys' is t.
266 Keys can be specified in any syntax supported by `define-key'.
267 The value of this option takes effect only at Org-mode's startup,
268 therefore you'll have to restart Emacs to apply it after changing."
269 :group 'org-startup
270 :type 'alist)
272 (defun org-key (key)
273 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
274 Or return the original if not disputed."
275 (if org-replace-disputed-keys
276 (let* ((nkey (key-description key))
277 (x (org-find-if (lambda (x)
278 (equal (key-description (car x)) nkey))
279 org-disputed-keys)))
280 (if x (cdr x) key))
281 key))
283 (defun org-find-if (predicate seq)
284 (catch 'exit
285 (while seq
286 (if (funcall predicate (car seq))
287 (throw 'exit (car seq))
288 (pop seq)))))
290 (defun org-defkey (keymap key def)
291 "Define a key, possibly translated, as returned by `org-key'."
292 (define-key keymap (org-key key) def))
294 (defcustom org-ellipsis nil
295 "The ellipsis to use in the Org-mode outline.
296 When nil, just use the standard three dots. When a string, use that instead,
297 When a face, use the standart 3 dots, but with the specified face.
298 The change affects only Org-mode (which will then use its own display table).
299 Changing this requires executing `M-x org-mode' in a buffer to become
300 effective."
301 :group 'org-startup
302 :type '(choice (const :tag "Default" nil)
303 (face :tag "Face" :value org-warning)
304 (string :tag "String" :value "...#")))
306 (defvar org-display-table nil
307 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
309 (defgroup org-keywords nil
310 "Keywords in Org-mode."
311 :tag "Org Keywords"
312 :group 'org)
314 (defcustom org-deadline-string "DEADLINE:"
315 "String to mark deadline entries.
316 A deadline is this string, followed by a time stamp. Should be a word,
317 terminated by a colon. You can insert a schedule keyword and
318 a timestamp with \\[org-deadline].
319 Changes become only effective after restarting Emacs."
320 :group 'org-keywords
321 :type 'string)
323 (defcustom org-scheduled-string "SCHEDULED:"
324 "String to mark scheduled TODO entries.
325 A schedule is this string, followed by a time stamp. Should be a word,
326 terminated by a colon. You can insert a schedule keyword and
327 a timestamp with \\[org-schedule].
328 Changes become only effective after restarting Emacs."
329 :group 'org-keywords
330 :type 'string)
332 (defcustom org-closed-string "CLOSED:"
333 "String used as the prefix for timestamps logging closing a TODO entry."
334 :group 'org-keywords
335 :type 'string)
337 (defcustom org-clock-string "CLOCK:"
338 "String used as prefix for timestamps clocking work hours on an item."
339 :group 'org-keywords
340 :type 'string)
342 (defcustom org-comment-string "COMMENT"
343 "Entries starting with this keyword will never be exported.
344 An entry can be toggled between COMMENT and normal with
345 \\[org-toggle-comment].
346 Changes become only effective after restarting Emacs."
347 :group 'org-keywords
348 :type 'string)
350 (defcustom org-quote-string "QUOTE"
351 "Entries starting with this keyword will be exported in fixed-width font.
352 Quoting applies only to the text in the entry following the headline, and does
353 not extend beyond the next headline, even if that is lower level.
354 An entry can be toggled between QUOTE and normal with
355 \\[org-toggle-fixed-width-section]."
356 :group 'org-keywords
357 :type 'string)
359 (defconst org-repeat-re
360 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
361 "Regular expression for specifying repeated events.
362 After a match, group 1 contains the repeat expression.")
364 (defgroup org-structure nil
365 "Options concerning the general structure of Org-mode files."
366 :tag "Org Structure"
367 :group 'org)
369 (defgroup org-reveal-location nil
370 "Options about how to make context of a location visible."
371 :tag "Org Reveal Location"
372 :group 'org-structure)
374 (defconst org-context-choice
375 '(choice
376 (const :tag "Always" t)
377 (const :tag "Never" nil)
378 (repeat :greedy t :tag "Individual contexts"
379 (cons
380 (choice :tag "Context"
381 (const agenda)
382 (const org-goto)
383 (const occur-tree)
384 (const tags-tree)
385 (const link-search)
386 (const mark-goto)
387 (const bookmark-jump)
388 (const isearch)
389 (const default))
390 (boolean))))
391 "Contexts for the reveal options.")
393 (defcustom org-show-hierarchy-above '((default . t))
394 "Non-nil means, show full hierarchy when revealing a location.
395 Org-mode often shows locations in an org-mode file which might have
396 been invisible before. When this is set, the hierarchy of headings
397 above the exposed location is shown.
398 Turning this off for example for sparse trees makes them very compact.
399 Instead of t, this can also be an alist specifying this option for different
400 contexts. Valid contexts are
401 agenda when exposing an entry from the agenda
402 org-goto when using the command `org-goto' on key C-c C-j
403 occur-tree when using the command `org-occur' on key C-c /
404 tags-tree when constructing a sparse tree based on tags matches
405 link-search when exposing search matches associated with a link
406 mark-goto when exposing the jump goal of a mark
407 bookmark-jump when exposing a bookmark location
408 isearch when exiting from an incremental search
409 default default for all contexts not set explicitly"
410 :group 'org-reveal-location
411 :type org-context-choice)
413 (defcustom org-show-following-heading '((default . nil))
414 "Non-nil means, show following heading 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 heading following the
417 match is shown.
418 Turning this off for example for sparse trees makes them very compact,
419 but makes it harder to edit the location of the match. In such a case,
420 use the command \\[org-reveal] to show more context.
421 Instead of t, this can also be an alist specifying this option for different
422 contexts. See `org-show-hierarchy-above' for valid contexts."
423 :group 'org-reveal-location
424 :type org-context-choice)
426 (defcustom org-show-siblings '((default . nil) (isearch t))
427 "Non-nil means, show all sibling heading when revealing a location.
428 Org-mode often shows locations in an org-mode file which might have
429 been invisible before. When this is set, the sibling of the current entry
430 heading are all made visible. If `org-show-hierarchy-above' is t,
431 the same happens on each level of the hierarchy above the current entry.
433 By default this is on for the isearch context, off for all other contexts.
434 Turning this off for example for sparse trees makes them very compact,
435 but makes it harder to edit the location of the match. In such a case,
436 use the command \\[org-reveal] to show more context.
437 Instead of t, this can also be an alist specifying this option for different
438 contexts. See `org-show-hierarchy-above' for valid contexts."
439 :group 'org-reveal-location
440 :type org-context-choice)
442 (defcustom org-show-entry-below '((default . nil))
443 "Non-nil means, show the entry below a headline when revealing a location.
444 Org-mode often shows locations in an org-mode file which might have
445 been invisible before. When this is set, the text below the headline that is
446 exposed is also shown.
448 By default this is off for all contexts.
449 Instead of t, this can also be an alist specifying this option for different
450 contexts. See `org-show-hierarchy-above' for valid contexts."
451 :group 'org-reveal-location
452 :type org-context-choice)
454 (defcustom org-indirect-buffer-display 'other-window
455 "How should indirect tree buffers be displayed?
456 This applies to indirect buffers created with the commands
457 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
458 Valid values are:
459 current-window Display in the current window
460 other-window Just display in another window.
461 dedicated-frame Create one new frame, and re-use it each time.
462 new-frame Make a new frame each time. Note that in this case
463 previously-made indirect buffers are kept, and you need to
464 kill these buffers yourself."
465 :group 'org-structure
466 :group 'org-agenda-windows
467 :type '(choice
468 (const :tag "In current window" current-window)
469 (const :tag "In current frame, other window" other-window)
470 (const :tag "Each time a new frame" new-frame)
471 (const :tag "One dedicated frame" dedicated-frame)))
473 (defgroup org-cycle nil
474 "Options concerning visibility cycling in Org-mode."
475 :tag "Org Cycle"
476 :group 'org-structure)
478 (defcustom org-drawers '("PROPERTIES" "CLOCK")
479 "Names of drawers. Drawers are not opened by cycling on the headline above.
480 Drawers only open with a TAB on the drawer line itself. A drawer looks like
481 this:
482 :DRAWERNAME:
483 .....
484 :END:
485 The drawer \"PROPERTIES\" is special for capturing properties through
486 the property API.
488 Drawers can be defined on the per-file basis with a line like:
490 #+DRAWERS: HIDDEN STATE PROPERTIES"
491 :group 'org-structure
492 :type '(repeat (string :tag "Drawer Name")))
494 (defcustom org-cycle-global-at-bob nil
495 "Cycle globally if cursor is at beginning of buffer and not at a headline.
496 This makes it possible to do global cycling without having to use S-TAB or
497 C-u TAB. For this special case to work, the first line of the buffer
498 must not be a headline - it may be empty ot some other text. When used in
499 this way, `org-cycle-hook' is disables temporarily, to make sure the
500 cursor stays at the beginning of the buffer.
501 When this option is nil, don't do anything special at the beginning
502 of the buffer."
503 :group 'org-cycle
504 :type 'boolean)
506 (defcustom org-cycle-emulate-tab t
507 "Where should `org-cycle' emulate TAB.
508 nil Never
509 white Only in completely white lines
510 whitestart Only at the beginning of lines, before the first non-white char
511 t Everywhere except in headlines
512 exc-hl-bol Everywhere except at the start of a headline
513 If TAB is used in a place where it does not emulate TAB, the current subtree
514 visibility is cycled."
515 :group 'org-cycle
516 :type '(choice (const :tag "Never" nil)
517 (const :tag "Only in completely white lines" white)
518 (const :tag "Before first char in a line" whitestart)
519 (const :tag "Everywhere except in headlines" t)
520 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
523 (defcustom org-cycle-separator-lines 2
524 "Number of empty lines needed to keep an empty line between collapsed trees.
525 If you leave an empty line between the end of a subtree and the following
526 headline, this empty line is hidden when the subtree is folded.
527 Org-mode will leave (exactly) one empty line visible if the number of
528 empty lines is equal or larger to the number given in this variable.
529 So the default 2 means, at least 2 empty lines after the end of a subtree
530 are needed to produce free space between a collapsed subtree and the
531 following headline.
533 Special case: when 0, never leave empty lines in collapsed view."
534 :group 'org-cycle
535 :type 'integer)
537 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
538 org-cycle-hide-drawers
539 org-cycle-show-empty-lines
540 org-optimize-window-after-visibility-change)
541 "Hook that is run after `org-cycle' has changed the buffer visibility.
542 The function(s) in this hook must accept a single argument which indicates
543 the new state that was set by the most recent `org-cycle' command. The
544 argument is a symbol. After a global state change, it can have the values
545 `overview', `content', or `all'. After a local state change, it can have
546 the values `folded', `children', or `subtree'."
547 :group 'org-cycle
548 :type 'hook)
550 (defgroup org-edit-structure nil
551 "Options concerning structure editing in Org-mode."
552 :tag "Org Edit Structure"
553 :group 'org-structure)
555 (defcustom org-odd-levels-only nil
556 "Non-nil means, skip even levels and only use odd levels for the outline.
557 This has the effect that two stars are being added/taken away in
558 promotion/demotion commands. It also influences how levels are
559 handled by the exporters.
560 Changing it requires restart of `font-lock-mode' to become effective
561 for fontification also in regions already fontified.
562 You may also set this on a per-file basis by adding one of the following
563 lines to the buffer:
565 #+STARTUP: odd
566 #+STARTUP: oddeven"
567 :group 'org-edit-structure
568 :group 'org-font-lock
569 :type 'boolean)
571 (defcustom org-adapt-indentation t
572 "Non-nil means, adapt indentation when promoting and demoting.
573 When this is set and the *entire* text in an entry is indented, the
574 indentation is increased by one space in a demotion command, and
575 decreased by one in a promotion command. If any line in the entry
576 body starts at column 0, indentation is not changed at all."
577 :group 'org-edit-structure
578 :type 'boolean)
580 (defcustom org-special-ctrl-a/e nil
581 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
582 When t, `C-a' will bring back the cursor to the beginning of the
583 headline text, i.e. after the stars and after a possible TODO keyword.
584 In an item, this will be the position after the bullet.
585 When the cursor is already at that position, another `C-a' will bring
586 it to the beginning of the line.
587 `C-e' will jump to the end of the headline, ignoring the presence of tags
588 in the headline. A second `C-e' will then jump to the true end of the
589 line, after any tags.
590 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
591 and only a directly following, identical keypress will bring the cursor
592 to the special positions."
593 :group 'org-edit-structure
594 :type '(choice
595 (const :tag "off" nil)
596 (const :tag "after bullet first" t)
597 (const :tag "border first" reversed)))
599 (if (fboundp 'defvaralias)
600 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
602 (defcustom org-special-ctrl-k nil
603 "Non-nil means `C-k' will behave specially in headlines.
604 When nil, `C-k' will call the default `kill-line' command.
605 When t, the following will happen while the cursor is in the headline:
607 - When the cursor is at the beginning of a headline, kill the entire
608 line and possible the folded subtree below the line.
609 - When in the middle of the headline text, kill the headline up to the tags.
610 - When after the headline text, kill the tags."
611 :group 'org-edit-structure
612 :type 'boolean)
614 (defcustom org-M-RET-may-split-line '((default . t))
615 "Non-nil means, M-RET will split the line at the cursor position.
616 When nil, it will go to the end of the line before making a
617 new line.
618 You may also set this option in a different way for different
619 contexts. Valid contexts are:
621 headline when creating a new headline
622 item when creating a new item
623 table in a table field
624 default the value to be used for all contexts not explicitly
625 customized"
626 :group 'org-structure
627 :group 'org-table
628 :type '(choice
629 (const :tag "Always" t)
630 (const :tag "Never" nil)
631 (repeat :greedy t :tag "Individual contexts"
632 (cons
633 (choice :tag "Context"
634 (const headline)
635 (const item)
636 (const table)
637 (const default))
638 (boolean)))))
641 (defcustom org-blank-before-new-entry '((heading . nil)
642 (plain-list-item . nil))
643 "Should `org-insert-heading' leave a blank line before new heading/item?
644 The value is an alist, with `heading' and `plain-list-item' as car,
645 and a boolean flag as cdr."
646 :group 'org-edit-structure
647 :type '(list
648 (cons (const heading) (boolean))
649 (cons (const plain-list-item) (boolean))))
651 (defcustom org-insert-heading-hook nil
652 "Hook being run after inserting a new heading."
653 :group 'org-edit-structure
654 :type 'hook)
656 (defcustom org-enable-fixed-width-editor t
657 "Non-nil means, lines starting with \":\" are treated as fixed-width.
658 This currently only means, they are never auto-wrapped.
659 When nil, such lines will be treated like ordinary lines.
660 See also the QUOTE keyword."
661 :group 'org-edit-structure
662 :type 'boolean)
664 (defcustom org-goto-auto-isearch t
665 "Non-nil means, typing characters in org-goto starts incremental search."
666 :group 'org-edit-structure
667 :type 'boolean)
669 (defgroup org-sparse-trees nil
670 "Options concerning sparse trees in Org-mode."
671 :tag "Org Sparse Trees"
672 :group 'org-structure)
674 (defcustom org-highlight-sparse-tree-matches t
675 "Non-nil means, highlight all matches that define a sparse tree.
676 The highlights will automatically disappear the next time the buffer is
677 changed by an edit command."
678 :group 'org-sparse-trees
679 :type 'boolean)
681 (defcustom org-remove-highlights-with-change t
682 "Non-nil means, any change to the buffer will remove temporary highlights.
683 Such highlights are created by `org-occur' and `org-clock-display'.
684 When nil, `C-c C-c needs to be used to get rid of the highlights.
685 The highlights created by `org-preview-latex-fragment' always need
686 `C-c C-c' to be removed."
687 :group 'org-sparse-trees
688 :group 'org-time
689 :type 'boolean)
692 (defcustom org-occur-hook '(org-first-headline-recenter)
693 "Hook that is run after `org-occur' has constructed a sparse tree.
694 This can be used to recenter the window to show as much of the structure
695 as possible."
696 :group 'org-sparse-trees
697 :type 'hook)
699 (defgroup org-plain-lists nil
700 "Options concerning plain lists in Org-mode."
701 :tag "Org Plain lists"
702 :group 'org-structure)
704 (defcustom org-cycle-include-plain-lists nil
705 "Non-nil means, include plain lists into visibility cycling.
706 This means that during cycling, plain list items will *temporarily* be
707 interpreted as outline headlines with a level given by 1000+i where i is the
708 indentation of the bullet. In all other operations, plain list items are
709 not seen as headlines. For example, you cannot assign a TODO keyword to
710 such an item."
711 :group 'org-plain-lists
712 :type 'boolean)
714 (defcustom org-plain-list-ordered-item-terminator t
715 "The character that makes a line with leading number an ordered list item.
716 Valid values are ?. and ?\). To get both terminators, use t. While
717 ?. may look nicer, it creates the danger that a line with leading
718 number may be incorrectly interpreted as an item. ?\) therefore is
719 the safe choice."
720 :group 'org-plain-lists
721 :type '(choice (const :tag "dot like in \"2.\"" ?.)
722 (const :tag "paren like in \"2)\"" ?\))
723 (const :tab "both" t)))
725 (defcustom org-auto-renumber-ordered-lists t
726 "Non-nil means, automatically renumber ordered plain lists.
727 Renumbering happens when the sequence have been changed with
728 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
729 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
730 :group 'org-plain-lists
731 :type 'boolean)
733 (defcustom org-provide-checkbox-statistics t
734 "Non-nil means, update checkbox statistics after insert and toggle.
735 When this is set, checkbox statistics is updated each time you either insert
736 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
737 with \\[org-ctrl-c-ctrl-c\\]."
738 :group 'org-plain-lists
739 :type 'boolean)
741 (defgroup org-archive nil
742 "Options concerning archiving in Org-mode."
743 :tag "Org Archive"
744 :group 'org-structure)
746 (defcustom org-archive-tag "ARCHIVE"
747 "The tag that marks a subtree as archived.
748 An archived subtree does not open during visibility cycling, and does
749 not contribute to the agenda listings.
750 After changing this, font-lock must be restarted in the relevant buffers to
751 get the proper fontification."
752 :group 'org-archive
753 :group 'org-keywords
754 :type 'string)
756 (defcustom org-agenda-skip-archived-trees t
757 "Non-nil means, the agenda will skip any items located in archived trees.
758 An archived tree is a tree marked with the tag ARCHIVE."
759 :group 'org-archive
760 :group 'org-agenda-skip
761 :type 'boolean)
763 (defcustom org-cycle-open-archived-trees nil
764 "Non-nil means, `org-cycle' will open archived trees.
765 An archived tree is a tree marked with the tag ARCHIVE.
766 When nil, archived trees will stay folded. You can still open them with
767 normal outline commands like `show-all', but not with the cycling commands."
768 :group 'org-archive
769 :group 'org-cycle
770 :type 'boolean)
772 (defcustom org-sparse-tree-open-archived-trees nil
773 "Non-nil means sparse tree construction shows matches in archived trees.
774 When nil, matches in these trees are highlighted, but the trees are kept in
775 collapsed state."
776 :group 'org-archive
777 :group 'org-sparse-trees
778 :type 'boolean)
780 (defcustom org-archive-location "%s_archive::"
781 "The location where subtrees should be archived.
782 This string consists of two parts, separated by a double-colon.
784 The first part is a file name - when omitted, archiving happens in the same
785 file. %s will be replaced by the current file name (without directory part).
786 Archiving to a different file is useful to keep archived entries from
787 contributing to the Org-mode Agenda.
789 The part after the double colon is a headline. The archived entries will be
790 filed under that headline. When omitted, the subtrees are simply filed away
791 at the end of the file, as top-level entries.
793 Here are a few examples:
794 \"%s_archive::\"
795 If the current file is Projects.org, archive in file
796 Projects.org_archive, as top-level trees. This is the default.
798 \"::* Archived Tasks\"
799 Archive in the current file, under the top-level headline
800 \"* Archived Tasks\".
802 \"~/org/archive.org::\"
803 Archive in file ~/org/archive.org (absolute path), as top-level trees.
805 \"basement::** Finished Tasks\"
806 Archive in file ./basement (relative path), as level 3 trees
807 below the level 2 heading \"** Finished Tasks\".
809 You may set this option on a per-file basis by adding to the buffer a
810 line like
812 #+ARCHIVE: basement::** Finished Tasks"
813 :group 'org-archive
814 :type 'string)
816 (defcustom org-archive-mark-done t
817 "Non-nil means, mark entries as DONE when they are moved to the archive file.
818 This can be a string to set the keyword to use. When t, Org-mode will
819 use the first keyword in its list that means done."
820 :group 'org-archive
821 :type '(choice
822 (const :tag "No" nil)
823 (const :tag "Yes" t)
824 (string :tag "Use this keyword")))
826 (defcustom org-archive-stamp-time t
827 "Non-nil means, add a time stamp to entries moved to an archive file.
828 This variable is obsolete and has no effect anymore, instead add ot remove
829 `time' from the variablle `org-archive-save-context-info'."
830 :group 'org-archive
831 :type 'boolean)
833 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
834 "Parts of context info that should be stored as properties when archiving.
835 When a subtree is moved to an archive file, it looses information given by
836 context, like inherited tags, the category, and possibly also the TODO
837 state (depending on the variable `org-archive-mark-done').
838 This variable can be a list of any of the following symbols:
840 time The time of archiving.
841 file The file where the entry originates.
842 itags The local tags, in the headline of the subtree.
843 ltags The tags the subtree inherits from further up the hierarchy.
844 todo The pre-archive TODO state.
845 category The category, taken from file name or #+CATEGORY lines.
846 olpath The outline path to the item. These are all headlines above
847 the current item, separated by /, like a file path.
849 For each symbol present in the list, a property will be created in
850 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
851 information."
852 :group 'org-archive
853 :type '(set :greedy t
854 (const :tag "Time" time)
855 (const :tag "File" file)
856 (const :tag "Category" category)
857 (const :tag "TODO state" todo)
858 (const :tag "TODO state" priority)
859 (const :tag "Inherited tags" itags)
860 (const :tag "Outline path" olpath)
861 (const :tag "Local tags" ltags)))
863 (defgroup org-imenu-and-speedbar nil
864 "Options concerning imenu and speedbar in Org-mode."
865 :tag "Org Imenu and Speedbar"
866 :group 'org-structure)
868 (defcustom org-imenu-depth 2
869 "The maximum level for Imenu access to Org-mode headlines.
870 This also applied for speedbar access."
871 :group 'org-imenu-and-speedbar
872 :type 'number)
874 (defgroup org-table nil
875 "Options concerning tables in Org-mode."
876 :tag "Org Table"
877 :group 'org)
879 (defcustom org-enable-table-editor 'optimized
880 "Non-nil means, lines starting with \"|\" are handled by the table editor.
881 When nil, such lines will be treated like ordinary lines.
883 When equal to the symbol `optimized', the table editor will be optimized to
884 do the following:
885 - Automatic overwrite mode in front of whitespace in table fields.
886 This makes the structure of the table stay in tact as long as the edited
887 field does not exceed the column width.
888 - Minimize the number of realigns. Normally, the table is aligned each time
889 TAB or RET are pressed to move to another field. With optimization this
890 happens only if changes to a field might have changed the column width.
891 Optimization requires replacing the functions `self-insert-command',
892 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
893 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
894 very good at guessing when a re-align will be necessary, but you can always
895 force one with \\[org-ctrl-c-ctrl-c].
897 If you would like to use the optimized version in Org-mode, but the
898 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
900 This variable can be used to turn on and off the table editor during a session,
901 but in order to toggle optimization, a restart is required.
903 See also the variable `org-table-auto-blank-field'."
904 :group 'org-table
905 :type '(choice
906 (const :tag "off" nil)
907 (const :tag "on" t)
908 (const :tag "on, optimized" optimized)))
910 (defcustom org-table-tab-recognizes-table.el t
911 "Non-nil means, TAB will automatically notice a table.el table.
912 When it sees such a table, it moves point into it and - if necessary -
913 calls `table-recognize-table'."
914 :group 'org-table-editing
915 :type 'boolean)
917 (defgroup org-link nil
918 "Options concerning links in Org-mode."
919 :tag "Org Link"
920 :group 'org)
922 (defvar org-link-abbrev-alist-local nil
923 "Buffer-local version of `org-link-abbrev-alist', which see.
924 The value of this is taken from the #+LINK lines.")
925 (make-variable-buffer-local 'org-link-abbrev-alist-local)
927 (defcustom org-link-abbrev-alist nil
928 "Alist of link abbreviations.
929 The car of each element is a string, to be replaced at the start of a link.
930 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
931 links in Org-mode buffers can have an optional tag after a double colon, e.g.
933 [[linkkey:tag][description]]
935 If REPLACE is a string, the tag will simply be appended to create the link.
936 If the string contains \"%s\", the tag will be inserted there.
938 REPLACE may also be a function that will be called with the tag as the
939 only argument to create the link, which should be returned as a string.
941 See the manual for examples."
942 :group 'org-link
943 :type 'alist)
945 (defcustom org-descriptive-links t
946 "Non-nil means, hide link part and only show description of bracket links.
947 Bracket links are like [[link][descritpion]]. This variable sets the initial
948 state in new org-mode buffers. The setting can then be toggled on a
949 per-buffer basis from the Org->Hyperlinks menu."
950 :group 'org-link
951 :type 'boolean)
953 (defcustom org-link-file-path-type 'adaptive
954 "How the path name in file links should be stored.
955 Valid values are:
957 relative Relative to the current directory, i.e. the directory of the file
958 into which the link is being inserted.
959 absolute Absolute path, if possible with ~ for home directory.
960 noabbrev Absolute path, no abbreviation of home directory.
961 adaptive Use relative path for files in the current directory and sub-
962 directories of it. For other files, use an absolute path."
963 :group 'org-link
964 :type '(choice
965 (const relative)
966 (const absolute)
967 (const noabbrev)
968 (const adaptive)))
970 (defcustom org-activate-links '(bracket angle plain radio tag date)
971 "Types of links that should be activated in Org-mode files.
972 This is a list of symbols, each leading to the activation of a certain link
973 type. In principle, it does not hurt to turn on most link types - there may
974 be a small gain when turning off unused link types. The types are:
976 bracket The recommended [[link][description]] or [[link]] links with hiding.
977 angular Links in angular brackes that may contain whitespace like
978 <bbdb:Carsten Dominik>.
979 plain Plain links in normal text, no whitespace, like http://google.com.
980 radio Text that is matched by a radio target, see manual for details.
981 tag Tag settings in a headline (link to tag search).
982 date Time stamps (link to calendar).
984 Changing this variable requires a restart of Emacs to become effective."
985 :group 'org-link
986 :type '(set (const :tag "Double bracket links (new style)" bracket)
987 (const :tag "Angular bracket links (old style)" angular)
988 (const :tag "Plain text links" plain)
989 (const :tag "Radio target matches" radio)
990 (const :tag "Tags" tag)
991 (const :tag "Timestamps" date)))
993 (defgroup org-link-store nil
994 "Options concerning storing links in Org-mode."
995 :tag "Org Store Link"
996 :group 'org-link)
998 (defcustom org-email-link-description-format "Email %c: %.30s"
999 "Format of the description part of a link to an email or usenet message.
1000 The following %-excapes will be replaced by corresponding information:
1002 %F full \"From\" field
1003 %f name, taken from \"From\" field, address if no name
1004 %T full \"To\" field
1005 %t first name in \"To\" field, address if no name
1006 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1007 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1008 %s subject
1009 %m message-id.
1011 You may use normal field width specification between the % and the letter.
1012 This is for example useful to limit the length of the subject.
1014 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1015 :group 'org-link-store
1016 :type 'string)
1018 (defcustom org-from-is-user-regexp
1019 (let (r1 r2)
1020 (when (and user-mail-address (not (string= user-mail-address "")))
1021 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1022 (when (and user-full-name (not (string= user-full-name "")))
1023 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1024 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1025 "Regexp mached against the \"From:\" header of an email or usenet message.
1026 It should match if the message is from the user him/herself."
1027 :group 'org-link-store
1028 :type 'regexp)
1030 (defcustom org-context-in-file-links t
1031 "Non-nil means, file links from `org-store-link' contain context.
1032 A search string will be added to the file name with :: as separator and
1033 used to find the context when the link is activated by the command
1034 `org-open-at-point'.
1035 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1036 negates this setting for the duration of the command."
1037 :group 'org-link-store
1038 :type 'boolean)
1040 (defcustom org-keep-stored-link-after-insertion nil
1041 "Non-nil means, keep link in list for entire session.
1043 The command `org-store-link' adds a link pointing to the current
1044 location to an internal list. These links accumulate during a session.
1045 The command `org-insert-link' can be used to insert links into any
1046 Org-mode file (offering completion for all stored links). When this
1047 option is nil, every link which has been inserted once using \\[org-insert-link]
1048 will be removed from the list, to make completing the unused links
1049 more efficient."
1050 :group 'org-link-store
1051 :type 'boolean)
1053 (defgroup org-link-follow nil
1054 "Options concerning following links in Org-mode."
1055 :tag "Org Follow Link"
1056 :group 'org-link)
1058 (defcustom org-follow-link-hook nil
1059 "Hook that is run after a link has been followed."
1060 :group 'org-link-follow
1061 :type 'hook)
1063 (defcustom org-tab-follows-link nil
1064 "Non-nil means, on links TAB will follow the link.
1065 Needs to be set before org.el is loaded."
1066 :group 'org-link-follow
1067 :type 'boolean)
1069 (defcustom org-return-follows-link nil
1070 "Non-nil means, on links RET will follow the link.
1071 Needs to be set before org.el is loaded."
1072 :group 'org-link-follow
1073 :type 'boolean)
1075 (defcustom org-mouse-1-follows-link
1076 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1077 "Non-nil means, mouse-1 on a link will follow the link.
1078 A longer mouse click will still set point. Does not work on XEmacs.
1079 Needs to be set before org.el is loaded."
1080 :group 'org-link-follow
1081 :type 'boolean)
1083 (defcustom org-mark-ring-length 4
1084 "Number of different positions to be recorded in the ring
1085 Changing this requires a restart of Emacs to work correctly."
1086 :group 'org-link-follow
1087 :type 'interger)
1089 (defcustom org-link-frame-setup
1090 '((vm . vm-visit-folder-other-frame)
1091 (gnus . gnus-other-frame)
1092 (file . find-file-other-window))
1093 "Setup the frame configuration for following links.
1094 When following a link with Emacs, it may often be useful to display
1095 this link in another window or frame. This variable can be used to
1096 set this up for the different types of links.
1097 For VM, use any of
1098 `vm-visit-folder'
1099 `vm-visit-folder-other-frame'
1100 For Gnus, use any of
1101 `gnus'
1102 `gnus-other-frame'
1103 For FILE, use any of
1104 `find-file'
1105 `find-file-other-window'
1106 `find-file-other-frame'
1107 For the calendar, use the variable `calendar-setup'.
1108 For BBDB, it is currently only possible to display the matches in
1109 another window."
1110 :group 'org-link-follow
1111 :type '(list
1112 (cons (const vm)
1113 (choice
1114 (const vm-visit-folder)
1115 (const vm-visit-folder-other-window)
1116 (const vm-visit-folder-other-frame)))
1117 (cons (const gnus)
1118 (choice
1119 (const gnus)
1120 (const gnus-other-frame)))
1121 (cons (const file)
1122 (choice
1123 (const find-file)
1124 (const find-file-other-window)
1125 (const find-file-other-frame)))))
1127 (defcustom org-display-internal-link-with-indirect-buffer nil
1128 "Non-nil means, use indirect buffer to display infile links.
1129 Activating internal links (from one location in a file to another location
1130 in the same file) normally just jumps to the location. When the link is
1131 activated with a C-u prefix (or with mouse-3), the link is displayed in
1132 another window. When this option is set, the other window actually displays
1133 an indirect buffer clone of the current buffer, to avoid any visibility
1134 changes to the current buffer."
1135 :group 'org-link-follow
1136 :type 'boolean)
1138 (defcustom org-open-non-existing-files nil
1139 "Non-nil means, `org-open-file' will open non-existing files.
1140 When nil, an error will be generated."
1141 :group 'org-link-follow
1142 :type 'boolean)
1144 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1145 "Function and arguments to call for following mailto links.
1146 This is a list with the first element being a lisp function, and the
1147 remaining elements being arguments to the function. In string arguments,
1148 %a will be replaced by the address, and %s will be replaced by the subject
1149 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1150 :group 'org-link-follow
1151 :type '(choice
1152 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1153 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1154 (const :tag "message-mail" (message-mail "%a" "%s"))
1155 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1157 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1158 "Non-nil means, ask for confirmation before executing shell links.
1159 Shell links can be dangerous: just think about a link
1161 [[shell:rm -rf ~/*][Google Search]]
1163 This link would show up in your Org-mode document as \"Google Search\",
1164 but really it would remove your entire home directory.
1165 Therefore we advise against setting this variable to nil.
1166 Just change it to `y-or-n-p' of you want to confirm with a
1167 single keystroke rather than having to type \"yes\"."
1168 :group 'org-link-follow
1169 :type '(choice
1170 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1171 (const :tag "with y-or-n (faster)" y-or-n-p)
1172 (const :tag "no confirmation (dangerous)" nil)))
1174 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1175 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1176 Elisp links can be dangerous: just think about a link
1178 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1180 This link would show up in your Org-mode document as \"Google Search\",
1181 but really it would remove your entire home directory.
1182 Therefore we advise against setting this variable to nil.
1183 Just change it to `y-or-n-p' of you want to confirm with a
1184 single keystroke rather than having to type \"yes\"."
1185 :group 'org-link-follow
1186 :type '(choice
1187 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1188 (const :tag "with y-or-n (faster)" y-or-n-p)
1189 (const :tag "no confirmation (dangerous)" nil)))
1191 (defconst org-file-apps-defaults-gnu
1192 '((remote . emacs)
1193 (t . mailcap))
1194 "Default file applications on a UNIX or GNU/Linux system.
1195 See `org-file-apps'.")
1197 (defconst org-file-apps-defaults-macosx
1198 '((remote . emacs)
1199 (t . "open %s")
1200 ("ps" . "gv %s")
1201 ("ps.gz" . "gv %s")
1202 ("eps" . "gv %s")
1203 ("eps.gz" . "gv %s")
1204 ("dvi" . "xdvi %s")
1205 ("fig" . "xfig %s"))
1206 "Default file applications on a MacOS X system.
1207 The system \"open\" is known as a default, but we use X11 applications
1208 for some files for which the OS does not have a good default.
1209 See `org-file-apps'.")
1211 (defconst org-file-apps-defaults-windowsnt
1212 (list
1213 '(remote . emacs)
1214 (cons t
1215 (list (if (featurep 'xemacs)
1216 'mswindows-shell-execute
1217 'w32-shell-execute)
1218 "open" 'file)))
1219 "Default file applications on a Windows NT system.
1220 The system \"open\" is used for most files.
1221 See `org-file-apps'.")
1223 (defcustom org-file-apps
1225 ("txt" . emacs)
1226 ("tex" . emacs)
1227 ("ltx" . emacs)
1228 ("org" . emacs)
1229 ("el" . emacs)
1230 ("bib" . emacs)
1232 "External applications for opening `file:path' items in a document.
1233 Org-mode uses system defaults for different file types, but
1234 you can use this variable to set the application for a given file
1235 extension. The entries in this list are cons cells where the car identifies
1236 files and the cdr the corresponding command. Possible values for the
1237 file identifier are
1238 \"ext\" A string identifying an extension
1239 `directory' Matches a directory
1240 `remote' Matches a remote file, accessible through tramp or efs.
1241 Remote files most likely should be visited through Emacs
1242 because external applications cannot handle such paths.
1243 t Default for all remaining files
1245 Possible values for the command are:
1246 `emacs' The file will be visited by the current Emacs process.
1247 `default' Use the default application for this file type.
1248 string A command to be executed by a shell; %s will be replaced
1249 by the path to the file.
1250 sexp A Lisp form which will be evaluated. The file path will
1251 be available in the Lisp variable `file'.
1252 For more examples, see the system specific constants
1253 `org-file-apps-defaults-macosx'
1254 `org-file-apps-defaults-windowsnt'
1255 `org-file-apps-defaults-gnu'."
1256 :group 'org-link-follow
1257 :type '(repeat
1258 (cons (choice :value ""
1259 (string :tag "Extension")
1260 (const :tag "Default for unrecognized files" t)
1261 (const :tag "Remote file" remote)
1262 (const :tag "Links to a directory" directory))
1263 (choice :value ""
1264 (const :tag "Visit with Emacs" emacs)
1265 (const :tag "Use system default" default)
1266 (string :tag "Command")
1267 (sexp :tag "Lisp form")))))
1269 (defgroup org-refile nil
1270 "Options concerning refiling entries in Org-mode."
1271 :tag "Org Remember"
1272 :group 'org)
1274 (defcustom org-directory "~/org"
1275 "Directory with org files.
1276 This directory will be used as default to prompt for org files.
1277 Used by the hooks for remember.el."
1278 :group 'org-refile
1279 :group 'org-remember
1280 :type 'directory)
1282 (defcustom org-default-notes-file "~/.notes"
1283 "Default target for storing notes.
1284 Used by the hooks for remember.el. This can be a string, or nil to mean
1285 the value of `remember-data-file'.
1286 You can set this on a per-template basis with the variable
1287 `org-remember-templates'."
1288 :group 'org-refile
1289 :group 'org-remember
1290 :type '(choice
1291 (const :tag "Default from remember-data-file" nil)
1292 file))
1294 (defcustom org-goto-interface 'outline
1295 "The default interface to be used for `org-goto'.
1296 Allowed vaues are:
1297 outline The interface shows an outline of the relevant file
1298 and the correct heading is found by moving through
1299 the outline or by searching with incremental search.
1300 outline-path-completion Headlines in the current buffer are offered via
1301 completion."
1302 :group 'org-refile
1303 :type '(choice
1304 (const :tag "Outline" outline)
1305 (const :tag "Outline-path-completion" outline-path-completion)))
1307 (defcustom org-reverse-note-order nil
1308 "Non-nil means, store new notes at the beginning of a file or entry.
1309 When nil, new notes will be filed to the end of a file or entry.
1310 This can also be a list with cons cells of regular expressions that
1311 are matched against file names, and values."
1312 :group 'org-remember
1313 :type '(choice
1314 (const :tag "Reverse always" t)
1315 (const :tag "Reverse never" nil)
1316 (repeat :tag "By file name regexp"
1317 (cons regexp boolean))))
1319 (defcustom org-refile-targets nil
1320 "Targets for refiling entries with \\[org-refile].
1321 This is list of cons cells. Each cell contains:
1322 - a specification of the files to be considered, either a list of files,
1323 or a symbol whose function or value fields will be used to retrieve
1324 a file name or a list of file names. Nil means, refile to a different
1325 heading in the current buffer.
1326 - A specification of how to find candidate refile targets. This may be
1327 any of
1328 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1329 This tag has to be present in all target headlines, inheritance will
1330 not be considered.
1331 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1332 todo keyword.
1333 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1334 headlines that are refiling targets.
1335 - a cons cell (:level . N). Any headline of level N is considered a target.
1336 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1337 ;; FIXME: what if there are a var and func with same name???
1338 :group 'org-remember
1339 :type '(repeat
1340 (cons
1341 (choice :value org-agenda-files
1342 (const :tag "All agenda files" org-agenda-files)
1343 (const :tag "Current buffer" nil)
1344 (function) (variable) (file))
1345 (choice :tag "Identify target headline by"
1346 (cons :tag "Specific tag" (const :tag) (string))
1347 (cons :tag "TODO keyword" (const :todo) (string))
1348 (cons :tag "Regular expression" (const :regexp) (regexp))
1349 (cons :tag "Level number" (const :level) (integer))
1350 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1352 (defcustom org-refile-use-outline-path nil
1353 "Non-nil means, provide refile targets as paths.
1354 So a level 3 headline will be available as level1/level2/level3.
1355 When the value is `file', also include the file name (without directory)
1356 into the path. When `full-file-path', include the full file path."
1357 :group 'org-remember
1358 :type '(choice
1359 (const :tag "Not" nil)
1360 (const :tag "Yes" t)
1361 (const :tag "Start with file name" file)
1362 (const :tag "Start with full file path" full-file-path)))
1364 (defgroup org-todo nil
1365 "Options concerning TODO items in Org-mode."
1366 :tag "Org TODO"
1367 :group 'org)
1369 (defgroup org-progress nil
1370 "Options concerning Progress logging in Org-mode."
1371 :tag "Org Progress"
1372 :group 'org-time)
1374 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1375 "List of TODO entry keyword sequences and their interpretation.
1376 \\<org-mode-map>This is a list of sequences.
1378 Each sequence starts with a symbol, either `sequence' or `type',
1379 indicating if the keywords should be interpreted as a sequence of
1380 action steps, or as different types of TODO items. The first
1381 keywords are states requiring action - these states will select a headline
1382 for inclusion into the global TODO list Org-mode produces. If one of
1383 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1384 signify that no further action is necessary. If \"|\" is not found,
1385 the last keyword is treated as the only DONE state of the sequence.
1387 The command \\[org-todo] cycles an entry through these states, and one
1388 additional state where no keyword is present. For details about this
1389 cycling, see the manual.
1391 TODO keywords and interpretation can also be set on a per-file basis with
1392 the special #+SEQ_TODO and #+TYP_TODO lines.
1394 Each keyword can optionally specify a character for fast state selection
1395 \(in combination with the variable `org-use-fast-todo-selection')
1396 and specifiers for state change logging, using the same syntax
1397 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1398 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1399 indicates to record a time stamp each time this state is selected.
1401 Each keyword may also specify if a timestamp or a note should be
1402 recorded when entering or leaving the state, by adding additional
1403 characters in the parenthesis after the keyword. This looks like this:
1404 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1405 record only the time of the state change. With X and Y being either
1406 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1407 Y when leaving the state if and only if the *target* state does not
1408 define X. You may omit any of the fast-selection key or X or /Y,
1409 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1411 For backward compatibility, this variable may also be just a list
1412 of keywords - in this case the interptetation (sequence or type) will be
1413 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1414 :group 'org-todo
1415 :group 'org-keywords
1416 :type '(choice
1417 (repeat :tag "Old syntax, just keywords"
1418 (string :tag "Keyword"))
1419 (repeat :tag "New syntax"
1420 (cons
1421 (choice
1422 :tag "Interpretation"
1423 (const :tag "Sequence (cycling hits every state)" sequence)
1424 (const :tag "Type (cycling directly to DONE)" type))
1425 (repeat
1426 (string :tag "Keyword"))))))
1428 (defvar org-todo-keywords-1 nil
1429 "All TODO and DONE keywords active in a buffer.")
1430 (make-variable-buffer-local 'org-todo-keywords-1)
1431 (defvar org-todo-keywords-for-agenda nil)
1432 (defvar org-done-keywords-for-agenda nil)
1433 (defvar org-not-done-keywords nil)
1434 (make-variable-buffer-local 'org-not-done-keywords)
1435 (defvar org-done-keywords nil)
1436 (make-variable-buffer-local 'org-done-keywords)
1437 (defvar org-todo-heads nil)
1438 (make-variable-buffer-local 'org-todo-heads)
1439 (defvar org-todo-sets nil)
1440 (make-variable-buffer-local 'org-todo-sets)
1441 (defvar org-todo-log-states nil)
1442 (make-variable-buffer-local 'org-todo-log-states)
1443 (defvar org-todo-kwd-alist nil)
1444 (make-variable-buffer-local 'org-todo-kwd-alist)
1445 (defvar org-todo-key-alist nil)
1446 (make-variable-buffer-local 'org-todo-key-alist)
1447 (defvar org-todo-key-trigger nil)
1448 (make-variable-buffer-local 'org-todo-key-trigger)
1450 (defcustom org-todo-interpretation 'sequence
1451 "Controls how TODO keywords are interpreted.
1452 This variable is in principle obsolete and is only used for
1453 backward compatibility, if the interpretation of todo keywords is
1454 not given already in `org-todo-keywords'. See that variable for
1455 more information."
1456 :group 'org-todo
1457 :group 'org-keywords
1458 :type '(choice (const sequence)
1459 (const type)))
1461 (defcustom org-use-fast-todo-selection 'prefix
1462 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1463 This variable describes if and under what circumstances the cycling
1464 mechanism for TODO keywords will be replaced by a single-key, direct
1465 selection scheme.
1467 When nil, fast selection is never used.
1469 When the symbol `prefix', it will be used when `org-todo' is called with
1470 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1471 in an agenda buffer.
1473 When t, fast selection is used by default. In this case, the prefix
1474 argument forces cycling instead.
1476 In all cases, the special interface is only used if access keys have actually
1477 been assigned by the user, i.e. if keywords in the configuration are followed
1478 by a letter in parenthesis, like TODO(t)."
1479 :group 'org-todo
1480 :type '(choice
1481 (const :tag "Never" nil)
1482 (const :tag "By default" t)
1483 (const :tag "Only with C-u C-c C-t" prefix)))
1485 (defcustom org-after-todo-state-change-hook nil
1486 "Hook which is run after the state of a TODO item was changed.
1487 The new state (a string with a TODO keyword, or nil) is available in the
1488 Lisp variable `state'."
1489 :group 'org-todo
1490 :type 'hook)
1492 (defcustom org-log-done nil
1493 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1494 When equal to the list (done), also prompt for a closing note.
1495 This can also be configured on a per-file basis by adding one of
1496 the following lines anywhere in the buffer:
1498 #+STARTUP: logdone
1499 #+STARTUP: lognotedone
1500 #+STARTUP: nologdone"
1501 :group 'org-todo
1502 :group 'org-progress
1503 :type '(choice
1504 (const :tag "No logging" nil)
1505 (const :tag "Record CLOSED timestamp" time)
1506 (const :tag "Record CLOSED timestamp with closing note." note)))
1508 ;; Normalize old uses of org-log-done.
1509 (cond
1510 ((eq org-log-done t) (setq org-log-done 'time))
1511 ((and (listp org-log-done) (memq 'done org-log-done))
1512 (setq org-log-done 'note)))
1514 ;; FIXME: document
1515 (defcustom org-log-note-clock-out nil
1516 "Non-nil means, recored a note when clocking out of an item.
1517 This can also be configured on a per-file basis by adding one of
1518 the following lines anywhere in the buffer:
1520 #+STARTUP: lognoteclock-out
1521 #+STARTUP: nolognoteclock-out"
1522 :group 'org-todo
1523 :group 'org-progress
1524 :type 'boolean)
1526 (defcustom org-log-done-with-time t
1527 "Non-nil means, the CLOSED time stamp will contain date and time.
1528 When nil, only the date will be recorded."
1529 :group 'org-progress
1530 :type 'boolean)
1532 (defcustom org-log-note-headings
1533 '((done . "CLOSING NOTE %t")
1534 (state . "State %-12s %t")
1535 (note . "Note taken on %t")
1536 (clock-out . ""))
1537 "Headings for notes added to entries.
1538 The value is an alist, with the car being a symbol indicating the note
1539 context, and the cdr is the heading to be used. The heading may also be the
1540 empty string.
1541 %t in the heading will be replaced by a time stamp.
1542 %s will be replaced by the new TODO state, in double quotes.
1543 %u will be replaced by the user name.
1544 %U will be replaced by the full user name."
1545 :group 'org-todo
1546 :group 'org-progress
1547 :type '(list :greedy t
1548 (cons (const :tag "Heading when closing an item" done) string)
1549 (cons (const :tag
1550 "Heading when changing todo state (todo sequence only)"
1551 state) string)
1552 (cons (const :tag "Heading when just taking a note" note) string)
1553 (cons (const :tag "Heading when clocking out" clock-out) string)))
1555 (unless (assq 'note org-log-note-headings)
1556 (push '(note . "%t") org-log-note-headings))
1558 (defcustom org-log-states-order-reversed t
1559 "Non-nil means, the latest state change note will be directly after heading.
1560 When nil, the notes will be orderer according to time."
1561 :group 'org-todo
1562 :group 'org-progress
1563 :type 'boolean)
1565 (defcustom org-log-repeat 'time
1566 "Non-nil means, record moving through the DONE state when triggering repeat.
1567 An auto-repeating tasks is immediately switched back to TODO when marked
1568 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1569 the TODO keyword definition, or recording a cloing note by setting
1570 `org-log-done', there will be no record of the task moving trhough DONE.
1571 This variable forces taking a note anyway. Possible values are:
1573 nil Don't force a record
1574 time Record a time stamp
1575 note Record a note
1577 This option can also be set with on a per-file-basis with
1579 #+STARTUP: logrepeat
1580 #+STARTUP: lognoterepeat
1581 #+STARTUP: nologrepeat
1583 You can have local logging settings for a subtree by setting the LOGGING
1584 property to one or more of these keywords."
1585 :group 'org-todo
1586 :group 'org-progress
1587 :type '(choice
1588 (const :tag "Don't force a record" nil)
1589 (const :tag "Force recording the DONE state" time)
1590 (const :tag "Force recording a note with the DONE state" note)))
1592 (defcustom org-clock-into-drawer 2
1593 "Should clocking info be wrapped into a drawer?
1594 When t, clocking info will always be inserted into a :CLOCK: drawer.
1595 If necessary, the drawer will be created.
1596 When nil, the drawer will not be created, but used when present.
1597 When an integer and the number of clocking entries in an item
1598 reaches or exceeds this number, a drawer will be created."
1599 :group 'org-todo
1600 :group 'org-progress
1601 :type '(choice
1602 (const :tag "Always" t)
1603 (const :tag "Only when drawer exists" nil)
1604 (integer :tag "When at least N clock entries")))
1606 (defcustom org-clock-out-when-done t
1607 "When t, the clock will be stopped when the relevant entry is marked DONE.
1608 Nil means, clock will keep running until stopped explicitly with
1609 `C-c C-x C-o', or until the clock is started in a different item."
1610 :group 'org-progress
1611 :type 'boolean)
1613 (defcustom org-clock-in-switch-to-state nil
1614 "Set task to a special todo state while clocking it.
1615 The value should be the state to which the entry should be switched."
1616 :group 'org-progress
1617 :group 'org-todo
1618 :type '(choice
1619 (const :tag "Don't force a state" nil)
1620 (string :tag "State")))
1622 (defgroup org-priorities nil
1623 "Priorities in Org-mode."
1624 :tag "Org Priorities"
1625 :group 'org-todo)
1627 (defcustom org-highest-priority ?A
1628 "The highest priority of TODO items. A character like ?A, ?B etc.
1629 Must have a smaller ASCII number than `org-lowest-priority'."
1630 :group 'org-priorities
1631 :type 'character)
1633 (defcustom org-lowest-priority ?C
1634 "The lowest priority of TODO items. A character like ?A, ?B etc.
1635 Must have a larger ASCII number than `org-highest-priority'."
1636 :group 'org-priorities
1637 :type 'character)
1639 (defcustom org-default-priority ?B
1640 "The default priority of TODO items.
1641 This is the priority an item get if no explicit priority is given."
1642 :group 'org-priorities
1643 :type 'character)
1645 (defcustom org-priority-start-cycle-with-default t
1646 "Non-nil means, start with default priority when starting to cycle.
1647 When this is nil, the first step in the cycle will be (depending on the
1648 command used) one higher or lower that the default priority."
1649 :group 'org-priorities
1650 :type 'boolean)
1652 (defgroup org-time nil
1653 "Options concerning time stamps and deadlines in Org-mode."
1654 :tag "Org Time"
1655 :group 'org)
1657 (defcustom org-insert-labeled-timestamps-at-point nil
1658 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1659 When nil, these labeled time stamps are forces into the second line of an
1660 entry, just after the headline. When scheduling from the global TODO list,
1661 the time stamp will always be forced into the second line."
1662 :group 'org-time
1663 :type 'boolean)
1665 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1666 "Formats for `format-time-string' which are used for time stamps.
1667 It is not recommended to change this constant.")
1669 (defcustom org-time-stamp-rounding-minutes '(0 5)
1670 "Number of minutes to round time stamps to.
1671 These are two values, the first applies when first creating a time stamp.
1672 The second applies when changing it with the commands `S-up' and `S-down'.
1673 When changing the time stamp, this means that it will change in steps
1674 of N minutes, as given by the second value.
1676 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1677 numbers should be factors of 60, so for example 5, 10, 15.
1679 When this is larger than 1, you can still force an exact time-stamp by using
1680 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1681 and by using a prefix arg to `S-up/down' to specify the exact number
1682 of minutes to shift."
1683 :group 'org-time
1684 :get '(lambda (var) ; Make sure all entries have 5 elements
1685 (if (integerp (default-value var))
1686 (list (default-value var) 5)
1687 (default-value var)))
1688 :type '(list
1689 (integer :tag "when inserting times")
1690 (integer :tag "when modifying times")))
1692 ;; Make sure old customizations of this variable don't lead to problems.
1693 (when (integerp org-time-stamp-rounding-minutes)
1694 (setq org-time-stamp-rounding-minutes
1695 (list org-time-stamp-rounding-minutes
1696 org-time-stamp-rounding-minutes)))
1698 (defcustom org-display-custom-times nil
1699 "Non-nil means, overlay custom formats over all time stamps.
1700 The formats are defined through the variable `org-time-stamp-custom-formats'.
1701 To turn this on on a per-file basis, insert anywhere in the file:
1702 #+STARTUP: customtime"
1703 :group 'org-time
1704 :set 'set-default
1705 :type 'sexp)
1706 (make-variable-buffer-local 'org-display-custom-times)
1708 (defcustom org-time-stamp-custom-formats
1709 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1710 "Custom formats for time stamps. See `format-time-string' for the syntax.
1711 These are overlayed over the default ISO format if the variable
1712 `org-display-custom-times' is set. Time like %H:%M should be at the
1713 end of the second format."
1714 :group 'org-time
1715 :type 'sexp)
1717 (defun org-time-stamp-format (&optional long inactive)
1718 "Get the right format for a time string."
1719 (let ((f (if long (cdr org-time-stamp-formats)
1720 (car org-time-stamp-formats))))
1721 (if inactive
1722 (concat "[" (substring f 1 -1) "]")
1723 f)))
1725 (defcustom org-deadline-warning-days 14
1726 "No. of days before expiration during which a deadline becomes active.
1727 This variable governs the display in sparse trees and in the agenda.
1728 When 0 or negative, it means use this number (the absolute value of it)
1729 even if a deadline has a different individual lead time specified."
1730 :group 'org-time
1731 :group 'org-agenda-daily/weekly
1732 :type 'number)
1734 (defcustom org-read-date-prefer-future t
1735 "Non-nil means, assume future for incomplete date input from user.
1736 This affects the following situations:
1737 1. The user gives a day, but no month.
1738 For example, if today is the 15th, and you enter \"3\", Org-mode will
1739 read this as the third of *next* month. However, if you enter \"17\",
1740 it will be considered as *this* month.
1741 2. The user gives a month but not a year.
1742 For example, if it is april and you enter \"feb 2\", this will be read
1743 as feb 2, *next* year. \"May 5\", however, will be this year.
1745 Currently this does not work for ISO week specifications.
1747 When this option is nil, the current month and year will always be used
1748 as defaults."
1749 :group 'org-time
1750 :type 'boolean)
1752 (defcustom org-read-date-display-live t
1753 "Non-nil means, display current interpretation of date prompt live.
1754 This display will be in an overlay, in the minibuffer."
1755 :group 'org-time
1756 :type 'boolean)
1758 (defcustom org-read-date-popup-calendar t
1759 "Non-nil means, pop up a calendar when prompting for a date.
1760 In the calendar, the date can be selected with mouse-1. However, the
1761 minibuffer will also be active, and you can simply enter the date as well.
1762 When nil, only the minibuffer will be available."
1763 :group 'org-time
1764 :type 'boolean)
1765 (if (fboundp 'defvaralias)
1766 (defvaralias 'org-popup-calendar-for-date-prompt
1767 'org-read-date-popup-calendar))
1769 (defcustom org-extend-today-until 0
1770 "The hour when your day really ends.
1771 This has influence for the following applications:
1772 - When switching the agenda to \"today\". It it is still earlier than
1773 the time given here, the day recognized as TODAY is actually yesterday.
1774 - When a date is read from the user and it is still before the time given
1775 here, the current date and time will be assumed to be yesterday, 23:59.
1777 FIXME:
1778 IMPORTANT: This is still a very experimental feature, it may disappear
1779 again or it may be extended to mean more things."
1780 :group 'org-time
1781 :type 'number)
1783 (defcustom org-edit-timestamp-down-means-later nil
1784 "Non-nil means, S-down will increase the time in a time stamp.
1785 When nil, S-up will increase."
1786 :group 'org-time
1787 :type 'boolean)
1789 (defcustom org-calendar-follow-timestamp-change t
1790 "Non-nil means, make the calendar window follow timestamp changes.
1791 When a timestamp is modified and the calendar window is visible, it will be
1792 moved to the new date."
1793 :group 'org-time
1794 :type 'boolean)
1796 (defcustom org-clock-heading-function nil
1797 "When non-nil, should be a function to create `org-clock-heading'.
1798 This is the string shown in the mode line when a clock is running.
1799 The function is called with point at the beginning of the headline."
1800 :group 'org-time ; FIXME: Should we have a separate group????
1801 :type 'function)
1803 (defgroup org-tags nil
1804 "Options concerning tags in Org-mode."
1805 :tag "Org Tags"
1806 :group 'org)
1808 (defcustom org-tag-alist nil
1809 "List of tags allowed in Org-mode files.
1810 When this list is nil, Org-mode will base TAG input on what is already in the
1811 buffer.
1812 The value of this variable is an alist, the car of each entry must be a
1813 keyword as a string, the cdr may be a character that is used to select
1814 that tag through the fast-tag-selection interface.
1815 See the manual for details."
1816 :group 'org-tags
1817 :type '(repeat
1818 (choice
1819 (cons (string :tag "Tag name")
1820 (character :tag "Access char"))
1821 (const :tag "Start radio group" (:startgroup))
1822 (const :tag "End radio group" (:endgroup)))))
1824 (defcustom org-use-fast-tag-selection 'auto
1825 "Non-nil means, use fast tag selection scheme.
1826 This is a special interface to select and deselect tags with single keys.
1827 When nil, fast selection is never used.
1828 When the symbol `auto', fast selection is used if and only if selection
1829 characters for tags have been configured, either through the variable
1830 `org-tag-alist' or through a #+TAGS line in the buffer.
1831 When t, fast selection is always used and selection keys are assigned
1832 automatically if necessary."
1833 :group 'org-tags
1834 :type '(choice
1835 (const :tag "Always" t)
1836 (const :tag "Never" nil)
1837 (const :tag "When selection characters are configured" 'auto)))
1839 (defcustom org-fast-tag-selection-single-key nil
1840 "Non-nil means, fast tag selection exits after first change.
1841 When nil, you have to press RET to exit it.
1842 During fast tag selection, you can toggle this flag with `C-c'.
1843 This variable can also have the value `expert'. In this case, the window
1844 displaying the tags menu is not even shown, until you press C-c again."
1845 :group 'org-tags
1846 :type '(choice
1847 (const :tag "No" nil)
1848 (const :tag "Yes" t)
1849 (const :tag "Expert" expert)))
1851 (defvar org-fast-tag-selection-include-todo nil
1852 "Non-nil means, fast tags selection interface will also offer TODO states.
1853 This is an undocumented feature, you should not rely on it.")
1855 (defcustom org-tags-column -80
1856 "The column to which tags should be indented in a headline.
1857 If this number is positive, it specifies the column. If it is negative,
1858 it means that the tags should be flushright to that column. For example,
1859 -80 works well for a normal 80 character screen."
1860 :group 'org-tags
1861 :type 'integer)
1863 (defcustom org-auto-align-tags t
1864 "Non-nil means, realign tags after pro/demotion of TODO state change.
1865 These operations change the length of a headline and therefore shift
1866 the tags around. With this options turned on, after each such operation
1867 the tags are again aligned to `org-tags-column'."
1868 :group 'org-tags
1869 :type 'boolean)
1871 (defcustom org-use-tag-inheritance t
1872 "Non-nil means, tags in levels apply also for sublevels.
1873 When nil, only the tags directly given in a specific line apply there.
1874 If you turn off this option, you very likely want to turn on the
1875 companion option `org-tags-match-list-sublevels'.
1877 This may also be a list of tags that should be inherited, or a regexp that
1878 matches tags that should be inherited."
1879 :group 'org-tags
1880 :type '(choice
1881 (const :tag "Not" nil)
1882 (const :tag "Always" t)
1883 (repeat :tag "Specific tags" (string :tag "Tag"))
1884 (regexp :tag "Tags matched by regexp")))
1886 (defun org-tag-inherit-p (tag)
1887 "Check if TAG is one that should be inherited."
1888 (cond
1889 ((eq org-use-tag-inheritance t) t)
1890 ((not org-use-tag-inheritance) nil)
1891 ((stringp org-use-tag-inheritance)
1892 (string-match org-use-tag-inheritance tag))
1893 ((listp org-use-tag-inheritance)
1894 (member tag org-use-tag-inheritance))
1895 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1897 (defcustom org-tags-match-list-sublevels nil
1898 "Non-nil means list also sublevels of headlines matching tag search.
1899 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1900 the sublevels of a headline matching a tag search often also match
1901 the same search. Listing all of them can create very long lists.
1902 Setting this variable to nil causes subtrees of a match to be skipped.
1903 This option is off by default, because inheritance in on. If you turn
1904 inheritance off, you very likely want to turn this option on.
1906 As a special case, if the tag search is restricted to TODO items, the
1907 value of this variable is ignored and sublevels are always checked, to
1908 make sure all corresponding TODO items find their way into the list."
1909 :group 'org-tags
1910 :type 'boolean)
1912 (defvar org-tags-history nil
1913 "History of minibuffer reads for tags.")
1914 (defvar org-last-tags-completion-table nil
1915 "The last used completion table for tags.")
1916 (defvar org-after-tags-change-hook nil
1917 "Hook that is run after the tags in a line have changed.")
1919 (defgroup org-properties nil
1920 "Options concerning properties in Org-mode."
1921 :tag "Org Properties"
1922 :group 'org)
1924 (defcustom org-property-format "%-10s %s"
1925 "How property key/value pairs should be formatted by `indent-line'.
1926 When `indent-line' hits a property definition, it will format the line
1927 according to this format, mainly to make sure that the values are
1928 lined-up with respect to each other."
1929 :group 'org-properties
1930 :type 'string)
1932 (defcustom org-use-property-inheritance nil
1933 "Non-nil means, properties apply also for sublevels.
1935 This setting is chiefly used during property searches. Turning it on can
1936 cause significant overhead when doing a search, which is why it is not
1937 on by default.
1939 When nil, only the properties directly given in the current entry count.
1940 When t, every property is inherited. The value may also be a list of
1941 properties that should have inheritance, or a regular expression matching
1942 properties that should be inherited.
1944 However, note that some special properties use inheritance under special
1945 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1946 and the properties ending in \"_ALL\" when they are used as descriptor
1947 for valid values of a property.
1949 Note for programmers:
1950 When querying an entry with `org-entry-get', you can control if inheritance
1951 should be used. By default, `org-entry-get' looks only at the local
1952 properties. You can request inheritance by setting the inherit argument
1953 to t (to force inheritance) or to `selective' (to respect the setting
1954 in this variable)."
1955 :group 'org-properties
1956 :type '(choice
1957 (const :tag "Not" nil)
1958 (const :tag "Always" t)
1959 (repeat :tag "Specific properties" (string :tag "Property"))
1960 (regexp :tag "Properties matched by regexp")))
1962 (defun org-property-inherit-p (property)
1963 "Check if PROPERTY is one that should be inherited."
1964 (cond
1965 ((eq org-use-property-inheritance t) t)
1966 ((not org-use-property-inheritance) nil)
1967 ((stringp org-use-property-inheritance)
1968 (string-match org-use-property-inheritance property))
1969 ((listp org-use-property-inheritance)
1970 (member property org-use-property-inheritance))
1971 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1973 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1974 "The default column format, if no other format has been defined.
1975 This variable can be set on the per-file basis by inserting a line
1977 #+COLUMNS: %25ITEM ....."
1978 :group 'org-properties
1979 :type 'string)
1981 (defcustom org-global-properties nil
1982 "List of property/value pairs that can be inherited by any entry.
1983 You can set buffer-local values for this by adding lines like
1985 #+PROPERTY: NAME VALUE"
1986 :group 'org-properties
1987 :type '(repeat
1988 (cons (string :tag "Property")
1989 (string :tag "Value"))))
1991 (defvar org-local-properties nil
1992 "List of property/value pairs that can be inherited by any entry.
1993 Valid for the current buffer.
1994 This variable is populated from #+PROPERTY lines.")
1996 (defgroup org-agenda nil
1997 "Options concerning agenda views in Org-mode."
1998 :tag "Org Agenda"
1999 :group 'org)
2001 (defvar org-category nil
2002 "Variable used by org files to set a category for agenda display.
2003 Such files should use a file variable to set it, for example
2005 # -*- mode: org; org-category: \"ELisp\"
2007 or contain a special line
2009 #+CATEGORY: ELisp
2011 If the file does not specify a category, then file's base name
2012 is used instead.")
2013 (make-variable-buffer-local 'org-category)
2015 (defcustom org-agenda-files nil
2016 "The files to be used for agenda display.
2017 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2018 \\[org-remove-file]. You can also use customize to edit the list.
2020 If an entry is a directory, all files in that directory that are matched by
2021 `org-agenda-file-regexp' will be part of the file list.
2023 If the value of the variable is not a list but a single file name, then
2024 the list of agenda files is actually stored and maintained in that file, one
2025 agenda file per line."
2026 :group 'org-agenda
2027 :type '(choice
2028 (repeat :tag "List of files and directories" file)
2029 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2031 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2032 "Regular expression to match files for `org-agenda-files'.
2033 If any element in the list in that variable contains a directory instead
2034 of a normal file, all files in that directory that are matched by this
2035 regular expression will be included."
2036 :group 'org-agenda
2037 :type 'regexp)
2039 (defcustom org-agenda-text-search-extra-files nil
2040 "List of extra files to be searched by text search commands.
2041 These files will be search in addition to the agenda files bu the
2042 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2043 Note that these files will only be searched for text search commands,
2044 not for the other agenda views like todo lists, tag earches or the weekly
2045 agenda. This variable is intended to list notes and possibly archive files
2046 that should also be searched by these two commands."
2047 :group 'org-agenda
2048 :type '(repeat file))
2050 (if (fboundp 'defvaralias)
2051 (defvaralias 'org-agenda-multi-occur-extra-files
2052 'org-agenda-text-search-extra-files))
2054 (defcustom org-agenda-skip-unavailable-files nil
2055 "t means to just skip non-reachable files in `org-agenda-files'.
2056 Nil means to remove them, after a query, from the list."
2057 :group 'org-agenda
2058 :type 'boolean)
2060 (defcustom org-calendar-to-agenda-key [?c]
2061 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2062 The command `org-calendar-goto-agenda' will be bound to this key. The
2063 default is the character `c' because then `c' can be used to switch back and
2064 forth between agenda and calendar."
2065 :group 'org-agenda
2066 :type 'sexp)
2068 (eval-after-load "calendar"
2069 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
2070 'org-calendar-goto-agenda))
2072 (defgroup org-latex nil
2073 "Options for embedding LaTeX code into Org-mode."
2074 :tag "Org LaTeX"
2075 :group 'org)
2077 (defcustom org-format-latex-options
2078 '(:foreground default :background default :scale 1.0
2079 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2080 :matchers ("begin" "$" "$$" "\\(" "\\["))
2081 "Options for creating images from LaTeX fragments.
2082 This is a property list with the following properties:
2083 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2084 `default' means use the forground of the default face.
2085 :background the background color, or \"Transparent\".
2086 `default' means use the background of the default face.
2087 :scale a scaling factor for the size of the images
2088 :html-foreground, :html-background, :html-scale
2089 The same numbers for HTML export.
2090 :matchers a list indicating which matchers should be used to
2091 find LaTeX fragments. Valid members of this list are:
2092 \"begin\" find environments
2093 \"$\" find math expressions surrounded by $...$
2094 \"$$\" find math expressions surrounded by $$....$$
2095 \"\\(\" find math expressions surrounded by \\(...\\)
2096 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2097 :group 'org-latex
2098 :type 'plist)
2100 (defcustom org-format-latex-header "\\documentclass{article}
2101 \\usepackage{fullpage} % do not remove
2102 \\usepackage{amssymb}
2103 \\usepackage[usenames]{color}
2104 \\usepackage{amsmath}
2105 \\usepackage{latexsym}
2106 \\usepackage[mathscr]{eucal}
2107 \\pagestyle{empty} % do not remove"
2108 "The document header used for processing LaTeX fragments."
2109 :group 'org-latex
2110 :type 'string)
2113 (defgroup org-font-lock nil
2114 "Font-lock settings for highlighting in Org-mode."
2115 :tag "Org Font Lock"
2116 :group 'org)
2118 (defcustom org-level-color-stars-only nil
2119 "Non-nil means fontify only the stars in each headline.
2120 When nil, the entire headline is fontified.
2121 Changing it requires restart of `font-lock-mode' to become effective
2122 also in regions already fontified."
2123 :group 'org-font-lock
2124 :type 'boolean)
2126 (defcustom org-hide-leading-stars nil
2127 "Non-nil means, hide the first N-1 stars in a headline.
2128 This works by using the face `org-hide' for these stars. This
2129 face is white for a light background, and black for a dark
2130 background. You may have to customize the face `org-hide' to
2131 make this work.
2132 Changing it requires restart of `font-lock-mode' to become effective
2133 also in regions already fontified.
2134 You may also set this on a per-file basis by adding one of the following
2135 lines to the buffer:
2137 #+STARTUP: hidestars
2138 #+STARTUP: showstars"
2139 :group 'org-font-lock
2140 :type 'boolean)
2142 (defcustom org-fontify-done-headline nil
2143 "Non-nil means, change the face of a headline if it is marked DONE.
2144 Normally, only the TODO/DONE keyword indicates the state of a headline.
2145 When this is non-nil, the headline after the keyword is set to the
2146 `org-headline-done' as an additional indication."
2147 :group 'org-font-lock
2148 :type 'boolean)
2150 (defcustom org-fontify-emphasized-text t
2151 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2152 Changing this variable requires a restart of Emacs to take effect."
2153 :group 'org-font-lock
2154 :type 'boolean)
2156 (defcustom org-highlight-latex-fragments-and-specials nil
2157 "Non-nil means, fontify what is treated specially by the exporters."
2158 :group 'org-font-lock
2159 :type 'boolean)
2161 (defcustom org-hide-emphasis-markers nil
2162 "Non-nil mean font-lock should hide the emphasis marker characters."
2163 :group 'org-font-lock
2164 :type 'boolean)
2166 (defvar org-emph-re nil
2167 "Regular expression for matching emphasis.")
2168 (defvar org-verbatim-re nil
2169 "Regular expression for matching verbatim text.")
2170 (defvar org-emphasis-regexp-components) ; defined just below
2171 (defvar org-emphasis-alist) ; defined just below
2172 (defun org-set-emph-re (var val)
2173 "Set variable and compute the emphasis regular expression."
2174 (set var val)
2175 (when (and (boundp 'org-emphasis-alist)
2176 (boundp 'org-emphasis-regexp-components)
2177 org-emphasis-alist org-emphasis-regexp-components)
2178 (let* ((e org-emphasis-regexp-components)
2179 (pre (car e))
2180 (post (nth 1 e))
2181 (border (nth 2 e))
2182 (body (nth 3 e))
2183 (nl (nth 4 e))
2184 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2185 (body1 (concat body "*?"))
2186 (markers (mapconcat 'car org-emphasis-alist ""))
2187 (vmarkers (mapconcat
2188 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2189 org-emphasis-alist "")))
2190 ;; make sure special characters appear at the right position in the class
2191 (if (string-match "\\^" markers)
2192 (setq markers (concat (replace-match "" t t markers) "^")))
2193 (if (string-match "-" markers)
2194 (setq markers (concat (replace-match "" t t markers) "-")))
2195 (if (string-match "\\^" vmarkers)
2196 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2197 (if (string-match "-" vmarkers)
2198 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2199 (if (> nl 0)
2200 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2201 (int-to-string nl) "\\}")))
2202 ;; Make the regexp
2203 (setq org-emph-re
2204 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2205 "\\("
2206 "\\([" markers "]\\)"
2207 "\\("
2208 "[^" border "]\\|"
2209 "[^" border (if (and nil stacked) markers) "]"
2210 body1
2211 "[^" border (if (and nil stacked) markers) "]"
2212 "\\)"
2213 "\\3\\)"
2214 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2215 (setq org-verbatim-re
2216 (concat "\\([" pre "]\\|^\\)"
2217 "\\("
2218 "\\([" vmarkers "]\\)"
2219 "\\("
2220 "[^" border "]\\|"
2221 "[^" border "]"
2222 body1
2223 "[^" border "]"
2224 "\\)"
2225 "\\3\\)"
2226 "\\([" post "]\\|$\\)")))))
2228 (defcustom org-emphasis-regexp-components
2229 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2230 "Components used to build the regular expression for emphasis.
2231 This is a list with 6 entries. Terminology: In an emphasis string
2232 like \" *strong word* \", we call the initial space PREMATCH, the final
2233 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2234 and \"trong wor\" is the body. The different components in this variable
2235 specify what is allowed/forbidden in each part:
2237 pre Chars allowed as prematch. Beginning of line will be allowed too.
2238 post Chars allowed as postmatch. End of line will be allowed too.
2239 border The chars *forbidden* as border characters.
2240 body-regexp A regexp like \".\" to match a body character. Don't use
2241 non-shy groups here, and don't allow newline here.
2242 newline The maximum number of newlines allowed in an emphasis exp.
2244 Use customize to modify this, or restart Emacs after changing it."
2245 :group 'org-font-lock
2246 :set 'org-set-emph-re
2247 :type '(list
2248 (sexp :tag "Allowed chars in pre ")
2249 (sexp :tag "Allowed chars in post ")
2250 (sexp :tag "Forbidden chars in border ")
2251 (sexp :tag "Regexp for body ")
2252 (integer :tag "number of newlines allowed")
2253 (option (boolean :tag "Stacking (DISABLED) "))))
2255 (defcustom org-emphasis-alist
2256 '(("*" bold "<b>" "</b>")
2257 ("/" italic "<i>" "</i>")
2258 ("_" underline "<u>" "</u>")
2259 ("=" org-code "<code>" "</code>" verbatim)
2260 ("~" org-verbatim "" "" verbatim)
2261 ("+" (:strike-through t) "<del>" "</del>")
2263 "Special syntax for emphasized text.
2264 Text starting and ending with a special character will be emphasized, for
2265 example *bold*, _underlined_ and /italic/. This variable sets the marker
2266 characters, the face to be used by font-lock for highlighting in Org-mode
2267 Emacs buffers, and the HTML tags to be used for this.
2268 Use customize to modify this, or restart Emacs after changing it."
2269 :group 'org-font-lock
2270 :set 'org-set-emph-re
2271 :type '(repeat
2272 (list
2273 (string :tag "Marker character")
2274 (choice
2275 (face :tag "Font-lock-face")
2276 (plist :tag "Face property list"))
2277 (string :tag "HTML start tag")
2278 (string :tag "HTML end tag")
2279 (option (const verbatim)))))
2281 ;;; The faces
2283 (defgroup org-faces nil
2284 "Faces in Org-mode."
2285 :tag "Org Faces"
2286 :group 'org-font-lock)
2288 (defface org-hide
2289 '((((background light)) (:foreground "white"))
2290 (((background dark)) (:foreground "black")))
2291 "Face used to hide leading stars in headlines.
2292 The forground color of this face should be equal to the background
2293 color of the frame."
2294 :group 'org-faces)
2296 (defface org-level-1 ;; font-lock-function-name-face
2297 (org-compatible-face 'outline-1
2298 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2299 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2300 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2301 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2302 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2303 (t (:bold t))))
2304 "Face used for level 1 headlines."
2305 :group 'org-faces)
2307 (defface org-level-2 ;; font-lock-variable-name-face
2308 (org-compatible-face 'outline-2
2309 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2310 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2311 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2312 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2313 (t (:bold t))))
2314 "Face used for level 2 headlines."
2315 :group 'org-faces)
2317 (defface org-level-3 ;; font-lock-keyword-face
2318 (org-compatible-face 'outline-3
2319 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2320 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2321 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2322 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2323 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2324 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2325 (t (:bold t))))
2326 "Face used for level 3 headlines."
2327 :group 'org-faces)
2329 (defface org-level-4 ;; font-lock-comment-face
2330 (org-compatible-face 'outline-4
2331 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2332 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2333 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2334 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2335 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2336 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2337 (t (:bold t))))
2338 "Face used for level 4 headlines."
2339 :group 'org-faces)
2341 (defface org-level-5 ;; font-lock-type-face
2342 (org-compatible-face 'outline-5
2343 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2344 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2345 (((class color) (min-colors 8)) (:foreground "green"))))
2346 "Face used for level 5 headlines."
2347 :group 'org-faces)
2349 (defface org-level-6 ;; font-lock-constant-face
2350 (org-compatible-face 'outline-6
2351 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2352 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2353 (((class color) (min-colors 8)) (:foreground "magenta"))))
2354 "Face used for level 6 headlines."
2355 :group 'org-faces)
2357 (defface org-level-7 ;; font-lock-builtin-face
2358 (org-compatible-face 'outline-7
2359 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2360 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2361 (((class color) (min-colors 8)) (:foreground "blue"))))
2362 "Face used for level 7 headlines."
2363 :group 'org-faces)
2365 (defface org-level-8 ;; font-lock-string-face
2366 (org-compatible-face 'outline-8
2367 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2368 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2369 (((class color) (min-colors 8)) (:foreground "green"))))
2370 "Face used for level 8 headlines."
2371 :group 'org-faces)
2373 (defface org-special-keyword ;; font-lock-string-face
2374 (org-compatible-face nil
2375 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2376 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2377 (t (:italic t))))
2378 "Face used for special keywords."
2379 :group 'org-faces)
2381 (defface org-drawer ;; font-lock-function-name-face
2382 (org-compatible-face nil
2383 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2384 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2385 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2386 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2387 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2388 (t (:bold t))))
2389 "Face used for drawers."
2390 :group 'org-faces)
2392 (defface org-property-value nil
2393 "Face used for the value of a property."
2394 :group 'org-faces)
2396 (defface org-column
2397 (org-compatible-face nil
2398 '((((class color) (min-colors 16) (background light))
2399 (:background "grey90"))
2400 (((class color) (min-colors 16) (background dark))
2401 (:background "grey30"))
2402 (((class color) (min-colors 8))
2403 (:background "cyan" :foreground "black"))
2404 (t (:inverse-video t))))
2405 "Face for column display of entry properties."
2406 :group 'org-faces)
2408 (when (fboundp 'set-face-attribute)
2409 ;; Make sure that a fixed-width face is used when we have a column table.
2410 (set-face-attribute 'org-column nil
2411 :height (face-attribute 'default :height)
2412 :family (face-attribute 'default :family)))
2414 (defface org-warning
2415 (org-compatible-face 'font-lock-warning-face
2416 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2417 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2418 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2419 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2420 (t (:bold t))))
2421 "Face for deadlines and TODO keywords."
2422 :group 'org-faces)
2424 (defface org-archived ; similar to shadow
2425 (org-compatible-face 'shadow
2426 '((((class color grayscale) (min-colors 88) (background light))
2427 (:foreground "grey50"))
2428 (((class color grayscale) (min-colors 88) (background dark))
2429 (:foreground "grey70"))
2430 (((class color) (min-colors 8) (background light))
2431 (:foreground "green"))
2432 (((class color) (min-colors 8) (background dark))
2433 (:foreground "yellow"))))
2434 "Face for headline with the ARCHIVE tag."
2435 :group 'org-faces)
2437 (defface org-link
2438 '((((class color) (background light)) (:foreground "Purple" :underline t))
2439 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2440 (t (:underline t)))
2441 "Face for links."
2442 :group 'org-faces)
2444 (defface org-ellipsis
2445 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
2446 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
2447 (t (:strike-through t)))
2448 "Face for the ellipsis in folded text."
2449 :group 'org-faces)
2451 (defface org-target
2452 '((((class color) (background light)) (:underline t))
2453 (((class color) (background dark)) (:underline t))
2454 (t (:underline t)))
2455 "Face for links."
2456 :group 'org-faces)
2458 (defface org-date
2459 '((((class color) (background light)) (:foreground "Purple" :underline t))
2460 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2461 (t (:underline t)))
2462 "Face for links."
2463 :group 'org-faces)
2465 (defface org-sexp-date
2466 '((((class color) (background light)) (:foreground "Purple"))
2467 (((class color) (background dark)) (:foreground "Cyan"))
2468 (t (:underline t)))
2469 "Face for links."
2470 :group 'org-faces)
2472 (defface org-tag
2473 '((t (:bold t)))
2474 "Face for tags."
2475 :group 'org-faces)
2477 (defface org-todo ; font-lock-warning-face
2478 (org-compatible-face nil
2479 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2480 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2481 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2482 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2483 (t (:inverse-video t :bold t))))
2484 "Face for TODO keywords."
2485 :group 'org-faces)
2487 (defface org-done ;; font-lock-type-face
2488 (org-compatible-face nil
2489 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2490 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2491 (((class color) (min-colors 8)) (:foreground "green"))
2492 (t (:bold t))))
2493 "Face used for todo keywords that indicate DONE items."
2494 :group 'org-faces)
2496 (defface org-headline-done ;; font-lock-string-face
2497 (org-compatible-face nil
2498 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2499 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2500 (((class color) (min-colors 8) (background light)) (:bold nil))))
2501 "Face used to indicate that a headline is DONE.
2502 This face is only used if `org-fontify-done-headline' is set. If applies
2503 to the part of the headline after the DONE keyword."
2504 :group 'org-faces)
2506 (defcustom org-todo-keyword-faces nil
2507 "Faces for specific TODO keywords.
2508 This is a list of cons cells, with TODO keywords in the car
2509 and faces in the cdr. The face can be a symbol, or a property
2510 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
2511 :group 'org-faces
2512 :group 'org-todo
2513 :type '(repeat
2514 (cons
2515 (string :tag "keyword")
2516 (sexp :tag "face"))))
2518 (defface org-table ;; font-lock-function-name-face
2519 (org-compatible-face nil
2520 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2521 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2522 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2523 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2524 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2525 (((class color) (min-colors 8) (background dark)))))
2526 "Face used for tables."
2527 :group 'org-faces)
2529 (defface org-formula
2530 (org-compatible-face nil
2531 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2532 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2533 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2534 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2535 (t (:bold t :italic t))))
2536 "Face for formulas."
2537 :group 'org-faces)
2539 (defface org-code
2540 (org-compatible-face nil
2541 '((((class color grayscale) (min-colors 88) (background light))
2542 (:foreground "grey50"))
2543 (((class color grayscale) (min-colors 88) (background dark))
2544 (:foreground "grey70"))
2545 (((class color) (min-colors 8) (background light))
2546 (:foreground "green"))
2547 (((class color) (min-colors 8) (background dark))
2548 (:foreground "yellow"))))
2549 "Face for fixed-with text like code snippets."
2550 :group 'org-faces
2551 :version "22.1")
2553 (defface org-verbatim
2554 (org-compatible-face nil
2555 '((((class color grayscale) (min-colors 88) (background light))
2556 (:foreground "grey50" :underline t))
2557 (((class color grayscale) (min-colors 88) (background dark))
2558 (:foreground "grey70" :underline t))
2559 (((class color) (min-colors 8) (background light))
2560 (:foreground "green" :underline t))
2561 (((class color) (min-colors 8) (background dark))
2562 (:foreground "yellow" :underline t))))
2563 "Face for fixed-with text like code snippets."
2564 :group 'org-faces
2565 :version "22.1")
2567 (defface org-agenda-structure ;; font-lock-function-name-face
2568 (org-compatible-face nil
2569 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2570 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2571 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2572 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2573 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2574 (t (:bold t))))
2575 "Face used in agenda for captions and dates."
2576 :group 'org-faces)
2578 (defface org-scheduled-today
2579 (org-compatible-face nil
2580 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2581 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2582 (((class color) (min-colors 8)) (:foreground "green"))
2583 (t (:bold t :italic t))))
2584 "Face for items scheduled for a certain day."
2585 :group 'org-faces)
2587 (defface org-scheduled-previously
2588 (org-compatible-face nil
2589 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2590 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2591 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2592 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2593 (t (:bold t))))
2594 "Face for items scheduled previously, and not yet done."
2595 :group 'org-faces)
2597 (defface org-upcoming-deadline
2598 (org-compatible-face nil
2599 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2600 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2601 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2602 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2603 (t (:bold t))))
2604 "Face for items scheduled previously, and not yet done."
2605 :group 'org-faces)
2607 (defcustom org-agenda-deadline-faces
2608 '((1.0 . org-warning)
2609 (0.5 . org-upcoming-deadline)
2610 (0.0 . default))
2611 "Faces for showing deadlines in the agenda.
2612 This is a list of cons cells. The cdr of each cell is a face to be used,
2613 and it can also just be like '(:foreground \"yellow\").
2614 Each car is a fraction of the head-warning time that must have passed for
2615 this the face in the cdr to be used for display. The numbers must be
2616 given in descending order. The head-warning time is normally taken
2617 from `org-deadline-warning-days', but can also be specified in the deadline
2618 timestamp itself, like this:
2620 DEADLINE: <2007-08-13 Mon -8d>
2622 You may use d for days, w for weeks, m for months and y for years. Months
2623 and years will only be treated in an approximate fashion (30.4 days for a
2624 month and 365.24 days for a year)."
2625 :group 'org-faces
2626 :group 'org-agenda-daily/weekly
2627 :type '(repeat
2628 (cons
2629 (number :tag "Fraction of head-warning time passed")
2630 (sexp :tag "Face"))))
2632 ;; FIXME: this is not a good face yet.
2633 (defface org-agenda-restriction-lock
2634 (org-compatible-face nil
2635 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
2636 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
2637 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
2638 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
2639 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
2640 (t (:inverse-video t))))
2641 "Face for showing the agenda restriction lock."
2642 :group 'org-faces)
2644 (defface org-time-grid ;; font-lock-variable-name-face
2645 (org-compatible-face nil
2646 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2647 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2648 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2649 "Face used for time grids."
2650 :group 'org-faces)
2652 (defconst org-level-faces
2653 '(org-level-1 org-level-2 org-level-3 org-level-4
2654 org-level-5 org-level-6 org-level-7 org-level-8
2657 (defcustom org-n-level-faces (length org-level-faces)
2658 "The number of different faces to be used for headlines.
2659 Org-mode defines 8 different headline faces, so this can be at most 8.
2660 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
2661 :type 'number
2662 :group 'org-faces)
2664 ;;; Functions and variables from ther packages
2665 ;; Declared here to avoid compiler warnings
2667 ;; XEmacs only
2668 (defvar outline-mode-menu-heading)
2669 (defvar outline-mode-menu-show)
2670 (defvar outline-mode-menu-hide)
2671 (defvar zmacs-regions) ; XEmacs regions
2673 ;; Emacs only
2674 (defvar mark-active)
2676 ;; Various packages
2677 ;; FIXME: get the argument lists for the UNKNOWN stuff
2678 (declare-function bibtex-beginning-of-entry "bibtex" ())
2679 (declare-function bibtex-generate-autokey "bibtex" ())
2680 (declare-function bibtex-parse-entry "bibtex" (&optional content))
2681 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
2682 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
2683 (declare-function calendar-forward-day "cal-move" (arg))
2684 (declare-function calendar-goto-date "cal-move" (date))
2685 (declare-function calendar-goto-today "cal-move" ())
2686 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
2687 (defvar calc-embedded-close-formula)
2688 (defvar calc-embedded-open-formula)
2689 (declare-function cdlatex-tab "ext:cdlatex" ())
2690 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2691 (defvar font-lock-unfontify-region-function)
2692 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2693 (declare-function org-agenda-skip "org-agenda" ())
2694 (declare-function org-format-agenda-item "org-agenda"
2695 (extra txt &optional category tags dotime noprefix remove-re))
2696 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2697 (declare-function org-agenda-change-all-lines "org-agenda"
2698 (newhead hdmarker &optional fixface))
2699 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2700 (declare-function org-agenda-maybe-redo "org-agenda" ())
2701 (declare-function parse-time-string "parse-time" (string))
2702 (declare-function remember "remember" (&optional initial))
2703 (declare-function remember-buffer-desc "remember" ())
2704 (declare-function remember-finalize "remember" ())
2705 (defvar remember-save-after-remembering)
2706 (defvar remember-data-file)
2707 (defvar remember-register)
2708 (defvar remember-buffer)
2709 (defvar remember-handler-functions)
2710 (defvar remember-annotation-functions)
2711 (defvar texmathp-why)
2712 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2713 (declare-function table--at-cell-p "table" (position &optional object at-column))
2715 (defvar w3m-current-url)
2716 (defvar w3m-current-title)
2718 (defvar org-latex-regexps)
2720 ;;; Autoload and prepare some org modules
2722 ;; Some table stuff that needs to be defined here, because it is used
2723 ;; by the functions setting up org-mode or checking for table context.
2725 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2726 "Detects an org-type or table-type table.")
2727 (defconst org-table-line-regexp "^[ \t]*|"
2728 "Detects an org-type table line.")
2729 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2730 "Detects an org-type table line.")
2731 (defconst org-table-hline-regexp "^[ \t]*|-"
2732 "Detects an org-type table hline.")
2733 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2734 "Detects a table-type table hline.")
2735 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2736 "Searching from within a table (any type) this finds the first line
2737 outside the table.")
2739 ;; Autoload the functions in org-table.el that are needed by functions here.
2741 (eval-and-compile
2742 (org-autoload "org-table"
2743 '(org-table-align org-table-begin org-table-blank-field
2744 org-table-convert org-table-convert-region org-table-copy-down
2745 org-table-copy-region org-table-create
2746 org-table-create-or-convert-from-region
2747 org-table-create-with-table.el org-table-current-dline
2748 org-table-cut-region org-table-delete-column org-table-edit-field
2749 org-table-edit-formulas org-table-end org-table-eval-formula
2750 org-table-export org-table-field-info
2751 org-table-get-stored-formulas org-table-goto-column
2752 org-table-hline-and-move org-table-import org-table-insert-column
2753 org-table-insert-hline org-table-insert-row org-table-iterate
2754 org-table-justify-field-maybe org-table-kill-row
2755 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2756 org-table-move-column org-table-move-column-left
2757 org-table-move-column-right org-table-move-row
2758 org-table-move-row-down org-table-move-row-up
2759 org-table-next-field org-table-next-row org-table-paste-rectangle
2760 org-table-previous-field org-table-recalculate
2761 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2762 org-table-toggle-coordinate-overlays
2763 org-table-toggle-formula-debugger org-table-wrap-region
2764 orgtbl-mode turn-on-orgtbl)))
2766 (defun org-at-table-p (&optional table-type)
2767 "Return t if the cursor is inside an org-type table.
2768 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2769 (if org-enable-table-editor
2770 (save-excursion
2771 (beginning-of-line 1)
2772 (looking-at (if table-type org-table-any-line-regexp
2773 org-table-line-regexp)))
2774 nil))
2775 (defsubst org-table-p () (org-at-table-p))
2777 (defun org-at-table.el-p ()
2778 "Return t if and only if we are at a table.el table."
2779 (and (org-at-table-p 'any)
2780 (save-excursion
2781 (goto-char (org-table-begin 'any))
2782 (looking-at org-table1-hline-regexp))))
2783 (defun org-table-recognize-table.el ()
2784 "If there is a table.el table nearby, recognize it and move into it."
2785 (if org-table-tab-recognizes-table.el
2786 (if (org-at-table.el-p)
2787 (progn
2788 (beginning-of-line 1)
2789 (if (looking-at org-table-dataline-regexp)
2791 (if (looking-at org-table1-hline-regexp)
2792 (progn
2793 (beginning-of-line 2)
2794 (if (looking-at org-table-any-border-regexp)
2795 (beginning-of-line -1)))))
2796 (if (re-search-forward "|" (org-table-end t) t)
2797 (progn
2798 (require 'table)
2799 (if (table--at-cell-p (point))
2801 (message "recognizing table.el table...")
2802 (table-recognize-table)
2803 (message "recognizing table.el table...done")))
2804 (error "This should not happen..."))
2806 nil)
2807 nil))
2809 (defun org-at-table-hline-p ()
2810 "Return t if the cursor is inside a hline in a table."
2811 (if org-enable-table-editor
2812 (save-excursion
2813 (beginning-of-line 1)
2814 (looking-at org-table-hline-regexp))
2815 nil))
2817 (defvar org-table-clean-did-remove-column nil)
2819 (defun org-table-map-tables (function)
2820 "Apply FUNCTION to the start of all tables in the buffer."
2821 (save-excursion
2822 (save-restriction
2823 (widen)
2824 (goto-char (point-min))
2825 (while (re-search-forward org-table-any-line-regexp nil t)
2826 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2827 (beginning-of-line 1)
2828 (if (looking-at org-table-line-regexp)
2829 (save-excursion (funcall function)))
2830 (re-search-forward org-table-any-border-regexp nil 1))))
2831 (message "Mapping tables: done"))
2833 ;; Declare and autoload functions from org-exp.el
2835 (declare-function org-default-export-plist "org-exp")
2836 (declare-function org-infile-export-plist "org-exp")
2837 (declare-function org-get-current-options "org-exp")
2838 (eval-and-compile
2839 (org-autoload "org-exp"
2840 '(org-export org-export-as-ascii org-export-visible
2841 org-insert-export-options-template org-export-as-html-and-open
2842 org-export-as-html-batch org-export-as-html-to-buffer
2843 org-replace-region-by-html org-export-region-as-html
2844 org-export-as-html org-export-icalendar-this-file
2845 org-export-icalendar-all-agenda-files
2846 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2848 ;; Autoload org-remember
2850 (eval-and-compile
2851 (org-autoload "org-remember"
2852 '(org-remember-insinuate org-remember-annotation
2853 org-remember-apply-template org-remember org-remember-handler)))
2855 ;;; Variables for pre-computed regular expressions, all buffer local
2857 (defvar org-drawer-regexp nil
2858 "Matches first line of a hidden block.")
2859 (make-variable-buffer-local 'org-drawer-regexp)
2860 (defvar org-todo-regexp nil
2861 "Matches any of the TODO state keywords.")
2862 (make-variable-buffer-local 'org-todo-regexp)
2863 (defvar org-not-done-regexp nil
2864 "Matches any of the TODO state keywords except the last one.")
2865 (make-variable-buffer-local 'org-not-done-regexp)
2866 (defvar org-todo-line-regexp nil
2867 "Matches a headline and puts TODO state into group 2 if present.")
2868 (make-variable-buffer-local 'org-todo-line-regexp)
2869 (defvar org-complex-heading-regexp nil
2870 "Matches a headline and puts everything into groups:
2871 group 1: the stars
2872 group 2: The todo keyword, maybe
2873 group 3: Priority cookie
2874 group 4: True headline
2875 group 5: Tags")
2876 (make-variable-buffer-local 'org-complex-heading-regexp)
2877 (defvar org-todo-line-tags-regexp nil
2878 "Matches a headline and puts TODO state into group 2 if present.
2879 Also put tags into group 4 if tags are present.")
2880 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2881 (defvar org-nl-done-regexp nil
2882 "Matches newline followed by a headline with the DONE keyword.")
2883 (make-variable-buffer-local 'org-nl-done-regexp)
2884 (defvar org-looking-at-done-regexp nil
2885 "Matches the DONE keyword a point.")
2886 (make-variable-buffer-local 'org-looking-at-done-regexp)
2887 (defvar org-ds-keyword-length 12
2888 "Maximum length of the Deadline and SCHEDULED keywords.")
2889 (make-variable-buffer-local 'org-ds-keyword-length)
2890 (defvar org-deadline-regexp nil
2891 "Matches the DEADLINE keyword.")
2892 (make-variable-buffer-local 'org-deadline-regexp)
2893 (defvar org-deadline-time-regexp nil
2894 "Matches the DEADLINE keyword together with a time stamp.")
2895 (make-variable-buffer-local 'org-deadline-time-regexp)
2896 (defvar org-deadline-line-regexp nil
2897 "Matches the DEADLINE keyword and the rest of the line.")
2898 (make-variable-buffer-local 'org-deadline-line-regexp)
2899 (defvar org-scheduled-regexp nil
2900 "Matches the SCHEDULED keyword.")
2901 (make-variable-buffer-local 'org-scheduled-regexp)
2902 (defvar org-scheduled-time-regexp nil
2903 "Matches the SCHEDULED keyword together with a time stamp.")
2904 (make-variable-buffer-local 'org-scheduled-time-regexp)
2905 (defvar org-closed-time-regexp nil
2906 "Matches the CLOSED keyword together with a time stamp.")
2907 (make-variable-buffer-local 'org-closed-time-regexp)
2909 (defvar org-keyword-time-regexp nil
2910 "Matches any of the 4 keywords, together with the time stamp.")
2911 (make-variable-buffer-local 'org-keyword-time-regexp)
2912 (defvar org-keyword-time-not-clock-regexp nil
2913 "Matches any of the 3 keywords, together with the time stamp.")
2914 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2915 (defvar org-maybe-keyword-time-regexp nil
2916 "Matches a timestamp, possibly preceeded by a keyword.")
2917 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2918 (defvar org-planning-or-clock-line-re nil
2919 "Matches a line with planning or clock info.")
2920 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2922 (defconst org-plain-time-of-day-regexp
2923 (concat
2924 "\\(\\<[012]?[0-9]"
2925 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2926 "\\(--?"
2927 "\\(\\<[012]?[0-9]"
2928 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2929 "\\)?")
2930 "Regular expression to match a plain time or time range.
2931 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2932 groups carry important information:
2933 0 the full match
2934 1 the first time, range or not
2935 8 the second time, if it is a range.")
2937 (defconst org-plain-time-extension-regexp
2938 (concat
2939 "\\(\\<[012]?[0-9]"
2940 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2941 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2942 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2943 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2944 groups carry important information:
2945 0 the full match
2946 7 hours of duration
2947 9 minutes of duration")
2949 (defconst org-stamp-time-of-day-regexp
2950 (concat
2951 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2952 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2953 "\\(--?"
2954 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2955 "Regular expression to match a timestamp time or time range.
2956 After a match, the following groups carry important information:
2957 0 the full match
2958 1 date plus weekday, for backreferencing to make sure both times on same day
2959 2 the first time, range or not
2960 4 the second time, if it is a range.")
2962 (defconst org-startup-options
2963 '(("fold" org-startup-folded t)
2964 ("overview" org-startup-folded t)
2965 ("nofold" org-startup-folded nil)
2966 ("showall" org-startup-folded nil)
2967 ("content" org-startup-folded content)
2968 ("hidestars" org-hide-leading-stars t)
2969 ("showstars" org-hide-leading-stars nil)
2970 ("odd" org-odd-levels-only t)
2971 ("oddeven" org-odd-levels-only nil)
2972 ("align" org-startup-align-all-tables t)
2973 ("noalign" org-startup-align-all-tables nil)
2974 ("customtime" org-display-custom-times t)
2975 ("logdone" org-log-done time)
2976 ("lognotedone" org-log-done note)
2977 ("nologdone" org-log-done nil)
2978 ("lognoteclock-out" org-log-note-clock-out t)
2979 ("nolognoteclock-out" org-log-note-clock-out nil)
2980 ("logrepeat" org-log-repeat state)
2981 ("lognoterepeat" org-log-repeat note)
2982 ("nologrepeat" org-log-repeat nil)
2983 ("constcgs" constants-unit-system cgs)
2984 ("constSI" constants-unit-system SI))
2985 "Variable associated with STARTUP options for org-mode.
2986 Each element is a list of three items: The startup options as written
2987 in the #+STARTUP line, the corresponding variable, and the value to
2988 set this variable to if the option is found. An optional forth element PUSH
2989 means to push this value onto the list in the variable.")
2991 (defun org-set-regexps-and-options ()
2992 "Precompute regular expressions for current buffer."
2993 (when (org-mode-p)
2994 (org-set-local 'org-todo-kwd-alist nil)
2995 (org-set-local 'org-todo-key-alist nil)
2996 (org-set-local 'org-todo-key-trigger nil)
2997 (org-set-local 'org-todo-keywords-1 nil)
2998 (org-set-local 'org-done-keywords nil)
2999 (org-set-local 'org-todo-heads nil)
3000 (org-set-local 'org-todo-sets nil)
3001 (org-set-local 'org-todo-log-states nil)
3002 (let ((re (org-make-options-regexp
3003 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3004 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
3005 "CONSTANTS" "PROPERTY" "DRAWERS")))
3006 (splitre "[ \t]+")
3007 kwds kws0 kwsa key log value cat arch tags const links hw dws
3008 tail sep kws1 prio props drawers)
3009 (save-excursion
3010 (save-restriction
3011 (widen)
3012 (goto-char (point-min))
3013 (while (re-search-forward re nil t)
3014 (setq key (match-string 1) value (org-match-string-no-properties 2))
3015 (cond
3016 ((equal key "CATEGORY")
3017 (if (string-match "[ \t]+$" value)
3018 (setq value (replace-match "" t t value)))
3019 (setq cat value))
3020 ((member key '("SEQ_TODO" "TODO"))
3021 (push (cons 'sequence (org-split-string value splitre)) kwds))
3022 ((equal key "TYP_TODO")
3023 (push (cons 'type (org-split-string value splitre)) kwds))
3024 ((equal key "TAGS")
3025 (setq tags (append tags (org-split-string value splitre))))
3026 ((equal key "COLUMNS")
3027 (org-set-local 'org-columns-default-format value))
3028 ((equal key "LINK")
3029 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3030 (push (cons (match-string 1 value)
3031 (org-trim (match-string 2 value)))
3032 links)))
3033 ((equal key "PRIORITIES")
3034 (setq prio (org-split-string value " +")))
3035 ((equal key "PROPERTY")
3036 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3037 (push (cons (match-string 1 value) (match-string 2 value))
3038 props)))
3039 ((equal key "DRAWERS")
3040 (setq drawers (org-split-string value splitre)))
3041 ((equal key "CONSTANTS")
3042 (setq const (append const (org-split-string value splitre))))
3043 ((equal key "STARTUP")
3044 (let ((opts (org-split-string value splitre))
3045 l var val)
3046 (while (setq l (pop opts))
3047 (when (setq l (assoc l org-startup-options))
3048 (setq var (nth 1 l) val (nth 2 l))
3049 (if (not (nth 3 l))
3050 (set (make-local-variable var) val)
3051 (if (not (listp (symbol-value var)))
3052 (set (make-local-variable var) nil))
3053 (set (make-local-variable var) (symbol-value var))
3054 (add-to-list var val))))))
3055 ((equal key "ARCHIVE")
3056 (string-match " *$" value)
3057 (setq arch (replace-match "" t t value))
3058 (remove-text-properties 0 (length arch)
3059 '(face t fontified t) arch)))
3061 (when cat
3062 (org-set-local 'org-category (intern cat))
3063 (push (cons "CATEGORY" cat) props))
3064 (when prio
3065 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3066 (setq prio (mapcar 'string-to-char prio))
3067 (org-set-local 'org-highest-priority (nth 0 prio))
3068 (org-set-local 'org-lowest-priority (nth 1 prio))
3069 (org-set-local 'org-default-priority (nth 2 prio)))
3070 (and props (org-set-local 'org-local-properties (nreverse props)))
3071 (and drawers (org-set-local 'org-drawers drawers))
3072 (and arch (org-set-local 'org-archive-location arch))
3073 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3074 ;; Process the TODO keywords
3075 (unless kwds
3076 ;; Use the global values as if they had been given locally.
3077 (setq kwds (default-value 'org-todo-keywords))
3078 (if (stringp (car kwds))
3079 (setq kwds (list (cons org-todo-interpretation
3080 (default-value 'org-todo-keywords)))))
3081 (setq kwds (reverse kwds)))
3082 (setq kwds (nreverse kwds))
3083 (let (inter kws kw)
3084 (while (setq kws (pop kwds))
3085 (setq inter (pop kws) sep (member "|" kws)
3086 kws0 (delete "|" (copy-sequence kws))
3087 kwsa nil
3088 kws1 (mapcar
3089 (lambda (x)
3090 ;; 1 2
3091 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3092 (progn
3093 (setq kw (match-string 1 x)
3094 key (and (match-end 2) (match-string 2 x))
3095 log (org-extract-log-state-settings x))
3096 (push (cons kw (and key (string-to-char key))) kwsa)
3097 (and log (push log org-todo-log-states))
3099 (error "Invalid TODO keyword %s" x)))
3100 kws0)
3101 kwsa (if kwsa (append '((:startgroup))
3102 (nreverse kwsa)
3103 '((:endgroup))))
3104 hw (car kws1)
3105 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3106 tail (list inter hw (car dws) (org-last dws)))
3107 (add-to-list 'org-todo-heads hw 'append)
3108 (push kws1 org-todo-sets)
3109 (setq org-done-keywords (append org-done-keywords dws nil))
3110 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3111 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3112 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3113 (setq org-todo-sets (nreverse org-todo-sets)
3114 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3115 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3116 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3117 ;; Process the constants
3118 (when const
3119 (let (e cst)
3120 (while (setq e (pop const))
3121 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3122 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3123 (setq org-table-formula-constants-local cst)))
3125 ;; Process the tags.
3126 (when tags
3127 (let (e tgs)
3128 (while (setq e (pop tags))
3129 (cond
3130 ((equal e "{") (push '(:startgroup) tgs))
3131 ((equal e "}") (push '(:endgroup) tgs))
3132 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3133 (push (cons (match-string 1 e)
3134 (string-to-char (match-string 2 e)))
3135 tgs))
3136 (t (push (list e) tgs))))
3137 (org-set-local 'org-tag-alist nil)
3138 (while (setq e (pop tgs))
3139 (or (and (stringp (car e))
3140 (assoc (car e) org-tag-alist))
3141 (push e org-tag-alist))))))
3143 ;; Compute the regular expressions and other local variables
3144 (if (not org-done-keywords)
3145 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3146 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3147 (length org-scheduled-string)))
3148 org-drawer-regexp
3149 (concat "^[ \t]*:\\("
3150 (mapconcat 'regexp-quote org-drawers "\\|")
3151 "\\):[ \t]*$")
3152 org-not-done-keywords
3153 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3154 org-todo-regexp
3155 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3156 "\\|") "\\)\\>")
3157 org-not-done-regexp
3158 (concat "\\<\\("
3159 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3160 "\\)\\>")
3161 org-todo-line-regexp
3162 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3163 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3164 "\\)\\>\\)?[ \t]*\\(.*\\)")
3165 org-complex-heading-regexp
3166 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3167 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3168 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3169 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3170 org-nl-done-regexp
3171 (concat "\n\\*+[ \t]+"
3172 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3173 "\\)" "\\>")
3174 org-todo-line-tags-regexp
3175 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3176 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3177 (org-re
3178 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3179 org-looking-at-done-regexp
3180 (concat "^" "\\(?:"
3181 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3182 "\\>")
3183 org-deadline-regexp (concat "\\<" org-deadline-string)
3184 org-deadline-time-regexp
3185 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3186 org-deadline-line-regexp
3187 (concat "\\<\\(" org-deadline-string "\\).*")
3188 org-scheduled-regexp
3189 (concat "\\<" org-scheduled-string)
3190 org-scheduled-time-regexp
3191 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3192 org-closed-time-regexp
3193 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3194 org-keyword-time-regexp
3195 (concat "\\<\\(" org-scheduled-string
3196 "\\|" org-deadline-string
3197 "\\|" org-closed-string
3198 "\\|" org-clock-string "\\)"
3199 " *[[<]\\([^]>]+\\)[]>]")
3200 org-keyword-time-not-clock-regexp
3201 (concat "\\<\\(" org-scheduled-string
3202 "\\|" org-deadline-string
3203 "\\|" org-closed-string
3204 "\\)"
3205 " *[[<]\\([^]>]+\\)[]>]")
3206 org-maybe-keyword-time-regexp
3207 (concat "\\(\\<\\(" org-scheduled-string
3208 "\\|" org-deadline-string
3209 "\\|" org-closed-string
3210 "\\|" org-clock-string "\\)\\)?"
3211 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3212 org-planning-or-clock-line-re
3213 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3214 "\\|" org-deadline-string
3215 "\\|" org-closed-string "\\|" org-clock-string
3216 "\\)\\>\\)")
3218 (org-compute-latex-and-specials-regexp)
3219 (org-set-font-lock-defaults)))
3221 (defun org-extract-log-state-settings (x)
3222 "Extract the log state setting from a TODO keyword string.
3223 This will extract info from a string like \"WAIT(w@/!)\"."
3224 (let (kw key log1 log2)
3225 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3226 (setq kw (match-string 1 x)
3227 key (and (match-end 2) (match-string 2 x))
3228 log1 (and (match-end 3) (match-string 3 x))
3229 log2 (and (match-end 4) (match-string 4 x)))
3230 (and (or log1 log2)
3231 (list kw
3232 (and log1 (if (equal log1 "!") 'time 'note))
3233 (and log2 (if (equal log2 "!") 'time 'note)))))))
3235 (defun org-remove-keyword-keys (list)
3236 "Remove a pair of parenthesis at the end of each string in LIST."
3237 (mapcar (lambda (x)
3238 (if (string-match "(.*)$" x)
3239 (substring x 0 (match-beginning 0))
3241 list))
3243 ;; FIXME: this could be done much better, using second characters etc.
3244 (defun org-assign-fast-keys (alist)
3245 "Assign fast keys to a keyword-key alist.
3246 Respect keys that are already there."
3247 (let (new e k c c1 c2 (char ?a))
3248 (while (setq e (pop alist))
3249 (cond
3250 ((equal e '(:startgroup)) (push e new))
3251 ((equal e '(:endgroup)) (push e new))
3253 (setq k (car e) c2 nil)
3254 (if (cdr e)
3255 (setq c (cdr e))
3256 ;; automatically assign a character.
3257 (setq c1 (string-to-char
3258 (downcase (substring
3259 k (if (= (string-to-char k) ?@) 1 0)))))
3260 (if (or (rassoc c1 new) (rassoc c1 alist))
3261 (while (or (rassoc char new) (rassoc char alist))
3262 (setq char (1+ char)))
3263 (setq c2 c1))
3264 (setq c (or c2 char)))
3265 (push (cons k c) new))))
3266 (nreverse new)))
3268 ;;; Some variables ujsed in various places
3270 (defvar org-window-configuration nil
3271 "Used in various places to store a window configuration.")
3272 (defvar org-finish-function nil
3273 "Function to be called when `C-c C-c' is used.
3274 This is for getting out of special buffers like remember.")
3277 ;; FIXME: Occasionally check by commenting these, to make sure
3278 ;; no other functions uses these, forgetting to let-bind them.
3279 (defvar entry)
3280 (defvar state)
3281 (defvar last-state)
3282 (defvar date)
3283 (defvar description)
3285 ;; Defined somewhere in this file, but used before definition.
3286 (defvar org-html-entities)
3287 (defvar org-struct-menu)
3288 (defvar org-org-menu)
3289 (defvar org-tbl-menu)
3290 (defvar org-agenda-keymap)
3292 ;;;; Define the Org-mode
3294 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3295 (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."))
3298 ;; We use a before-change function to check if a table might need
3299 ;; an update.
3300 (defvar org-table-may-need-update t
3301 "Indicates that a table might need an update.
3302 This variable is set by `org-before-change-function'.
3303 `org-table-align' sets it back to nil.")
3304 (defun org-before-change-function (beg end)
3305 "Every change indicates that a table might need an update."
3306 (setq org-table-may-need-update t))
3307 (defvar org-mode-map)
3308 (defvar org-mode-hook nil)
3309 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3310 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3311 (defvar org-table-buffer-is-an nil)
3312 (defconst org-outline-regexp "\\*+ ")
3314 ;;;###autoload
3315 (define-derived-mode org-mode outline-mode "Org"
3316 "Outline-based notes management and organizer, alias
3317 \"Carsten's outline-mode for keeping track of everything.\"
3319 Org-mode develops organizational tasks around a NOTES file which
3320 contains information about projects as plain text. Org-mode is
3321 implemented on top of outline-mode, which is ideal to keep the content
3322 of large files well structured. It supports ToDo items, deadlines and
3323 time stamps, which magically appear in the diary listing of the Emacs
3324 calendar. Tables are easily created with a built-in table editor.
3325 Plain text URL-like links connect to websites, emails (VM), Usenet
3326 messages (Gnus), BBDB entries, and any files related to the project.
3327 For printing and sharing of notes, an Org-mode file (or a part of it)
3328 can be exported as a structured ASCII or HTML file.
3330 The following commands are available:
3332 \\{org-mode-map}"
3334 ;; Get rid of Outline menus, they are not needed
3335 ;; Need to do this here because define-derived-mode sets up
3336 ;; the keymap so late. Still, it is a waste to call this each time
3337 ;; we switch another buffer into org-mode.
3338 (if (featurep 'xemacs)
3339 (when (boundp 'outline-mode-menu-heading)
3340 ;; Assume this is Greg's port, it used easymenu
3341 (easy-menu-remove outline-mode-menu-heading)
3342 (easy-menu-remove outline-mode-menu-show)
3343 (easy-menu-remove outline-mode-menu-hide))
3344 (define-key org-mode-map [menu-bar headings] 'undefined)
3345 (define-key org-mode-map [menu-bar hide] 'undefined)
3346 (define-key org-mode-map [menu-bar show] 'undefined))
3348 (org-load-modules-maybe)
3349 (easy-menu-add org-org-menu)
3350 (easy-menu-add org-tbl-menu)
3351 (org-install-agenda-files-menu)
3352 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3353 (org-add-to-invisibility-spec '(org-cwidth))
3354 (when (featurep 'xemacs)
3355 (org-set-local 'line-move-ignore-invisible t))
3356 (org-set-local 'outline-regexp org-outline-regexp)
3357 (org-set-local 'outline-level 'org-outline-level)
3358 (when (and org-ellipsis
3359 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3360 (fboundp 'make-glyph-code))
3361 (unless org-display-table
3362 (setq org-display-table (make-display-table)))
3363 (set-display-table-slot
3364 org-display-table 4
3365 (vconcat (mapcar
3366 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3367 org-ellipsis)))
3368 (if (stringp org-ellipsis) org-ellipsis "..."))))
3369 (setq buffer-display-table org-display-table))
3370 (org-set-regexps-and-options)
3371 ;; Calc embedded
3372 (org-set-local 'calc-embedded-open-mode "# ")
3373 (modify-syntax-entry ?# "<")
3374 (modify-syntax-entry ?@ "w")
3375 (if org-startup-truncated (setq truncate-lines t))
3376 (org-set-local 'font-lock-unfontify-region-function
3377 'org-unfontify-region)
3378 ;; Activate before-change-function
3379 (org-set-local 'org-table-may-need-update t)
3380 (org-add-hook 'before-change-functions 'org-before-change-function nil
3381 'local)
3382 ;; Check for running clock before killing a buffer
3383 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3384 ;; Paragraphs and auto-filling
3385 (org-set-autofill-regexps)
3386 (setq indent-line-function 'org-indent-line-function)
3387 (org-update-radio-target-regexp)
3389 ;; Comment characters
3390 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3391 (org-set-local 'comment-padding " ")
3393 ;; Align options lines
3394 (org-set-local
3395 'align-mode-rules-list
3396 '((org-in-buffer-settings
3397 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3398 (modes . '(org-mode)))))
3400 ;; Imenu
3401 (org-set-local 'imenu-create-index-function
3402 'org-imenu-get-tree)
3404 ;; Make isearch reveal context
3405 (if (or (featurep 'xemacs)
3406 (not (boundp 'outline-isearch-open-invisible-function)))
3407 ;; Emacs 21 and XEmacs make use of the hook
3408 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3409 ;; Emacs 22 deals with this through a special variable
3410 (org-set-local 'outline-isearch-open-invisible-function
3411 (lambda (&rest ignore) (org-show-context 'isearch))))
3413 ;; If empty file that did not turn on org-mode automatically, make it to.
3414 (if (and org-insert-mode-line-in-empty-file
3415 (interactive-p)
3416 (= (point-min) (point-max)))
3417 (insert "# -*- mode: org -*-\n\n"))
3419 (unless org-inhibit-startup
3420 (when org-startup-align-all-tables
3421 (let ((bmp (buffer-modified-p)))
3422 (org-table-map-tables 'org-table-align)
3423 (set-buffer-modified-p bmp)))
3424 (org-cycle-hide-drawers 'all)
3425 (cond
3426 ((eq org-startup-folded t)
3427 (org-cycle '(4)))
3428 ((eq org-startup-folded 'content)
3429 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3430 (org-cycle '(4)) (org-cycle '(4)))))))
3432 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3434 (defun org-current-time ()
3435 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3436 (if (> (car org-time-stamp-rounding-minutes) 1)
3437 (let ((r (car org-time-stamp-rounding-minutes))
3438 (time (decode-time)))
3439 (apply 'encode-time
3440 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3441 (nthcdr 2 time))))
3442 (current-time)))
3444 ;;;; Font-Lock stuff, including the activators
3446 (defvar org-mouse-map (make-sparse-keymap))
3447 (org-defkey org-mouse-map
3448 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3449 (org-defkey org-mouse-map
3450 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3451 (when org-mouse-1-follows-link
3452 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3453 (when org-tab-follows-link
3454 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3455 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3456 (when org-return-follows-link
3457 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3458 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3460 (require 'font-lock)
3462 (defconst org-non-link-chars "]\t\n\r<>")
3463 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3464 "shell" "elisp"))
3465 (defvar org-link-re-with-space nil
3466 "Matches a link with spaces, optional angular brackets around it.")
3467 (defvar org-link-re-with-space2 nil
3468 "Matches a link with spaces, optional angular brackets around it.")
3469 (defvar org-angle-link-re nil
3470 "Matches link with angular brackets, spaces are allowed.")
3471 (defvar org-plain-link-re nil
3472 "Matches plain link, without spaces.")
3473 (defvar org-bracket-link-regexp nil
3474 "Matches a link in double brackets.")
3475 (defvar org-bracket-link-analytic-regexp nil
3476 "Regular expression used to analyze links.
3477 Here is what the match groups contain after a match:
3478 1: http:
3479 2: http
3480 3: path
3481 4: [desc]
3482 5: desc")
3483 (defvar org-any-link-re nil
3484 "Regular expression matching any link.")
3486 (defun org-make-link-regexps ()
3487 "Update the link regular expressions.
3488 This should be called after the variable `org-link-types' has changed."
3489 (setq org-link-re-with-space
3490 (concat
3491 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3492 "\\([^" org-non-link-chars " ]"
3493 "[^" org-non-link-chars "]*"
3494 "[^" org-non-link-chars " ]\\)>?")
3495 org-link-re-with-space2
3496 (concat
3497 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3498 "\\([^" org-non-link-chars " ]"
3499 "[^]\t\n\r]*"
3500 "[^" org-non-link-chars " ]\\)>?")
3501 org-angle-link-re
3502 (concat
3503 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3504 "\\([^" org-non-link-chars " ]"
3505 "[^" org-non-link-chars "]*"
3506 "\\)>")
3507 org-plain-link-re
3508 (concat
3509 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3510 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3511 org-bracket-link-regexp
3512 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3513 org-bracket-link-analytic-regexp
3514 (concat
3515 "\\[\\["
3516 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3517 "\\([^]]+\\)"
3518 "\\]"
3519 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3520 "\\]")
3521 org-any-link-re
3522 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3523 org-angle-link-re "\\)\\|\\("
3524 org-plain-link-re "\\)")))
3526 (org-make-link-regexps)
3528 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3529 "Regular expression for fast time stamp matching.")
3530 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3531 "Regular expression for fast time stamp matching.")
3532 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3533 "Regular expression matching time strings for analysis.
3534 This one does not require the space after the date, so it can be used
3535 on a string that terminates immediately after the date.")
3536 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3537 "Regular expression matching time strings for analysis.")
3538 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3539 "Regular expression matching time stamps, with groups.")
3540 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3541 "Regular expression matching time stamps (also [..]), with groups.")
3542 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3543 "Regular expression matching a time stamp range.")
3544 (defconst org-tr-regexp-both
3545 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3546 "Regular expression matching a time stamp range.")
3547 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3548 org-ts-regexp "\\)?")
3549 "Regular expression matching a time stamp or time stamp range.")
3550 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3551 org-ts-regexp-both "\\)?")
3552 "Regular expression matching a time stamp or time stamp range.
3553 The time stamps may be either active or inactive.")
3555 (defvar org-emph-face nil)
3557 (defun org-do-emphasis-faces (limit)
3558 "Run through the buffer and add overlays to links."
3559 (let (rtn)
3560 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3561 (if (not (= (char-after (match-beginning 3))
3562 (char-after (match-beginning 4))))
3563 (progn
3564 (setq rtn t)
3565 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3566 'face
3567 (nth 1 (assoc (match-string 3)
3568 org-emphasis-alist)))
3569 (add-text-properties (match-beginning 2) (match-end 2)
3570 '(font-lock-multiline t))
3571 (when org-hide-emphasis-markers
3572 (add-text-properties (match-end 4) (match-beginning 5)
3573 '(invisible org-link))
3574 (add-text-properties (match-beginning 3) (match-end 3)
3575 '(invisible org-link)))))
3576 (backward-char 1))
3577 rtn))
3579 (defun org-emphasize (&optional char)
3580 "Insert or change an emphasis, i.e. a font like bold or italic.
3581 If there is an active region, change that region to a new emphasis.
3582 If there is no region, just insert the marker characters and position
3583 the cursor between them.
3584 CHAR should be either the marker character, or the first character of the
3585 HTML tag associated with that emphasis. If CHAR is a space, the means
3586 to remove the emphasis of the selected region.
3587 If char is not given (for example in an interactive call) it
3588 will be prompted for."
3589 (interactive)
3590 (let ((eal org-emphasis-alist) e det
3591 (erc org-emphasis-regexp-components)
3592 (prompt "")
3593 (string "") beg end move tag c s)
3594 (if (org-region-active-p)
3595 (setq beg (region-beginning) end (region-end)
3596 string (buffer-substring beg end))
3597 (setq move t))
3599 (while (setq e (pop eal))
3600 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3601 c (aref tag 0))
3602 (push (cons c (string-to-char (car e))) det)
3603 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3604 (substring tag 1)))))
3605 (unless char
3606 (message "%s" (concat "Emphasis marker or tag:" prompt))
3607 (setq char (read-char-exclusive)))
3608 (setq char (or (cdr (assoc char det)) char))
3609 (if (equal char ?\ )
3610 (setq s "" move nil)
3611 (unless (assoc (char-to-string char) org-emphasis-alist)
3612 (error "No such emphasis marker: \"%c\"" char))
3613 (setq s (char-to-string char)))
3614 (while (and (> (length string) 1)
3615 (equal (substring string 0 1) (substring string -1))
3616 (assoc (substring string 0 1) org-emphasis-alist))
3617 (setq string (substring string 1 -1)))
3618 (setq string (concat s string s))
3619 (if beg (delete-region beg end))
3620 (unless (or (bolp)
3621 (string-match (concat "[" (nth 0 erc) "\n]")
3622 (char-to-string (char-before (point)))))
3623 (insert " "))
3624 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3625 (char-to-string (char-after (point))))
3626 (insert " ") (backward-char 1))
3627 (insert string)
3628 (and move (backward-char 1))))
3630 (defconst org-nonsticky-props
3631 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3634 (defun org-activate-plain-links (limit)
3635 "Run through the buffer and add overlays to links."
3636 (catch 'exit
3637 (let (f)
3638 (while (re-search-forward org-plain-link-re limit t)
3639 (setq f (get-text-property (match-beginning 0) 'face))
3640 (if (or (eq f 'org-tag)
3641 (and (listp f) (memq 'org-tag f)))
3643 (add-text-properties (match-beginning 0) (match-end 0)
3644 (list 'mouse-face 'highlight
3645 'rear-nonsticky org-nonsticky-props
3646 'keymap org-mouse-map
3648 (throw 'exit t))))))
3650 (defun org-activate-code (limit)
3651 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3652 (unless (get-text-property (match-beginning 1) 'face)
3653 (remove-text-properties (match-beginning 0) (match-end 0)
3654 '(display t invisible t intangible t))
3655 t)))
3657 (defun org-activate-angle-links (limit)
3658 "Run through the buffer and add overlays to links."
3659 (if (re-search-forward org-angle-link-re limit t)
3660 (progn
3661 (add-text-properties (match-beginning 0) (match-end 0)
3662 (list 'mouse-face 'highlight
3663 'rear-nonsticky org-nonsticky-props
3664 'keymap org-mouse-map
3666 t)))
3668 (defun org-activate-bracket-links (limit)
3669 "Run through the buffer and add overlays to bracketed links."
3670 (if (re-search-forward org-bracket-link-regexp limit t)
3671 (let* ((help (concat "LINK: "
3672 (org-match-string-no-properties 1)))
3673 ;; FIXME: above we should remove the escapes.
3674 ;; but that requires another match, protecting match data,
3675 ;; a lot of overhead for font-lock.
3676 (ip (org-maybe-intangible
3677 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3678 'keymap org-mouse-map 'mouse-face 'highlight
3679 'font-lock-multiline t 'help-echo help)))
3680 (vp (list 'rear-nonsticky org-nonsticky-props
3681 'keymap org-mouse-map 'mouse-face 'highlight
3682 ' font-lock-multiline t 'help-echo help)))
3683 ;; We need to remove the invisible property here. Table narrowing
3684 ;; may have made some of this invisible.
3685 (remove-text-properties (match-beginning 0) (match-end 0)
3686 '(invisible nil))
3687 (if (match-end 3)
3688 (progn
3689 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3690 (add-text-properties (match-beginning 3) (match-end 3) vp)
3691 (add-text-properties (match-end 3) (match-end 0) ip))
3692 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3693 (add-text-properties (match-beginning 1) (match-end 1) vp)
3694 (add-text-properties (match-end 1) (match-end 0) ip))
3695 t)))
3697 (defun org-activate-dates (limit)
3698 "Run through the buffer and add overlays to dates."
3699 (if (re-search-forward org-tsr-regexp-both limit t)
3700 (progn
3701 (add-text-properties (match-beginning 0) (match-end 0)
3702 (list 'mouse-face 'highlight
3703 'rear-nonsticky org-nonsticky-props
3704 'keymap org-mouse-map))
3705 (when org-display-custom-times
3706 (if (match-end 3)
3707 (org-display-custom-time (match-beginning 3) (match-end 3)))
3708 (org-display-custom-time (match-beginning 1) (match-end 1)))
3709 t)))
3711 (defvar org-target-link-regexp nil
3712 "Regular expression matching radio targets in plain text.")
3713 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3714 "Regular expression matching a link target.")
3715 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3716 "Regular expression matching a radio target.")
3717 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3718 "Regular expression matching any target.")
3720 (defun org-activate-target-links (limit)
3721 "Run through the buffer and add overlays to target matches."
3722 (when org-target-link-regexp
3723 (let ((case-fold-search t))
3724 (if (re-search-forward org-target-link-regexp limit t)
3725 (progn
3726 (add-text-properties (match-beginning 0) (match-end 0)
3727 (list 'mouse-face 'highlight
3728 'rear-nonsticky org-nonsticky-props
3729 'keymap org-mouse-map
3730 'help-echo "Radio target link"
3731 'org-linked-text t))
3732 t)))))
3734 (defun org-update-radio-target-regexp ()
3735 "Find all radio targets in this file and update the regular expression."
3736 (interactive)
3737 (when (memq 'radio org-activate-links)
3738 (setq org-target-link-regexp
3739 (org-make-target-link-regexp (org-all-targets 'radio)))
3740 (org-restart-font-lock)))
3742 (defun org-hide-wide-columns (limit)
3743 (let (s e)
3744 (setq s (text-property-any (point) (or limit (point-max))
3745 'org-cwidth t))
3746 (when s
3747 (setq e (next-single-property-change s 'org-cwidth))
3748 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3749 (goto-char e)
3750 t)))
3752 (defvar org-latex-and-specials-regexp nil
3753 "Regular expression for highlighting export special stuff.")
3754 (defvar org-match-substring-regexp)
3755 (defvar org-match-substring-with-braces-regexp)
3756 (defvar org-export-html-special-string-regexps)
3758 (defun org-compute-latex-and-specials-regexp ()
3759 "Compute regular expression for stuff treated specially by exporters."
3760 (if (not org-highlight-latex-fragments-and-specials)
3761 (org-set-local 'org-latex-and-specials-regexp nil)
3762 (require 'org-exp)
3763 (let*
3764 ((matchers (plist-get org-format-latex-options :matchers))
3765 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3766 org-latex-regexps)))
3767 (options (org-combine-plists (org-default-export-plist)
3768 (org-infile-export-plist)))
3769 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3770 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3771 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3772 (org-export-html-expand (plist-get options :expand-quoted-html))
3773 (org-export-with-special-strings (plist-get options :special-strings))
3774 (re-sub
3775 (cond
3776 ((equal org-export-with-sub-superscripts '{})
3777 (list org-match-substring-with-braces-regexp))
3778 (org-export-with-sub-superscripts
3779 (list org-match-substring-regexp))
3780 (t nil)))
3781 (re-latex
3782 (if org-export-with-LaTeX-fragments
3783 (mapcar (lambda (x) (nth 1 x)) latexs)))
3784 (re-macros
3785 (if org-export-with-TeX-macros
3786 (list (concat "\\\\"
3787 (regexp-opt
3788 (append (mapcar 'car org-html-entities)
3789 (if (boundp 'org-latex-entities)
3790 org-latex-entities nil))
3791 'words))) ; FIXME
3793 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3794 (re-special (if org-export-with-special-strings
3795 (mapcar (lambda (x) (car x))
3796 org-export-html-special-string-regexps)))
3797 (re-rest
3798 (delq nil
3799 (list
3800 (if org-export-html-expand "@<[^>\n]+>")
3801 ))))
3802 (org-set-local
3803 'org-latex-and-specials-regexp
3804 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3805 re-rest) "\\|")))))
3807 (defface org-latex-and-export-specials
3808 (let ((font (cond ((assq :inherit custom-face-attributes)
3809 '(:inherit underline))
3810 (t '(:underline t)))))
3811 `((((class grayscale) (background light))
3812 (:foreground "DimGray" ,@font))
3813 (((class grayscale) (background dark))
3814 (:foreground "LightGray" ,@font))
3815 (((class color) (background light))
3816 (:foreground "SaddleBrown"))
3817 (((class color) (background dark))
3818 (:foreground "burlywood"))
3819 (t (,@font))))
3820 "Face used to highlight math latex and other special exporter stuff."
3821 :group 'org-faces)
3823 (defun org-do-latex-and-special-faces (limit)
3824 "Run through the buffer and add overlays to links."
3825 (when org-latex-and-specials-regexp
3826 (let (rtn d)
3827 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3828 limit t))
3829 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3830 'face))
3831 '(org-code org-verbatim underline)))
3832 (progn
3833 (setq rtn t
3834 d (cond ((member (char-after (1+ (match-beginning 0)))
3835 '(?_ ?^)) 1)
3836 (t 0)))
3837 (font-lock-prepend-text-property
3838 (+ d (match-beginning 0)) (match-end 0)
3839 'face 'org-latex-and-export-specials)
3840 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3841 '(font-lock-multiline t)))))
3842 rtn)))
3844 (defun org-restart-font-lock ()
3845 "Restart font-lock-mode, to force refontification."
3846 (when (and (boundp 'font-lock-mode) font-lock-mode)
3847 (font-lock-mode -1)
3848 (font-lock-mode 1)))
3850 (defun org-all-targets (&optional radio)
3851 "Return a list of all targets in this file.
3852 With optional argument RADIO, only find radio targets."
3853 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3854 rtn)
3855 (save-excursion
3856 (goto-char (point-min))
3857 (while (re-search-forward re nil t)
3858 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3859 rtn)))
3861 (defun org-make-target-link-regexp (targets)
3862 "Make regular expression matching all strings in TARGETS.
3863 The regular expression finds the targets also if there is a line break
3864 between words."
3865 (and targets
3866 (concat
3867 "\\<\\("
3868 (mapconcat
3869 (lambda (x)
3870 (while (string-match " +" x)
3871 (setq x (replace-match "\\s-+" t t x)))
3873 targets
3874 "\\|")
3875 "\\)\\>")))
3877 (defun org-activate-tags (limit)
3878 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3879 (progn
3880 (add-text-properties (match-beginning 1) (match-end 1)
3881 (list 'mouse-face 'highlight
3882 'rear-nonsticky org-nonsticky-props
3883 'keymap org-mouse-map))
3884 t)))
3886 (defun org-outline-level ()
3887 (save-excursion
3888 (looking-at outline-regexp)
3889 (if (match-beginning 1)
3890 (+ (org-get-string-indentation (match-string 1)) 1000)
3891 (1- (- (match-end 0) (match-beginning 0))))))
3893 (defvar org-font-lock-keywords nil)
3895 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
3896 "Regular expression matching a property line.")
3898 (defun org-set-font-lock-defaults ()
3899 (let* ((em org-fontify-emphasized-text)
3900 (lk org-activate-links)
3901 (org-font-lock-extra-keywords
3902 (list
3903 ;; Headlines
3904 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3905 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3906 ;; Table lines
3907 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3908 (1 'org-table t))
3909 ;; Table internals
3910 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3911 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3912 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3913 ;; Drawers
3914 (list org-drawer-regexp '(0 'org-special-keyword t))
3915 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3916 ;; Properties
3917 (list org-property-re
3918 '(1 'org-special-keyword t)
3919 '(3 'org-property-value t))
3920 (if org-format-transports-properties-p
3921 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3922 ;; Links
3923 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3924 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3925 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3926 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3927 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3928 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3929 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3930 '(org-hide-wide-columns (0 nil append))
3931 ;; TODO lines
3932 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3933 '(1 (org-get-todo-face 1) t))
3934 ;; DONE
3935 (if org-fontify-done-headline
3936 (list (concat "^[*]+ +\\<\\("
3937 (mapconcat 'regexp-quote org-done-keywords "\\|")
3938 "\\)\\(.*\\)")
3939 '(2 'org-headline-done t))
3940 nil)
3941 ;; Priorities
3942 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3943 ;; Special keywords
3944 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3945 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3946 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3947 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3948 ;; Emphasis
3949 (if em
3950 (if (featurep 'xemacs)
3951 '(org-do-emphasis-faces (0 nil append))
3952 '(org-do-emphasis-faces)))
3953 ;; Checkboxes
3954 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3955 2 'bold prepend)
3956 (if org-provide-checkbox-statistics
3957 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3958 (0 (org-get-checkbox-statistics-face) t)))
3959 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3960 '(1 'org-archived prepend))
3961 ;; Specials
3962 '(org-do-latex-and-special-faces)
3963 ;; Code
3964 '(org-activate-code (1 'org-code t))
3965 ;; COMMENT
3966 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3967 "\\|" org-quote-string "\\)\\>")
3968 '(1 'org-special-keyword t))
3969 '("^#.*" (0 'font-lock-comment-face t))
3971 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3972 ;; Now set the full font-lock-keywords
3973 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3974 (org-set-local 'font-lock-defaults
3975 '(org-font-lock-keywords t nil nil backward-paragraph))
3976 (kill-local-variable 'font-lock-keywords) nil))
3978 (defvar org-m nil)
3979 (defvar org-l nil)
3980 (defvar org-f nil)
3981 (defun org-get-level-face (n)
3982 "Get the right face for match N in font-lock matching of healdines."
3983 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3984 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3985 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3986 (cond
3987 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3988 ((eq n 2) org-f)
3989 (t (if org-level-color-stars-only nil org-f))))
3991 (defun org-get-todo-face (kwd)
3992 "Get the right face for a TODO keyword KWD.
3993 If KWD is a number, get the corresponding match group."
3994 (if (numberp kwd) (setq kwd (match-string kwd)))
3995 (or (cdr (assoc kwd org-todo-keyword-faces))
3996 (and (member kwd org-done-keywords) 'org-done)
3997 'org-todo))
3999 (defun org-unfontify-region (beg end &optional maybe_loudly)
4000 "Remove fontification and activation overlays from links."
4001 (font-lock-default-unfontify-region beg end)
4002 (let* ((buffer-undo-list t)
4003 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4004 (inhibit-modification-hooks t)
4005 deactivate-mark buffer-file-name buffer-file-truename)
4006 (remove-text-properties beg end
4007 '(mouse-face t keymap t org-linked-text t
4008 invisible t intangible t))))
4010 ;;;; Visibility cycling, including org-goto and indirect buffer
4012 ;;; Cycling
4014 (defvar org-cycle-global-status nil)
4015 (make-variable-buffer-local 'org-cycle-global-status)
4016 (defvar org-cycle-subtree-status nil)
4017 (make-variable-buffer-local 'org-cycle-subtree-status)
4019 ;;;###autoload
4020 (defun org-cycle (&optional arg)
4021 "Visibility cycling for Org-mode.
4023 - When this function is called with a prefix argument, rotate the entire
4024 buffer through 3 states (global cycling)
4025 1. OVERVIEW: Show only top-level headlines.
4026 2. CONTENTS: Show all headlines of all levels, but no body text.
4027 3. SHOW ALL: Show everything.
4029 - When point is at the beginning of a headline, rotate the subtree started
4030 by this line through 3 different states (local cycling)
4031 1. FOLDED: Only the main headline is shown.
4032 2. CHILDREN: The main headline and the direct children are shown.
4033 From this state, you can move to one of the children
4034 and zoom in further.
4035 3. SUBTREE: Show the entire subtree, including body text.
4037 - When there is a numeric prefix, go up to a heading with level ARG, do
4038 a `show-subtree' and return to the previous cursor position. If ARG
4039 is negative, go up that many levels.
4041 - When point is not at the beginning of a headline, execute
4042 `indent-relative', like TAB normally does. See the option
4043 `org-cycle-emulate-tab' for details.
4045 - Special case: if point is at the beginning of the buffer and there is
4046 no headline in line 1, this function will act as if called with prefix arg.
4047 But only if also the variable `org-cycle-global-at-bob' is t."
4048 (interactive "P")
4049 (org-load-modules-maybe)
4050 (let* ((outline-regexp
4051 (if (and (org-mode-p) org-cycle-include-plain-lists)
4052 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4053 outline-regexp))
4054 (bob-special (and org-cycle-global-at-bob (bobp)
4055 (not (looking-at outline-regexp))))
4056 (org-cycle-hook
4057 (if bob-special
4058 (delq 'org-optimize-window-after-visibility-change
4059 (copy-sequence org-cycle-hook))
4060 org-cycle-hook))
4061 (pos (point)))
4063 (if (or bob-special (equal arg '(4)))
4064 ;; special case: use global cycling
4065 (setq arg t))
4067 (cond
4069 ((org-at-table-p 'any)
4070 ;; Enter the table or move to the next field in the table
4071 (or (org-table-recognize-table.el)
4072 (progn
4073 (if arg (org-table-edit-field t)
4074 (org-table-justify-field-maybe)
4075 (call-interactively 'org-table-next-field)))))
4077 ((eq arg t) ;; Global cycling
4079 (cond
4080 ((and (eq last-command this-command)
4081 (eq org-cycle-global-status 'overview))
4082 ;; We just created the overview - now do table of contents
4083 ;; This can be slow in very large buffers, so indicate action
4084 (message "CONTENTS...")
4085 (org-content)
4086 (message "CONTENTS...done")
4087 (setq org-cycle-global-status 'contents)
4088 (run-hook-with-args 'org-cycle-hook 'contents))
4090 ((and (eq last-command this-command)
4091 (eq org-cycle-global-status 'contents))
4092 ;; We just showed the table of contents - now show everything
4093 (show-all)
4094 (message "SHOW ALL")
4095 (setq org-cycle-global-status 'all)
4096 (run-hook-with-args 'org-cycle-hook 'all))
4099 ;; Default action: go to overview
4100 (org-overview)
4101 (message "OVERVIEW")
4102 (setq org-cycle-global-status 'overview)
4103 (run-hook-with-args 'org-cycle-hook 'overview))))
4105 ((and org-drawers org-drawer-regexp
4106 (save-excursion
4107 (beginning-of-line 1)
4108 (looking-at org-drawer-regexp)))
4109 ;; Toggle block visibility
4110 (org-flag-drawer
4111 (not (get-char-property (match-end 0) 'invisible))))
4113 ((integerp arg)
4114 ;; Show-subtree, ARG levels up from here.
4115 (save-excursion
4116 (org-back-to-heading)
4117 (outline-up-heading (if (< arg 0) (- arg)
4118 (- (funcall outline-level) arg)))
4119 (org-show-subtree)))
4121 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4122 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4123 ;; At a heading: rotate between three different views
4124 (org-back-to-heading)
4125 (let ((goal-column 0) eoh eol eos)
4126 ;; First, some boundaries
4127 (save-excursion
4128 (org-back-to-heading)
4129 (save-excursion
4130 (beginning-of-line 2)
4131 (while (and (not (eobp)) ;; this is like `next-line'
4132 (get-char-property (1- (point)) 'invisible))
4133 (beginning-of-line 2)) (setq eol (point)))
4134 (outline-end-of-heading) (setq eoh (point))
4135 (org-end-of-subtree t)
4136 (unless (eobp)
4137 (skip-chars-forward " \t\n")
4138 (beginning-of-line 1) ; in case this is an item
4140 (setq eos (1- (point))))
4141 ;; Find out what to do next and set `this-command'
4142 (cond
4143 ((= eos eoh)
4144 ;; Nothing is hidden behind this heading
4145 (message "EMPTY ENTRY")
4146 (setq org-cycle-subtree-status nil)
4147 (save-excursion
4148 (goto-char eos)
4149 (outline-next-heading)
4150 (if (org-invisible-p) (org-flag-heading nil))))
4151 ((or (>= eol eos)
4152 (not (string-match "\\S-" (buffer-substring eol eos))))
4153 ;; Entire subtree is hidden in one line: open it
4154 (org-show-entry)
4155 (show-children)
4156 (message "CHILDREN")
4157 (save-excursion
4158 (goto-char eos)
4159 (outline-next-heading)
4160 (if (org-invisible-p) (org-flag-heading nil)))
4161 (setq org-cycle-subtree-status 'children)
4162 (run-hook-with-args 'org-cycle-hook 'children))
4163 ((and (eq last-command this-command)
4164 (eq org-cycle-subtree-status 'children))
4165 ;; We just showed the children, now show everything.
4166 (org-show-subtree)
4167 (message "SUBTREE")
4168 (setq org-cycle-subtree-status 'subtree)
4169 (run-hook-with-args 'org-cycle-hook 'subtree))
4171 ;; Default action: hide the subtree.
4172 (hide-subtree)
4173 (message "FOLDED")
4174 (setq org-cycle-subtree-status 'folded)
4175 (run-hook-with-args 'org-cycle-hook 'folded)))))
4177 ;; TAB emulation
4178 (buffer-read-only (org-back-to-heading))
4180 ((org-try-cdlatex-tab))
4182 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4183 (or (not (bolp))
4184 (not (looking-at outline-regexp))))
4185 (call-interactively (global-key-binding "\t")))
4187 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4188 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4189 (or (and (eq org-cycle-emulate-tab 'white)
4190 (= (match-end 0) (point-at-eol)))
4191 (and (eq org-cycle-emulate-tab 'whitestart)
4192 (>= (match-end 0) pos))))
4194 (eq org-cycle-emulate-tab t))
4195 ; (if (and (looking-at "[ \n\r\t]")
4196 ; (string-match "^[ \t]*$" (buffer-substring
4197 ; (point-at-bol) (point))))
4198 ; (progn
4199 ; (beginning-of-line 1)
4200 ; (and (looking-at "[ \t]+") (replace-match ""))))
4201 (call-interactively (global-key-binding "\t")))
4203 (t (save-excursion
4204 (org-back-to-heading)
4205 (org-cycle))))))
4207 ;;;###autoload
4208 (defun org-global-cycle (&optional arg)
4209 "Cycle the global visibility. For details see `org-cycle'."
4210 (interactive "P")
4211 (let ((org-cycle-include-plain-lists
4212 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4213 (if (integerp arg)
4214 (progn
4215 (show-all)
4216 (hide-sublevels arg)
4217 (setq org-cycle-global-status 'contents))
4218 (org-cycle '(4)))))
4220 (defun org-overview ()
4221 "Switch to overview mode, shoing only top-level headlines.
4222 Really, this shows all headlines with level equal or greater than the level
4223 of the first headline in the buffer. This is important, because if the
4224 first headline is not level one, then (hide-sublevels 1) gives confusing
4225 results."
4226 (interactive)
4227 (let ((level (save-excursion
4228 (goto-char (point-min))
4229 (if (re-search-forward (concat "^" outline-regexp) nil t)
4230 (progn
4231 (goto-char (match-beginning 0))
4232 (funcall outline-level))))))
4233 (and level (hide-sublevels level))))
4235 (defun org-content (&optional arg)
4236 "Show all headlines in the buffer, like a table of contents.
4237 With numerical argument N, show content up to level N."
4238 (interactive "P")
4239 (save-excursion
4240 ;; Visit all headings and show their offspring
4241 (and (integerp arg) (org-overview))
4242 (goto-char (point-max))
4243 (catch 'exit
4244 (while (and (progn (condition-case nil
4245 (outline-previous-visible-heading 1)
4246 (error (goto-char (point-min))))
4248 (looking-at outline-regexp))
4249 (if (integerp arg)
4250 (show-children (1- arg))
4251 (show-branches))
4252 (if (bobp) (throw 'exit nil))))))
4255 (defun org-optimize-window-after-visibility-change (state)
4256 "Adjust the window after a change in outline visibility.
4257 This function is the default value of the hook `org-cycle-hook'."
4258 (when (get-buffer-window (current-buffer))
4259 (cond
4260 ; ((eq state 'overview) (org-first-headline-recenter 1))
4261 ; ((eq state 'overview) (org-beginning-of-line))
4262 ((eq state 'content) nil)
4263 ((eq state 'all) nil)
4264 ((eq state 'folded) nil)
4265 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4266 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4268 (defun org-compact-display-after-subtree-move ()
4269 (let (beg end)
4270 (save-excursion
4271 (if (org-up-heading-safe)
4272 (progn
4273 (hide-subtree)
4274 (show-entry)
4275 (show-children)
4276 (org-cycle-show-empty-lines 'children)
4277 (org-cycle-hide-drawers 'children))
4278 (org-overview)))))
4280 (defun org-cycle-show-empty-lines (state)
4281 "Show empty lines above all visible headlines.
4282 The region to be covered depends on STATE when called through
4283 `org-cycle-hook'. Lisp program can use t for STATE to get the
4284 entire buffer covered. Note that an empty line is only shown if there
4285 are at least `org-cycle-separator-lines' empty lines before the headeline."
4286 (when (> org-cycle-separator-lines 0)
4287 (save-excursion
4288 (let* ((n org-cycle-separator-lines)
4289 (re (cond
4290 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4291 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4292 (t (let ((ns (number-to-string (- n 2))))
4293 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4294 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4295 beg end)
4296 (cond
4297 ((memq state '(overview contents t))
4298 (setq beg (point-min) end (point-max)))
4299 ((memq state '(children folded))
4300 (setq beg (point) end (progn (org-end-of-subtree t t)
4301 (beginning-of-line 2)
4302 (point)))))
4303 (when beg
4304 (goto-char beg)
4305 (while (re-search-forward re end t)
4306 (if (not (get-char-property (match-end 1) 'invisible))
4307 (outline-flag-region
4308 (match-beginning 1) (match-end 1) nil)))))))
4309 ;; Never hide empty lines at the end of the file.
4310 (save-excursion
4311 (goto-char (point-max))
4312 (outline-previous-heading)
4313 (outline-end-of-heading)
4314 (if (and (looking-at "[ \t\n]+")
4315 (= (match-end 0) (point-max)))
4316 (outline-flag-region (point) (match-end 0) nil))))
4318 (defun org-subtree-end-visible-p ()
4319 "Is the end of the current subtree visible?"
4320 (pos-visible-in-window-p
4321 (save-excursion (org-end-of-subtree t) (point))))
4323 (defun org-first-headline-recenter (&optional N)
4324 "Move cursor to the first headline and recenter the headline.
4325 Optional argument N means, put the headline into the Nth line of the window."
4326 (goto-char (point-min))
4327 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4328 (beginning-of-line)
4329 (recenter (prefix-numeric-value N))))
4331 ;;; Org-goto
4333 (defvar org-goto-window-configuration nil)
4334 (defvar org-goto-marker nil)
4335 (defvar org-goto-map
4336 (let ((map (make-sparse-keymap)))
4337 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4338 (while (setq cmd (pop cmds))
4339 (substitute-key-definition cmd cmd map global-map)))
4340 (suppress-keymap map)
4341 (org-defkey map "\C-m" 'org-goto-ret)
4342 (org-defkey map [(return)] 'org-goto-ret)
4343 (org-defkey map [(left)] 'org-goto-left)
4344 (org-defkey map [(right)] 'org-goto-right)
4345 (org-defkey map [(control ?g)] 'org-goto-quit)
4346 (org-defkey map "\C-i" 'org-cycle)
4347 (org-defkey map [(tab)] 'org-cycle)
4348 (org-defkey map [(down)] 'outline-next-visible-heading)
4349 (org-defkey map [(up)] 'outline-previous-visible-heading)
4350 (if org-goto-auto-isearch
4351 (if (fboundp 'define-key-after)
4352 (define-key-after map [t] 'org-goto-local-auto-isearch)
4353 nil)
4354 (org-defkey map "q" 'org-goto-quit)
4355 (org-defkey map "n" 'outline-next-visible-heading)
4356 (org-defkey map "p" 'outline-previous-visible-heading)
4357 (org-defkey map "f" 'outline-forward-same-level)
4358 (org-defkey map "b" 'outline-backward-same-level)
4359 (org-defkey map "u" 'outline-up-heading))
4360 (org-defkey map "/" 'org-occur)
4361 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4362 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4363 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4364 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4365 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4366 map))
4368 (defconst org-goto-help
4369 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4370 RET=jump to location [Q]uit and return to previous location
4371 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4373 (defvar org-goto-start-pos) ; dynamically scoped parameter
4375 (defun org-goto (&optional alternative-interface)
4376 "Look up a different location in the current file, keeping current visibility.
4378 When you want look-up or go to a different location in a document, the
4379 fastest way is often to fold the entire buffer and then dive into the tree.
4380 This method has the disadvantage, that the previous location will be folded,
4381 which may not be what you want.
4383 This command works around this by showing a copy of the current buffer
4384 in an indirect buffer, in overview mode. You can dive into the tree in
4385 that copy, use org-occur and incremental search to find a location.
4386 When pressing RET or `Q', the command returns to the original buffer in
4387 which the visibility is still unchanged. After RET is will also jump to
4388 the location selected in the indirect buffer and expose the
4389 the headline hierarchy above."
4390 (interactive "P")
4391 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4392 (org-refile-use-outline-path t)
4393 (interface
4394 (if (not alternative-interface)
4395 org-goto-interface
4396 (if (eq org-goto-interface 'outline)
4397 'outline-path-completion
4398 'outline)))
4399 (org-goto-start-pos (point))
4400 (selected-point
4401 (if (eq interface 'outline)
4402 (car (org-get-location (current-buffer) org-goto-help))
4403 (nth 3 (org-refile-get-location "Goto: ")))))
4404 (if selected-point
4405 (progn
4406 (org-mark-ring-push org-goto-start-pos)
4407 (goto-char selected-point)
4408 (if (or (org-invisible-p) (org-invisible-p2))
4409 (org-show-context 'org-goto)))
4410 (message "Quit"))))
4412 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4413 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4414 (defvar org-goto-local-auto-isearch-map) ; defined below
4416 (defun org-get-location (buf help)
4417 "Let the user select a location in the Org-mode buffer BUF.
4418 This function uses a recursive edit. It returns the selected position
4419 or nil."
4420 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4421 (isearch-hide-immediately nil)
4422 (isearch-search-fun-function
4423 (lambda () 'org-goto-local-search-forward-headings))
4424 (org-goto-selected-point org-goto-exit-command))
4425 (save-excursion
4426 (save-window-excursion
4427 (delete-other-windows)
4428 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4429 (switch-to-buffer
4430 (condition-case nil
4431 (make-indirect-buffer (current-buffer) "*org-goto*")
4432 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4433 (with-output-to-temp-buffer "*Help*"
4434 (princ help))
4435 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4436 (setq buffer-read-only nil)
4437 (let ((org-startup-truncated t)
4438 (org-startup-folded nil)
4439 (org-startup-align-all-tables nil))
4440 (org-mode)
4441 (org-overview))
4442 (setq buffer-read-only t)
4443 (if (and (boundp 'org-goto-start-pos)
4444 (integer-or-marker-p org-goto-start-pos))
4445 (let ((org-show-hierarchy-above t)
4446 (org-show-siblings t)
4447 (org-show-following-heading t))
4448 (goto-char org-goto-start-pos)
4449 (and (org-invisible-p) (org-show-context)))
4450 (goto-char (point-min)))
4451 (org-beginning-of-line)
4452 (message "Select location and press RET")
4453 (use-local-map org-goto-map)
4454 (recursive-edit)
4456 (kill-buffer "*org-goto*")
4457 (cons org-goto-selected-point org-goto-exit-command)))
4459 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4460 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4461 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4462 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4464 (defun org-goto-local-search-forward-headings (string bound noerror)
4465 "Search and make sure that anu matches are in headlines."
4466 (catch 'return
4467 (while (search-forward string bound noerror)
4468 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4469 (and (member :headline context)
4470 (not (member :tags context))))
4471 (throw 'return (point))))))
4473 (defun org-goto-local-auto-isearch ()
4474 "Start isearch."
4475 (interactive)
4476 (goto-char (point-min))
4477 (let ((keys (this-command-keys)))
4478 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4479 (isearch-mode t)
4480 (isearch-process-search-char (string-to-char keys)))))
4482 (defun org-goto-ret (&optional arg)
4483 "Finish `org-goto' by going to the new location."
4484 (interactive "P")
4485 (setq org-goto-selected-point (point)
4486 org-goto-exit-command 'return)
4487 (throw 'exit nil))
4489 (defun org-goto-left ()
4490 "Finish `org-goto' by going to the new location."
4491 (interactive)
4492 (if (org-on-heading-p)
4493 (progn
4494 (beginning-of-line 1)
4495 (setq org-goto-selected-point (point)
4496 org-goto-exit-command 'left)
4497 (throw 'exit nil))
4498 (error "Not on a heading")))
4500 (defun org-goto-right ()
4501 "Finish `org-goto' by going to the new location."
4502 (interactive)
4503 (if (org-on-heading-p)
4504 (progn
4505 (setq org-goto-selected-point (point)
4506 org-goto-exit-command 'right)
4507 (throw 'exit nil))
4508 (error "Not on a heading")))
4510 (defun org-goto-quit ()
4511 "Finish `org-goto' without cursor motion."
4512 (interactive)
4513 (setq org-goto-selected-point nil)
4514 (setq org-goto-exit-command 'quit)
4515 (throw 'exit nil))
4517 ;;; Indirect buffer display of subtrees
4519 (defvar org-indirect-dedicated-frame nil
4520 "This is the frame being used for indirect tree display.")
4521 (defvar org-last-indirect-buffer nil)
4523 (defun org-tree-to-indirect-buffer (&optional arg)
4524 "Create indirect buffer and narrow it to current subtree.
4525 With numerical prefix ARG, go up to this level and then take that tree.
4526 If ARG is negative, go up that many levels.
4527 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4528 indirect buffer previously made with this command, to avoid proliferation of
4529 indirect buffers. However, when you call the command with a `C-u' prefix, or
4530 when `org-indirect-buffer-display' is `new-frame', the last buffer
4531 is kept so that you can work with several indirect buffers at the same time.
4532 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4533 requests that a new frame be made for the new buffer, so that the dedicated
4534 frame is not changed."
4535 (interactive "P")
4536 (let ((cbuf (current-buffer))
4537 (cwin (selected-window))
4538 (pos (point))
4539 beg end level heading ibuf)
4540 (save-excursion
4541 (org-back-to-heading t)
4542 (when (numberp arg)
4543 (setq level (org-outline-level))
4544 (if (< arg 0) (setq arg (+ level arg)))
4545 (while (> (setq level (org-outline-level)) arg)
4546 (outline-up-heading 1 t)))
4547 (setq beg (point)
4548 heading (org-get-heading))
4549 (org-end-of-subtree t) (setq end (point)))
4550 (if (and (buffer-live-p org-last-indirect-buffer)
4551 (not (eq org-indirect-buffer-display 'new-frame))
4552 (not arg))
4553 (kill-buffer org-last-indirect-buffer))
4554 (setq ibuf (org-get-indirect-buffer cbuf)
4555 org-last-indirect-buffer ibuf)
4556 (cond
4557 ((or (eq org-indirect-buffer-display 'new-frame)
4558 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4559 (select-frame (make-frame))
4560 (delete-other-windows)
4561 (switch-to-buffer ibuf)
4562 (org-set-frame-title heading))
4563 ((eq org-indirect-buffer-display 'dedicated-frame)
4564 (raise-frame
4565 (select-frame (or (and org-indirect-dedicated-frame
4566 (frame-live-p org-indirect-dedicated-frame)
4567 org-indirect-dedicated-frame)
4568 (setq org-indirect-dedicated-frame (make-frame)))))
4569 (delete-other-windows)
4570 (switch-to-buffer ibuf)
4571 (org-set-frame-title (concat "Indirect: " heading)))
4572 ((eq org-indirect-buffer-display 'current-window)
4573 (switch-to-buffer ibuf))
4574 ((eq org-indirect-buffer-display 'other-window)
4575 (pop-to-buffer ibuf))
4576 (t (error "Invalid value.")))
4577 (if (featurep 'xemacs)
4578 (save-excursion (org-mode) (turn-on-font-lock)))
4579 (narrow-to-region beg end)
4580 (show-all)
4581 (goto-char pos)
4582 (and (window-live-p cwin) (select-window cwin))))
4584 (defun org-get-indirect-buffer (&optional buffer)
4585 (setq buffer (or buffer (current-buffer)))
4586 (let ((n 1) (base (buffer-name buffer)) bname)
4587 (while (buffer-live-p
4588 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4589 (setq n (1+ n)))
4590 (condition-case nil
4591 (make-indirect-buffer buffer bname 'clone)
4592 (error (make-indirect-buffer buffer bname)))))
4594 (defun org-set-frame-title (title)
4595 "Set the title of the current frame to the string TITLE."
4596 ;; FIXME: how to name a single frame in XEmacs???
4597 (unless (featurep 'xemacs)
4598 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4600 ;;;; Structure editing
4602 ;;; Inserting headlines
4604 (defun org-insert-heading (&optional force-heading)
4605 "Insert a new heading or item with same depth at point.
4606 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4607 If point is at the beginning of a headline, insert a sibling before the
4608 current headline. If point is not at the beginning, do not split the line,
4609 but create the new hedline after the current line."
4610 (interactive "P")
4611 (if (= (buffer-size) 0)
4612 (insert "\n* ")
4613 (when (or force-heading (not (org-insert-item)))
4614 (let* ((head (save-excursion
4615 (condition-case nil
4616 (progn
4617 (org-back-to-heading)
4618 (match-string 0))
4619 (error "*"))))
4620 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4621 pos)
4622 (cond
4623 ((and (org-on-heading-p) (bolp)
4624 (or (bobp)
4625 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4626 ;; insert before the current line
4627 (open-line (if blank 2 1)))
4628 ((and (bolp)
4629 (or (bobp)
4630 (save-excursion
4631 (backward-char 1) (not (org-invisible-p)))))
4632 ;; insert right here
4633 nil)
4635 ; ;; in the middle of the line
4636 ; (org-show-entry)
4637 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
4638 ; (if (and
4639 ; (org-on-heading-p)
4640 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
4641 ; ;; protect the tags
4642 ;; (let ((tags (match-string 2)) pos)
4643 ; (delete-region (match-beginning 1) (match-end 1))
4644 ; (setq pos (point-at-bol))
4645 ; (newline (if blank 2 1))
4646 ; (save-excursion
4647 ; (goto-char pos)
4648 ; (end-of-line 1)
4649 ; (insert " " tags)
4650 ; (org-set-tags nil 'align)))
4651 ; (newline (if blank 2 1)))
4652 ; (newline (if blank 2 1))))
4655 ;; in the middle of the line
4656 (org-show-entry)
4657 (let ((split
4658 (org-get-alist-option org-M-RET-may-split-line 'headline))
4659 tags pos)
4660 (if (org-on-heading-p)
4661 (progn
4662 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4663 (setq tags (and (match-end 2) (match-string 2)))
4664 (and (match-end 1)
4665 (delete-region (match-beginning 1) (match-end 1)))
4666 (setq pos (point-at-bol))
4667 (or split (end-of-line 1))
4668 (delete-horizontal-space)
4669 (newline (if blank 2 1))
4670 (when tags
4671 (save-excursion
4672 (goto-char pos)
4673 (end-of-line 1)
4674 (insert " " tags)
4675 (org-set-tags nil 'align))))
4676 (or split (end-of-line 1))
4677 (newline (if blank 2 1))))))
4678 (insert head) (just-one-space)
4679 (setq pos (point))
4680 (end-of-line 1)
4681 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4682 (run-hooks 'org-insert-heading-hook)))))
4684 (defun org-insert-heading-after-current ()
4685 "Insert a new heading with same level as current, after current subtree."
4686 (interactive)
4687 (org-back-to-heading)
4688 (org-insert-heading)
4689 (org-move-subtree-down)
4690 (end-of-line 1))
4692 (defun org-insert-todo-heading (arg)
4693 "Insert a new heading with the same level and TODO state as current heading.
4694 If the heading has no TODO state, or if the state is DONE, use the first
4695 state (TODO by default). Also with prefix arg, force first state."
4696 (interactive "P")
4697 (when (not (org-insert-item 'checkbox))
4698 (org-insert-heading)
4699 (save-excursion
4700 (org-back-to-heading)
4701 (outline-previous-heading)
4702 (looking-at org-todo-line-regexp))
4703 (if (or arg
4704 (not (match-beginning 2))
4705 (member (match-string 2) org-done-keywords))
4706 (insert (car org-todo-keywords-1) " ")
4707 (insert (match-string 2) " "))))
4709 (defun org-insert-subheading (arg)
4710 "Insert a new subheading and demote it.
4711 Works for outline headings and for plain lists alike."
4712 (interactive "P")
4713 (org-insert-heading arg)
4714 (cond
4715 ((org-on-heading-p) (org-do-demote))
4716 ((org-at-item-p) (org-indent-item 1))))
4718 (defun org-insert-todo-subheading (arg)
4719 "Insert a new subheading with TODO keyword or checkbox and demote it.
4720 Works for outline headings and for plain lists alike."
4721 (interactive "P")
4722 (org-insert-todo-heading arg)
4723 (cond
4724 ((org-on-heading-p) (org-do-demote))
4725 ((org-at-item-p) (org-indent-item 1))))
4727 ;;; Promotion and Demotion
4729 (defun org-promote-subtree ()
4730 "Promote the entire subtree.
4731 See also `org-promote'."
4732 (interactive)
4733 (save-excursion
4734 (org-map-tree 'org-promote))
4735 (org-fix-position-after-promote))
4737 (defun org-demote-subtree ()
4738 "Demote the entire subtree. See `org-demote'.
4739 See also `org-promote'."
4740 (interactive)
4741 (save-excursion
4742 (org-map-tree 'org-demote))
4743 (org-fix-position-after-promote))
4746 (defun org-do-promote ()
4747 "Promote the current heading higher up the tree.
4748 If the region is active in `transient-mark-mode', promote all headings
4749 in the region."
4750 (interactive)
4751 (save-excursion
4752 (if (org-region-active-p)
4753 (org-map-region 'org-promote (region-beginning) (region-end))
4754 (org-promote)))
4755 (org-fix-position-after-promote))
4757 (defun org-do-demote ()
4758 "Demote the current heading lower down the tree.
4759 If the region is active in `transient-mark-mode', demote all headings
4760 in the region."
4761 (interactive)
4762 (save-excursion
4763 (if (org-region-active-p)
4764 (org-map-region 'org-demote (region-beginning) (region-end))
4765 (org-demote)))
4766 (org-fix-position-after-promote))
4768 (defun org-fix-position-after-promote ()
4769 "Make sure that after pro/demotion cursor position is right."
4770 (let ((pos (point)))
4771 (when (save-excursion
4772 (beginning-of-line 1)
4773 (looking-at org-todo-line-regexp)
4774 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4775 (cond ((eobp) (insert " "))
4776 ((eolp) (insert " "))
4777 ((equal (char-after) ?\ ) (forward-char 1))))))
4779 (defun org-reduced-level (l)
4780 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4782 (defun org-get-valid-level (level &optional change)
4783 "Rectify a level change under the influence of `org-odd-levels-only'
4784 LEVEL is a current level, CHANGE is by how much the level should be
4785 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4786 even level numbers will become the next higher odd number."
4787 (if org-odd-levels-only
4788 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4789 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4790 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4791 (max 1 (+ level change))))
4793 (if (featurep 'xemacs)
4794 (define-obsolete-function-alias 'org-get-legal-level
4795 'org-get-valid-level)
4796 (define-obsolete-function-alias 'org-get-legal-level
4797 'org-get-valid-level "23.1"))
4799 (defun org-promote ()
4800 "Promote the current heading higher up the tree.
4801 If the region is active in `transient-mark-mode', promote all headings
4802 in the region."
4803 (org-back-to-heading t)
4804 (let* ((level (save-match-data (funcall outline-level)))
4805 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4806 (diff (abs (- level (length up-head) -1))))
4807 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4808 (replace-match up-head nil t)
4809 ;; Fixup tag positioning
4810 (and org-auto-align-tags (org-set-tags nil t))
4811 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4813 (defun org-demote ()
4814 "Demote the current heading lower down the tree.
4815 If the region is active in `transient-mark-mode', demote all headings
4816 in the region."
4817 (org-back-to-heading t)
4818 (let* ((level (save-match-data (funcall outline-level)))
4819 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4820 (diff (abs (- level (length down-head) -1))))
4821 (replace-match down-head nil t)
4822 ;; Fixup tag positioning
4823 (and org-auto-align-tags (org-set-tags nil t))
4824 (if org-adapt-indentation (org-fixup-indentation diff))))
4826 (defun org-map-tree (fun)
4827 "Call FUN for every heading underneath the current one."
4828 (org-back-to-heading)
4829 (let ((level (funcall outline-level)))
4830 (save-excursion
4831 (funcall fun)
4832 (while (and (progn
4833 (outline-next-heading)
4834 (> (funcall outline-level) level))
4835 (not (eobp)))
4836 (funcall fun)))))
4838 (defun org-map-region (fun beg end)
4839 "Call FUN for every heading between BEG and END."
4840 (let ((org-ignore-region t))
4841 (save-excursion
4842 (setq end (copy-marker end))
4843 (goto-char beg)
4844 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4845 (< (point) end))
4846 (funcall fun))
4847 (while (and (progn
4848 (outline-next-heading)
4849 (< (point) end))
4850 (not (eobp)))
4851 (funcall fun)))))
4853 (defun org-fixup-indentation (diff)
4854 "Change the indentation in the current entry by DIFF
4855 However, if any line in the current entry has no indentation, or if it
4856 would end up with no indentation after the change, nothing at all is done."
4857 (save-excursion
4858 (let ((end (save-excursion (outline-next-heading)
4859 (point-marker)))
4860 (prohibit (if (> diff 0)
4861 "^\\S-"
4862 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4863 col)
4864 (unless (save-excursion (end-of-line 1)
4865 (re-search-forward prohibit end t))
4866 (while (and (< (point) end)
4867 (re-search-forward "^[ \t]+" end t))
4868 (goto-char (match-end 0))
4869 (setq col (current-column))
4870 (if (< diff 0) (replace-match ""))
4871 (indent-to (+ diff col))))
4872 (move-marker end nil))))
4874 (defun org-convert-to-odd-levels ()
4875 "Convert an org-mode file with all levels allowed to one with odd levels.
4876 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4877 level 5 etc."
4878 (interactive)
4879 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4880 (let ((org-odd-levels-only nil) n)
4881 (save-excursion
4882 (goto-char (point-min))
4883 (while (re-search-forward "^\\*\\*+ " nil t)
4884 (setq n (- (length (match-string 0)) 2))
4885 (while (>= (setq n (1- n)) 0)
4886 (org-demote))
4887 (end-of-line 1))))))
4890 (defun org-convert-to-oddeven-levels ()
4891 "Convert an org-mode file with only odd levels to one with odd and even levels.
4892 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4893 section with an even level, conversion would destroy the structure of the file. An error
4894 is signaled in this case."
4895 (interactive)
4896 (goto-char (point-min))
4897 ;; First check if there are no even levels
4898 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4899 (org-show-context t)
4900 (error "Not all levels are odd in this file. Conversion not possible."))
4901 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4902 (let ((org-odd-levels-only nil) n)
4903 (save-excursion
4904 (goto-char (point-min))
4905 (while (re-search-forward "^\\*\\*+ " nil t)
4906 (setq n (/ (1- (length (match-string 0))) 2))
4907 (while (>= (setq n (1- n)) 0)
4908 (org-promote))
4909 (end-of-line 1))))))
4911 (defun org-tr-level (n)
4912 "Make N odd if required."
4913 (if org-odd-levels-only (1+ (/ n 2)) n))
4915 ;;; Vertical tree motion, cutting and pasting of subtrees
4917 (defun org-move-subtree-up (&optional arg)
4918 "Move the current subtree up past ARG headlines of the same level."
4919 (interactive "p")
4920 (org-move-subtree-down (- (prefix-numeric-value arg))))
4922 (defun org-move-subtree-down (&optional arg)
4923 "Move the current subtree down past ARG headlines of the same level."
4924 (interactive "p")
4925 (setq arg (prefix-numeric-value arg))
4926 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4927 'outline-get-last-sibling))
4928 (ins-point (make-marker))
4929 (cnt (abs arg))
4930 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4931 ;; Select the tree
4932 (org-back-to-heading)
4933 (setq beg0 (point))
4934 (save-excursion
4935 (setq ne-beg (org-back-over-empty-lines))
4936 (setq beg (point)))
4937 (save-match-data
4938 (save-excursion (outline-end-of-heading)
4939 (setq folded (org-invisible-p)))
4940 (outline-end-of-subtree))
4941 (outline-next-heading)
4942 (setq ne-end (org-back-over-empty-lines))
4943 (setq end (point))
4944 (goto-char beg0)
4945 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4946 ;; include less whitespace
4947 (save-excursion
4948 (goto-char beg)
4949 (forward-line (- ne-beg ne-end))
4950 (setq beg (point))))
4951 ;; Find insertion point, with error handling
4952 (while (> cnt 0)
4953 (or (and (funcall movfunc) (looking-at outline-regexp))
4954 (progn (goto-char beg0)
4955 (error "Cannot move past superior level or buffer limit")))
4956 (setq cnt (1- cnt)))
4957 (if (> arg 0)
4958 ;; Moving forward - still need to move over subtree
4959 (progn (org-end-of-subtree t t)
4960 (save-excursion
4961 (org-back-over-empty-lines)
4962 (or (bolp) (newline)))))
4963 (setq ne-ins (org-back-over-empty-lines))
4964 (move-marker ins-point (point))
4965 (setq txt (buffer-substring beg end))
4966 (delete-region beg end)
4967 (outline-flag-region (1- beg) beg nil)
4968 (outline-flag-region (1- (point)) (point) nil)
4969 (insert txt)
4970 (or (bolp) (insert "\n"))
4971 (setq ins-end (point))
4972 (goto-char ins-point)
4973 (org-skip-whitespace)
4974 (when (and (< arg 0)
4975 (org-first-sibling-p)
4976 (> ne-ins ne-beg))
4977 ;; Move whitespace back to beginning
4978 (save-excursion
4979 (goto-char ins-end)
4980 (let ((kill-whole-line t))
4981 (kill-line (- ne-ins ne-beg)) (point)))
4982 (insert (make-string (- ne-ins ne-beg) ?\n)))
4983 (move-marker ins-point nil)
4984 (org-compact-display-after-subtree-move)
4985 (unless folded
4986 (org-show-entry)
4987 (show-children)
4988 (org-cycle-hide-drawers 'children))))
4990 (defvar org-subtree-clip ""
4991 "Clipboard for cut and paste of subtrees.
4992 This is actually only a copy of the kill, because we use the normal kill
4993 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4995 (defvar org-subtree-clip-folded nil
4996 "Was the last copied subtree folded?
4997 This is used to fold the tree back after pasting.")
4999 (defun org-cut-subtree (&optional n)
5000 "Cut the current subtree into the clipboard.
5001 With prefix arg N, cut this many sequential subtrees.
5002 This is a short-hand for marking the subtree and then cutting it."
5003 (interactive "p")
5004 (org-copy-subtree n 'cut))
5006 (defun org-copy-subtree (&optional n cut)
5007 "Cut the current subtree into the clipboard.
5008 With prefix arg N, cut this many sequential subtrees.
5009 This is a short-hand for marking the subtree and then copying it.
5010 If CUT is non-nil, actually cut the subtree."
5011 (interactive "p")
5012 (let (beg end folded (beg0 (point)))
5013 (if (interactive-p)
5014 (org-back-to-heading nil) ; take what looks like a subtree
5015 (org-back-to-heading t)) ; take what is really there
5016 (org-back-over-empty-lines)
5017 (setq beg (point))
5018 (skip-chars-forward " \t\r\n")
5019 (save-match-data
5020 (save-excursion (outline-end-of-heading)
5021 (setq folded (org-invisible-p)))
5022 (condition-case nil
5023 (outline-forward-same-level (1- n))
5024 (error nil))
5025 (org-end-of-subtree t t))
5026 (org-back-over-empty-lines)
5027 (setq end (point))
5028 (goto-char beg0)
5029 (when (> end beg)
5030 (setq org-subtree-clip-folded folded)
5031 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5032 (setq org-subtree-clip (current-kill 0))
5033 (message "%s: Subtree(s) with %d characters"
5034 (if cut "Cut" "Copied")
5035 (length org-subtree-clip)))))
5037 (defun org-paste-subtree (&optional level tree)
5038 "Paste the clipboard as a subtree, with modification of headline level.
5039 The entire subtree is promoted or demoted in order to match a new headline
5040 level. By default, the new level is derived from the visible headings
5041 before and after the insertion point, and taken to be the inferior headline
5042 level of the two. So if the previous visible heading is level 3 and the
5043 next is level 4 (or vice versa), level 4 will be used for insertion.
5044 This makes sure that the subtree remains an independent subtree and does
5045 not swallow low level entries.
5047 You can also force a different level, either by using a numeric prefix
5048 argument, or by inserting the heading marker by hand. For example, if the
5049 cursor is after \"*****\", then the tree will be shifted to level 5.
5051 If you want to insert the tree as is, just use \\[yank].
5053 If optional TREE is given, use this text instead of the kill ring."
5054 (interactive "P")
5055 (unless (org-kill-is-subtree-p tree)
5056 (error "%s"
5057 (substitute-command-keys
5058 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5059 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5060 (^re (concat "^\\(" outline-regexp "\\)"))
5061 (re (concat "\\(" outline-regexp "\\)"))
5062 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5064 (old-level (if (string-match ^re txt)
5065 (- (match-end 0) (match-beginning 0) 1)
5066 -1))
5067 (force-level (cond (level (prefix-numeric-value level))
5068 ((string-match
5069 ^re_ (buffer-substring (point-at-bol) (point)))
5070 (- (match-end 1) (match-beginning 1)))
5071 (t nil)))
5072 (previous-level (save-excursion
5073 (condition-case nil
5074 (progn
5075 (outline-previous-visible-heading 1)
5076 (if (looking-at re)
5077 (- (match-end 0) (match-beginning 0) 1)
5079 (error 1))))
5080 (next-level (save-excursion
5081 (condition-case nil
5082 (progn
5083 (or (looking-at outline-regexp)
5084 (outline-next-visible-heading 1))
5085 (if (looking-at re)
5086 (- (match-end 0) (match-beginning 0) 1)
5088 (error 1))))
5089 (new-level (or force-level (max previous-level next-level)))
5090 (shift (if (or (= old-level -1)
5091 (= new-level -1)
5092 (= old-level new-level))
5094 (- new-level old-level)))
5095 (delta (if (> shift 0) -1 1))
5096 (func (if (> shift 0) 'org-demote 'org-promote))
5097 (org-odd-levels-only nil)
5098 beg end)
5099 ;; Remove the forced level indicator
5100 (if force-level
5101 (delete-region (point-at-bol) (point)))
5102 ;; Paste
5103 (beginning-of-line 1)
5104 (org-back-over-empty-lines) ;; FIXME: correct fix????
5105 (setq beg (point))
5106 (insert-before-markers txt) ;; FIXME: correct fix????
5107 (unless (string-match "\n\\'" txt) (insert "\n"))
5108 (setq end (point))
5109 (goto-char beg)
5110 (skip-chars-forward " \t\n\r")
5111 (setq beg (point))
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+ (match-beginning 2))))
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 (defun org-narrow-to-subtree ()
5153 "Narrow buffer to the current subtree."
5154 (interactive)
5155 (save-excursion
5156 (save-match-data
5157 (narrow-to-region
5158 (progn (org-back-to-heading) (point))
5159 (progn (org-end-of-subtree t t) (point))))))
5162 ;;; Outline Sorting
5164 (defun org-sort (with-case)
5165 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5166 Optional argument WITH-CASE means sort case-sensitively."
5167 (interactive "P")
5168 (if (org-at-table-p)
5169 (org-call-with-arg 'org-table-sort-lines with-case)
5170 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5172 (defun org-sort-remove-invisible (s)
5173 (remove-text-properties 0 (length s) org-rm-props s)
5174 (while (string-match org-bracket-link-regexp s)
5175 (setq s (replace-match (if (match-end 2)
5176 (match-string 3 s)
5177 (match-string 1 s)) t t s)))
5180 (defvar org-priority-regexp) ; defined later in the file
5182 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5183 "Sort entries on a certain level of an outline tree.
5184 If there is an active region, the entries in the region are sorted.
5185 Else, if the cursor is before the first entry, sort the top-level items.
5186 Else, the children of the entry at point are sorted.
5188 Sorting can be alphabetically, numerically, and by date/time as given by
5189 the first time stamp in the entry. The command prompts for the sorting
5190 type unless it has been given to the function through the SORTING-TYPE
5191 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5192 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5193 called with point at the beginning of the record. It must return either
5194 a string or a number that should serve as the sorting key for that record.
5196 Comparing entries ignores case by default. However, with an optional argument
5197 WITH-CASE, the sorting considers case as well."
5198 (interactive "P")
5199 (let ((case-func (if with-case 'identity 'downcase))
5200 start beg end stars re re2
5201 txt what tmp plain-list-p)
5202 ;; Find beginning and end of region to sort
5203 (cond
5204 ((org-region-active-p)
5205 ;; we will sort the region
5206 (setq end (region-end)
5207 what "region")
5208 (goto-char (region-beginning))
5209 (if (not (org-on-heading-p)) (outline-next-heading))
5210 (setq start (point)))
5211 ((org-at-item-p)
5212 ;; we will sort this plain list
5213 (org-beginning-of-item-list) (setq start (point))
5214 (org-end-of-item-list) (setq end (point))
5215 (goto-char start)
5216 (setq plain-list-p t
5217 what "plain list"))
5218 ((or (org-on-heading-p)
5219 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5220 ;; we will sort the children of the current headline
5221 (org-back-to-heading)
5222 (setq start (point)
5223 end (progn (org-end-of-subtree t t)
5224 (org-back-over-empty-lines)
5225 (point))
5226 what "children")
5227 (goto-char start)
5228 (show-subtree)
5229 (outline-next-heading))
5231 ;; we will sort the top-level entries in this file
5232 (goto-char (point-min))
5233 (or (org-on-heading-p) (outline-next-heading))
5234 (setq start (point) end (point-max) what "top-level")
5235 (goto-char start)
5236 (show-all)))
5238 (setq beg (point))
5239 (if (>= beg end) (error "Nothing to sort"))
5241 (unless plain-list-p
5242 (looking-at "\\(\\*+\\)")
5243 (setq stars (match-string 1)
5244 re (concat "^" (regexp-quote stars) " +")
5245 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5246 txt (buffer-substring beg end))
5247 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5248 (if (and (not (equal stars "*")) (string-match re2 txt))
5249 (error "Region to sort contains a level above the first entry")))
5251 (unless sorting-type
5252 (message
5253 (if plain-list-p
5254 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5255 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
5256 what)
5257 (setq sorting-type (read-char-exclusive))
5259 (and (= (downcase sorting-type) ?f)
5260 (setq getkey-func
5261 (completing-read "Sort using function: "
5262 obarray 'fboundp t nil nil))
5263 (setq getkey-func (intern getkey-func)))
5265 (and (= (downcase sorting-type) ?r)
5266 (setq property
5267 (completing-read "Property: "
5268 (mapcar 'list (org-buffer-property-keys t))
5269 nil t))))
5271 (message "Sorting entries...")
5273 (save-restriction
5274 (narrow-to-region start end)
5276 (let ((dcst (downcase sorting-type))
5277 (now (current-time)))
5278 (sort-subr
5279 (/= dcst sorting-type)
5280 ;; This function moves to the beginning character of the "record" to
5281 ;; be sorted.
5282 (if plain-list-p
5283 (lambda nil
5284 (if (org-at-item-p) t (goto-char (point-max))))
5285 (lambda nil
5286 (if (re-search-forward re nil t)
5287 (goto-char (match-beginning 0))
5288 (goto-char (point-max)))))
5289 ;; This function moves to the last character of the "record" being
5290 ;; sorted.
5291 (if plain-list-p
5292 'org-end-of-item
5293 (lambda nil
5294 (save-match-data
5295 (condition-case nil
5296 (outline-forward-same-level 1)
5297 (error
5298 (goto-char (point-max)))))))
5300 ;; This function returns the value that gets sorted against.
5301 (if plain-list-p
5302 (lambda nil
5303 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5304 (cond
5305 ((= dcst ?n)
5306 (string-to-number (buffer-substring (match-end 0)
5307 (point-at-eol))))
5308 ((= dcst ?a)
5309 (buffer-substring (match-end 0) (point-at-eol)))
5310 ((= dcst ?t)
5311 (if (re-search-forward org-ts-regexp
5312 (point-at-eol) t)
5313 (org-time-string-to-time (match-string 0))
5314 now))
5315 ((= dcst ?f)
5316 (if getkey-func
5317 (progn
5318 (setq tmp (funcall getkey-func))
5319 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5320 tmp)
5321 (error "Invalid key function `%s'" getkey-func)))
5322 (t (error "Invalid sorting type `%c'" sorting-type)))))
5323 (lambda nil
5324 (cond
5325 ((= dcst ?n)
5326 (if (looking-at outline-regexp)
5327 (string-to-number (buffer-substring (match-end 0)
5328 (point-at-eol)))
5329 nil))
5330 ((= dcst ?a)
5331 (funcall case-func (buffer-substring (point-at-bol)
5332 (point-at-eol))))
5333 ((= dcst ?t)
5334 (if (re-search-forward org-ts-regexp
5335 (save-excursion
5336 (forward-line 2)
5337 (point)) t)
5338 (org-time-string-to-time (match-string 0))
5339 now))
5340 ((= dcst ?p)
5341 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5342 (string-to-char (match-string 2))
5343 org-default-priority))
5344 ((= dcst ?r)
5345 (or (org-entry-get nil property) ""))
5346 ((= dcst ?f)
5347 (if getkey-func
5348 (progn
5349 (setq tmp (funcall getkey-func))
5350 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5351 tmp)
5352 (error "Invalid key function `%s'" getkey-func)))
5353 (t (error "Invalid sorting type `%c'" sorting-type)))))
5355 (cond
5356 ((= dcst ?a) 'string<)
5357 ((= dcst ?t) 'time-less-p)
5358 (t nil)))))
5359 (message "Sorting entries...done")))
5361 (defun org-do-sort (table what &optional with-case sorting-type)
5362 "Sort TABLE of WHAT according to SORTING-TYPE.
5363 The user will be prompted for the SORTING-TYPE if the call to this
5364 function does not specify it. WHAT is only for the prompt, to indicate
5365 what is being sorted. The sorting key will be extracted from
5366 the car of the elements of the table.
5367 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5368 (unless sorting-type
5369 (message
5370 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5371 what)
5372 (setq sorting-type (read-char-exclusive)))
5373 (let ((dcst (downcase sorting-type))
5374 extractfun comparefun)
5375 ;; Define the appropriate functions
5376 (cond
5377 ((= dcst ?n)
5378 (setq extractfun 'string-to-number
5379 comparefun (if (= dcst sorting-type) '< '>)))
5380 ((= dcst ?a)
5381 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5382 (lambda(x) (downcase (org-sort-remove-invisible x))))
5383 comparefun (if (= dcst sorting-type)
5384 'string<
5385 (lambda (a b) (and (not (string< a b))
5386 (not (string= a b)))))))
5387 ((= dcst ?t)
5388 (setq extractfun
5389 (lambda (x)
5390 (if (string-match org-ts-regexp x)
5391 (time-to-seconds
5392 (org-time-string-to-time (match-string 0 x)))
5394 comparefun (if (= dcst sorting-type) '< '>)))
5395 (t (error "Invalid sorting type `%c'" sorting-type)))
5397 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5398 table)
5399 (lambda (a b) (funcall comparefun (car a) (car b))))))
5401 ;;;; Plain list items, including checkboxes
5403 ;;; Plain list items
5405 (defun org-at-item-p ()
5406 "Is point in a line starting a hand-formatted item?"
5407 (let ((llt org-plain-list-ordered-item-terminator))
5408 (save-excursion
5409 (goto-char (point-at-bol))
5410 (looking-at
5411 (cond
5412 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5413 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5414 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5415 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5417 (defun org-in-item-p ()
5418 "It the cursor inside a plain list item.
5419 Does not have to be the first line."
5420 (save-excursion
5421 (condition-case nil
5422 (progn
5423 (org-beginning-of-item)
5424 (org-at-item-p)
5426 (error nil))))
5428 (defun org-insert-item (&optional checkbox)
5429 "Insert a new item at the current level.
5430 Return t when things worked, nil when we are not in an item."
5431 (when (save-excursion
5432 (condition-case nil
5433 (progn
5434 (org-beginning-of-item)
5435 (org-at-item-p)
5436 (if (org-invisible-p) (error "Invisible item"))
5438 (error nil)))
5439 (let* ((bul (match-string 0))
5440 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5441 (match-end 0)))
5442 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5443 pos)
5444 (cond
5445 ((and (org-at-item-p) (<= (point) eow))
5446 ;; before the bullet
5447 (beginning-of-line 1)
5448 (open-line (if blank 2 1)))
5449 ((<= (point) eow)
5450 (beginning-of-line 1))
5452 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5453 (end-of-line 1)
5454 (delete-horizontal-space))
5455 (newline (if blank 2 1))))
5456 (insert bul (if checkbox "[ ]" ""))
5457 (just-one-space)
5458 (setq pos (point))
5459 (end-of-line 1)
5460 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5461 (org-maybe-renumber-ordered-list)
5462 (and checkbox (org-update-checkbox-count-maybe))
5465 ;;; Checkboxes
5467 (defun org-at-item-checkbox-p ()
5468 "Is point at a line starting a plain-list item with a checklet?"
5469 (and (org-at-item-p)
5470 (save-excursion
5471 (goto-char (match-end 0))
5472 (skip-chars-forward " \t")
5473 (looking-at "\\[[- X]\\]"))))
5475 (defun org-toggle-checkbox (&optional arg)
5476 "Toggle the checkbox in the current line."
5477 (interactive "P")
5478 (catch 'exit
5479 (let (beg end status (firstnew 'unknown))
5480 (cond
5481 ((org-region-active-p)
5482 (setq beg (region-beginning) end (region-end)))
5483 ((org-on-heading-p)
5484 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5485 ((org-at-item-checkbox-p)
5486 (let ((pos (point)))
5487 (replace-match
5488 (cond (arg "[-]")
5489 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5490 (t "[ ]"))
5491 t t)
5492 (goto-char pos))
5493 (throw 'exit t))
5494 (t (error "Not at a checkbox or heading, and no active region")))
5495 (save-excursion
5496 (goto-char beg)
5497 (while (< (point) end)
5498 (when (org-at-item-checkbox-p)
5499 (setq status (equal (match-string 0) "[X]"))
5500 (when (eq firstnew 'unknown)
5501 (setq firstnew (not status)))
5502 (replace-match
5503 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5504 (beginning-of-line 2)))))
5505 (org-update-checkbox-count-maybe))
5507 (defun org-update-checkbox-count-maybe ()
5508 "Update checkbox statistics unless turned off by user."
5509 (when org-provide-checkbox-statistics
5510 (org-update-checkbox-count)))
5512 (defun org-update-checkbox-count (&optional all)
5513 "Update the checkbox statistics in the current section.
5514 This will find all statistic cookies like [57%] and [6/12] and update them
5515 with the current numbers. With optional prefix argument ALL, do this for
5516 the whole buffer."
5517 (interactive "P")
5518 (save-excursion
5519 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5520 (beg (condition-case nil
5521 (progn (outline-back-to-heading) (point))
5522 (error (point-min))))
5523 (end (move-marker (make-marker)
5524 (progn (outline-next-heading) (point))))
5525 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5526 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5527 (re-find (concat re "\\|" re-box))
5528 beg-cookie end-cookie is-percent c-on c-off lim
5529 eline curr-ind next-ind continue-from startsearch
5530 (cstat 0)
5532 (when all
5533 (goto-char (point-min))
5534 (outline-next-heading)
5535 (setq beg (point) end (point-max)))
5536 (goto-char end)
5537 ;; find each statistic cookie
5538 (while (re-search-backward re-find beg t)
5539 (setq beg-cookie (match-beginning 1)
5540 end-cookie (match-end 1)
5541 cstat (+ cstat (if end-cookie 1 0))
5542 startsearch (point-at-eol)
5543 continue-from (point-at-bol)
5544 is-percent (match-beginning 2)
5545 lim (cond
5546 ((org-on-heading-p) (outline-next-heading) (point))
5547 ((org-at-item-p) (org-end-of-item) (point))
5548 (t nil))
5549 c-on 0
5550 c-off 0)
5551 (when lim
5552 ;; find first checkbox for this cookie and gather
5553 ;; statistics from all that are at this indentation level
5554 (goto-char startsearch)
5555 (if (re-search-forward re-box lim t)
5556 (progn
5557 (org-beginning-of-item)
5558 (setq curr-ind (org-get-indentation))
5559 (setq next-ind curr-ind)
5560 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5561 (save-excursion (end-of-line) (setq eline (point)))
5562 (if (re-search-forward re-box eline t)
5563 (if (member (match-string 2) '("[ ]" "[-]"))
5564 (setq c-off (1+ c-off))
5565 (setq c-on (1+ c-on))
5568 (org-end-of-item)
5569 (setq next-ind (org-get-indentation))
5571 (goto-char continue-from)
5572 ;; update cookie
5573 (when end-cookie
5574 (delete-region beg-cookie end-cookie)
5575 (goto-char beg-cookie)
5576 (insert
5577 (if is-percent
5578 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5579 (format "[%d/%d]" c-on (+ c-on c-off)))))
5580 ;; update items checkbox if it has one
5581 (when (org-at-item-p)
5582 (org-beginning-of-item)
5583 (when (and (> (+ c-on c-off) 0)
5584 (re-search-forward re-box (point-at-eol) t))
5585 (setq beg-cookie (match-beginning 2)
5586 end-cookie (match-end 2))
5587 (delete-region beg-cookie end-cookie)
5588 (goto-char beg-cookie)
5589 (cond ((= c-off 0) (insert "[X]"))
5590 ((= c-on 0) (insert "[ ]"))
5591 (t (insert "[-]")))
5593 (goto-char continue-from))
5594 (when (interactive-p)
5595 (message "Checkbox satistics updated %s (%d places)"
5596 (if all "in entire file" "in current outline entry") cstat)))))
5598 (defun org-get-checkbox-statistics-face ()
5599 "Select the face for checkbox statistics.
5600 The face will be `org-done' when all relevant boxes are checked. Otherwise
5601 it will be `org-todo'."
5602 (if (match-end 1)
5603 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5604 (if (and (> (match-end 2) (match-beginning 2))
5605 (equal (match-string 2) (match-string 3)))
5606 'org-done
5607 'org-todo)))
5609 (defun org-get-indentation (&optional line)
5610 "Get the indentation of the current line, interpreting tabs.
5611 When LINE is given, assume it represents a line and compute its indentation."
5612 (if line
5613 (if (string-match "^ *" (org-remove-tabs line))
5614 (match-end 0))
5615 (save-excursion
5616 (beginning-of-line 1)
5617 (skip-chars-forward " \t")
5618 (current-column))))
5620 (defun org-remove-tabs (s &optional width)
5621 "Replace tabulators in S with spaces.
5622 Assumes that s is a single line, starting in column 0."
5623 (setq width (or width tab-width))
5624 (while (string-match "\t" s)
5625 (setq s (replace-match
5626 (make-string
5627 (- (* width (/ (+ (match-beginning 0) width) width))
5628 (match-beginning 0)) ?\ )
5629 t t s)))
5632 (defun org-fix-indentation (line ind)
5633 "Fix indentation in LINE.
5634 IND is a cons cell with target and minimum indentation.
5635 If the current indenation in LINE is smaller than the minimum,
5636 leave it alone. If it is larger than ind, set it to the target."
5637 (let* ((l (org-remove-tabs line))
5638 (i (org-get-indentation l))
5639 (i1 (car ind)) (i2 (cdr ind)))
5640 (if (>= i i2) (setq l (substring line i2)))
5641 (if (> i1 0)
5642 (concat (make-string i1 ?\ ) l)
5643 l)))
5645 (defcustom org-empty-line-terminates-plain-lists nil
5646 "Non-nil means, an empty line ends all plain list levels.
5647 When nil, empty lines are part of the preceeding item."
5648 :group 'org-plain-lists
5649 :type 'boolean)
5651 (defun org-beginning-of-item ()
5652 "Go to the beginning of the current hand-formatted item.
5653 If the cursor is not in an item, throw an error."
5654 (interactive)
5655 (let ((pos (point))
5656 (limit (save-excursion
5657 (condition-case nil
5658 (progn
5659 (org-back-to-heading)
5660 (beginning-of-line 2) (point))
5661 (error (point-min)))))
5662 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5663 ind ind1)
5664 (if (org-at-item-p)
5665 (beginning-of-line 1)
5666 (beginning-of-line 1)
5667 (skip-chars-forward " \t")
5668 (setq ind (current-column))
5669 (if (catch 'exit
5670 (while t
5671 (beginning-of-line 0)
5672 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5674 (if (looking-at "[ \t]*$")
5675 (setq ind1 ind-empty)
5676 (skip-chars-forward " \t")
5677 (setq ind1 (current-column)))
5678 (if (< ind1 ind)
5679 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5681 (goto-char pos)
5682 (error "Not in an item")))))
5684 (defun org-end-of-item ()
5685 "Go to the end of the current hand-formatted item.
5686 If the cursor is not in an item, throw an error."
5687 (interactive)
5688 (let* ((pos (point))
5689 ind1
5690 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5691 (limit (save-excursion (outline-next-heading) (point)))
5692 (ind (save-excursion
5693 (org-beginning-of-item)
5694 (skip-chars-forward " \t")
5695 (current-column)))
5696 (end (catch 'exit
5697 (while t
5698 (beginning-of-line 2)
5699 (if (eobp) (throw 'exit (point)))
5700 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5701 (if (looking-at "[ \t]*$")
5702 (setq ind1 ind-empty)
5703 (skip-chars-forward " \t")
5704 (setq ind1 (current-column)))
5705 (if (<= ind1 ind)
5706 (throw 'exit (point-at-bol)))))))
5707 (if end
5708 (goto-char end)
5709 (goto-char pos)
5710 (error "Not in an item"))))
5712 (defun org-next-item ()
5713 "Move to the beginning of the next item in the current plain list.
5714 Error if not at a plain list, or if this is the last item in the list."
5715 (interactive)
5716 (let (ind ind1 (pos (point)))
5717 (org-beginning-of-item)
5718 (setq ind (org-get-indentation))
5719 (org-end-of-item)
5720 (setq ind1 (org-get-indentation))
5721 (unless (and (org-at-item-p) (= ind ind1))
5722 (goto-char pos)
5723 (error "On last item"))))
5725 (defun org-previous-item ()
5726 "Move to the beginning of the previous item in the current plain list.
5727 Error if not at a plain list, or if this is the first item in the list."
5728 (interactive)
5729 (let (beg ind ind1 (pos (point)))
5730 (org-beginning-of-item)
5731 (setq beg (point))
5732 (setq ind (org-get-indentation))
5733 (goto-char beg)
5734 (catch 'exit
5735 (while t
5736 (beginning-of-line 0)
5737 (if (looking-at "[ \t]*$")
5739 (if (<= (setq ind1 (org-get-indentation)) ind)
5740 (throw 'exit t)))))
5741 (condition-case nil
5742 (if (or (not (org-at-item-p))
5743 (< ind1 (1- ind)))
5744 (error "")
5745 (org-beginning-of-item))
5746 (error (goto-char pos)
5747 (error "On first item")))))
5749 (defun org-first-list-item-p ()
5750 "Is this heading the item in a plain list?"
5751 (unless (org-at-item-p)
5752 (error "Not at a plain list item"))
5753 (org-beginning-of-item)
5754 (= (point) (save-excursion (org-beginning-of-item-list))))
5756 (defun org-move-item-down ()
5757 "Move the plain list item at point down, i.e. swap with following item.
5758 Subitems (items with larger indentation) are considered part of the item,
5759 so this really moves item trees."
5760 (interactive)
5761 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5762 (org-beginning-of-item)
5763 (setq beg0 (point))
5764 (save-excursion
5765 (setq ne-beg (org-back-over-empty-lines))
5766 (setq beg (point)))
5767 (goto-char beg0)
5768 (setq ind (org-get-indentation))
5769 (org-end-of-item)
5770 (setq end0 (point))
5771 (setq ind1 (org-get-indentation))
5772 (setq ne-end (org-back-over-empty-lines))
5773 (setq end (point))
5774 (goto-char beg0)
5775 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5776 ;; include less whitespace
5777 (save-excursion
5778 (goto-char beg)
5779 (forward-line (- ne-beg ne-end))
5780 (setq beg (point))))
5781 (goto-char end0)
5782 (if (and (org-at-item-p) (= ind ind1))
5783 (progn
5784 (org-end-of-item)
5785 (org-back-over-empty-lines)
5786 (setq txt (buffer-substring beg end))
5787 (save-excursion
5788 (delete-region beg end))
5789 (setq pos (point))
5790 (insert txt)
5791 (goto-char pos) (org-skip-whitespace)
5792 (org-maybe-renumber-ordered-list))
5793 (goto-char pos)
5794 (error "Cannot move this item further down"))))
5796 (defun org-move-item-up (arg)
5797 "Move the plain list item at point up, i.e. swap with previous item.
5798 Subitems (items with larger indentation) are considered part of the item,
5799 so this really moves item trees."
5800 (interactive "p")
5801 (let (beg beg0 end ind ind1 (pos (point)) txt
5802 ne-beg ne-ins ins-end)
5803 (org-beginning-of-item)
5804 (setq beg0 (point))
5805 (setq ind (org-get-indentation))
5806 (save-excursion
5807 (setq ne-beg (org-back-over-empty-lines))
5808 (setq beg (point)))
5809 (goto-char beg0)
5810 (org-end-of-item)
5811 (setq end (point))
5812 (goto-char beg0)
5813 (catch 'exit
5814 (while t
5815 (beginning-of-line 0)
5816 (if (looking-at "[ \t]*$")
5817 (if org-empty-line-terminates-plain-lists
5818 (progn
5819 (goto-char pos)
5820 (error "Cannot move this item further up"))
5821 nil)
5822 (if (<= (setq ind1 (org-get-indentation)) ind)
5823 (throw 'exit t)))))
5824 (condition-case nil
5825 (org-beginning-of-item)
5826 (error (goto-char beg)
5827 (error "Cannot move this item further up")))
5828 (setq ind1 (org-get-indentation))
5829 (if (and (org-at-item-p) (= ind ind1))
5830 (progn
5831 (setq ne-ins (org-back-over-empty-lines))
5832 (setq txt (buffer-substring beg end))
5833 (save-excursion
5834 (delete-region beg end))
5835 (setq pos (point))
5836 (insert txt)
5837 (setq ins-end (point))
5838 (goto-char pos) (org-skip-whitespace)
5840 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5841 ;; Move whitespace back to beginning
5842 (save-excursion
5843 (goto-char ins-end)
5844 (let ((kill-whole-line t))
5845 (kill-line (- ne-ins ne-beg)) (point)))
5846 (insert (make-string (- ne-ins ne-beg) ?\n)))
5848 (org-maybe-renumber-ordered-list))
5849 (goto-char pos)
5850 (error "Cannot move this item further up"))))
5852 (defun org-maybe-renumber-ordered-list ()
5853 "Renumber the ordered list at point if setup allows it.
5854 This tests the user option `org-auto-renumber-ordered-lists' before
5855 doing the renumbering."
5856 (interactive)
5857 (when (and org-auto-renumber-ordered-lists
5858 (org-at-item-p))
5859 (if (match-beginning 3)
5860 (org-renumber-ordered-list 1)
5861 (org-fix-bullet-type))))
5863 (defun org-maybe-renumber-ordered-list-safe ()
5864 (condition-case nil
5865 (save-excursion
5866 (org-maybe-renumber-ordered-list))
5867 (error nil)))
5869 (defun org-cycle-list-bullet (&optional which)
5870 "Cycle through the different itemize/enumerate bullets.
5871 This cycle the entire list level through the sequence:
5873 `-' -> `+' -> `*' -> `1.' -> `1)'
5875 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5876 0 meand `-', 1 means `+' etc."
5877 (interactive "P")
5878 (org-preserve-lc
5879 (org-beginning-of-item-list)
5880 (org-at-item-p)
5881 (beginning-of-line 1)
5882 (let ((current (match-string 0))
5883 (prevp (eq which 'previous))
5884 new)
5885 (setq new (cond
5886 ((and (numberp which)
5887 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5888 ((string-match "-" current) (if prevp "1)" "+"))
5889 ((string-match "\\+" current)
5890 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5891 ((string-match "\\*" current) (if prevp "+" "1."))
5892 ((string-match "\\." current) (if prevp "*" "1)"))
5893 ((string-match ")" current) (if prevp "1." "-"))
5894 (t (error "This should not happen"))))
5895 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5896 (org-fix-bullet-type)
5897 (org-maybe-renumber-ordered-list))))
5899 (defun org-get-string-indentation (s)
5900 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5901 (let ((n -1) (i 0) (w tab-width) c)
5902 (catch 'exit
5903 (while (< (setq n (1+ n)) (length s))
5904 (setq c (aref s n))
5905 (cond ((= c ?\ ) (setq i (1+ i)))
5906 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5907 (t (throw 'exit t)))))
5910 (defun org-renumber-ordered-list (arg)
5911 "Renumber an ordered plain list.
5912 Cursor needs to be in the first line of an item, the line that starts
5913 with something like \"1.\" or \"2)\"."
5914 (interactive "p")
5915 (unless (and (org-at-item-p)
5916 (match-beginning 3))
5917 (error "This is not an ordered list"))
5918 (let ((line (org-current-line))
5919 (col (current-column))
5920 (ind (org-get-string-indentation
5921 (buffer-substring (point-at-bol) (match-beginning 3))))
5922 ;; (term (substring (match-string 3) -1))
5923 ind1 (n (1- arg))
5924 fmt)
5925 ;; find where this list begins
5926 (org-beginning-of-item-list)
5927 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5928 (setq fmt (concat "%d" (match-string 1)))
5929 (beginning-of-line 0)
5930 ;; walk forward and replace these numbers
5931 (catch 'exit
5932 (while t
5933 (catch 'next
5934 (beginning-of-line 2)
5935 (if (eobp) (throw 'exit nil))
5936 (if (looking-at "[ \t]*$") (throw 'next nil))
5937 (skip-chars-forward " \t") (setq ind1 (current-column))
5938 (if (> ind1 ind) (throw 'next t))
5939 (if (< ind1 ind) (throw 'exit t))
5940 (if (not (org-at-item-p)) (throw 'exit nil))
5941 (delete-region (match-beginning 2) (match-end 2))
5942 (goto-char (match-beginning 2))
5943 (insert (format fmt (setq n (1+ n)))))))
5944 (goto-line line)
5945 (move-to-column col)))
5947 (defun org-fix-bullet-type ()
5948 "Make sure all items in this list have the same bullet as the firsst item."
5949 (interactive)
5950 (unless (org-at-item-p) (error "This is not a list"))
5951 (let ((line (org-current-line))
5952 (col (current-column))
5953 (ind (current-indentation))
5954 ind1 bullet)
5955 ;; find where this list begins
5956 (org-beginning-of-item-list)
5957 (beginning-of-line 1)
5958 ;; find out what the bullet type is
5959 (looking-at "[ \t]*\\(\\S-+\\)")
5960 (setq bullet (match-string 1))
5961 ;; walk forward and replace these numbers
5962 (beginning-of-line 0)
5963 (catch 'exit
5964 (while t
5965 (catch 'next
5966 (beginning-of-line 2)
5967 (if (eobp) (throw 'exit nil))
5968 (if (looking-at "[ \t]*$") (throw 'next nil))
5969 (skip-chars-forward " \t") (setq ind1 (current-column))
5970 (if (> ind1 ind) (throw 'next t))
5971 (if (< ind1 ind) (throw 'exit t))
5972 (if (not (org-at-item-p)) (throw 'exit nil))
5973 (skip-chars-forward " \t")
5974 (looking-at "\\S-+")
5975 (replace-match bullet))))
5976 (goto-line line)
5977 (move-to-column col)
5978 (if (string-match "[0-9]" bullet)
5979 (org-renumber-ordered-list 1))))
5981 (defun org-beginning-of-item-list ()
5982 "Go to the beginning of the current item list.
5983 I.e. to the first item in this list."
5984 (interactive)
5985 (org-beginning-of-item)
5986 (let ((pos (point-at-bol))
5987 (ind (org-get-indentation))
5988 ind1)
5989 ;; find where this list begins
5990 (catch 'exit
5991 (while t
5992 (catch 'next
5993 (beginning-of-line 0)
5994 (if (looking-at "[ \t]*$")
5995 (throw (if (bobp) 'exit 'next) t))
5996 (skip-chars-forward " \t") (setq ind1 (current-column))
5997 (if (or (< ind1 ind)
5998 (and (= ind1 ind)
5999 (not (org-at-item-p)))
6000 (bobp))
6001 (throw 'exit t)
6002 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6003 (goto-char pos)))
6006 (defun org-end-of-item-list ()
6007 "Go to the end of the current item list.
6008 I.e. to the text after the last item."
6009 (interactive)
6010 (org-beginning-of-item)
6011 (let ((pos (point-at-bol))
6012 (ind (org-get-indentation))
6013 ind1)
6014 ;; find where this list begins
6015 (catch 'exit
6016 (while t
6017 (catch 'next
6018 (beginning-of-line 2)
6019 (if (looking-at "[ \t]*$")
6020 (throw (if (eobp) 'exit 'next) t))
6021 (skip-chars-forward " \t") (setq ind1 (current-column))
6022 (if (or (< ind1 ind)
6023 (and (= ind1 ind)
6024 (not (org-at-item-p)))
6025 (eobp))
6026 (progn
6027 (setq pos (point-at-bol))
6028 (throw 'exit t))))))
6029 (goto-char pos)))
6032 (defvar org-last-indent-begin-marker (make-marker))
6033 (defvar org-last-indent-end-marker (make-marker))
6035 (defun org-outdent-item (arg)
6036 "Outdent a local list item."
6037 (interactive "p")
6038 (org-indent-item (- arg)))
6040 (defun org-indent-item (arg)
6041 "Indent a local list item."
6042 (interactive "p")
6043 (unless (org-at-item-p)
6044 (error "Not on an item"))
6045 (save-excursion
6046 (let (beg end ind ind1 tmp delta ind-down ind-up)
6047 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6048 (setq beg org-last-indent-begin-marker
6049 end org-last-indent-end-marker)
6050 (org-beginning-of-item)
6051 (setq beg (move-marker org-last-indent-begin-marker (point)))
6052 (org-end-of-item)
6053 (setq end (move-marker org-last-indent-end-marker (point))))
6054 (goto-char beg)
6055 (setq tmp (org-item-indent-positions)
6056 ind (car tmp)
6057 ind-down (nth 2 tmp)
6058 ind-up (nth 1 tmp)
6059 delta (if (> arg 0)
6060 (if ind-down (- ind-down ind) 2)
6061 (if ind-up (- ind-up ind) -2)))
6062 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6063 (while (< (point) end)
6064 (beginning-of-line 1)
6065 (skip-chars-forward " \t") (setq ind1 (current-column))
6066 (delete-region (point-at-bol) (point))
6067 (or (eolp) (indent-to-column (+ ind1 delta)))
6068 (beginning-of-line 2))))
6069 (org-fix-bullet-type)
6070 (org-maybe-renumber-ordered-list-safe)
6071 (save-excursion
6072 (beginning-of-line 0)
6073 (condition-case nil (org-beginning-of-item) (error nil))
6074 (org-maybe-renumber-ordered-list-safe)))
6076 (defun org-item-indent-positions ()
6077 "Return indentation for plain list items.
6078 This returns a list with three values: The current indentation, the
6079 parent indentation and the indentation a child should habe.
6080 Assumes cursor in item line."
6081 (let* ((bolpos (point-at-bol))
6082 (ind (org-get-indentation))
6083 ind-down ind-up pos)
6084 (save-excursion
6085 (org-beginning-of-item-list)
6086 (skip-chars-backward "\n\r \t")
6087 (when (org-in-item-p)
6088 (org-beginning-of-item)
6089 (setq ind-up (org-get-indentation))))
6090 (setq pos (point))
6091 (save-excursion
6092 (cond
6093 ((and (condition-case nil (progn (org-previous-item) t)
6094 (error nil))
6095 (or (forward-char 1) t)
6096 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6097 (setq ind-down (org-get-indentation)))
6098 ((and (goto-char pos)
6099 (org-at-item-p))
6100 (goto-char (match-end 0))
6101 (skip-chars-forward " \t")
6102 (setq ind-down (current-column)))))
6103 (list ind ind-up ind-down)))
6105 ;;; The orgstruct minor mode
6107 ;; Define a minor mode which can be used in other modes in order to
6108 ;; integrate the org-mode structure editing commands.
6110 ;; This is really a hack, because the org-mode structure commands use
6111 ;; keys which normally belong to the major mode. Here is how it
6112 ;; works: The minor mode defines all the keys necessary to operate the
6113 ;; structure commands, but wraps the commands into a function which
6114 ;; tests if the cursor is currently at a headline or a plain list
6115 ;; item. If that is the case, the structure command is used,
6116 ;; temporarily setting many Org-mode variables like regular
6117 ;; expressions for filling etc. However, when any of those keys is
6118 ;; used at a different location, function uses `key-binding' to look
6119 ;; up if the key has an associated command in another currently active
6120 ;; keymap (minor modes, major mode, global), and executes that
6121 ;; command. There might be problems if any of the keys is otherwise
6122 ;; used as a prefix key.
6124 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6125 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6126 ;; addresses this by checking explicitly for both bindings.
6128 (defvar orgstruct-mode-map (make-sparse-keymap)
6129 "Keymap for the minor `orgstruct-mode'.")
6131 (defvar org-local-vars nil
6132 "List of local variables, for use by `orgstruct-mode'")
6134 ;;;###autoload
6135 (define-minor-mode orgstruct-mode
6136 "Toggle the minor more `orgstruct-mode'.
6137 This mode is for using Org-mode structure commands in other modes.
6138 The following key behave as if Org-mode was active, if the cursor
6139 is on a headline, or on a plain list item (both in the definition
6140 of Org-mode).
6142 M-up Move entry/item up
6143 M-down Move entry/item down
6144 M-left Promote
6145 M-right Demote
6146 M-S-up Move entry/item up
6147 M-S-down Move entry/item down
6148 M-S-left Promote subtree
6149 M-S-right Demote subtree
6150 M-q Fill paragraph and items like in Org-mode
6151 C-c ^ Sort entries
6152 C-c - Cycle list bullet
6153 TAB Cycle item visibility
6154 M-RET Insert new heading/item
6155 S-M-RET Insert new TODO heading / Chekbox item
6156 C-c C-c Set tags / toggle checkbox"
6157 nil " OrgStruct" nil
6158 (org-load-modules-maybe)
6159 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6161 ;;;###autoload
6162 (defun turn-on-orgstruct ()
6163 "Unconditionally turn on `orgstruct-mode'."
6164 (orgstruct-mode 1))
6166 ;;;###autoload
6167 (defun turn-on-orgstruct++ ()
6168 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6169 In addition to setting orgstruct-mode, this also exports all indentation and
6170 autofilling variables from org-mode into the buffer. Note that turning
6171 off orgstruct-mode will *not* remove these additional settings."
6172 (orgstruct-mode 1)
6173 (let (var val)
6174 (mapc
6175 (lambda (x)
6176 (when (string-match
6177 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6178 (symbol-name (car x)))
6179 (setq var (car x) val (nth 1 x))
6180 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6181 org-local-vars)))
6183 (defun orgstruct-error ()
6184 "Error when there is no default binding for a structure key."
6185 (interactive)
6186 (error "This key has no function outside structure elements"))
6188 (defun orgstruct-setup ()
6189 "Setup orgstruct keymaps."
6190 (let ((nfunc 0)
6191 (bindings
6192 (list
6193 '([(meta up)] org-metaup)
6194 '([(meta down)] org-metadown)
6195 '([(meta left)] org-metaleft)
6196 '([(meta right)] org-metaright)
6197 '([(meta shift up)] org-shiftmetaup)
6198 '([(meta shift down)] org-shiftmetadown)
6199 '([(meta shift left)] org-shiftmetaleft)
6200 '([(meta shift right)] org-shiftmetaright)
6201 '([(shift up)] org-shiftup)
6202 '([(shift down)] org-shiftdown)
6203 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6204 '("\M-q" fill-paragraph)
6205 '("\C-c^" org-sort)
6206 '("\C-c-" org-cycle-list-bullet)))
6207 elt key fun cmd)
6208 (while (setq elt (pop bindings))
6209 (setq nfunc (1+ nfunc))
6210 (setq key (org-key (car elt))
6211 fun (nth 1 elt)
6212 cmd (orgstruct-make-binding fun nfunc key))
6213 (org-defkey orgstruct-mode-map key cmd))
6215 ;; Special treatment needed for TAB and RET
6216 (org-defkey orgstruct-mode-map [(tab)]
6217 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6218 (org-defkey orgstruct-mode-map "\C-i"
6219 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6221 (org-defkey orgstruct-mode-map "\M-\C-m"
6222 (orgstruct-make-binding 'org-insert-heading 105
6223 "\M-\C-m" [(meta return)]))
6224 (org-defkey orgstruct-mode-map [(meta return)]
6225 (orgstruct-make-binding 'org-insert-heading 106
6226 [(meta return)] "\M-\C-m"))
6228 (org-defkey orgstruct-mode-map [(shift meta return)]
6229 (orgstruct-make-binding 'org-insert-todo-heading 107
6230 [(meta return)] "\M-\C-m"))
6232 (unless org-local-vars
6233 (setq org-local-vars (org-get-local-variables)))
6237 (defun orgstruct-make-binding (fun n &rest keys)
6238 "Create a function for binding in the structure minor mode.
6239 FUN is the command to call inside a table. N is used to create a unique
6240 command name. KEYS are keys that should be checked in for a command
6241 to execute outside of tables."
6242 (eval
6243 (list 'defun
6244 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6245 '(arg)
6246 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6247 "Outside of structure, run the binding of `"
6248 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6249 "'.")
6250 '(interactive "p")
6251 (list 'if
6252 '(org-context-p 'headline 'item)
6253 (list 'org-run-like-in-org-mode (list 'quote fun))
6254 (list 'let '(orgstruct-mode)
6255 (list 'call-interactively
6256 (append '(or)
6257 (mapcar (lambda (k)
6258 (list 'key-binding k))
6259 keys)
6260 '('orgstruct-error))))))))
6262 (defun org-context-p (&rest contexts)
6263 "Check if local context is and of CONTEXTS.
6264 Possible values in the list of contexts are `table', `headline', and `item'."
6265 (let ((pos (point)))
6266 (goto-char (point-at-bol))
6267 (prog1 (or (and (memq 'table contexts)
6268 (looking-at "[ \t]*|"))
6269 (and (memq 'headline contexts)
6270 (looking-at "\\*+"))
6271 (and (memq 'item contexts)
6272 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6273 (goto-char pos))))
6275 (defun org-get-local-variables ()
6276 "Return a list of all local variables in an org-mode buffer."
6277 (let (varlist)
6278 (with-current-buffer (get-buffer-create "*Org tmp*")
6279 (erase-buffer)
6280 (org-mode)
6281 (setq varlist (buffer-local-variables)))
6282 (kill-buffer "*Org tmp*")
6283 (delq nil
6284 (mapcar
6285 (lambda (x)
6286 (setq x
6287 (if (symbolp x)
6288 (list x)
6289 (list (car x) (list 'quote (cdr x)))))
6290 (if (string-match
6291 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6292 (symbol-name (car x)))
6293 x nil))
6294 varlist))))
6296 ;;;###autoload
6297 (defun org-run-like-in-org-mode (cmd)
6298 (org-load-modules-maybe)
6299 (unless org-local-vars
6300 (setq org-local-vars (org-get-local-variables)))
6301 (eval (list 'let org-local-vars
6302 (list 'call-interactively (list 'quote cmd)))))
6304 ;;;; Archiving
6306 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6308 (defun org-archive-subtree (&optional find-done)
6309 "Move the current subtree to the archive.
6310 The archive can be a certain top-level heading in the current file, or in
6311 a different file. The tree will be moved to that location, the subtree
6312 heading be marked DONE, and the current time will be added.
6314 When called with prefix argument FIND-DONE, find whole trees without any
6315 open TODO items and archive them (after getting confirmation from the user).
6316 If the cursor is not at a headline when this comand is called, try all level
6317 1 trees. If the cursor is on a headline, only try the direct children of
6318 this heading."
6319 (interactive "P")
6320 (if find-done
6321 (org-archive-all-done)
6322 ;; Save all relevant TODO keyword-relatex variables
6324 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6325 (tr-org-todo-keywords-1 org-todo-keywords-1)
6326 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6327 (tr-org-done-keywords org-done-keywords)
6328 (tr-org-todo-regexp org-todo-regexp)
6329 (tr-org-todo-line-regexp org-todo-line-regexp)
6330 (tr-org-odd-levels-only org-odd-levels-only)
6331 (this-buffer (current-buffer))
6332 (org-archive-location org-archive-location)
6333 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6334 ;; start of variables that will be used for saving context
6335 ;; The compiler complains about them - keep them anyway!
6336 (file (abbreviate-file-name (buffer-file-name)))
6337 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
6338 (time (format-time-string
6339 (substring (cdr org-time-stamp-formats) 1 -1)
6340 (current-time)))
6341 afile heading buffer level newfile-p
6342 category todo priority
6343 ;; start of variables that will be used for savind context
6344 ltags itags prop)
6346 ;; Try to find a local archive location
6347 (save-excursion
6348 (save-restriction
6349 (widen)
6350 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
6351 (if (and prop (string-match "\\S-" prop))
6352 (setq org-archive-location prop)
6353 (if (or (re-search-backward re nil t)
6354 (re-search-forward re nil t))
6355 (setq org-archive-location (match-string 1))))))
6357 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6358 (progn
6359 (setq afile (format (match-string 1 org-archive-location)
6360 (file-name-nondirectory buffer-file-name))
6361 heading (match-string 2 org-archive-location)))
6362 (error "Invalid `org-archive-location'"))
6363 (if (> (length afile) 0)
6364 (setq newfile-p (not (file-exists-p afile))
6365 buffer (find-file-noselect afile))
6366 (setq buffer (current-buffer)))
6367 (unless buffer
6368 (error "Cannot access file \"%s\"" afile))
6369 (if (and (> (length heading) 0)
6370 (string-match "^\\*+" heading))
6371 (setq level (match-end 0))
6372 (setq heading nil level 0))
6373 (save-excursion
6374 (org-back-to-heading t)
6375 ;; Get context information that will be lost by moving the tree
6376 (org-refresh-category-properties)
6377 (setq category (org-get-category)
6378 todo (and (looking-at org-todo-line-regexp)
6379 (match-string 2))
6380 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
6381 ltags (org-get-tags)
6382 itags (org-delete-all ltags (org-get-tags-at)))
6383 (setq ltags (mapconcat 'identity ltags " ")
6384 itags (mapconcat 'identity itags " "))
6385 ;; We first only copy, in case something goes wrong
6386 ;; we need to protect this-command, to avoid kill-region sets it,
6387 ;; which would lead to duplication of subtrees
6388 (let (this-command) (org-copy-subtree))
6389 (set-buffer buffer)
6390 ;; Enforce org-mode for the archive buffer
6391 (if (not (org-mode-p))
6392 ;; Force the mode for future visits.
6393 (let ((org-insert-mode-line-in-empty-file t)
6394 (org-inhibit-startup t))
6395 (call-interactively 'org-mode)))
6396 (when newfile-p
6397 (goto-char (point-max))
6398 (insert (format "\nArchived entries from file %s\n\n"
6399 (buffer-file-name this-buffer))))
6400 ;; Force the TODO keywords of the original buffer
6401 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
6402 (org-todo-keywords-1 tr-org-todo-keywords-1)
6403 (org-todo-kwd-alist tr-org-todo-kwd-alist)
6404 (org-done-keywords tr-org-done-keywords)
6405 (org-todo-regexp tr-org-todo-regexp)
6406 (org-todo-line-regexp tr-org-todo-line-regexp)
6407 (org-odd-levels-only
6408 (if (local-variable-p 'org-odd-levels-only (current-buffer))
6409 org-odd-levels-only
6410 tr-org-odd-levels-only)))
6411 (goto-char (point-min))
6412 (show-all)
6413 (if heading
6414 (progn
6415 (if (re-search-forward
6416 (concat "^" (regexp-quote heading)
6417 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
6418 nil t)
6419 (goto-char (match-end 0))
6420 ;; Heading not found, just insert it at the end
6421 (goto-char (point-max))
6422 (or (bolp) (insert "\n"))
6423 (insert "\n" heading "\n")
6424 (end-of-line 0))
6425 ;; Make the subtree visible
6426 (show-subtree)
6427 (org-end-of-subtree t)
6428 (skip-chars-backward " \t\r\n")
6429 (and (looking-at "[ \t\r\n]*")
6430 (replace-match "\n\n")))
6431 ;; No specific heading, just go to end of file.
6432 (goto-char (point-max)) (insert "\n"))
6433 ;; Paste
6434 (org-paste-subtree (org-get-valid-level level 1))
6436 ;; Mark the entry as done
6437 (when (and org-archive-mark-done
6438 (looking-at org-todo-line-regexp)
6439 (or (not (match-end 2))
6440 (not (member (match-string 2) org-done-keywords))))
6441 (let (org-log-done org-todo-log-states)
6442 (org-todo
6443 (car (or (member org-archive-mark-done org-done-keywords)
6444 org-done-keywords)))))
6446 ;; Add the context info
6447 (when org-archive-save-context-info
6448 (let ((l org-archive-save-context-info) e n v)
6449 (while (setq e (pop l))
6450 (when (and (setq v (symbol-value e))
6451 (stringp v) (string-match "\\S-" v))
6452 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
6453 (org-entry-put (point) n v)))))
6455 ;; Save and kill the buffer, if it is not the same buffer.
6456 (if (not (eq this-buffer buffer))
6457 (progn (save-buffer) (kill-buffer buffer)))))
6458 ;; Here we are back in the original buffer. Everything seems to have
6459 ;; worked. So now cut the tree and finish up.
6460 (let (this-command) (org-cut-subtree))
6461 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
6462 (message "Subtree archived %s"
6463 (if (eq this-buffer buffer)
6464 (concat "under heading: " heading)
6465 (concat "in file: " (abbreviate-file-name afile)))))))
6467 (defun org-refresh-category-properties ()
6468 "Refresh category text properties in teh buffer."
6469 (let ((def-cat (cond
6470 ((null org-category)
6471 (if buffer-file-name
6472 (file-name-sans-extension
6473 (file-name-nondirectory buffer-file-name))
6474 "???"))
6475 ((symbolp org-category) (symbol-name org-category))
6476 (t org-category)))
6477 beg end cat pos optionp)
6478 (org-unmodified
6479 (save-excursion
6480 (save-restriction
6481 (widen)
6482 (goto-char (point-min))
6483 (put-text-property (point) (point-max) 'org-category def-cat)
6484 (while (re-search-forward
6485 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6486 (setq pos (match-end 0)
6487 optionp (equal (char-after (match-beginning 0)) ?#)
6488 cat (org-trim (match-string 2)))
6489 (if optionp
6490 (setq beg (point-at-bol) end (point-max))
6491 (org-back-to-heading t)
6492 (setq beg (point) end (org-end-of-subtree t t)))
6493 (put-text-property beg end 'org-category cat)
6494 (goto-char pos)))))))
6496 (defun org-archive-all-done (&optional tag)
6497 "Archive sublevels of the current tree without open TODO items.
6498 If the cursor is not on a headline, try all level 1 trees. If
6499 it is on a headline, try all direct children.
6500 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
6501 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
6502 (rea (concat ".*:" org-archive-tag ":"))
6503 (begm (make-marker))
6504 (endm (make-marker))
6505 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
6506 "Move subtree to archive (no open TODO items)? "))
6507 beg end (cntarch 0))
6508 (if (org-on-heading-p)
6509 (progn
6510 (setq re1 (concat "^" (regexp-quote
6511 (make-string
6512 (1+ (- (match-end 0) (match-beginning 0) 1))
6513 ?*))
6514 " "))
6515 (move-marker begm (point))
6516 (move-marker endm (org-end-of-subtree t)))
6517 (setq re1 "^* ")
6518 (move-marker begm (point-min))
6519 (move-marker endm (point-max)))
6520 (save-excursion
6521 (goto-char begm)
6522 (while (re-search-forward re1 endm t)
6523 (setq beg (match-beginning 0)
6524 end (save-excursion (org-end-of-subtree t) (point)))
6525 (goto-char beg)
6526 (if (re-search-forward re end t)
6527 (goto-char end)
6528 (goto-char beg)
6529 (if (and (or (not tag) (not (looking-at rea)))
6530 (y-or-n-p question))
6531 (progn
6532 (if tag
6533 (org-toggle-tag org-archive-tag 'on)
6534 (org-archive-subtree))
6535 (setq cntarch (1+ cntarch)))
6536 (goto-char end)))))
6537 (message "%d trees archived" cntarch)))
6539 (defun org-cycle-hide-drawers (state)
6540 "Re-hide all drawers after a visibility state change."
6541 (when (and (org-mode-p)
6542 (not (memq state '(overview folded))))
6543 (save-excursion
6544 (let* ((globalp (memq state '(contents all)))
6545 (beg (if globalp (point-min) (point)))
6546 (end (if globalp (point-max) (org-end-of-subtree t))))
6547 (goto-char beg)
6548 (while (re-search-forward org-drawer-regexp end t)
6549 (org-flag-drawer t))))))
6551 (defun org-flag-drawer (flag)
6552 (save-excursion
6553 (beginning-of-line 1)
6554 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6555 (let ((b (match-end 0))
6556 (outline-regexp org-outline-regexp))
6557 (if (re-search-forward
6558 "^[ \t]*:END:"
6559 (save-excursion (outline-next-heading) (point)) t)
6560 (outline-flag-region b (point-at-eol) flag)
6561 (error ":END: line missing"))))))
6563 (defun org-cycle-hide-archived-subtrees (state)
6564 "Re-hide all archived subtrees after a visibility state change."
6565 (when (and (not org-cycle-open-archived-trees)
6566 (not (memq state '(overview folded))))
6567 (save-excursion
6568 (let* ((globalp (memq state '(contents all)))
6569 (beg (if globalp (point-min) (point)))
6570 (end (if globalp (point-max) (org-end-of-subtree t))))
6571 (org-hide-archived-subtrees beg end)
6572 (goto-char beg)
6573 (if (looking-at (concat ".*:" org-archive-tag ":"))
6574 (message "%s" (substitute-command-keys
6575 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
6577 (defun org-force-cycle-archived ()
6578 "Cycle subtree even if it is archived."
6579 (interactive)
6580 (setq this-command 'org-cycle)
6581 (let ((org-cycle-open-archived-trees t))
6582 (call-interactively 'org-cycle)))
6584 (defun org-hide-archived-subtrees (beg end)
6585 "Re-hide all archived subtrees after a visibility state change."
6586 (save-excursion
6587 (let* ((re (concat ":" org-archive-tag ":")))
6588 (goto-char beg)
6589 (while (re-search-forward re end t)
6590 (and (org-on-heading-p) (hide-subtree))
6591 (org-end-of-subtree t)))))
6593 (defun org-toggle-tag (tag &optional onoff)
6594 "Toggle the tag TAG for the current line.
6595 If ONOFF is `on' or `off', don't toggle but set to this state."
6596 (unless (org-on-heading-p t) (error "Not on headling"))
6597 (let (res current)
6598 (save-excursion
6599 (beginning-of-line)
6600 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
6601 (point-at-eol) t)
6602 (progn
6603 (setq current (match-string 1))
6604 (replace-match ""))
6605 (setq current ""))
6606 (setq current (nreverse (org-split-string current ":")))
6607 (cond
6608 ((eq onoff 'on)
6609 (setq res t)
6610 (or (member tag current) (push tag current)))
6611 ((eq onoff 'off)
6612 (or (not (member tag current)) (setq current (delete tag current))))
6613 (t (if (member tag current)
6614 (setq current (delete tag current))
6615 (setq res t)
6616 (push tag current))))
6617 (end-of-line 1)
6618 (if current
6619 (progn
6620 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
6621 (org-set-tags nil t))
6622 (delete-horizontal-space))
6623 (run-hooks 'org-after-tags-change-hook))
6624 res))
6626 (defun org-toggle-archive-tag (&optional arg)
6627 "Toggle the archive tag for the current headline.
6628 With prefix ARG, check all children of current headline and offer tagging
6629 the children that do not contain any open TODO items."
6630 (interactive "P")
6631 (if arg
6632 (org-archive-all-done 'tag)
6633 (let (set)
6634 (save-excursion
6635 (org-back-to-heading t)
6636 (setq set (org-toggle-tag org-archive-tag))
6637 (when set (hide-subtree)))
6638 (and set (beginning-of-line 1))
6639 (message "Subtree %s" (if set "archived" "unarchived")))))
6641 ;;;; Link Stuff
6643 ;;; Link abbreviations
6645 (defun org-link-expand-abbrev (link)
6646 "Apply replacements as defined in `org-link-abbrev-alist."
6647 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6648 (let* ((key (match-string 1 link))
6649 (as (or (assoc key org-link-abbrev-alist-local)
6650 (assoc key org-link-abbrev-alist)))
6651 (tag (and (match-end 2) (match-string 3 link)))
6652 rpl)
6653 (if (not as)
6654 link
6655 (setq rpl (cdr as))
6656 (cond
6657 ((symbolp rpl) (funcall rpl tag))
6658 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6659 (t (concat rpl tag)))))
6660 link))
6662 ;;; Storing and inserting links
6664 (defvar org-insert-link-history nil
6665 "Minibuffer history for links inserted with `org-insert-link'.")
6667 (defvar org-stored-links nil
6668 "Contains the links stored with `org-store-link'.")
6670 (defvar org-store-link-plist nil
6671 "Plist with info about the most recently link created with `org-store-link'.")
6673 (defvar org-link-protocols nil
6674 "Link protocols added to Org-mode using `org-add-link-type'.")
6676 (defvar org-store-link-functions nil
6677 "List of functions that are called to create and store a link.
6678 Each function will be called in turn until one returns a non-nil
6679 value. Each function should check if it is responsible for creating
6680 this link (for example by looking at the major mode).
6681 If not, it must exit and return nil.
6682 If yes, it should return a non-nil value after a calling
6683 `org-store-link-props' with a list of properties and values.
6684 Special properties are:
6686 :type The link prefix. like \"http\". This must be given.
6687 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6688 This is obligatory as well.
6689 :description Optional default description for the second pair
6690 of brackets in an Org-mode link. The user can still change
6691 this when inserting this link into an Org-mode buffer.
6693 In addition to these, any additional properties can be specified
6694 and then used in remember templates.")
6696 (defun org-add-link-type (type &optional follow export)
6697 "Add TYPE to the list of `org-link-types'.
6698 Re-compute all regular expressions depending on `org-link-types'
6700 FOLLOW and EXPORT are two functions.
6702 FOLLOW should take the link path as the single argument and do whatever
6703 is necessary to follow the link, for example find a file or display
6704 a mail message.
6706 EXPORT should format the link path for export to one of the export formats.
6707 It should be a function accepting three arguments:
6709 path the path of the link, the text after the prefix (like \"http:\")
6710 desc the description of the link, if any, nil if there was no descripton
6711 format the export format, a symbol like `html' or `latex'.
6713 The function may use the FORMAT information to return different values
6714 depending on the format. The return value will be put literally into
6715 the exported file.
6716 Org-mode has a built-in default for exporting links. If you are happy with
6717 this default, there is no need to define an export function for the link
6718 type. For a simple example of an export function, see `org-bbdb.el'."
6719 (add-to-list 'org-link-types type t)
6720 (org-make-link-regexps)
6721 (if (assoc type org-link-protocols)
6722 (setcdr (assoc type org-link-protocols) (list follow export))
6723 (push (list type follow export) org-link-protocols)))
6726 ;;;###autoload
6727 (defun org-store-link (arg)
6728 "\\<org-mode-map>Store an org-link to the current location.
6729 This link is added to `org-stored-links' and can later be inserted
6730 into an org-buffer with \\[org-insert-link].
6732 For some link types, a prefix arg is interpreted:
6733 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6734 For file links, arg negates `org-context-in-file-links'."
6735 (interactive "P")
6736 (org-load-modules-maybe)
6737 (setq org-store-link-plist nil) ; reset
6738 (let (link cpltxt desc description search txt)
6739 (cond
6741 ((run-hook-with-args-until-success 'org-store-link-functions)
6742 (setq link (plist-get org-store-link-plist :link)
6743 desc (or (plist-get org-store-link-plist :description) link)))
6745 ((eq major-mode 'calendar-mode)
6746 (let ((cd (calendar-cursor-to-date)))
6747 (setq link
6748 (format-time-string
6749 (car org-time-stamp-formats)
6750 (apply 'encode-time
6751 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6752 nil nil nil))))
6753 (org-store-link-props :type "calendar" :date cd)))
6755 ((eq major-mode 'w3-mode)
6756 (setq cpltxt (url-view-url t)
6757 link (org-make-link cpltxt))
6758 (org-store-link-props :type "w3" :url (url-view-url t)))
6760 ((eq major-mode 'w3m-mode)
6761 (setq cpltxt (or w3m-current-title w3m-current-url)
6762 link (org-make-link w3m-current-url))
6763 (org-store-link-props :type "w3m" :url (url-view-url t)))
6765 ((setq search (run-hook-with-args-until-success
6766 'org-create-file-search-functions))
6767 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6768 "::" search))
6769 (setq cpltxt (or description link)))
6771 ((eq major-mode 'image-mode)
6772 (setq cpltxt (concat "file:"
6773 (abbreviate-file-name buffer-file-name))
6774 link (org-make-link cpltxt))
6775 (org-store-link-props :type "image" :file buffer-file-name))
6777 ((eq major-mode 'dired-mode)
6778 ;; link to the file in the current line
6779 (setq cpltxt (concat "file:"
6780 (abbreviate-file-name
6781 (expand-file-name
6782 (dired-get-filename nil t))))
6783 link (org-make-link cpltxt)))
6785 ((and buffer-file-name (org-mode-p))
6786 ;; Just link to current headline
6787 (setq cpltxt (concat "file:"
6788 (abbreviate-file-name buffer-file-name)))
6789 ;; Add a context search string
6790 (when (org-xor org-context-in-file-links arg)
6791 ;; Check if we are on a target
6792 (if (org-in-regexp "<<\\(.*?\\)>>")
6793 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6794 (setq txt (cond
6795 ((org-on-heading-p) nil)
6796 ((org-region-active-p)
6797 (buffer-substring (region-beginning) (region-end)))
6798 (t (buffer-substring (point-at-bol) (point-at-eol)))))
6799 (when (or (null txt) (string-match "\\S-" txt))
6800 (setq cpltxt
6801 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6802 desc "NONE"))))
6803 (if (string-match "::\\'" cpltxt)
6804 (setq cpltxt (substring cpltxt 0 -2)))
6805 (setq link (org-make-link cpltxt)))
6807 ((buffer-file-name (buffer-base-buffer))
6808 ;; Just link to this file here.
6809 (setq cpltxt (concat "file:"
6810 (abbreviate-file-name
6811 (buffer-file-name (buffer-base-buffer)))))
6812 ;; Add a context string
6813 (when (org-xor org-context-in-file-links arg)
6814 (setq txt (if (org-region-active-p)
6815 (buffer-substring (region-beginning) (region-end))
6816 (buffer-substring (point-at-bol) (point-at-eol))))
6817 ;; Only use search option if there is some text.
6818 (when (string-match "\\S-" txt)
6819 (setq cpltxt
6820 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6821 desc "NONE")))
6822 (setq link (org-make-link cpltxt)))
6824 ((interactive-p)
6825 (error "Cannot link to a buffer which is not visiting a file"))
6827 (t (setq link nil)))
6829 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6830 (setq link (or link cpltxt)
6831 desc (or desc cpltxt))
6832 (if (equal desc "NONE") (setq desc nil))
6834 (if (and (interactive-p) link)
6835 (progn
6836 (setq org-stored-links
6837 (cons (list link desc) org-stored-links))
6838 (message "Stored: %s" (or desc link)))
6839 (and link (org-make-link-string link desc)))))
6841 (defun org-store-link-props (&rest plist)
6842 "Store link properties, extract names and addresses."
6843 (let (x adr)
6844 (when (setq x (plist-get plist :from))
6845 (setq adr (mail-extract-address-components x))
6846 (plist-put plist :fromname (car adr))
6847 (plist-put plist :fromaddress (nth 1 adr)))
6848 (when (setq x (plist-get plist :to))
6849 (setq adr (mail-extract-address-components x))
6850 (plist-put plist :toname (car adr))
6851 (plist-put plist :toaddress (nth 1 adr))))
6852 (let ((from (plist-get plist :from))
6853 (to (plist-get plist :to)))
6854 (when (and from to org-from-is-user-regexp)
6855 (plist-put plist :fromto
6856 (if (string-match org-from-is-user-regexp from)
6857 (concat "to %t")
6858 (concat "from %f")))))
6859 (setq org-store-link-plist plist))
6861 (defun org-add-link-props (&rest plist)
6862 "Add these properties to the link property list."
6863 (let (key value)
6864 (while plist
6865 (setq key (pop plist) value (pop plist))
6866 (setq org-store-link-plist
6867 (plist-put org-store-link-plist key value)))))
6869 (defun org-email-link-description (&optional fmt)
6870 "Return the description part of an email link.
6871 This takes information from `org-store-link-plist' and formats it
6872 according to FMT (default from `org-email-link-description-format')."
6873 (setq fmt (or fmt org-email-link-description-format))
6874 (let* ((p org-store-link-plist)
6875 (to (plist-get p :toaddress))
6876 (from (plist-get p :fromaddress))
6877 (table
6878 (list
6879 (cons "%c" (plist-get p :fromto))
6880 (cons "%F" (plist-get p :from))
6881 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6882 (cons "%T" (plist-get p :to))
6883 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6884 (cons "%s" (plist-get p :subject))
6885 (cons "%m" (plist-get p :message-id)))))
6886 (when (string-match "%c" fmt)
6887 ;; Check if the user wrote this message
6888 (if (and org-from-is-user-regexp from to
6889 (save-match-data (string-match org-from-is-user-regexp from)))
6890 (setq fmt (replace-match "to %t" t t fmt))
6891 (setq fmt (replace-match "from %f" t t fmt))))
6892 (org-replace-escapes fmt table)))
6894 (defun org-make-org-heading-search-string (&optional string heading)
6895 "Make search string for STRING or current headline."
6896 (interactive)
6897 (let ((s (or string (org-get-heading))))
6898 (unless (and string (not heading))
6899 ;; We are using a headline, clean up garbage in there.
6900 (if (string-match org-todo-regexp s)
6901 (setq s (replace-match "" t t s)))
6902 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6903 (setq s (replace-match "" t t s)))
6904 (setq s (org-trim s))
6905 (if (string-match (concat "^\\(" org-quote-string "\\|"
6906 org-comment-string "\\)") s)
6907 (setq s (replace-match "" t t s)))
6908 (while (string-match org-ts-regexp s)
6909 (setq s (replace-match "" t t s))))
6910 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6911 (setq s (replace-match " " t t s)))
6912 (or string (setq s (concat "*" s))) ; Add * for headlines
6913 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6915 (defun org-make-link (&rest strings)
6916 "Concatenate STRINGS."
6917 (apply 'concat strings))
6919 (defun org-make-link-string (link &optional description)
6920 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6921 (unless (string-match "\\S-" link)
6922 (error "Empty link"))
6923 (when (stringp description)
6924 ;; Remove brackets from the description, they are fatal.
6925 (while (string-match "\\[" description)
6926 (setq description (replace-match "{" t t description)))
6927 (while (string-match "\\]" description)
6928 (setq description (replace-match "}" t t description))))
6929 (when (equal (org-link-escape link) description)
6930 ;; No description needed, it is identical
6931 (setq description nil))
6932 (when (and (not description)
6933 (not (equal link (org-link-escape link))))
6934 (setq description link))
6935 (concat "[[" (org-link-escape link) "]"
6936 (if description (concat "[" description "]") "")
6937 "]"))
6939 (defconst org-link-escape-chars
6940 '((?\ . "%20")
6941 (?\[ . "%5B")
6942 (?\] . "%5D")
6943 (?\340 . "%E0") ; `a
6944 (?\342 . "%E2") ; ^a
6945 (?\347 . "%E7") ; ,c
6946 (?\350 . "%E8") ; `e
6947 (?\351 . "%E9") ; 'e
6948 (?\352 . "%EA") ; ^e
6949 (?\356 . "%EE") ; ^i
6950 (?\364 . "%F4") ; ^o
6951 (?\371 . "%F9") ; `u
6952 (?\373 . "%FB") ; ^u
6953 (?\; . "%3B")
6954 (?? . "%3F")
6955 (?= . "%3D")
6956 (?+ . "%2B")
6958 "Association list of escapes for some characters problematic in links.
6959 This is the list that is used for internal purposes.")
6961 (defconst org-link-escape-chars-browser
6962 '((?\ . "%20")) ; 32 for the SPC char
6963 "Association list of escapes for some characters problematic in links.
6964 This is the list that is used before handing over to the browser.")
6966 (defun org-link-escape (text &optional table)
6967 "Escape charaters in TEXT that are problematic for links."
6968 (setq table (or table org-link-escape-chars))
6969 (when text
6970 (let ((re (mapconcat (lambda (x) (regexp-quote
6971 (char-to-string (car x))))
6972 table "\\|")))
6973 (while (string-match re text)
6974 (setq text
6975 (replace-match
6976 (cdr (assoc (string-to-char (match-string 0 text))
6977 table))
6978 t t text)))
6979 text)))
6981 (defun org-link-unescape (text &optional table)
6982 "Reverse the action of `org-link-escape'."
6983 (setq table (or table org-link-escape-chars))
6984 (when text
6985 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6986 table "\\|")))
6987 (while (string-match re text)
6988 (setq text
6989 (replace-match
6990 (char-to-string (car (rassoc (match-string 0 text) table)))
6991 t t text)))
6992 text)))
6994 (defun org-xor (a b)
6995 "Exclusive or."
6996 (if a (not b) b))
6998 (defun org-get-header (header)
6999 "Find a header field in the current buffer."
7000 (save-excursion
7001 (goto-char (point-min))
7002 (let ((case-fold-search t) s)
7003 (cond
7004 ((eq header 'from)
7005 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7006 (setq s (match-string 1)))
7007 (while (string-match "\"" s)
7008 (setq s (replace-match "" t t s)))
7009 (if (string-match "[<(].*" s)
7010 (setq s (replace-match "" t t s))))
7011 ((eq header 'message-id)
7012 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7013 (setq s (match-string 1))))
7014 ((eq header 'subject)
7015 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7016 (setq s (match-string 1)))))
7017 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7018 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7019 s)))
7022 (defun org-fixup-message-id-for-http (s)
7023 "Replace special characters in a message id, so it can be used in an http query."
7024 (while (string-match "<" s)
7025 (setq s (replace-match "%3C" t t s)))
7026 (while (string-match ">" s)
7027 (setq s (replace-match "%3E" t t s)))
7028 (while (string-match "@" s)
7029 (setq s (replace-match "%40" t t s)))
7032 ;;;###autoload
7033 (defun org-insert-link-global ()
7034 "Insert a link like Org-mode does.
7035 This command can be called in any mode to insert a link in Org-mode syntax."
7036 (interactive)
7037 (org-load-modules-maybe)
7038 (org-run-like-in-org-mode 'org-insert-link))
7040 (defun org-insert-link (&optional complete-file)
7041 "Insert a link. At the prompt, enter the link.
7043 Completion can be used to select a link previously stored with
7044 `org-store-link'. When the empty string is entered (i.e. if you just
7045 press RET at the prompt), the link defaults to the most recently
7046 stored link. As SPC triggers completion in the minibuffer, you need to
7047 use M-SPC or C-q SPC to force the insertion of a space character.
7049 You will also be prompted for a description, and if one is given, it will
7050 be displayed in the buffer instead of the link.
7052 If there is already a link at point, this command will allow you to edit link
7053 and description parts.
7055 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7056 selected using completion. The path to the file will be relative to
7057 the current directory if the file is in the current directory or a
7058 subdirectory. Otherwise, the link will be the absolute path as
7059 completed in the minibuffer (i.e. normally ~/path/to/file).
7061 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7062 is in the current directory or below.
7063 With three \\[universal-argument] prefixes, negate the meaning of
7064 `org-keep-stored-link-after-insertion'."
7065 (interactive "P")
7066 (let* ((wcf (current-window-configuration))
7067 (region (if (org-region-active-p)
7068 (buffer-substring (region-beginning) (region-end))))
7069 (remove (and region (list (region-beginning) (region-end))))
7070 (desc region)
7071 tmphist ; byte-compile incorrectly complains about this
7072 link entry file)
7073 (cond
7074 ((org-in-regexp org-bracket-link-regexp 1)
7075 ;; We do have a link at point, and we are going to edit it.
7076 (setq remove (list (match-beginning 0) (match-end 0)))
7077 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7078 (setq link (read-string "Link: "
7079 (org-link-unescape
7080 (org-match-string-no-properties 1)))))
7081 ((or (org-in-regexp org-angle-link-re)
7082 (org-in-regexp org-plain-link-re))
7083 ;; Convert to bracket link
7084 (setq remove (list (match-beginning 0) (match-end 0))
7085 link (read-string "Link: "
7086 (org-remove-angle-brackets (match-string 0)))))
7087 ((equal complete-file '(4))
7088 ;; Completing read for file names.
7089 (setq file (read-file-name "File: "))
7090 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7091 (pwd1 (file-name-as-directory (abbreviate-file-name
7092 (expand-file-name ".")))))
7093 (cond
7094 ((equal complete-file '(16))
7095 (setq link (org-make-link
7096 "file:"
7097 (abbreviate-file-name (expand-file-name file)))))
7098 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7099 (setq link (org-make-link "file:" (match-string 1 file))))
7100 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7101 (expand-file-name file))
7102 (setq link (org-make-link
7103 "file:" (match-string 1 (expand-file-name file)))))
7104 (t (setq link (org-make-link "file:" file))))))
7106 ;; Read link, with completion for stored links.
7107 (with-output-to-temp-buffer "*Org Links*"
7108 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7109 (when org-stored-links
7110 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7111 (princ (mapconcat
7112 (lambda (x)
7113 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7114 (reverse org-stored-links) "\n"))))
7115 (let ((cw (selected-window)))
7116 (select-window (get-buffer-window "*Org Links*"))
7117 (shrink-window-if-larger-than-buffer)
7118 (setq truncate-lines t)
7119 (select-window cw))
7120 ;; Fake a link history, containing the stored links.
7121 (setq tmphist (append (mapcar 'car org-stored-links)
7122 org-insert-link-history))
7123 (unwind-protect
7124 (setq link (org-completing-read
7125 "Link: "
7126 (append
7127 (mapcar (lambda (x) (list (concat (car x) ":")))
7128 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7129 (mapcar (lambda (x) (list (concat x ":")))
7130 org-link-types))
7131 nil nil nil
7132 'tmphist
7133 (or (car (car org-stored-links)))))
7134 (set-window-configuration wcf)
7135 (kill-buffer "*Org Links*"))
7136 (setq entry (assoc link org-stored-links))
7137 (or entry (push link org-insert-link-history))
7138 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7139 (not org-keep-stored-link-after-insertion))
7140 (setq org-stored-links (delq (assoc link org-stored-links)
7141 org-stored-links)))
7142 (setq desc (or desc (nth 1 entry)))))
7144 (if (string-match org-plain-link-re link)
7145 ;; URL-like link, normalize the use of angular brackets.
7146 (setq link (org-make-link (org-remove-angle-brackets link))))
7148 ;; Check if we are linking to the current file with a search option
7149 ;; If yes, simplify the link by using only the search option.
7150 (when (and buffer-file-name
7151 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
7152 (let* ((path (match-string 1 link))
7153 (case-fold-search nil)
7154 (search (match-string 2 link)))
7155 (save-match-data
7156 (if (equal (file-truename buffer-file-name) (file-truename path))
7157 ;; We are linking to this same file, with a search option
7158 (setq link search)))))
7160 ;; Check if we can/should use a relative path. If yes, simplify the link
7161 (when (string-match "\\<file:\\(.*\\)" link)
7162 (let* ((path (match-string 1 link))
7163 (origpath path)
7164 (case-fold-search nil))
7165 (cond
7166 ((eq org-link-file-path-type 'absolute)
7167 (setq path (abbreviate-file-name (expand-file-name path))))
7168 ((eq org-link-file-path-type 'noabbrev)
7169 (setq path (expand-file-name path)))
7170 ((eq org-link-file-path-type 'relative)
7171 (setq path (file-relative-name path)))
7173 (save-match-data
7174 (if (string-match (concat "^" (regexp-quote
7175 (file-name-as-directory
7176 (expand-file-name "."))))
7177 (expand-file-name path))
7178 ;; We are linking a file with relative path name.
7179 (setq path (substring (expand-file-name path)
7180 (match-end 0)))))))
7181 (setq link (concat "file:" path))
7182 (if (equal desc origpath)
7183 (setq desc path))))
7185 (setq desc (read-string "Description: " desc))
7186 (unless (string-match "\\S-" desc) (setq desc nil))
7187 (if remove (apply 'delete-region remove))
7188 (insert (org-make-link-string link desc))))
7190 (defun org-completing-read (&rest args)
7191 (let ((minibuffer-local-completion-map
7192 (copy-keymap minibuffer-local-completion-map)))
7193 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7194 (apply 'completing-read args)))
7196 ;;; Opening/following a link
7197 (defvar org-link-search-failed nil)
7199 (defun org-next-link ()
7200 "Move forward to the next link.
7201 If the link is in hidden text, expose it."
7202 (interactive)
7203 (when (and org-link-search-failed (eq this-command last-command))
7204 (goto-char (point-min))
7205 (message "Link search wrapped back to beginning of buffer"))
7206 (setq org-link-search-failed nil)
7207 (let* ((pos (point))
7208 (ct (org-context))
7209 (a (assoc :link ct)))
7210 (if a (goto-char (nth 2 a)))
7211 (if (re-search-forward org-any-link-re nil t)
7212 (progn
7213 (goto-char (match-beginning 0))
7214 (if (org-invisible-p) (org-show-context)))
7215 (goto-char pos)
7216 (setq org-link-search-failed t)
7217 (error "No further link found"))))
7219 (defun org-previous-link ()
7220 "Move backward to the previous link.
7221 If the link is in hidden text, expose it."
7222 (interactive)
7223 (when (and org-link-search-failed (eq this-command last-command))
7224 (goto-char (point-max))
7225 (message "Link search wrapped back to end of buffer"))
7226 (setq org-link-search-failed nil)
7227 (let* ((pos (point))
7228 (ct (org-context))
7229 (a (assoc :link ct)))
7230 (if a (goto-char (nth 1 a)))
7231 (if (re-search-backward org-any-link-re nil t)
7232 (progn
7233 (goto-char (match-beginning 0))
7234 (if (org-invisible-p) (org-show-context)))
7235 (goto-char pos)
7236 (setq org-link-search-failed t)
7237 (error "No further link found"))))
7239 (defun org-find-file-at-mouse (ev)
7240 "Open file link or URL at mouse."
7241 (interactive "e")
7242 (mouse-set-point ev)
7243 (org-open-at-point 'in-emacs))
7245 (defun org-open-at-mouse (ev)
7246 "Open file link or URL at mouse."
7247 (interactive "e")
7248 (mouse-set-point ev)
7249 (org-open-at-point))
7251 (defvar org-window-config-before-follow-link nil
7252 "The window configuration before following a link.
7253 This is saved in case the need arises to restore it.")
7255 (defvar org-open-link-marker (make-marker)
7256 "Marker pointing to the location where `org-open-at-point; was called.")
7258 ;;;###autoload
7259 (defun org-open-at-point-global ()
7260 "Follow a link like Org-mode does.
7261 This command can be called in any mode to follow a link that has
7262 Org-mode syntax."
7263 (interactive)
7264 (org-run-like-in-org-mode 'org-open-at-point))
7266 (defun org-open-at-point (&optional in-emacs)
7267 "Open link at or after point.
7268 If there is no link at point, this function will search forward up to
7269 the end of the current subtree.
7270 Normally, files will be opened by an appropriate application. If the
7271 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7272 (interactive "P")
7273 (org-load-modules-maybe)
7274 (move-marker org-open-link-marker (point))
7275 (setq org-window-config-before-follow-link (current-window-configuration))
7276 (org-remove-occur-highlights nil nil t)
7277 (if (org-at-timestamp-p t)
7278 (org-follow-timestamp-link)
7279 (let (type path link line search (pos (point)))
7280 (catch 'match
7281 (save-excursion
7282 (skip-chars-forward "^]\n\r")
7283 (when (org-in-regexp org-bracket-link-regexp)
7284 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7285 (while (string-match " *\n *" link)
7286 (setq link (replace-match " " t t link)))
7287 (setq link (org-link-expand-abbrev link))
7288 (if (string-match org-link-re-with-space2 link)
7289 (setq type (match-string 1 link) path (match-string 2 link))
7290 (setq type "thisfile" path link))
7291 (throw 'match t)))
7293 (when (get-text-property (point) 'org-linked-text)
7294 (setq type "thisfile"
7295 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7296 (1+ (point)) (point))
7297 path (buffer-substring
7298 (previous-single-property-change pos 'org-linked-text)
7299 (next-single-property-change pos 'org-linked-text)))
7300 (throw 'match t))
7302 (save-excursion
7303 (when (or (org-in-regexp org-angle-link-re)
7304 (org-in-regexp org-plain-link-re))
7305 (setq type (match-string 1) path (match-string 2))
7306 (throw 'match t)))
7307 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7308 (setq type "tree-match"
7309 path (match-string 1))
7310 (throw 'match t))
7311 (save-excursion
7312 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7313 (setq type "tags"
7314 path (match-string 1))
7315 (while (string-match ":" path)
7316 (setq path (replace-match "+" t t path)))
7317 (throw 'match t))))
7318 (unless path
7319 (error "No link found"))
7320 ;; Remove any trailing spaces in path
7321 (if (string-match " +\\'" path)
7322 (setq path (replace-match "" t t path)))
7324 (cond
7326 ((assoc type org-link-protocols)
7327 (funcall (nth 1 (assoc type org-link-protocols)) path))
7329 ((equal type "mailto")
7330 (let ((cmd (car org-link-mailto-program))
7331 (args (cdr org-link-mailto-program)) args1
7332 (address path) (subject "") a)
7333 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7334 (setq address (match-string 1 path)
7335 subject (org-link-escape (match-string 2 path))))
7336 (while args
7337 (cond
7338 ((not (stringp (car args))) (push (pop args) args1))
7339 (t (setq a (pop args))
7340 (if (string-match "%a" a)
7341 (setq a (replace-match address t t a)))
7342 (if (string-match "%s" a)
7343 (setq a (replace-match subject t t a)))
7344 (push a args1))))
7345 (apply cmd (nreverse args1))))
7347 ((member type '("http" "https" "ftp" "news"))
7348 (browse-url (concat type ":" (org-link-escape
7349 path org-link-escape-chars-browser))))
7351 ((member type '("message"))
7352 (browse-url (concat type ":" path)))
7354 ((string= type "tags")
7355 (org-tags-view in-emacs path))
7356 ((string= type "thisfile")
7357 (if in-emacs
7358 (switch-to-buffer-other-window
7359 (org-get-buffer-for-internal-link (current-buffer)))
7360 (org-mark-ring-push))
7361 (let ((cmd `(org-link-search
7362 ,path
7363 ,(cond ((equal in-emacs '(4)) 'occur)
7364 ((equal in-emacs '(16)) 'org-occur)
7365 (t nil))
7366 ,pos)))
7367 (condition-case nil (eval cmd)
7368 (error (progn (widen) (eval cmd))))))
7370 ((string= type "tree-match")
7371 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7373 ((string= type "file")
7374 (if (string-match "::\\([0-9]+\\)\\'" path)
7375 (setq line (string-to-number (match-string 1 path))
7376 path (substring path 0 (match-beginning 0)))
7377 (if (string-match "::\\(.+\\)\\'" path)
7378 (setq search (match-string 1 path)
7379 path (substring path 0 (match-beginning 0)))))
7380 (if (string-match "[*?{]" (file-name-nondirectory path))
7381 (dired path)
7382 (org-open-file path in-emacs line search)))
7384 ((string= type "news")
7385 (require 'org-gnus)
7386 (org-gnus-follow-link path))
7388 ((string= type "shell")
7389 (let ((cmd path))
7390 (if (or (not org-confirm-shell-link-function)
7391 (funcall org-confirm-shell-link-function
7392 (format "Execute \"%s\" in shell? "
7393 (org-add-props cmd nil
7394 'face 'org-warning))))
7395 (progn
7396 (message "Executing %s" cmd)
7397 (shell-command cmd))
7398 (error "Abort"))))
7400 ((string= type "elisp")
7401 (let ((cmd path))
7402 (if (or (not org-confirm-elisp-link-function)
7403 (funcall org-confirm-elisp-link-function
7404 (format "Execute \"%s\" as elisp? "
7405 (org-add-props cmd nil
7406 'face 'org-warning))))
7407 (message "%s => %s" cmd (eval (read cmd)))
7408 (error "Abort"))))
7411 (browse-url-at-point)))))
7412 (move-marker org-open-link-marker nil)
7413 (run-hook-with-args 'org-follow-link-hook))
7415 ;;; File search
7417 (defvar org-create-file-search-functions nil
7418 "List of functions to construct the right search string for a file link.
7419 These functions are called in turn with point at the location to
7420 which the link should point.
7422 A function in the hook should first test if it would like to
7423 handle this file type, for example by checking the major-mode or
7424 the file extension. If it decides not to handle this file, it
7425 should just return nil to give other functions a chance. If it
7426 does handle the file, it must return the search string to be used
7427 when following the link. The search string will be part of the
7428 file link, given after a double colon, and `org-open-at-point'
7429 will automatically search for it. If special measures must be
7430 taken to make the search successful, another function should be
7431 added to the companion hook `org-execute-file-search-functions',
7432 which see.
7434 A function in this hook may also use `setq' to set the variable
7435 `description' to provide a suggestion for the descriptive text to
7436 be used for this link when it gets inserted into an Org-mode
7437 buffer with \\[org-insert-link].")
7439 (defvar org-execute-file-search-functions nil
7440 "List of functions to execute a file search triggered by a link.
7442 Functions added to this hook must accept a single argument, the
7443 search string that was part of the file link, the part after the
7444 double colon. The function must first check if it would like to
7445 handle this search, for example by checking the major-mode or the
7446 file extension. If it decides not to handle this search, it
7447 should just return nil to give other functions a chance. If it
7448 does handle the search, it must return a non-nil value to keep
7449 other functions from trying.
7451 Each function can access the current prefix argument through the
7452 variable `current-prefix-argument'. Note that a single prefix is
7453 used to force opening a link in Emacs, so it may be good to only
7454 use a numeric or double prefix to guide the search function.
7456 In case this is needed, a function in this hook can also restore
7457 the window configuration before `org-open-at-point' was called using:
7459 (set-window-configuration org-window-config-before-follow-link)")
7461 (defun org-link-search (s &optional type avoid-pos)
7462 "Search for a link search option.
7463 If S is surrounded by forward slashes, it is interpreted as a
7464 regular expression. In org-mode files, this will create an `org-occur'
7465 sparse tree. In ordinary files, `occur' will be used to list matches.
7466 If the current buffer is in `dired-mode', grep will be used to search
7467 in all files. If AVOID-POS is given, ignore matches near that position."
7468 (let ((case-fold-search t)
7469 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7470 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7471 (append '(("") (" ") ("\t") ("\n"))
7472 org-emphasis-alist)
7473 "\\|") "\\)"))
7474 (pos (point))
7475 (pre "") (post "")
7476 words re0 re1 re2 re3 re4 re5 re2a reall)
7477 (cond
7478 ;; First check if there are any special
7479 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7480 ;; Now try the builtin stuff
7481 ((save-excursion
7482 (goto-char (point-min))
7483 (and
7484 (re-search-forward
7485 (concat "<<" (regexp-quote s0) ">>") nil t)
7486 (setq pos (match-beginning 0))))
7487 ;; There is an exact target for this
7488 (goto-char pos))
7489 ((string-match "^/\\(.*\\)/$" s)
7490 ;; A regular expression
7491 (cond
7492 ((org-mode-p)
7493 (org-occur (match-string 1 s)))
7494 ;;((eq major-mode 'dired-mode)
7495 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7496 (t (org-do-occur (match-string 1 s)))))
7498 ;; A normal search strings
7499 (when (equal (string-to-char s) ?*)
7500 ;; Anchor on headlines, post may include tags.
7501 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7502 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7503 s (substring s 1)))
7504 (remove-text-properties
7505 0 (length s)
7506 '(face nil mouse-face nil keymap nil fontified nil) s)
7507 ;; Make a series of regular expressions to find a match
7508 (setq words (org-split-string s "[ \n\r\t]+")
7509 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7510 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7511 "\\)" markers)
7512 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7513 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7514 re1 (concat pre re2 post)
7515 re3 (concat pre re4 post)
7516 re5 (concat pre ".*" re4)
7517 re2 (concat pre re2)
7518 re2a (concat pre re2a)
7519 re4 (concat pre re4)
7520 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7521 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7522 re5 "\\)"
7524 (cond
7525 ((eq type 'org-occur) (org-occur reall))
7526 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7527 (t (goto-char (point-min))
7528 (if (or (org-search-not-self 1 re0 nil t)
7529 (org-search-not-self 1 re1 nil t)
7530 (org-search-not-self 1 re2 nil t)
7531 (org-search-not-self 1 re2a nil t)
7532 (org-search-not-self 1 re3 nil t)
7533 (org-search-not-self 1 re4 nil t)
7534 (org-search-not-self 1 re5 nil t)
7536 (goto-char (match-beginning 1))
7537 (goto-char pos)
7538 (error "No match")))))
7540 ;; Normal string-search
7541 (goto-char (point-min))
7542 (if (search-forward s nil t)
7543 (goto-char (match-beginning 0))
7544 (error "No match"))))
7545 (and (org-mode-p) (org-show-context 'link-search))))
7547 (defun org-search-not-self (group &rest args)
7548 "Execute `re-search-forward', but only accept matches that do not
7549 enclose the position of `org-open-link-marker'."
7550 (let ((m org-open-link-marker))
7551 (catch 'exit
7552 (while (apply 're-search-forward args)
7553 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7554 (goto-char (match-end group))
7555 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7556 (> (match-beginning 0) (marker-position m))
7557 (< (match-end 0) (marker-position m)))
7558 (save-match-data
7559 (or (not (org-in-regexp
7560 org-bracket-link-analytic-regexp 1))
7561 (not (match-end 4)) ; no description
7562 (and (<= (match-beginning 4) (point))
7563 (>= (match-end 4) (point))))))
7564 (throw 'exit (point))))))))
7566 (defun org-get-buffer-for-internal-link (buffer)
7567 "Return a buffer to be used for displaying the link target of internal links."
7568 (cond
7569 ((not org-display-internal-link-with-indirect-buffer)
7570 buffer)
7571 ((string-match "(Clone)$" (buffer-name buffer))
7572 (message "Buffer is already a clone, not making another one")
7573 ;; we also do not modify visibility in this case
7574 buffer)
7575 (t ; make a new indirect buffer for displaying the link
7576 (let* ((bn (buffer-name buffer))
7577 (ibn (concat bn "(Clone)"))
7578 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7579 (with-current-buffer ib (org-overview))
7580 ib))))
7582 (defun org-do-occur (regexp &optional cleanup)
7583 "Call the Emacs command `occur'.
7584 If CLEANUP is non-nil, remove the printout of the regular expression
7585 in the *Occur* buffer. This is useful if the regex is long and not useful
7586 to read."
7587 (occur regexp)
7588 (when cleanup
7589 (let ((cwin (selected-window)) win beg end)
7590 (when (setq win (get-buffer-window "*Occur*"))
7591 (select-window win))
7592 (goto-char (point-min))
7593 (when (re-search-forward "match[a-z]+" nil t)
7594 (setq beg (match-end 0))
7595 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7596 (setq end (1- (match-beginning 0)))))
7597 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7598 (goto-char (point-min))
7599 (select-window cwin))))
7601 ;;; The mark ring for links jumps
7603 (defvar org-mark-ring nil
7604 "Mark ring for positions before jumps in Org-mode.")
7605 (defvar org-mark-ring-last-goto nil
7606 "Last position in the mark ring used to go back.")
7607 ;; Fill and close the ring
7608 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7609 (loop for i from 1 to org-mark-ring-length do
7610 (push (make-marker) org-mark-ring))
7611 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7612 org-mark-ring)
7614 (defun org-mark-ring-push (&optional pos buffer)
7615 "Put the current position or POS into the mark ring and rotate it."
7616 (interactive)
7617 (setq pos (or pos (point)))
7618 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7619 (move-marker (car org-mark-ring)
7620 (or pos (point))
7621 (or buffer (current-buffer)))
7622 (message "%s"
7623 (substitute-command-keys
7624 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7626 (defun org-mark-ring-goto (&optional n)
7627 "Jump to the previous position in the mark ring.
7628 With prefix arg N, jump back that many stored positions. When
7629 called several times in succession, walk through the entire ring.
7630 Org-mode commands jumping to a different position in the current file,
7631 or to another Org-mode file, automatically push the old position
7632 onto the ring."
7633 (interactive "p")
7634 (let (p m)
7635 (if (eq last-command this-command)
7636 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7637 (setq p org-mark-ring))
7638 (setq org-mark-ring-last-goto p)
7639 (setq m (car p))
7640 (switch-to-buffer (marker-buffer m))
7641 (goto-char m)
7642 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7644 (defun org-remove-angle-brackets (s)
7645 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7646 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7648 (defun org-add-angle-brackets (s)
7649 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7650 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7653 ;;; Following specific links
7655 (defun org-follow-timestamp-link ()
7656 (cond
7657 ((org-at-date-range-p t)
7658 (let ((org-agenda-start-on-weekday)
7659 (t1 (match-string 1))
7660 (t2 (match-string 2)))
7661 (setq t1 (time-to-days (org-time-string-to-time t1))
7662 t2 (time-to-days (org-time-string-to-time t2)))
7663 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7664 ((org-at-timestamp-p t)
7665 (org-agenda-list nil (time-to-days (org-time-string-to-time
7666 (substring (match-string 1) 0 10)))
7668 (t (error "This should not happen"))))
7671 ;;; BibTeX links
7673 ;; Use the custom search meachnism to construct and use search strings for
7674 ;; file links to BibTeX database entries.
7676 (defun org-create-file-search-in-bibtex ()
7677 "Create the search string and description for a BibTeX database entry."
7678 (when (eq major-mode 'bibtex-mode)
7679 ;; yes, we want to construct this search string.
7680 ;; Make a good description for this entry, using names, year and the title
7681 ;; Put it into the `description' variable which is dynamically scoped.
7682 (let ((bibtex-autokey-names 1)
7683 (bibtex-autokey-names-stretch 1)
7684 (bibtex-autokey-name-case-convert-function 'identity)
7685 (bibtex-autokey-name-separator " & ")
7686 (bibtex-autokey-additional-names " et al.")
7687 (bibtex-autokey-year-length 4)
7688 (bibtex-autokey-name-year-separator " ")
7689 (bibtex-autokey-titlewords 3)
7690 (bibtex-autokey-titleword-separator " ")
7691 (bibtex-autokey-titleword-case-convert-function 'identity)
7692 (bibtex-autokey-titleword-length 'infty)
7693 (bibtex-autokey-year-title-separator ": "))
7694 (setq description (bibtex-generate-autokey)))
7695 ;; Now parse the entry, get the key and return it.
7696 (save-excursion
7697 (bibtex-beginning-of-entry)
7698 (cdr (assoc "=key=" (bibtex-parse-entry))))))
7700 (defun org-execute-file-search-in-bibtex (s)
7701 "Find the link search string S as a key for a database entry."
7702 (when (eq major-mode 'bibtex-mode)
7703 ;; Yes, we want to do the search in this file.
7704 ;; We construct a regexp that searches for "@entrytype{" followed by the key
7705 (goto-char (point-min))
7706 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
7707 (regexp-quote s) "[ \t\n]*,") nil t)
7708 (goto-char (match-beginning 0)))
7709 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
7710 ;; Use double prefix to indicate that any web link should be browsed
7711 (let ((b (current-buffer)) (p (point)))
7712 ;; Restore the window configuration because we just use the web link
7713 (set-window-configuration org-window-config-before-follow-link)
7714 (save-excursion (set-buffer b) (goto-char p)
7715 (bibtex-url)))
7716 (recenter 0)) ; Move entry start to beginning of window
7717 ;; return t to indicate that the search is done.
7720 ;; Finally add the functions to the right hooks.
7721 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
7722 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
7724 ;; end of Bibtex link setup
7726 ;;; Following file links
7728 (defun org-open-file (path &optional in-emacs line search)
7729 "Open the file at PATH.
7730 First, this expands any special file name abbreviations. Then the
7731 configuration variable `org-file-apps' is checked if it contains an
7732 entry for this file type, and if yes, the corresponding command is launched.
7733 If no application is found, Emacs simply visits the file.
7734 With optional argument IN-EMACS, Emacs will visit the file.
7735 Optional LINE specifies a line to go to, optional SEARCH a string to
7736 search for. If LINE or SEARCH is given, the file will always be
7737 opened in Emacs.
7738 If the file does not exist, an error is thrown."
7739 (setq in-emacs (or in-emacs line search))
7740 (let* ((file (if (equal path "")
7741 buffer-file-name
7742 (substitute-in-file-name (expand-file-name path))))
7743 (apps (append org-file-apps (org-default-apps)))
7744 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7745 (dirp (if remp nil (file-directory-p file)))
7746 (dfile (downcase file))
7747 (old-buffer (current-buffer))
7748 (old-pos (point))
7749 (old-mode major-mode)
7750 ext cmd)
7751 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7752 (setq ext (match-string 1 dfile))
7753 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7754 (setq ext (match-string 1 dfile))))
7755 (if in-emacs
7756 (setq cmd 'emacs)
7757 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7758 (and dirp (cdr (assoc 'directory apps)))
7759 (cdr (assoc ext apps))
7760 (cdr (assoc t apps)))))
7761 (when (eq cmd 'mailcap)
7762 (require 'mailcap)
7763 (mailcap-parse-mailcaps)
7764 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7765 (command (mailcap-mime-info mime-type)))
7766 (if (stringp command)
7767 (setq cmd command)
7768 (setq cmd 'emacs))))
7769 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7770 (not (file-exists-p file))
7771 (not org-open-non-existing-files))
7772 (error "No such file: %s" file))
7773 (cond
7774 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7775 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7776 (while (string-match "['\"]%s['\"]" cmd)
7777 (setq cmd (replace-match "%s" t t cmd)))
7778 (while (string-match "%s" cmd)
7779 (setq cmd (replace-match
7780 (save-match-data (shell-quote-argument file))
7781 t t cmd)))
7782 (save-window-excursion
7783 (start-process-shell-command cmd nil cmd)))
7784 ((or (stringp cmd)
7785 (eq cmd 'emacs))
7786 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7787 (widen)
7788 (if line (goto-line line)
7789 (if search (org-link-search search))))
7790 ((consp cmd)
7791 (eval cmd))
7792 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7793 (and (org-mode-p) (eq old-mode 'org-mode)
7794 (or (not (equal old-buffer (current-buffer)))
7795 (not (equal old-pos (point))))
7796 (org-mark-ring-push old-pos old-buffer))))
7798 (defun org-default-apps ()
7799 "Return the default applications for this operating system."
7800 (cond
7801 ((eq system-type 'darwin)
7802 org-file-apps-defaults-macosx)
7803 ((eq system-type 'windows-nt)
7804 org-file-apps-defaults-windowsnt)
7805 (t org-file-apps-defaults-gnu)))
7807 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7808 (defun org-file-remote-p (file)
7809 "Test whether FILE specifies a location on a remote system.
7810 Return non-nil if the location is indeed remote.
7812 For example, the filename \"/user@host:/foo\" specifies a location
7813 on the system \"/user@host:\"."
7814 (cond ((fboundp 'file-remote-p)
7815 (file-remote-p file))
7816 ((fboundp 'tramp-handle-file-remote-p)
7817 (tramp-handle-file-remote-p file))
7818 ((and (boundp 'ange-ftp-name-format)
7819 (string-match (car ange-ftp-name-format) file))
7821 (t nil)))
7824 ;;;; Hooks for remember.el, and refiling
7826 (defun org-get-org-file ()
7827 "Read a filename, with default directory `org-directory'."
7828 (let ((default (or org-default-notes-file remember-data-file)))
7829 (read-file-name (format "File name [%s]: " default)
7830 (file-name-as-directory org-directory)
7831 default)))
7833 (defun org-notes-order-reversed-p ()
7834 "Check if the current file should receive notes in reversed order."
7835 (cond
7836 ((not org-reverse-note-order) nil)
7837 ((eq t org-reverse-note-order) t)
7838 ((not (listp org-reverse-note-order)) nil)
7839 (t (catch 'exit
7840 (let ((all org-reverse-note-order)
7841 entry)
7842 (while (setq entry (pop all))
7843 (if (string-match (car entry) buffer-file-name)
7844 (throw 'exit (cdr entry))))
7845 nil)))))
7847 ;;;; Refiling
7849 (defvar org-refile-target-table nil
7850 "The list of refile targets, created by `org-refile'.")
7852 (defvar org-agenda-new-buffers nil
7853 "Buffers created to visit agenda files.")
7855 (defun org-get-refile-targets (&optional default-buffer)
7856 "Produce a table with refile targets."
7857 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7858 targets txt re files f desc descre)
7859 (with-current-buffer (or default-buffer (current-buffer))
7860 (while (setq entry (pop entries))
7861 (setq files (car entry) desc (cdr entry))
7862 (cond
7863 ((null files) (setq files (list (current-buffer))))
7864 ((eq files 'org-agenda-files)
7865 (setq files (org-agenda-files 'unrestricted)))
7866 ((and (symbolp files) (fboundp files))
7867 (setq files (funcall files)))
7868 ((and (symbolp files) (boundp files))
7869 (setq files (symbol-value files))))
7870 (if (stringp files) (setq files (list files)))
7871 (cond
7872 ((eq (car desc) :tag)
7873 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7874 ((eq (car desc) :todo)
7875 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7876 ((eq (car desc) :regexp)
7877 (setq descre (cdr desc)))
7878 ((eq (car desc) :level)
7879 (setq descre (concat "^\\*\\{" (number-to-string
7880 (if org-odd-levels-only
7881 (1- (* 2 (cdr desc)))
7882 (cdr desc)))
7883 "\\}[ \t]")))
7884 ((eq (car desc) :maxlevel)
7885 (setq descre (concat "^\\*\\{1," (number-to-string
7886 (if org-odd-levels-only
7887 (1- (* 2 (cdr desc)))
7888 (cdr desc)))
7889 "\\}[ \t]")))
7890 (t (error "Bad refiling target description %s" desc)))
7891 (while (setq f (pop files))
7892 (save-excursion
7893 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7894 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7895 (save-excursion
7896 (save-restriction
7897 (widen)
7898 (goto-char (point-min))
7899 (while (re-search-forward descre nil t)
7900 (goto-char (point-at-bol))
7901 (when (looking-at org-complex-heading-regexp)
7902 (setq txt (match-string 4)
7903 re (concat "^" (regexp-quote
7904 (buffer-substring (match-beginning 1)
7905 (match-end 4)))))
7906 (if (match-end 5) (setq re (concat re "[ \t]+"
7907 (regexp-quote
7908 (match-string 5)))))
7909 (setq re (concat re "[ \t]*$"))
7910 (when org-refile-use-outline-path
7911 (setq txt (mapconcat 'identity
7912 (append
7913 (if (eq org-refile-use-outline-path 'file)
7914 (list (file-name-nondirectory
7915 (buffer-file-name (buffer-base-buffer))))
7916 (if (eq org-refile-use-outline-path 'full-file-path)
7917 (list (buffer-file-name (buffer-base-buffer)))))
7918 (org-get-outline-path)
7919 (list txt))
7920 "/")))
7921 (push (list txt f re (point)) targets))
7922 (goto-char (point-at-eol))))))))
7923 (nreverse targets))))
7925 (defun org-get-outline-path ()
7926 "Return the outline path to the current entry, as a list."
7927 (let (rtn)
7928 (save-excursion
7929 (while (org-up-heading-safe)
7930 (when (looking-at org-complex-heading-regexp)
7931 (push (org-match-string-no-properties 4) rtn)))
7932 rtn)))
7934 (defvar org-refile-history nil
7935 "History for refiling operations.")
7937 (defun org-refile (&optional goto default-buffer)
7938 "Move the entry at point to another heading.
7939 The list of target headings is compiled using the information in
7940 `org-refile-targets', which see. This list is created upon first use, and
7941 you can update it by calling this command with a double prefix (`C-u C-u').
7942 FIXME: Can we find a better way of updating?
7944 At the target location, the entry is filed as a subitem of the target heading.
7945 Depending on `org-reverse-note-order', the new subitem will either be the
7946 first of the last subitem.
7948 With prefix arg GOTO, the command will only visit the target location,
7949 not actually move anything.
7950 With a double prefix `C-c C-c', go to the location where the last refiling
7951 operation has put the subtree.
7953 With a double prefix argument, the command can be used to jump to any
7954 heading in the current buffer."
7955 (interactive "P")
7956 (let* ((cbuf (current-buffer))
7957 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7958 pos it nbuf file re level reversed)
7959 (if (equal goto '(16))
7960 (org-refile-goto-last-stored)
7961 (when (setq it (org-refile-get-location
7962 (if goto "Goto: " "Refile to: ") default-buffer))
7963 (setq file (nth 1 it)
7964 re (nth 2 it)
7965 pos (nth 3 it))
7966 (setq nbuf (or (find-buffer-visiting file)
7967 (find-file-noselect file)))
7968 (if goto
7969 (progn
7970 (switch-to-buffer nbuf)
7971 (goto-char pos)
7972 (org-show-context 'org-goto))
7973 (org-copy-special)
7974 (save-excursion
7975 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7976 (find-file-noselect file))))
7977 (setq reversed (org-notes-order-reversed-p))
7978 (save-excursion
7979 (save-restriction
7980 (widen)
7981 (goto-char pos)
7982 (looking-at outline-regexp)
7983 (setq level (org-get-valid-level (funcall outline-level) 1))
7984 (goto-char
7985 (if reversed
7986 (outline-next-heading)
7987 (or (save-excursion (outline-get-next-sibling))
7988 (org-end-of-subtree t t)
7989 (point-max))))
7990 (bookmark-set "org-refile-last-stored")
7991 (org-paste-subtree level))))
7992 (org-cut-special)
7993 (message "Entry refiled to \"%s\"" (car it)))))))
7995 (defun org-refile-goto-last-stored ()
7996 "Go to the location where the last refile was stored."
7997 (interactive)
7998 (bookmark-jump "org-refile-last-stored")
7999 (message "This is the location of the last refile"))
8001 (defun org-refile-get-location (&optional prompt default-buffer)
8002 "Prompt the user for a refile location, using PROMPT."
8003 (let ((org-refile-targets org-refile-targets)
8004 (org-refile-use-outline-path org-refile-use-outline-path))
8005 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8006 (unless org-refile-target-table
8007 (error "No refile targets"))
8008 (let* ((cbuf (current-buffer))
8009 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8010 (fname (and filename (file-truename filename)))
8011 (tbl (mapcar
8012 (lambda (x)
8013 (if (not (equal fname (file-truename (nth 1 x))))
8014 (cons (concat (car x) " (" (file-name-nondirectory
8015 (nth 1 x)) ")")
8016 (cdr x))
8018 org-refile-target-table))
8019 (completion-ignore-case t))
8020 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
8021 tbl)))
8023 ;;;; Dynamic blocks
8025 (defun org-find-dblock (name)
8026 "Find the first dynamic block with name NAME in the buffer.
8027 If not found, stay at current position and return nil."
8028 (let (pos)
8029 (save-excursion
8030 (goto-char (point-min))
8031 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8032 nil t)
8033 (match-beginning 0))))
8034 (if pos (goto-char pos))
8035 pos))
8037 (defconst org-dblock-start-re
8038 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8039 "Matches the startline of a dynamic block, with parameters.")
8041 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8042 "Matches the end of a dyhamic block.")
8044 (defun org-create-dblock (plist)
8045 "Create a dynamic block section, with parameters taken from PLIST.
8046 PLIST must containe a :name entry which is used as name of the block."
8047 (unless (bolp) (newline))
8048 (let ((name (plist-get plist :name)))
8049 (insert "#+BEGIN: " name)
8050 (while plist
8051 (if (eq (car plist) :name)
8052 (setq plist (cddr plist))
8053 (insert " " (prin1-to-string (pop plist)))))
8054 (insert "\n\n#+END:\n")
8055 (beginning-of-line -2)))
8057 (defun org-prepare-dblock ()
8058 "Prepare dynamic block for refresh.
8059 This empties the block, puts the cursor at the insert position and returns
8060 the property list including an extra property :name with the block name."
8061 (unless (looking-at org-dblock-start-re)
8062 (error "Not at a dynamic block"))
8063 (let* ((begdel (1+ (match-end 0)))
8064 (name (org-no-properties (match-string 1)))
8065 (params (append (list :name name)
8066 (read (concat "(" (match-string 3) ")")))))
8067 (unless (re-search-forward org-dblock-end-re nil t)
8068 (error "Dynamic block not terminated"))
8069 (setq params
8070 (append params
8071 (list :content (buffer-substring
8072 begdel (match-beginning 0)))))
8073 (delete-region begdel (match-beginning 0))
8074 (goto-char begdel)
8075 (open-line 1)
8076 params))
8078 (defun org-map-dblocks (&optional command)
8079 "Apply COMMAND to all dynamic blocks in the current buffer.
8080 If COMMAND is not given, use `org-update-dblock'."
8081 (let ((cmd (or command 'org-update-dblock))
8082 pos)
8083 (save-excursion
8084 (goto-char (point-min))
8085 (while (re-search-forward org-dblock-start-re nil t)
8086 (goto-char (setq pos (match-beginning 0)))
8087 (condition-case nil
8088 (funcall cmd)
8089 (error (message "Error during update of dynamic block")))
8090 (goto-char pos)
8091 (unless (re-search-forward org-dblock-end-re nil t)
8092 (error "Dynamic block not terminated"))))))
8094 (defun org-dblock-update (&optional arg)
8095 "User command for updating dynamic blocks.
8096 Update the dynamic block at point. With prefix ARG, update all dynamic
8097 blocks in the buffer."
8098 (interactive "P")
8099 (if arg
8100 (org-update-all-dblocks)
8101 (or (looking-at org-dblock-start-re)
8102 (org-beginning-of-dblock))
8103 (org-update-dblock)))
8105 (defun org-update-dblock ()
8106 "Update the dynamic block at point
8107 This means to empty the block, parse for parameters and then call
8108 the correct writing function."
8109 (save-window-excursion
8110 (let* ((pos (point))
8111 (line (org-current-line))
8112 (params (org-prepare-dblock))
8113 (name (plist-get params :name))
8114 (cmd (intern (concat "org-dblock-write:" name))))
8115 (message "Updating dynamic block `%s' at line %d..." name line)
8116 (funcall cmd params)
8117 (message "Updating dynamic block `%s' at line %d...done" name line)
8118 (goto-char pos))))
8120 (defun org-beginning-of-dblock ()
8121 "Find the beginning of the dynamic block at point.
8122 Error if there is no scuh block at point."
8123 (let ((pos (point))
8124 beg)
8125 (end-of-line 1)
8126 (if (and (re-search-backward org-dblock-start-re nil t)
8127 (setq beg (match-beginning 0))
8128 (re-search-forward org-dblock-end-re nil t)
8129 (> (match-end 0) pos))
8130 (goto-char beg)
8131 (goto-char pos)
8132 (error "Not in a dynamic block"))))
8134 (defun org-update-all-dblocks ()
8135 "Update all dynamic blocks in the buffer.
8136 This function can be used in a hook."
8137 (when (org-mode-p)
8138 (org-map-dblocks 'org-update-dblock)))
8141 ;;;; Completion
8143 (defconst org-additional-option-like-keywords
8144 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8145 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8146 "BEGIN_EXAMPLE" "END_EXAMPLE"))
8148 (defun org-complete (&optional arg)
8149 "Perform completion on word at point.
8150 At the beginning of a headline, this completes TODO keywords as given in
8151 `org-todo-keywords'.
8152 If the current word is preceded by a backslash, completes the TeX symbols
8153 that are supported for HTML support.
8154 If the current word is preceded by \"#+\", completes special words for
8155 setting file options.
8156 In the line after \"#+STARTUP:, complete valid keywords.\"
8157 At all other locations, this simply calls the value of
8158 `org-completion-fallback-command'."
8159 (interactive "P")
8160 (org-without-partial-completion
8161 (catch 'exit
8162 (let* ((end (point))
8163 (beg1 (save-excursion
8164 (skip-chars-backward (org-re "[:alnum:]_@"))
8165 (point)))
8166 (beg (save-excursion
8167 (skip-chars-backward "a-zA-Z0-9_:$")
8168 (point)))
8169 (confirm (lambda (x) (stringp (car x))))
8170 (searchhead (equal (char-before beg) ?*))
8171 (tag (and (equal (char-before beg1) ?:)
8172 (equal (char-after (point-at-bol)) ?*)))
8173 (prop (and (equal (char-before beg1) ?:)
8174 (not (equal (char-after (point-at-bol)) ?*))))
8175 (texp (equal (char-before beg) ?\\))
8176 (link (equal (char-before beg) ?\[))
8177 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8178 beg)
8179 "#+"))
8180 (startup (string-match "^#\\+STARTUP:.*"
8181 (buffer-substring (point-at-bol) (point))))
8182 (completion-ignore-case opt)
8183 (type nil)
8184 (tbl nil)
8185 (table (cond
8186 (opt
8187 (setq type :opt)
8188 (require 'org-exp)
8189 (append
8190 (mapcar
8191 (lambda (x)
8192 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8193 (cons (match-string 2 x) (match-string 1 x)))
8194 (org-split-string (org-get-current-options) "\n"))
8195 (mapcar 'list org-additional-option-like-keywords)))
8196 (startup
8197 (setq type :startup)
8198 org-startup-options)
8199 (link (append org-link-abbrev-alist-local
8200 org-link-abbrev-alist))
8201 (texp
8202 (setq type :tex)
8203 org-html-entities)
8204 ((string-match "\\`\\*+[ \t]+\\'"
8205 (buffer-substring (point-at-bol) beg))
8206 (setq type :todo)
8207 (mapcar 'list org-todo-keywords-1))
8208 (searchhead
8209 (setq type :searchhead)
8210 (save-excursion
8211 (goto-char (point-min))
8212 (while (re-search-forward org-todo-line-regexp nil t)
8213 (push (list
8214 (org-make-org-heading-search-string
8215 (match-string 3) t))
8216 tbl)))
8217 tbl)
8218 (tag (setq type :tag beg beg1)
8219 (or org-tag-alist (org-get-buffer-tags)))
8220 (prop (setq type :prop beg beg1)
8221 (mapcar 'list (org-buffer-property-keys nil t t)))
8222 (t (progn
8223 (call-interactively org-completion-fallback-command)
8224 (throw 'exit nil)))))
8225 (pattern (buffer-substring-no-properties beg end))
8226 (completion (try-completion pattern table confirm)))
8227 (cond ((eq completion t)
8228 (if (not (assoc (upcase pattern) table))
8229 (message "Already complete")
8230 (if (and (equal type :opt)
8231 (not (member (car (assoc (upcase pattern) table))
8232 org-additional-option-like-keywords)))
8233 (insert (substring (cdr (assoc (upcase pattern) table))
8234 (length pattern)))
8235 (if (memq type '(:tag :prop)) (insert ":")))))
8236 ((null completion)
8237 (message "Can't find completion for \"%s\"" pattern)
8238 (ding))
8239 ((not (string= pattern completion))
8240 (delete-region beg end)
8241 (if (string-match " +$" completion)
8242 (setq completion (replace-match "" t t completion)))
8243 (insert completion)
8244 (if (get-buffer-window "*Completions*")
8245 (delete-window (get-buffer-window "*Completions*")))
8246 (if (assoc completion table)
8247 (if (eq type :todo) (insert " ")
8248 (if (memq type '(:tag :prop)) (insert ":"))))
8249 (if (and (equal type :opt) (assoc completion table))
8250 (message "%s" (substitute-command-keys
8251 "Press \\[org-complete] again to insert example settings"))))
8253 (message "Making completion list...")
8254 (let ((list (sort (all-completions pattern table confirm)
8255 'string<)))
8256 (with-output-to-temp-buffer "*Completions*"
8257 (condition-case nil
8258 ;; Protection needed for XEmacs and emacs 21
8259 (display-completion-list list pattern)
8260 (error (display-completion-list list)))))
8261 (message "Making completion list...%s" "done")))))))
8263 ;;;; TODO, DEADLINE, Comments
8265 (defun org-toggle-comment ()
8266 "Change the COMMENT state of an entry."
8267 (interactive)
8268 (save-excursion
8269 (org-back-to-heading)
8270 (let (case-fold-search)
8271 (if (looking-at (concat outline-regexp
8272 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8273 (replace-match "" t t nil 1)
8274 (if (looking-at outline-regexp)
8275 (progn
8276 (goto-char (match-end 0))
8277 (insert org-comment-string " ")))))))
8279 (defvar org-last-todo-state-is-todo nil
8280 "This is non-nil when the last TODO state change led to a TODO state.
8281 If the last change removed the TODO tag or switched to DONE, then
8282 this is nil.")
8284 (defvar org-setting-tags nil) ; dynamically skiped
8286 ;; FIXME: better place
8287 (defun org-property-or-variable-value (var &optional inherit)
8288 "Check if there is a property fixing the value of VAR.
8289 If yes, return this value. If not, return the current value of the variable."
8290 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
8291 (if (and prop (stringp prop) (string-match "\\S-" prop))
8292 (read prop)
8293 (symbol-value var))))
8295 (defun org-parse-local-options (string var)
8296 "Parse STRING for startup setting relevant for variable VAR."
8297 (let ((rtn (symbol-value var))
8298 e opts)
8299 (save-match-data
8300 (if (or (not string) (not (string-match "\\S-" string)))
8302 (setq opts (delq nil (mapcar (lambda (x)
8303 (setq e (assoc x org-startup-options))
8304 (if (eq (nth 1 e) var) e nil))
8305 (org-split-string string "[ \t]+"))))
8306 (if (not opts)
8308 (setq rtn nil)
8309 (while (setq e (pop opts))
8310 (if (not (nth 3 e))
8311 (setq rtn (nth 2 e))
8312 (if (not (listp rtn)) (setq rtn nil))
8313 (push (nth 2 e) rtn)))
8314 rtn)))))
8316 (defvar org-blocker-hook nil
8317 "Hook for functions that are allowed to block a state change.
8319 Each function gets as its single argument a property list, see
8320 `org-trigger-hook' for more information about this list.
8322 If any of the functions in this hook returns nil, the state change
8323 is blocked.")
8325 (defvar org-trigger-hook nil
8326 "Hook for functions that are triggered by a state change.
8328 Each function gets as its single argument a property list with at least
8329 the following elements:
8331 (:type type-of-change :position pos-at-entry-start
8332 :from old-state :to new-state)
8334 Depending on the type, more properties may be present.
8336 This mechanism is currently implemented for:
8338 TODO state changes
8339 ------------------
8340 :type todo-state-change
8341 :from previous state (keyword as a string), or nil
8342 :to new state (keyword as a string), or nil")
8345 (defun org-todo (&optional arg)
8346 "Change the TODO state of an item.
8347 The state of an item is given by a keyword at the start of the heading,
8348 like
8349 *** TODO Write paper
8350 *** DONE Call mom
8352 The different keywords are specified in the variable `org-todo-keywords'.
8353 By default the available states are \"TODO\" and \"DONE\".
8354 So for this example: when the item starts with TODO, it is changed to DONE.
8355 When it starts with DONE, the DONE is removed. And when neither TODO nor
8356 DONE are present, add TODO at the beginning of the heading.
8358 With C-u prefix arg, use completion to determine the new state.
8359 With numeric prefix arg, switch to that state.
8361 For calling through lisp, arg is also interpreted in the following way:
8362 'none -> empty state
8363 \"\"(empty string) -> switch to empty state
8364 'done -> switch to DONE
8365 'nextset -> switch to the next set of keywords
8366 'previousset -> switch to the previous set of keywords
8367 \"WAITING\" -> switch to the specified keyword, but only if it
8368 really is a member of `org-todo-keywords'."
8369 (interactive "P")
8370 (save-excursion
8371 (catch 'exit
8372 (org-back-to-heading)
8373 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8374 (or (looking-at (concat " +" org-todo-regexp " *"))
8375 (looking-at " *"))
8376 (let* ((match-data (match-data))
8377 (startpos (point-at-bol))
8378 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8379 (org-log-done org-log-done)
8380 (org-log-repeat org-log-repeat)
8381 (org-todo-log-states org-todo-log-states)
8382 (this (match-string 1))
8383 (hl-pos (match-beginning 0))
8384 (head (org-get-todo-sequence-head this))
8385 (ass (assoc head org-todo-kwd-alist))
8386 (interpret (nth 1 ass))
8387 (done-word (nth 3 ass))
8388 (final-done-word (nth 4 ass))
8389 (last-state (or this ""))
8390 (completion-ignore-case t)
8391 (member (member this org-todo-keywords-1))
8392 (tail (cdr member))
8393 (state (cond
8394 ((and org-todo-key-trigger
8395 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8396 (and (not arg) org-use-fast-todo-selection
8397 (not (eq org-use-fast-todo-selection 'prefix)))))
8398 ;; Use fast selection
8399 (org-fast-todo-selection))
8400 ((and (equal arg '(4))
8401 (or (not org-use-fast-todo-selection)
8402 (not org-todo-key-trigger)))
8403 ;; Read a state with completion
8404 (completing-read "State: " (mapcar (lambda(x) (list x))
8405 org-todo-keywords-1)
8406 nil t))
8407 ((eq arg 'right)
8408 (if this
8409 (if tail (car tail) nil)
8410 (car org-todo-keywords-1)))
8411 ((eq arg 'left)
8412 (if (equal member org-todo-keywords-1)
8414 (if this
8415 (nth (- (length org-todo-keywords-1) (length tail) 2)
8416 org-todo-keywords-1)
8417 (org-last org-todo-keywords-1))))
8418 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8419 (setq arg nil))) ; hack to fall back to cycling
8420 (arg
8421 ;; user or caller requests a specific state
8422 (cond
8423 ((equal arg "") nil)
8424 ((eq arg 'none) nil)
8425 ((eq arg 'done) (or done-word (car org-done-keywords)))
8426 ((eq arg 'nextset)
8427 (or (car (cdr (member head org-todo-heads)))
8428 (car org-todo-heads)))
8429 ((eq arg 'previousset)
8430 (let ((org-todo-heads (reverse org-todo-heads)))
8431 (or (car (cdr (member head org-todo-heads)))
8432 (car org-todo-heads))))
8433 ((car (member arg org-todo-keywords-1)))
8434 ((nth (1- (prefix-numeric-value arg))
8435 org-todo-keywords-1))))
8436 ((null member) (or head (car org-todo-keywords-1)))
8437 ((equal this final-done-word) nil) ;; -> make empty
8438 ((null tail) nil) ;; -> first entry
8439 ((eq interpret 'sequence)
8440 (car tail))
8441 ((memq interpret '(type priority))
8442 (if (eq this-command last-command)
8443 (car tail)
8444 (if (> (length tail) 0)
8445 (or done-word (car org-done-keywords))
8446 nil)))
8447 (t nil)))
8448 (next (if state (concat " " state " ") " "))
8449 (change-plist (list :type 'todo-state-change :from this :to state
8450 :position startpos))
8451 dolog now-done-p)
8452 (when org-blocker-hook
8453 (unless (save-excursion
8454 (save-match-data
8455 (run-hook-with-args-until-failure
8456 'org-blocker-hook change-plist)))
8457 (if (interactive-p)
8458 (error "TODO state change from %s to %s blocked" this state)
8459 ;; fail silently
8460 (message "TODO state change from %s to %s blocked" this state)
8461 (throw 'exit nil))))
8462 (store-match-data match-data)
8463 (replace-match next t t)
8464 (unless (pos-visible-in-window-p hl-pos)
8465 (message "TODO state changed to %s" (org-trim next)))
8466 (unless head
8467 (setq head (org-get-todo-sequence-head state)
8468 ass (assoc head org-todo-kwd-alist)
8469 interpret (nth 1 ass)
8470 done-word (nth 3 ass)
8471 final-done-word (nth 4 ass)))
8472 (when (memq arg '(nextset previousset))
8473 (message "Keyword-Set %d/%d: %s"
8474 (- (length org-todo-sets) -1
8475 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8476 (length org-todo-sets)
8477 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8478 (setq org-last-todo-state-is-todo
8479 (not (member state org-done-keywords)))
8480 (setq now-done-p (and (member state org-done-keywords)
8481 (not (member this org-done-keywords))))
8482 (and logging (org-local-logging logging))
8483 (when (and (or org-todo-log-states org-log-done)
8484 (not (memq arg '(nextset previousset))))
8485 ;; we need to look at recording a time and note
8486 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8487 (nth 2 (assoc this org-todo-log-states))))
8488 (when (and state
8489 (member state org-not-done-keywords)
8490 (not (member this org-not-done-keywords)))
8491 ;; This is now a todo state and was not one before
8492 ;; If there was a CLOSED time stamp, get rid of it.
8493 (org-add-planning-info nil nil 'closed))
8494 (when (and now-done-p org-log-done)
8495 ;; It is now done, and it was not done before
8496 (org-add-planning-info 'closed (org-current-time))
8497 (if (and (not dolog) (eq 'note org-log-done))
8498 (org-add-log-setup 'done state 'findpos 'note)))
8499 (when (and state dolog)
8500 ;; This is a non-nil state, and we need to log it
8501 (org-add-log-setup 'state state 'findpos dolog)))
8502 ;; Fixup tag positioning
8503 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8504 (run-hooks 'org-after-todo-state-change-hook)
8505 (if (and arg (not (member state org-done-keywords)))
8506 (setq head (org-get-todo-sequence-head state)))
8507 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8508 ;; Do we need to trigger a repeat?
8509 (when now-done-p (org-auto-repeat-maybe state))
8510 ;; Fixup cursor location if close to the keyword
8511 (if (and (outline-on-heading-p)
8512 (not (bolp))
8513 (save-excursion (beginning-of-line 1)
8514 (looking-at org-todo-line-regexp))
8515 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8516 (progn
8517 (goto-char (or (match-end 2) (match-end 1)))
8518 (just-one-space)))
8519 (when org-trigger-hook
8520 (save-excursion
8521 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8523 (defun org-local-logging (value)
8524 "Get logging settings from a property VALUE."
8525 (let* (words w a)
8526 ;; directly set the variables, they are already local.
8527 (setq org-log-done nil
8528 org-log-repeat nil
8529 org-todo-log-states nil)
8530 (setq words (org-split-string value))
8531 (while (setq w (pop words))
8532 (cond
8533 ((setq a (assoc w org-startup-options))
8534 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8535 (set (nth 1 a) (nth 2 a))))
8536 ((setq a (org-extract-log-state-settings w))
8537 (and (member (car a) org-todo-keywords-1)
8538 (push a org-todo-log-states)))))))
8540 (defun org-get-todo-sequence-head (kwd)
8541 "Return the head of the TODO sequence to which KWD belongs.
8542 If KWD is not set, check if there is a text property remembering the
8543 right sequence."
8544 (let (p)
8545 (cond
8546 ((not kwd)
8547 (or (get-text-property (point-at-bol) 'org-todo-head)
8548 (progn
8549 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8550 nil (point-at-eol)))
8551 (get-text-property p 'org-todo-head))))
8552 ((not (member kwd org-todo-keywords-1))
8553 (car org-todo-keywords-1))
8554 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8556 (defun org-fast-todo-selection ()
8557 "Fast TODO keyword selection with single keys.
8558 Returns the new TODO keyword, or nil if no state change should occur."
8559 (let* ((fulltable org-todo-key-alist)
8560 (done-keywords org-done-keywords) ;; needed for the faces.
8561 (maxlen (apply 'max (mapcar
8562 (lambda (x)
8563 (if (stringp (car x)) (string-width (car x)) 0))
8564 fulltable)))
8565 (expert nil)
8566 (fwidth (+ maxlen 3 1 3))
8567 (ncol (/ (- (window-width) 4) fwidth))
8568 tg cnt e c tbl
8569 groups ingroup)
8570 (save-window-excursion
8571 (if expert
8572 (set-buffer (get-buffer-create " *Org todo*"))
8573 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8574 (erase-buffer)
8575 (org-set-local 'org-done-keywords done-keywords)
8576 (setq tbl fulltable cnt 0)
8577 (while (setq e (pop tbl))
8578 (cond
8579 ((equal e '(:startgroup))
8580 (push '() groups) (setq ingroup t)
8581 (when (not (= cnt 0))
8582 (setq cnt 0)
8583 (insert "\n"))
8584 (insert "{ "))
8585 ((equal e '(:endgroup))
8586 (setq ingroup nil cnt 0)
8587 (insert "}\n"))
8589 (setq tg (car e) c (cdr e))
8590 (if ingroup (push tg (car groups)))
8591 (setq tg (org-add-props tg nil 'face
8592 (org-get-todo-face tg)))
8593 (if (and (= cnt 0) (not ingroup)) (insert " "))
8594 (insert "[" c "] " tg (make-string
8595 (- fwidth 4 (length tg)) ?\ ))
8596 (when (= (setq cnt (1+ cnt)) ncol)
8597 (insert "\n")
8598 (if ingroup (insert " "))
8599 (setq cnt 0)))))
8600 (insert "\n")
8601 (goto-char (point-min))
8602 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8603 (fit-window-to-buffer))
8604 (message "[a-z..]:Set [SPC]:clear")
8605 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8606 (cond
8607 ((or (= c ?\C-g)
8608 (and (= c ?q) (not (rassoc c fulltable))))
8609 (setq quit-flag t))
8610 ((= c ?\ ) nil)
8611 ((setq e (rassoc c fulltable) tg (car e))
8613 (t (setq quit-flag t))))))
8615 (defun org-entry-is-todo-p ()
8616 (member (org-get-todo-state) org-not-done-keywords))
8618 (defun org-entry-is-done-p ()
8619 (member (org-get-todo-state) org-done-keywords))
8621 (defun org-get-todo-state ()
8622 (save-excursion
8623 (org-back-to-heading t)
8624 (and (looking-at org-todo-line-regexp)
8625 (match-end 2)
8626 (match-string 2))))
8628 (defun org-at-date-range-p (&optional inactive-ok)
8629 "Is the cursor inside a date range?"
8630 (interactive)
8631 (save-excursion
8632 (catch 'exit
8633 (let ((pos (point)))
8634 (skip-chars-backward "^[<\r\n")
8635 (skip-chars-backward "<[")
8636 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8637 (>= (match-end 0) pos)
8638 (throw 'exit t))
8639 (skip-chars-backward "^<[\r\n")
8640 (skip-chars-backward "<[")
8641 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8642 (>= (match-end 0) pos)
8643 (throw 'exit t)))
8644 nil)))
8646 (defun org-get-repeat ()
8647 "Check if tere is a deadline/schedule with repeater in this entry."
8648 (save-match-data
8649 (save-excursion
8650 (org-back-to-heading t)
8651 (if (re-search-forward
8652 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8653 (match-string 1)))))
8655 (defvar org-last-changed-timestamp)
8656 (defvar org-log-post-message)
8657 (defvar org-log-note-purpose)
8658 (defun org-auto-repeat-maybe (done-word)
8659 "Check if the current headline contains a repeated deadline/schedule.
8660 If yes, set TODO state back to what it was and change the base date
8661 of repeating deadline/scheduled time stamps to new date.
8662 This function is run automatically after each state change to a DONE state."
8663 ;; last-state is dynamically scoped into this function
8664 (let* ((repeat (org-get-repeat))
8665 (aa (assoc last-state org-todo-kwd-alist))
8666 (interpret (nth 1 aa))
8667 (head (nth 2 aa))
8668 (whata '(("d" . day) ("m" . month) ("y" . year)))
8669 (msg "Entry repeats: ")
8670 (org-log-done nil)
8671 (org-todo-log-states nil)
8672 (nshiftmax 10) (nshift 0)
8673 re type n what ts mb0 time)
8674 (when repeat
8675 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8676 (org-todo (if (eq interpret 'type) last-state head))
8677 (when (and org-log-repeat
8678 (or (not (memq 'org-add-log-note
8679 (default-value 'post-command-hook)))
8680 (eq org-log-note-purpose 'done)))
8681 ;; Make sure a note is taken;
8682 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8683 'findpos org-log-repeat))
8684 (org-back-to-heading t)
8685 (org-add-planning-info nil nil 'closed)
8686 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8687 org-deadline-time-regexp "\\)\\|\\("
8688 org-ts-regexp "\\)"))
8689 (while (re-search-forward
8690 re (save-excursion (outline-next-heading) (point)) t)
8691 (setq type (if (match-end 1) org-scheduled-string
8692 (if (match-end 3) org-deadline-string "Plain:"))
8693 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8694 mb0 (match-beginning 0))
8695 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8696 (setq n (string-to-number (match-string 2 ts))
8697 what (match-string 3 ts))
8698 (if (equal what "w") (setq n (* n 7) what "d"))
8699 ;; Preparation, see if we need to modify the start date for the change
8700 (when (match-end 1)
8701 (setq time (save-match-data (org-time-string-to-time ts)))
8702 (cond
8703 ((equal (match-string 1 ts) ".")
8704 ;; Shift starting date to today
8705 (org-timestamp-change
8706 (- (time-to-days (current-time)) (time-to-days time))
8707 'day))
8708 ((equal (match-string 1 ts) "+")
8709 (while (or (= nshift 0)
8710 (<= (time-to-days time) (time-to-days (current-time))))
8711 (when (= (incf nshift) nshiftmax)
8712 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8713 (error "Abort")))
8714 (org-timestamp-change n (cdr (assoc what whata)))
8715 (org-at-timestamp-p t)
8716 (setq ts (match-string 1))
8717 (setq time (save-match-data (org-time-string-to-time ts))))
8718 (org-timestamp-change (- n) (cdr (assoc what whata)))
8719 ;; rematch, so that we have everything in place for the real shift
8720 (org-at-timestamp-p t)
8721 (setq ts (match-string 1))
8722 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8723 (org-timestamp-change n (cdr (assoc what whata)))
8724 (setq msg (concat msg type org-last-changed-timestamp " "))))
8725 (setq org-log-post-message msg)
8726 (message "%s" msg))))
8728 (defun org-show-todo-tree (arg)
8729 "Make a compact tree which shows all headlines marked with TODO.
8730 The tree will show the lines where the regexp matches, and all higher
8731 headlines above the match.
8732 With a \\[universal-argument] prefix, also show the DONE entries.
8733 With a numeric prefix N, construct a sparse tree for the Nth element
8734 of `org-todo-keywords-1'."
8735 (interactive "P")
8736 (let ((case-fold-search nil)
8737 (kwd-re
8738 (cond ((null arg) org-not-done-regexp)
8739 ((equal arg '(4))
8740 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8741 (mapcar 'list org-todo-keywords-1))))
8742 (concat "\\("
8743 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8744 "\\)\\>")))
8745 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8746 (regexp-quote (nth (1- (prefix-numeric-value arg))
8747 org-todo-keywords-1)))
8748 (t (error "Invalid prefix argument: %s" arg)))))
8749 (message "%d TODO entries found"
8750 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8752 (defun org-deadline (&optional remove)
8753 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8754 With argument REMOVE, remove any deadline from the item."
8755 (interactive "P")
8756 (if remove
8757 (progn
8758 (org-remove-timestamp-with-keyword org-deadline-string)
8759 (message "Item no longer has a deadline."))
8760 (org-add-planning-info 'deadline nil 'closed)))
8762 (defun org-schedule (&optional remove)
8763 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8764 With argument REMOVE, remove any scheduling date from the item."
8765 (interactive "P")
8766 (if remove
8767 (progn
8768 (org-remove-timestamp-with-keyword org-scheduled-string)
8769 (message "Item is no longer scheduled."))
8770 (org-add-planning-info 'scheduled nil 'closed)))
8772 (defun org-remove-timestamp-with-keyword (keyword)
8773 "Remove all time stamps with KEYWORD in the current entry."
8774 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8775 beg)
8776 (save-excursion
8777 (org-back-to-heading t)
8778 (setq beg (point))
8779 (org-end-of-subtree t t)
8780 (while (re-search-backward re beg t)
8781 (replace-match "")
8782 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8783 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8785 (defun org-add-planning-info (what &optional time &rest remove)
8786 "Insert new timestamp with keyword in the line directly after the headline.
8787 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8788 If non is given, the user is prompted for a date.
8789 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8790 be removed."
8791 (interactive)
8792 (let (org-time-was-given org-end-time-was-given ts
8793 end default-time default-input)
8795 (when (and (not time) (memq what '(scheduled deadline)))
8796 ;; Try to get a default date/time from existing timestamp
8797 (save-excursion
8798 (org-back-to-heading t)
8799 (setq end (save-excursion (outline-next-heading) (point)))
8800 (when (re-search-forward (if (eq what 'scheduled)
8801 org-scheduled-time-regexp
8802 org-deadline-time-regexp)
8803 end t)
8804 (setq ts (match-string 1)
8805 default-time
8806 (apply 'encode-time (org-parse-time-string ts))
8807 default-input (and ts (org-get-compact-tod ts))))))
8808 (when what
8809 ;; If necessary, get the time from the user
8810 (setq time (or time (org-read-date nil 'to-time nil nil
8811 default-time default-input))))
8813 (when (and org-insert-labeled-timestamps-at-point
8814 (member what '(scheduled deadline)))
8815 (insert
8816 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8817 (org-insert-time-stamp time org-time-was-given
8818 nil nil nil (list org-end-time-was-given))
8819 (setq what nil))
8820 (save-excursion
8821 (save-restriction
8822 (let (col list elt ts buffer-invisibility-spec)
8823 (org-back-to-heading t)
8824 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8825 (goto-char (match-end 1))
8826 (setq col (current-column))
8827 (goto-char (match-end 0))
8828 (if (eobp) (insert "\n") (forward-char 1))
8829 (if (and (not (looking-at outline-regexp))
8830 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8831 "[^\r\n]*"))
8832 (not (equal (match-string 1) org-clock-string)))
8833 (narrow-to-region (match-beginning 0) (match-end 0))
8834 (insert-before-markers "\n")
8835 (backward-char 1)
8836 (narrow-to-region (point) (point))
8837 (indent-to-column col))
8838 ;; Check if we have to remove something.
8839 (setq list (cons what remove))
8840 (while list
8841 (setq elt (pop list))
8842 (goto-char (point-min))
8843 (when (or (and (eq elt 'scheduled)
8844 (re-search-forward org-scheduled-time-regexp nil t))
8845 (and (eq elt 'deadline)
8846 (re-search-forward org-deadline-time-regexp nil t))
8847 (and (eq elt 'closed)
8848 (re-search-forward org-closed-time-regexp nil t)))
8849 (replace-match "")
8850 (if (looking-at "--+<[^>]+>") (replace-match ""))
8851 (if (looking-at " +") (replace-match ""))))
8852 (goto-char (point-max))
8853 (when what
8854 (insert
8855 (if (not (equal (char-before) ?\ )) " " "")
8856 (cond ((eq what 'scheduled) org-scheduled-string)
8857 ((eq what 'deadline) org-deadline-string)
8858 ((eq what 'closed) org-closed-string))
8859 " ")
8860 (setq ts (org-insert-time-stamp
8861 time
8862 (or org-time-was-given
8863 (and (eq what 'closed) org-log-done-with-time))
8864 (eq what 'closed)
8865 nil nil (list org-end-time-was-given)))
8866 (end-of-line 1))
8867 (goto-char (point-min))
8868 (widen)
8869 (if (looking-at "[ \t]+\r?\n")
8870 (replace-match ""))
8871 ts)))))
8873 (defvar org-log-note-marker (make-marker))
8874 (defvar org-log-note-purpose nil)
8875 (defvar org-log-note-state nil)
8876 (defvar org-log-note-how nil)
8877 (defvar org-log-note-window-configuration nil)
8878 (defvar org-log-note-return-to (make-marker))
8879 (defvar org-log-post-message nil
8880 "Message to be displayed after a log note has been stored.
8881 The auto-repeater uses this.")
8883 (defun org-add-note ()
8884 "Add a note to the current entry.
8885 This is done in the same way as adding a state change note."
8886 (interactive)
8887 (org-add-log-setup 'note nil t nil))
8889 (defun org-add-log-setup (&optional purpose state findpos how)
8890 "Set up the post command hook to take a note.
8891 If this is about to TODO state change, the new state is expected in STATE.
8892 When FINDPOS is non-nil, find the correct position for the note in
8893 the current entry. If not, assume that it can be inserted at point."
8894 (save-excursion
8895 (when findpos
8896 (org-back-to-heading t)
8897 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8898 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8899 "[^\r\n]*\\)?"))
8900 (goto-char (match-end 0))
8901 (unless org-log-states-order-reversed
8902 (and (= (char-after) ?\n) (forward-char 1))
8903 (org-skip-over-state-notes)
8904 (skip-chars-backward " \t\n\r")))
8905 (move-marker org-log-note-marker (point))
8906 (setq org-log-note-purpose purpose
8907 org-log-note-state state
8908 org-log-note-how how)
8909 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8911 (defun org-skip-over-state-notes ()
8912 "Skip past the list of State notes in an entry."
8913 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8914 (while (looking-at "[ \t]*- State")
8915 (condition-case nil
8916 (org-next-item)
8917 (error (org-end-of-item)))))
8919 (defun org-add-log-note (&optional purpose)
8920 "Pop up a window for taking a note, and add this note later at point."
8921 (remove-hook 'post-command-hook 'org-add-log-note)
8922 (setq org-log-note-window-configuration (current-window-configuration))
8923 (delete-other-windows)
8924 (move-marker org-log-note-return-to (point))
8925 (switch-to-buffer (marker-buffer org-log-note-marker))
8926 (goto-char org-log-note-marker)
8927 (org-switch-to-buffer-other-window "*Org Note*")
8928 (erase-buffer)
8929 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
8930 (org-store-log-note)
8931 (let ((org-inhibit-startup t)) (org-mode))
8932 (insert (format "# Insert note for %s.
8933 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8934 (cond
8935 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8936 ((eq org-log-note-purpose 'done) "closed todo item")
8937 ((eq org-log-note-purpose 'state)
8938 (format "state change to \"%s\"" org-log-note-state))
8939 ((eq org-log-note-purpose 'note)
8940 "this entry")
8941 (t (error "This should not happen")))))
8942 (org-set-local 'org-finish-function 'org-store-log-note)))
8944 (defvar org-note-abort nil) ; dynamically scoped
8945 (defun org-store-log-note ()
8946 "Finish taking a log note, and insert it to where it belongs."
8947 (let ((txt (buffer-string))
8948 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8949 lines ind)
8950 (kill-buffer (current-buffer))
8951 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8952 (setq txt (replace-match "" t t txt)))
8953 (if (string-match "\\s-+\\'" txt)
8954 (setq txt (replace-match "" t t txt)))
8955 (setq lines (org-split-string txt "\n"))
8956 (when (and note (string-match "\\S-" note))
8957 (setq note
8958 (org-replace-escapes
8959 note
8960 (list (cons "%u" (user-login-name))
8961 (cons "%U" user-full-name)
8962 (cons "%t" (format-time-string
8963 (org-time-stamp-format 'long 'inactive)
8964 (current-time)))
8965 (cons "%s" (if org-log-note-state
8966 (concat "\"" org-log-note-state "\"")
8967 "")))))
8968 (if lines (setq note (concat note " \\\\")))
8969 (push note lines))
8970 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8971 (when lines
8972 (save-excursion
8973 (set-buffer (marker-buffer org-log-note-marker))
8974 (save-excursion
8975 (goto-char org-log-note-marker)
8976 (move-marker org-log-note-marker nil)
8977 (end-of-line 1)
8978 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8979 (indent-relative nil)
8980 (insert "- " (pop lines))
8981 (org-indent-line-function)
8982 (beginning-of-line 1)
8983 (looking-at "[ \t]*")
8984 (setq ind (concat (match-string 0) " "))
8985 (end-of-line 1)
8986 (while lines (insert "\n" ind (pop lines)))))))
8987 (set-window-configuration org-log-note-window-configuration)
8988 (with-current-buffer (marker-buffer org-log-note-return-to)
8989 (goto-char org-log-note-return-to))
8990 (move-marker org-log-note-return-to nil)
8991 (and org-log-post-message (message "%s" org-log-post-message)))
8993 ;; FIXME: what else would be useful?
8994 ;; - priority
8995 ;; - date
8997 (defun org-sparse-tree (&optional arg)
8998 "Create a sparse tree, prompt for the details.
8999 This command can create sparse trees. You first need to select the type
9000 of match used to create the tree:
9002 t Show entries with a specific TODO keyword.
9003 T Show entries selected by a tags match.
9004 p Enter a property name and its value (both with completion on existing
9005 names/values) and show entries with that property.
9006 r Show entries matching a regular expression
9007 d Show deadlines due within `org-deadline-warning-days'."
9008 (interactive "P")
9009 (let (ans kwd value)
9010 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9011 (setq ans (read-char-exclusive))
9012 (cond
9013 ((equal ans ?d)
9014 (call-interactively 'org-check-deadlines))
9015 ((equal ans ?b)
9016 (call-interactively 'org-check-before-date))
9017 ((equal ans ?t)
9018 (org-show-todo-tree '(4)))
9019 ((equal ans ?T)
9020 (call-interactively 'org-tags-sparse-tree))
9021 ((member ans '(?p ?P))
9022 (setq kwd (completing-read "Property: "
9023 (mapcar 'list (org-buffer-property-keys))))
9024 (setq value (completing-read "Value: "
9025 (mapcar 'list (org-property-values kwd))))
9026 (unless (string-match "\\`{.*}\\'" value)
9027 (setq value (concat "\"" value "\"")))
9028 (org-tags-sparse-tree arg (concat kwd "=" value)))
9029 ((member ans '(?r ?R ?/))
9030 (call-interactively 'org-occur))
9031 (t (error "No such sparse tree command \"%c\"" ans)))))
9033 (defvar org-occur-highlights nil
9034 "List of overlays used for occur matches.")
9035 (make-variable-buffer-local 'org-occur-highlights)
9036 (defvar org-occur-parameters nil
9037 "Parameters of the active org-occur calls.
9038 This is a list, each call to org-occur pushes as cons cell,
9039 containing the regular expression and the callback, onto the list.
9040 The list can contain several entries if `org-occur' has been called
9041 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9042 will only contain one set of parameters. When the highlights are
9043 removed (for example with `C-c C-c', or with the next edit (depending
9044 on `org-remove-highlights-with-change'), this variable is emptied
9045 as well.")
9046 (make-variable-buffer-local 'org-occur-parameters)
9048 (defun org-occur (regexp &optional keep-previous callback)
9049 "Make a compact tree which shows all matches of REGEXP.
9050 The tree will show the lines where the regexp matches, and all higher
9051 headlines above the match. It will also show the heading after the match,
9052 to make sure editing the matching entry is easy.
9053 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9054 call to `org-occur' will be kept, to allow stacking of calls to this
9055 command.
9056 If CALLBACK is non-nil, it is a function which is called to confirm
9057 that the match should indeed be shown."
9058 (interactive "sRegexp: \nP")
9059 (unless keep-previous
9060 (org-remove-occur-highlights nil nil t))
9061 (push (cons regexp callback) org-occur-parameters)
9062 (let ((cnt 0))
9063 (save-excursion
9064 (goto-char (point-min))
9065 (if (or (not keep-previous) ; do not want to keep
9066 (not org-occur-highlights)) ; no previous matches
9067 ;; hide everything
9068 (org-overview))
9069 (while (re-search-forward regexp nil t)
9070 (when (or (not callback)
9071 (save-match-data (funcall callback)))
9072 (setq cnt (1+ cnt))
9073 (when org-highlight-sparse-tree-matches
9074 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9075 (org-show-context 'occur-tree))))
9076 (when org-remove-highlights-with-change
9077 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9078 nil 'local))
9079 (unless org-sparse-tree-open-archived-trees
9080 (org-hide-archived-subtrees (point-min) (point-max)))
9081 (run-hooks 'org-occur-hook)
9082 (if (interactive-p)
9083 (message "%d match(es) for regexp %s" cnt regexp))
9084 cnt))
9086 (defun org-show-context (&optional key)
9087 "Make sure point and context and visible.
9088 How much context is shown depends upon the variables
9089 `org-show-hierarchy-above', `org-show-following-heading'. and
9090 `org-show-siblings'."
9091 (let ((heading-p (org-on-heading-p t))
9092 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9093 (following-p (org-get-alist-option org-show-following-heading key))
9094 (entry-p (org-get-alist-option org-show-entry-below key))
9095 (siblings-p (org-get-alist-option org-show-siblings key)))
9096 (catch 'exit
9097 ;; Show heading or entry text
9098 (if (and heading-p (not entry-p))
9099 (org-flag-heading nil) ; only show the heading
9100 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9101 (org-show-hidden-entry))) ; show entire entry
9102 (when following-p
9103 ;; Show next sibling, or heading below text
9104 (save-excursion
9105 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9106 (org-flag-heading nil))))
9107 (when siblings-p (org-show-siblings))
9108 (when hierarchy-p
9109 ;; show all higher headings, possibly with siblings
9110 (save-excursion
9111 (while (and (condition-case nil
9112 (progn (org-up-heading-all 1) t)
9113 (error nil))
9114 (not (bobp)))
9115 (org-flag-heading nil)
9116 (when siblings-p (org-show-siblings))))))))
9118 (defun org-reveal (&optional siblings)
9119 "Show current entry, hierarchy above it, and the following headline.
9120 This can be used to show a consistent set of context around locations
9121 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9122 not t for the search context.
9124 With optional argument SIBLINGS, on each level of the hierarchy all
9125 siblings are shown. This repairs the tree structure to what it would
9126 look like when opened with hierarchical calls to `org-cycle'."
9127 (interactive "P")
9128 (let ((org-show-hierarchy-above t)
9129 (org-show-following-heading t)
9130 (org-show-siblings (if siblings t org-show-siblings)))
9131 (org-show-context nil)))
9133 (defun org-highlight-new-match (beg end)
9134 "Highlight from BEG to END and mark the highlight is an occur headline."
9135 (let ((ov (org-make-overlay beg end)))
9136 (org-overlay-put ov 'face 'secondary-selection)
9137 (push ov org-occur-highlights)))
9139 (defun org-remove-occur-highlights (&optional beg end noremove)
9140 "Remove the occur highlights from the buffer.
9141 BEG and END are ignored. If NOREMOVE is nil, remove this function
9142 from the `before-change-functions' in the current buffer."
9143 (interactive)
9144 (unless org-inhibit-highlight-removal
9145 (mapc 'org-delete-overlay org-occur-highlights)
9146 (setq org-occur-highlights nil)
9147 (setq org-occur-parameters nil)
9148 (unless noremove
9149 (remove-hook 'before-change-functions
9150 'org-remove-occur-highlights 'local))))
9152 ;;;; Priorities
9154 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9155 "Regular expression matching the priority indicator.")
9157 (defvar org-remove-priority-next-time nil)
9159 (defun org-priority-up ()
9160 "Increase the priority of the current item."
9161 (interactive)
9162 (org-priority 'up))
9164 (defun org-priority-down ()
9165 "Decrease the priority of the current item."
9166 (interactive)
9167 (org-priority 'down))
9169 (defun org-priority (&optional action)
9170 "Change the priority of an item by ARG.
9171 ACTION can be `set', `up', `down', or a character."
9172 (interactive)
9173 (setq action (or action 'set))
9174 (let (current new news have remove)
9175 (save-excursion
9176 (org-back-to-heading)
9177 (if (looking-at org-priority-regexp)
9178 (setq current (string-to-char (match-string 2))
9179 have t)
9180 (setq current org-default-priority))
9181 (cond
9182 ((or (eq action 'set) (integerp action))
9183 (if (integerp action)
9184 (setq new action)
9185 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
9186 (setq new (read-char-exclusive)))
9187 (if (and (= (upcase org-highest-priority) org-highest-priority)
9188 (= (upcase org-lowest-priority) org-lowest-priority))
9189 (setq new (upcase new)))
9190 (cond ((equal new ?\ ) (setq remove t))
9191 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9192 (error "Priority must be between `%c' and `%c'"
9193 org-highest-priority org-lowest-priority))))
9194 ((eq action 'up)
9195 (if (and (not have) (eq last-command this-command))
9196 (setq new org-lowest-priority)
9197 (setq new (if (and org-priority-start-cycle-with-default (not have))
9198 org-default-priority (1- current)))))
9199 ((eq action 'down)
9200 (if (and (not have) (eq last-command this-command))
9201 (setq new org-highest-priority)
9202 (setq new (if (and org-priority-start-cycle-with-default (not have))
9203 org-default-priority (1+ current)))))
9204 (t (error "Invalid action")))
9205 (if (or (< (upcase new) org-highest-priority)
9206 (> (upcase new) org-lowest-priority))
9207 (setq remove t))
9208 (setq news (format "%c" new))
9209 (if have
9210 (if remove
9211 (replace-match "" t t nil 1)
9212 (replace-match news t t nil 2))
9213 (if remove
9214 (error "No priority cookie found in line")
9215 (looking-at org-todo-line-regexp)
9216 (if (match-end 2)
9217 (progn
9218 (goto-char (match-end 2))
9219 (insert " [#" news "]"))
9220 (goto-char (match-beginning 3))
9221 (insert "[#" news "] ")))))
9222 (org-preserve-lc (org-set-tags nil 'align))
9223 (if remove
9224 (message "Priority removed")
9225 (message "Priority of current item set to %s" news))))
9228 (defun org-get-priority (s)
9229 "Find priority cookie and return priority."
9230 (save-match-data
9231 (if (not (string-match org-priority-regexp s))
9232 (* 1000 (- org-lowest-priority org-default-priority))
9233 (* 1000 (- org-lowest-priority
9234 (string-to-char (match-string 2 s)))))))
9236 ;;;; Tags
9238 (defun org-scan-tags (action matcher &optional todo-only)
9239 "Scan headline tags with inheritance and produce output ACTION.
9240 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
9241 evaluated, testing if a given set of tags qualifies a headline for
9242 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
9243 are included in the output."
9244 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9245 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9246 (org-re
9247 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9248 (props (list 'face nil
9249 'done-face 'org-done
9250 'undone-face nil
9251 'mouse-face 'highlight
9252 'org-not-done-regexp org-not-done-regexp
9253 'org-todo-regexp org-todo-regexp
9254 'keymap org-agenda-keymap
9255 'help-echo
9256 (format "mouse-2 or RET jump to org file %s"
9257 (abbreviate-file-name
9258 (or (buffer-file-name (buffer-base-buffer))
9259 (buffer-name (buffer-base-buffer)))))))
9260 (case-fold-search nil)
9261 lspos
9262 tags tags-list tags-alist (llast 0) rtn level category i txt
9263 todo marker entry priority)
9264 (save-excursion
9265 (goto-char (point-min))
9266 (when (eq action 'sparse-tree)
9267 (org-overview)
9268 (org-remove-occur-highlights))
9269 (while (re-search-forward re nil t)
9270 (catch :skip
9271 (setq todo (if (match-end 1) (match-string 2))
9272 tags (if (match-end 4) (match-string 4)))
9273 (goto-char (setq lspos (1+ (match-beginning 0))))
9274 (setq level (org-reduced-level (funcall outline-level))
9275 category (org-get-category))
9276 (setq i llast llast level)
9277 ;; remove tag lists from same and sublevels
9278 (while (>= i level)
9279 (when (setq entry (assoc i tags-alist))
9280 (setq tags-alist (delete entry tags-alist)))
9281 (setq i (1- i)))
9282 ;; add the next tags
9283 (when tags
9284 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9285 tags-alist
9286 (cons (cons level tags) tags-alist)))
9287 ;; compile tags for current headline
9288 (setq tags-list
9289 (if org-use-tag-inheritance
9290 (apply 'append (mapcar 'cdr tags-alist))
9291 tags))
9292 (when (and tags org-use-tag-inheritance
9293 (not (eq t org-use-tag-inheritance)))
9294 ;; selective inheritance, remove uninherited ones
9295 (setcdr (car tags-alist)
9296 (org-remove-uniherited-tags (cdar tags-alist))))
9297 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9298 (eval matcher)
9299 (or (not org-agenda-skip-archived-trees)
9300 (not (member org-archive-tag tags-list))))
9301 (and (eq action 'agenda) (org-agenda-skip))
9302 ;; list this headline
9304 (if (eq action 'sparse-tree)
9305 (progn
9306 (and org-highlight-sparse-tree-matches
9307 (org-get-heading) (match-end 0)
9308 (org-highlight-new-match
9309 (match-beginning 0) (match-beginning 1)))
9310 (org-show-context 'tags-tree))
9311 (setq txt (org-format-agenda-item
9313 (concat
9314 (if org-tags-match-list-sublevels
9315 (make-string (1- level) ?.) "")
9316 (org-get-heading))
9317 category tags-list)
9318 priority (org-get-priority txt))
9319 (goto-char lspos)
9320 (setq marker (org-agenda-new-marker))
9321 (org-add-props txt props
9322 'org-marker marker 'org-hd-marker marker 'org-category category
9323 'priority priority 'type "tagsmatch")
9324 (push txt rtn))
9325 ;; if we are to skip sublevels, jump to end of subtree
9326 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9327 (when (and (eq action 'sparse-tree)
9328 (not org-sparse-tree-open-archived-trees))
9329 (org-hide-archived-subtrees (point-min) (point-max)))
9330 (nreverse rtn)))
9332 (defun org-remove-uniherited-tags (tags)
9333 "Remove all tags that are not inherited from the list TAGS."
9334 (cond
9335 ((eq org-use-tag-inheritance t) tags)
9336 ((not org-use-tag-inheritance) nil)
9337 ((stringp org-use-tag-inheritance)
9338 (delq nil (mapcar
9339 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9340 tags)))
9341 ((listp org-use-tag-inheritance)
9342 (org-delete-all org-use-tag-inheritance tags))))
9344 (defvar todo-only) ;; dynamically scoped
9346 (defun org-tags-sparse-tree (&optional todo-only match)
9347 "Create a sparse tree according to tags string MATCH.
9348 MATCH can contain positive and negative selection of tags, like
9349 \"+WORK+URGENT-WITHBOSS\".
9350 If optional argument TODO_ONLY is non-nil, only select lines that are
9351 also TODO lines."
9352 (interactive "P")
9353 (org-prepare-agenda-buffers (list (current-buffer)))
9354 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9356 (defvar org-cached-props nil)
9357 (defun org-cached-entry-get (pom property)
9358 (if (or (eq t org-use-property-inheritance)
9359 (and (stringp org-use-property-inheritance)
9360 (string-match org-use-property-inheritance property))
9361 (and (listp org-use-property-inheritance)
9362 (member property org-use-property-inheritance)))
9363 ;; Caching is not possible, check it directly
9364 (org-entry-get pom property 'inherit)
9365 ;; Get all properties, so that we can do complicated checks easily
9366 (cdr (assoc property (or org-cached-props
9367 (setq org-cached-props
9368 (org-entry-properties pom)))))))
9370 (defun org-global-tags-completion-table (&optional files)
9371 "Return the list of all tags in all agenda buffer/files."
9372 (save-excursion
9373 (org-uniquify
9374 (delq nil
9375 (apply 'append
9376 (mapcar
9377 (lambda (file)
9378 (set-buffer (find-file-noselect file))
9379 (append (org-get-buffer-tags)
9380 (mapcar (lambda (x) (if (stringp (car-safe x))
9381 (list (car-safe x)) nil))
9382 org-tag-alist)))
9383 (if (and files (car files))
9384 files
9385 (org-agenda-files))))))))
9387 (defun org-make-tags-matcher (match)
9388 "Create the TAGS//TODO matcher form for the selection string MATCH."
9389 ;; todo-only is scoped dynamically into this function, and the function
9390 ;; may change it it the matcher asksk for it.
9391 (unless match
9392 ;; Get a new match request, with completion
9393 (let ((org-last-tags-completion-table
9394 (org-global-tags-completion-table)))
9395 (setq match (completing-read
9396 "Match: " 'org-tags-completion-function nil nil nil
9397 'org-tags-history))))
9399 ;; Parse the string and create a lisp form
9400 (let ((match0 match)
9401 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
9402 minus tag mm
9403 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9404 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
9405 (if (string-match "/+" match)
9406 ;; match contains also a todo-matching request
9407 (progn
9408 (setq tagsmatch (substring match 0 (match-beginning 0))
9409 todomatch (substring match (match-end 0)))
9410 (if (string-match "^!" todomatch)
9411 (setq todo-only t todomatch (substring todomatch 1)))
9412 (if (string-match "^\\s-*$" todomatch)
9413 (setq todomatch nil)))
9414 ;; only matching tags
9415 (setq tagsmatch match todomatch nil))
9417 ;; Make the tags matcher
9418 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9419 (setq tagsmatcher t)
9420 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9421 (while (setq term (pop orterms))
9422 (while (and (equal (substring term -1) "\\") orterms)
9423 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9424 (while (string-match re term)
9425 (setq minus (and (match-end 1)
9426 (equal (match-string 1 term) "-"))
9427 tag (match-string 2 term)
9428 re-p (equal (string-to-char tag) ?{)
9429 level-p (match-end 3)
9430 prop-p (match-end 4)
9431 mm (cond
9432 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9433 (level-p `(= level ,(string-to-number
9434 (match-string 3 term))))
9435 (prop-p
9436 (setq pn (match-string 4 term)
9437 pv (match-string 5 term)
9438 cat-p (equal pn "CATEGORY")
9439 re-p (equal (string-to-char pv) ?{)
9440 pv (substring pv 1 -1))
9441 (if (equal pn "CATEGORY")
9442 (setq gv '(get-text-property (point) 'org-category))
9443 (setq gv `(org-cached-entry-get nil ,pn)))
9444 (if re-p
9445 `(string-match ,pv (or ,gv ""))
9446 `(equal ,pv (or ,gv ""))))
9447 (t `(member ,(downcase tag) tags-list)))
9448 mm (if minus (list 'not mm) mm)
9449 term (substring term (match-end 0)))
9450 (push mm tagsmatcher))
9451 (push (if (> (length tagsmatcher) 1)
9452 (cons 'and tagsmatcher)
9453 (car tagsmatcher))
9454 orlist)
9455 (setq tagsmatcher nil))
9456 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9457 (setq tagsmatcher
9458 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9460 ;; Make the todo matcher
9461 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9462 (setq todomatcher t)
9463 (setq orterms (org-split-string todomatch "|") orlist nil)
9464 (while (setq term (pop orterms))
9465 (while (string-match re term)
9466 (setq minus (and (match-end 1)
9467 (equal (match-string 1 term) "-"))
9468 kwd (match-string 2 term)
9469 re-p (equal (string-to-char kwd) ?{)
9470 term (substring term (match-end 0))
9471 mm (if re-p
9472 `(string-match ,(substring kwd 1 -1) todo)
9473 (list 'equal 'todo kwd))
9474 mm (if minus (list 'not mm) mm))
9475 (push mm todomatcher))
9476 (push (if (> (length todomatcher) 1)
9477 (cons 'and todomatcher)
9478 (car todomatcher))
9479 orlist)
9480 (setq todomatcher nil))
9481 (setq todomatcher (if (> (length orlist) 1)
9482 (cons 'or orlist) (car orlist))))
9484 ;; Return the string and lisp forms of the matcher
9485 (setq matcher (if todomatcher
9486 (list 'and tagsmatcher todomatcher)
9487 tagsmatcher))
9488 (cons match0 matcher)))
9490 (defun org-match-any-p (re list)
9491 "Does re match any element of list?"
9492 (setq list (mapcar (lambda (x) (string-match re x)) list))
9493 (delq nil list))
9495 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9496 (defvar org-tags-overlay (org-make-overlay 1 1))
9497 (org-detach-overlay org-tags-overlay)
9499 (defun org-align-tags-here (to-col)
9500 ;; Assumes that this is a headline
9501 (let ((pos (point)) (col (current-column)) tags)
9502 (beginning-of-line 1)
9503 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9504 (< pos (match-beginning 2)))
9505 (progn
9506 (setq tags (match-string 2))
9507 (goto-char (match-beginning 1))
9508 (insert " ")
9509 (delete-region (point) (1+ (match-end 0)))
9510 (backward-char 1)
9511 (move-to-column
9512 (max (1+ (current-column))
9513 (1+ col)
9514 (if (> to-col 0)
9515 to-col
9516 (- (abs to-col) (length tags))))
9518 (insert tags)
9519 (move-to-column (min (current-column) col) t))
9520 (goto-char pos))))
9522 (defun org-set-tags (&optional arg just-align)
9523 "Set the tags for the current headline.
9524 With prefix ARG, realign all tags in headings in the current buffer."
9525 (interactive "P")
9526 (let* ((re (concat "^" outline-regexp))
9527 (current (org-get-tags-string))
9528 (col (current-column))
9529 (org-setting-tags t)
9530 table current-tags inherited-tags ; computed below when needed
9531 tags p0 c0 c1 rpl)
9532 (if arg
9533 (save-excursion
9534 (goto-char (point-min))
9535 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9536 (while (re-search-forward re nil t)
9537 (org-set-tags nil t)
9538 (end-of-line 1)))
9539 (message "All tags realigned to column %d" org-tags-column))
9540 (if just-align
9541 (setq tags current)
9542 ;; Get a new set of tags from the user
9543 (save-excursion
9544 (setq table (or org-tag-alist (org-get-buffer-tags))
9545 org-last-tags-completion-table table
9546 current-tags (org-split-string current ":")
9547 inherited-tags (nreverse
9548 (nthcdr (length current-tags)
9549 (nreverse (org-get-tags-at))))
9550 tags
9551 (if (or (eq t org-use-fast-tag-selection)
9552 (and org-use-fast-tag-selection
9553 (delq nil (mapcar 'cdr table))))
9554 (org-fast-tag-selection
9555 current-tags inherited-tags table
9556 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9557 (let ((org-add-colon-after-tag-completion t))
9558 (org-trim
9559 (org-without-partial-completion
9560 (completing-read "Tags: " 'org-tags-completion-function
9561 nil nil current 'org-tags-history)))))))
9562 (while (string-match "[-+&]+" tags)
9563 ;; No boolean logic, just a list
9564 (setq tags (replace-match ":" t t tags))))
9566 (if (string-match "\\`[\t ]*\\'" tags)
9567 (setq tags "")
9568 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9569 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9571 ;; Insert new tags at the correct column
9572 (beginning-of-line 1)
9573 (cond
9574 ((and (equal current "") (equal tags "")))
9575 ((re-search-forward
9576 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9577 (point-at-eol) t)
9578 (if (equal tags "")
9579 (setq rpl "")
9580 (goto-char (match-beginning 0))
9581 (setq c0 (current-column) p0 (point)
9582 c1 (max (1+ c0) (if (> org-tags-column 0)
9583 org-tags-column
9584 (- (- org-tags-column) (length tags))))
9585 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9586 (replace-match rpl t t)
9587 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9588 tags)
9589 (t (error "Tags alignment failed")))
9590 (move-to-column col)
9591 (unless just-align
9592 (run-hooks 'org-after-tags-change-hook)))))
9594 (defun org-change-tag-in-region (beg end tag off)
9595 "Add or remove TAG for each entry in the region.
9596 This works in the agenda, and also in an org-mode buffer."
9597 (interactive
9598 (list (region-beginning) (region-end)
9599 (let ((org-last-tags-completion-table
9600 (if (org-mode-p)
9601 (org-get-buffer-tags)
9602 (org-global-tags-completion-table))))
9603 (completing-read
9604 "Tag: " 'org-tags-completion-function nil nil nil
9605 'org-tags-history))
9606 (progn
9607 (message "[s]et or [r]emove? ")
9608 (equal (read-char-exclusive) ?r))))
9609 (if (fboundp 'deactivate-mark) (deactivate-mark))
9610 (let ((agendap (equal major-mode 'org-agenda-mode))
9611 l1 l2 m buf pos newhead (cnt 0))
9612 (goto-char end)
9613 (setq l2 (1- (org-current-line)))
9614 (goto-char beg)
9615 (setq l1 (org-current-line))
9616 (loop for l from l1 to l2 do
9617 (goto-line l)
9618 (setq m (get-text-property (point) 'org-hd-marker))
9619 (when (or (and (org-mode-p) (org-on-heading-p))
9620 (and agendap m))
9621 (setq buf (if agendap (marker-buffer m) (current-buffer))
9622 pos (if agendap m (point)))
9623 (with-current-buffer buf
9624 (save-excursion
9625 (save-restriction
9626 (goto-char pos)
9627 (setq cnt (1+ cnt))
9628 (org-toggle-tag tag (if off 'off 'on))
9629 (setq newhead (org-get-heading)))))
9630 (and agendap (org-agenda-change-all-lines newhead m))))
9631 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9633 (defun org-tags-completion-function (string predicate &optional flag)
9634 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9635 (confirm (lambda (x) (stringp (car x)))))
9636 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9637 (setq s1 (match-string 1 string)
9638 s2 (match-string 2 string))
9639 (setq s1 "" s2 string))
9640 (cond
9641 ((eq flag nil)
9642 ;; try completion
9643 (setq rtn (try-completion s2 ctable confirm))
9644 (if (stringp rtn)
9645 (setq rtn
9646 (concat s1 s2 (substring rtn (length s2))
9647 (if (and org-add-colon-after-tag-completion
9648 (assoc rtn ctable))
9649 ":" ""))))
9650 rtn)
9651 ((eq flag t)
9652 ;; all-completions
9653 (all-completions s2 ctable confirm)
9655 ((eq flag 'lambda)
9656 ;; exact match?
9657 (assoc s2 ctable)))
9660 (defun org-fast-tag-insert (kwd tags face &optional end)
9661 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9662 (insert (format "%-12s" (concat kwd ":"))
9663 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9664 (or end "")))
9666 (defun org-fast-tag-show-exit (flag)
9667 (save-excursion
9668 (goto-line 3)
9669 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9670 (replace-match ""))
9671 (when flag
9672 (end-of-line 1)
9673 (move-to-column (- (window-width) 19) t)
9674 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9676 (defun org-set-current-tags-overlay (current prefix)
9677 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9678 (if (featurep 'xemacs)
9679 (org-overlay-display org-tags-overlay (concat prefix s)
9680 'secondary-selection)
9681 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9682 (org-overlay-display org-tags-overlay (concat prefix s)))))
9684 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9685 "Fast tag selection with single keys.
9686 CURRENT is the current list of tags in the headline, INHERITED is the
9687 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9688 possibly with grouping information. TODO-TABLE is a similar table with
9689 TODO keywords, should these have keys assigned to them.
9690 If the keys are nil, a-z are automatically assigned.
9691 Returns the new tags string, or nil to not change the current settings."
9692 (let* ((fulltable (append table todo-table))
9693 (maxlen (apply 'max (mapcar
9694 (lambda (x)
9695 (if (stringp (car x)) (string-width (car x)) 0))
9696 fulltable)))
9697 (buf (current-buffer))
9698 (expert (eq org-fast-tag-selection-single-key 'expert))
9699 (buffer-tags nil)
9700 (fwidth (+ maxlen 3 1 3))
9701 (ncol (/ (- (window-width) 4) fwidth))
9702 (i-face 'org-done)
9703 (c-face 'org-todo)
9704 tg cnt e c char c1 c2 ntable tbl rtn
9705 ov-start ov-end ov-prefix
9706 (exit-after-next org-fast-tag-selection-single-key)
9707 (done-keywords org-done-keywords)
9708 groups ingroup)
9709 (save-excursion
9710 (beginning-of-line 1)
9711 (if (looking-at
9712 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9713 (setq ov-start (match-beginning 1)
9714 ov-end (match-end 1)
9715 ov-prefix "")
9716 (setq ov-start (1- (point-at-eol))
9717 ov-end (1+ ov-start))
9718 (skip-chars-forward "^\n\r")
9719 (setq ov-prefix
9720 (concat
9721 (buffer-substring (1- (point)) (point))
9722 (if (> (current-column) org-tags-column)
9724 (make-string (- org-tags-column (current-column)) ?\ ))))))
9725 (org-move-overlay org-tags-overlay ov-start ov-end)
9726 (save-window-excursion
9727 (if expert
9728 (set-buffer (get-buffer-create " *Org tags*"))
9729 (delete-other-windows)
9730 (split-window-vertically)
9731 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9732 (erase-buffer)
9733 (org-set-local 'org-done-keywords done-keywords)
9734 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9735 (org-fast-tag-insert "Current" current c-face "\n\n")
9736 (org-fast-tag-show-exit exit-after-next)
9737 (org-set-current-tags-overlay current ov-prefix)
9738 (setq tbl fulltable char ?a cnt 0)
9739 (while (setq e (pop tbl))
9740 (cond
9741 ((equal e '(:startgroup))
9742 (push '() groups) (setq ingroup t)
9743 (when (not (= cnt 0))
9744 (setq cnt 0)
9745 (insert "\n"))
9746 (insert "{ "))
9747 ((equal e '(:endgroup))
9748 (setq ingroup nil cnt 0)
9749 (insert "}\n"))
9751 (setq tg (car e) c2 nil)
9752 (if (cdr e)
9753 (setq c (cdr e))
9754 ;; automatically assign a character.
9755 (setq c1 (string-to-char
9756 (downcase (substring
9757 tg (if (= (string-to-char tg) ?@) 1 0)))))
9758 (if (or (rassoc c1 ntable) (rassoc c1 table))
9759 (while (or (rassoc char ntable) (rassoc char table))
9760 (setq char (1+ char)))
9761 (setq c2 c1))
9762 (setq c (or c2 char)))
9763 (if ingroup (push tg (car groups)))
9764 (setq tg (org-add-props tg nil 'face
9765 (cond
9766 ((not (assoc tg table))
9767 (org-get-todo-face tg))
9768 ((member tg current) c-face)
9769 ((member tg inherited) i-face)
9770 (t nil))))
9771 (if (and (= cnt 0) (not ingroup)) (insert " "))
9772 (insert "[" c "] " tg (make-string
9773 (- fwidth 4 (length tg)) ?\ ))
9774 (push (cons tg c) ntable)
9775 (when (= (setq cnt (1+ cnt)) ncol)
9776 (insert "\n")
9777 (if ingroup (insert " "))
9778 (setq cnt 0)))))
9779 (setq ntable (nreverse ntable))
9780 (insert "\n")
9781 (goto-char (point-min))
9782 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9783 (fit-window-to-buffer))
9784 (setq rtn
9785 (catch 'exit
9786 (while t
9787 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9788 (if groups " [!] no groups" " [!]groups")
9789 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9790 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9791 (cond
9792 ((= c ?\r) (throw 'exit t))
9793 ((= c ?!)
9794 (setq groups (not groups))
9795 (goto-char (point-min))
9796 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9797 ((= c ?\C-c)
9798 (if (not expert)
9799 (org-fast-tag-show-exit
9800 (setq exit-after-next (not exit-after-next)))
9801 (setq expert nil)
9802 (delete-other-windows)
9803 (split-window-vertically)
9804 (org-switch-to-buffer-other-window " *Org tags*")
9805 (and (fboundp 'fit-window-to-buffer)
9806 (fit-window-to-buffer))))
9807 ((or (= c ?\C-g)
9808 (and (= c ?q) (not (rassoc c ntable))))
9809 (org-detach-overlay org-tags-overlay)
9810 (setq quit-flag t))
9811 ((= c ?\ )
9812 (setq current nil)
9813 (if exit-after-next (setq exit-after-next 'now)))
9814 ((= c ?\t)
9815 (condition-case nil
9816 (setq tg (completing-read
9817 "Tag: "
9818 (or buffer-tags
9819 (with-current-buffer buf
9820 (org-get-buffer-tags)))))
9821 (quit (setq tg "")))
9822 (when (string-match "\\S-" tg)
9823 (add-to-list 'buffer-tags (list tg))
9824 (if (member tg current)
9825 (setq current (delete tg current))
9826 (push tg current)))
9827 (if exit-after-next (setq exit-after-next 'now)))
9828 ((setq e (rassoc c todo-table) tg (car e))
9829 (with-current-buffer buf
9830 (save-excursion (org-todo tg)))
9831 (if exit-after-next (setq exit-after-next 'now)))
9832 ((setq e (rassoc c ntable) tg (car e))
9833 (if (member tg current)
9834 (setq current (delete tg current))
9835 (loop for g in groups do
9836 (if (member tg g)
9837 (mapc (lambda (x)
9838 (setq current (delete x current)))
9839 g)))
9840 (push tg current))
9841 (if exit-after-next (setq exit-after-next 'now))))
9843 ;; Create a sorted list
9844 (setq current
9845 (sort current
9846 (lambda (a b)
9847 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9848 (if (eq exit-after-next 'now) (throw 'exit t))
9849 (goto-char (point-min))
9850 (beginning-of-line 2)
9851 (delete-region (point) (point-at-eol))
9852 (org-fast-tag-insert "Current" current c-face)
9853 (org-set-current-tags-overlay current ov-prefix)
9854 (while (re-search-forward
9855 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9856 (setq tg (match-string 1))
9857 (add-text-properties
9858 (match-beginning 1) (match-end 1)
9859 (list 'face
9860 (cond
9861 ((member tg current) c-face)
9862 ((member tg inherited) i-face)
9863 (t (get-text-property (match-beginning 1) 'face))))))
9864 (goto-char (point-min)))))
9865 (org-detach-overlay org-tags-overlay)
9866 (if rtn
9867 (mapconcat 'identity current ":")
9868 nil))))
9870 (defun org-get-tags-string ()
9871 "Get the TAGS string in the current headline."
9872 (unless (org-on-heading-p t)
9873 (error "Not on a heading"))
9874 (save-excursion
9875 (beginning-of-line 1)
9876 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9877 (org-match-string-no-properties 1)
9878 "")))
9880 (defun org-get-tags ()
9881 "Get the list of tags specified in the current headline."
9882 (org-split-string (org-get-tags-string) ":"))
9884 (defun org-get-buffer-tags ()
9885 "Get a table of all tags used in the buffer, for completion."
9886 (let (tags)
9887 (save-excursion
9888 (goto-char (point-min))
9889 (while (re-search-forward
9890 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9891 (when (equal (char-after (point-at-bol 0)) ?*)
9892 (mapc (lambda (x) (add-to-list 'tags x))
9893 (org-split-string (org-match-string-no-properties 1) ":")))))
9894 (mapcar 'list tags)))
9897 ;;;; Properties
9899 ;;; Setting and retrieving properties
9901 (defconst org-special-properties
9902 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9903 "TIMESTAMP" "TIMESTAMP_IA")
9904 "The special properties valid in Org-mode.
9906 These are properties that are not defined in the property drawer,
9907 but in some other way.")
9909 (defconst org-default-properties
9910 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9911 "LOCATION" "LOGGING" "COLUMNS")
9912 "Some properties that are used by Org-mode for various purposes.
9913 Being in this list makes sure that they are offered for completion.")
9915 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9916 "Regular expression matching the first line of a property drawer.")
9918 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9919 "Regular expression matching the first line of a property drawer.")
9921 (defun org-property-action ()
9922 "Do an action on properties."
9923 (interactive)
9924 (let (c)
9925 (org-at-property-p)
9926 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9927 (setq c (read-char-exclusive))
9928 (cond
9929 ((equal c ?s)
9930 (call-interactively 'org-set-property))
9931 ((equal c ?d)
9932 (call-interactively 'org-delete-property))
9933 ((equal c ?D)
9934 (call-interactively 'org-delete-property-globally))
9935 ((equal c ?c)
9936 (call-interactively 'org-compute-property-at-point))
9937 (t (error "No such property action %c" c)))))
9939 (defun org-at-property-p ()
9940 "Is the cursor in a property line?"
9941 ;; FIXME: Does not check if we are actually in the drawer.
9942 ;; FIXME: also returns true on any drawers.....
9943 ;; This is used by C-c C-c for property action.
9944 (save-excursion
9945 (beginning-of-line 1)
9946 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9948 (defun org-get-property-block (&optional beg end force)
9949 "Return the (beg . end) range of the body of the property drawer.
9950 BEG and END can be beginning and end of subtree, if not given
9951 they will be found.
9952 If the drawer does not exist and FORCE is non-nil, create the drawer."
9953 (catch 'exit
9954 (save-excursion
9955 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9956 (end (or end (progn (outline-next-heading) (point)))))
9957 (goto-char beg)
9958 (if (re-search-forward org-property-start-re end t)
9959 (setq beg (1+ (match-end 0)))
9960 (if force
9961 (save-excursion
9962 (org-insert-property-drawer)
9963 (setq end (progn (outline-next-heading) (point))))
9964 (throw 'exit nil))
9965 (goto-char beg)
9966 (if (re-search-forward org-property-start-re end t)
9967 (setq beg (1+ (match-end 0)))))
9968 (if (re-search-forward org-property-end-re end t)
9969 (setq end (match-beginning 0))
9970 (or force (throw 'exit nil))
9971 (goto-char beg)
9972 (setq end beg)
9973 (org-indent-line-function)
9974 (insert ":END:\n"))
9975 (cons beg end)))))
9977 (defun org-entry-properties (&optional pom which)
9978 "Get all properties of the entry at point-or-marker POM.
9979 This includes the TODO keyword, the tags, time strings for deadline,
9980 scheduled, and clocking, and any additional properties defined in the
9981 entry. The return value is an alist, keys may occur multiple times
9982 if the property key was used several times.
9983 POM may also be nil, in which case the current entry is used.
9984 If WHICH is nil or `all', get all properties. If WHICH is
9985 `special' or `standard', only get that subclass."
9986 (setq which (or which 'all))
9987 (org-with-point-at pom
9988 (let ((clockstr (substring org-clock-string 0 -1))
9989 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9990 beg end range props sum-props key value string clocksum)
9991 (save-excursion
9992 (when (condition-case nil (org-back-to-heading t) (error nil))
9993 (setq beg (point))
9994 (setq sum-props (get-text-property (point) 'org-summaries))
9995 (setq clocksum (get-text-property (point) :org-clock-minutes))
9996 (outline-next-heading)
9997 (setq end (point))
9998 (when (memq which '(all special))
9999 ;; Get the special properties, like TODO and tags
10000 (goto-char beg)
10001 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10002 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10003 (when (looking-at org-priority-regexp)
10004 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10005 (when (and (setq value (org-get-tags-string))
10006 (string-match "\\S-" value))
10007 (push (cons "TAGS" value) props))
10008 (when (setq value (org-get-tags-at))
10009 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10010 props))
10011 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10012 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10013 string (if (equal key clockstr)
10014 (org-no-properties
10015 (org-trim
10016 (buffer-substring
10017 (match-beginning 3) (goto-char (point-at-eol)))))
10018 (substring (org-match-string-no-properties 3) 1 -1)))
10019 (unless key
10020 (if (= (char-after (match-beginning 3)) ?\[)
10021 (setq key "TIMESTAMP_IA")
10022 (setq key "TIMESTAMP")))
10023 (when (or (equal key clockstr) (not (assoc key props)))
10024 (push (cons key string) props)))
10028 (when (memq which '(all standard))
10029 ;; Get the standard properties, like :PORP: ...
10030 (setq range (org-get-property-block beg end))
10031 (when range
10032 (goto-char (car range))
10033 (while (re-search-forward
10034 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10035 (cdr range) t)
10036 (setq key (org-match-string-no-properties 1)
10037 value (org-trim (or (org-match-string-no-properties 2) "")))
10038 (unless (member key excluded)
10039 (push (cons key (or value "")) props)))))
10040 (if clocksum
10041 (push (cons "CLOCKSUM"
10042 (org-column-number-to-string (/ (float clocksum) 60.)
10043 'add_times))
10044 props))
10045 (append sum-props (nreverse props)))))))
10047 (defun org-entry-get (pom property &optional inherit)
10048 "Get value of PROPERTY for entry at point-or-marker POM.
10049 If INHERIT is non-nil and the entry does not have the property,
10050 then also check higher levels of the hierarchy.
10051 If INHERIT is the symbol `selective', use inheritance only if the setting
10052 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10053 If the property is present but empty, the return value is the empty string.
10054 If the property is not present at all, nil is returned."
10055 (org-with-point-at pom
10056 (if (and inherit (if (eq inherit 'selective)
10057 (org-property-inherit-p property)
10059 (org-entry-get-with-inheritance property)
10060 (if (member property org-special-properties)
10061 ;; We need a special property. Use brute force, get all properties.
10062 (cdr (assoc property (org-entry-properties nil 'special)))
10063 (let ((range (org-get-property-block)))
10064 (if (and range
10065 (goto-char (car range))
10066 (re-search-forward
10067 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10068 (cdr range) t))
10069 ;; Found the property, return it.
10070 (if (match-end 1)
10071 (org-match-string-no-properties 1)
10072 "")))))))
10074 (defun org-entry-delete (pom property)
10075 "Delete the property PROPERTY from entry at point-or-marker POM."
10076 (org-with-point-at pom
10077 (if (member property org-special-properties)
10078 nil ; cannot delete these properties.
10079 (let ((range (org-get-property-block)))
10080 (if (and range
10081 (goto-char (car range))
10082 (re-search-forward
10083 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10084 (cdr range) t))
10085 (progn
10086 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10088 nil)))))
10090 ;; Multi-values properties are properties that contain multiple values
10091 ;; These values are assumed to be single words, separated by whitespace.
10092 (defun org-entry-add-to-multivalued-property (pom property value)
10093 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10094 (let* ((old (org-entry-get pom property))
10095 (values (and old (org-split-string old "[ \t]"))))
10096 (unless (member value values)
10097 (setq values (cons value values))
10098 (org-entry-put pom property
10099 (mapconcat 'identity values " ")))))
10101 (defun org-entry-remove-from-multivalued-property (pom property value)
10102 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10103 (let* ((old (org-entry-get pom property))
10104 (values (and old (org-split-string old "[ \t]"))))
10105 (when (member value values)
10106 (setq values (delete value values))
10107 (org-entry-put pom property
10108 (mapconcat 'identity values " ")))))
10110 (defun org-entry-member-in-multivalued-property (pom property value)
10111 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10112 (let* ((old (org-entry-get pom property))
10113 (values (and old (org-split-string old "[ \t]"))))
10114 (member value values)))
10116 (defvar org-entry-property-inherited-from (make-marker))
10118 (defun org-entry-get-with-inheritance (property)
10119 "Get entry property, and search higher levels if not present."
10120 (let (tmp)
10121 (save-excursion
10122 (save-restriction
10123 (widen)
10124 (catch 'ex
10125 (while t
10126 (when (setq tmp (org-entry-get nil property))
10127 (org-back-to-heading t)
10128 (move-marker org-entry-property-inherited-from (point))
10129 (throw 'ex tmp))
10130 (or (org-up-heading-safe) (throw 'ex nil)))))
10131 (or tmp (cdr (assoc property org-local-properties))
10132 (cdr (assoc property org-global-properties))))))
10134 (defun org-entry-put (pom property value)
10135 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10136 (org-with-point-at pom
10137 (org-back-to-heading t)
10138 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10139 range)
10140 (cond
10141 ((equal property "TODO")
10142 (when (and (stringp value) (string-match "\\S-" value)
10143 (not (member value org-todo-keywords-1)))
10144 (error "\"%s\" is not a valid TODO state" value))
10145 (if (or (not value)
10146 (not (string-match "\\S-" value)))
10147 (setq value 'none))
10148 (org-todo value)
10149 (org-set-tags nil 'align))
10150 ((equal property "PRIORITY")
10151 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10152 (string-to-char value) ?\ ))
10153 (org-set-tags nil 'align))
10154 ((equal property "SCHEDULED")
10155 (if (re-search-forward org-scheduled-time-regexp end t)
10156 (cond
10157 ((eq value 'earlier) (org-timestamp-change -1 'day))
10158 ((eq value 'later) (org-timestamp-change 1 'day))
10159 (t (call-interactively 'org-schedule)))
10160 (call-interactively 'org-schedule)))
10161 ((equal property "DEADLINE")
10162 (if (re-search-forward org-deadline-time-regexp end t)
10163 (cond
10164 ((eq value 'earlier) (org-timestamp-change -1 'day))
10165 ((eq value 'later) (org-timestamp-change 1 'day))
10166 (t (call-interactively 'org-deadline)))
10167 (call-interactively 'org-deadline)))
10168 ((member property org-special-properties)
10169 (error "The %s property can not yet be set with `org-entry-put'"
10170 property))
10171 (t ; a non-special property
10172 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10173 (setq range (org-get-property-block beg end 'force))
10174 (goto-char (car range))
10175 (if (re-search-forward
10176 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10177 (progn
10178 (delete-region (match-beginning 1) (match-end 1))
10179 (goto-char (match-beginning 1)))
10180 (goto-char (cdr range))
10181 (insert "\n")
10182 (backward-char 1)
10183 (org-indent-line-function)
10184 (insert ":" property ":"))
10185 (and value (insert " " value))
10186 (org-indent-line-function)))))))
10188 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10189 "Get all property keys in the current buffer.
10190 With INCLUDE-SPECIALS, also list the special properties that relect things
10191 like tags and TODO state.
10192 With INCLUDE-DEFAULTS, also include properties that has special meaning
10193 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10194 With INCLUDE-COLUMNS, also include property names given in COLUMN
10195 formats in the current buffer."
10196 (let (rtn range cfmt cols s p)
10197 (save-excursion
10198 (save-restriction
10199 (widen)
10200 (goto-char (point-min))
10201 (while (re-search-forward org-property-start-re nil t)
10202 (setq range (org-get-property-block))
10203 (goto-char (car range))
10204 (while (re-search-forward
10205 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10206 (cdr range) t)
10207 (add-to-list 'rtn (org-match-string-no-properties 1)))
10208 (outline-next-heading))))
10210 (when include-specials
10211 (setq rtn (append org-special-properties rtn)))
10213 (when include-defaults
10214 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10216 (when include-columns
10217 (save-excursion
10218 (save-restriction
10219 (widen)
10220 (goto-char (point-min))
10221 (while (re-search-forward
10222 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10223 nil t)
10224 (setq cfmt (match-string 2) s 0)
10225 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10226 cfmt s)
10227 (setq s (match-end 0)
10228 p (match-string 1 cfmt))
10229 (unless (or (equal p "ITEM")
10230 (member p org-special-properties))
10231 (add-to-list 'rtn (match-string 1 cfmt))))))))
10233 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10235 (defun org-property-values (key)
10236 "Return a list of all values of property KEY."
10237 (save-excursion
10238 (save-restriction
10239 (widen)
10240 (goto-char (point-min))
10241 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10242 values)
10243 (while (re-search-forward re nil t)
10244 (add-to-list 'values (org-trim (match-string 1))))
10245 (delete "" values)))))
10247 (defun org-insert-property-drawer ()
10248 "Insert a property drawer into the current entry."
10249 (interactive)
10250 (org-back-to-heading t)
10251 (looking-at outline-regexp)
10252 (let ((indent (- (match-end 0)(match-beginning 0)))
10253 (beg (point))
10254 (re (concat "^[ \t]*" org-keyword-time-regexp))
10255 end hiddenp)
10256 (outline-next-heading)
10257 (setq end (point))
10258 (goto-char beg)
10259 (while (re-search-forward re end t))
10260 (setq hiddenp (org-invisible-p))
10261 (end-of-line 1)
10262 (and (equal (char-after) ?\n) (forward-char 1))
10263 (org-skip-over-state-notes)
10264 (skip-chars-backward " \t\n\r")
10265 (if (eq (char-before) ?*) (forward-char 1))
10266 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10267 (beginning-of-line 0)
10268 (indent-to-column indent)
10269 (beginning-of-line 2)
10270 (indent-to-column indent)
10271 (beginning-of-line 0)
10272 (if hiddenp
10273 (save-excursion
10274 (org-back-to-heading t)
10275 (hide-entry))
10276 (org-flag-drawer t))))
10278 (defun org-set-property (property value)
10279 "In the current entry, set PROPERTY to VALUE.
10280 When called interactively, this will prompt for a property name, offering
10281 completion on existing and default properties. And then it will prompt
10282 for a value, offering competion either on allowed values (via an inherited
10283 xxx_ALL property) or on existing values in other instances of this property
10284 in the current file."
10285 (interactive
10286 (let* ((prop (completing-read
10287 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
10288 (cur (org-entry-get nil prop))
10289 (allowed (org-property-get-allowed-values nil prop 'table))
10290 (existing (mapcar 'list (org-property-values prop)))
10291 (val (if allowed
10292 (completing-read "Value: " allowed nil 'req-match)
10293 (completing-read
10294 (concat "Value" (if (and cur (string-match "\\S-" cur))
10295 (concat "[" cur "]") "")
10296 ": ")
10297 existing nil nil "" nil cur))))
10298 (list prop (if (equal val "") cur val))))
10299 (unless (equal (org-entry-get nil property) value)
10300 (org-entry-put nil property value)))
10302 (defun org-delete-property (property)
10303 "In the current entry, delete PROPERTY."
10304 (interactive
10305 (let* ((prop (completing-read
10306 "Property: " (org-entry-properties nil 'standard))))
10307 (list prop)))
10308 (message "Property %s %s" property
10309 (if (org-entry-delete nil property)
10310 "deleted"
10311 "was not present in the entry")))
10313 (defun org-delete-property-globally (property)
10314 "Remove PROPERTY globally, from all entries."
10315 (interactive
10316 (let* ((prop (completing-read
10317 "Globally remove property: "
10318 (mapcar 'list (org-buffer-property-keys)))))
10319 (list prop)))
10320 (save-excursion
10321 (save-restriction
10322 (widen)
10323 (goto-char (point-min))
10324 (let ((cnt 0))
10325 (while (re-search-forward
10326 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10327 nil t)
10328 (setq cnt (1+ cnt))
10329 (replace-match ""))
10330 (message "Property \"%s\" removed from %d entries" property cnt)))))
10332 (defvar org-columns-current-fmt-compiled) ; defined below
10334 (defun org-compute-property-at-point ()
10335 "Compute the property at point.
10336 This looks for an enclosing column format, extracts the operator and
10337 then applies it to the proerty in the column format's scope."
10338 (interactive)
10339 (unless (org-at-property-p)
10340 (error "Not at a property"))
10341 (let ((prop (org-match-string-no-properties 2)))
10342 (org-columns-get-format-and-top-level)
10343 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10344 (error "No operator defined for property %s" prop))
10345 (org-columns-compute prop)))
10347 (defun org-property-get-allowed-values (pom property &optional table)
10348 "Get allowed values for the property PROPERTY.
10349 When TABLE is non-nil, return an alist that can directly be used for
10350 completion."
10351 (let (vals)
10352 (cond
10353 ((equal property "TODO")
10354 (setq vals (org-with-point-at pom
10355 (append org-todo-keywords-1 '("")))))
10356 ((equal property "PRIORITY")
10357 (let ((n org-lowest-priority))
10358 (while (>= n org-highest-priority)
10359 (push (char-to-string n) vals)
10360 (setq n (1- n)))))
10361 ((member property org-special-properties))
10363 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10365 (when (and vals (string-match "\\S-" vals))
10366 (setq vals (car (read-from-string (concat "(" vals ")"))))
10367 (setq vals (mapcar (lambda (x)
10368 (cond ((stringp x) x)
10369 ((numberp x) (number-to-string x))
10370 ((symbolp x) (symbol-name x))
10371 (t "???")))
10372 vals)))))
10373 (if table (mapcar 'list vals) vals)))
10375 (defun org-property-previous-allowed-value (&optional previous)
10376 "Switch to the next allowed value for this property."
10377 (interactive)
10378 (org-property-next-allowed-value t))
10380 (defun org-property-next-allowed-value (&optional previous)
10381 "Switch to the next allowed value for this property."
10382 (interactive)
10383 (unless (org-at-property-p)
10384 (error "Not at a property"))
10385 (let* ((key (match-string 2))
10386 (value (match-string 3))
10387 (allowed (or (org-property-get-allowed-values (point) key)
10388 (and (member value '("[ ]" "[-]" "[X]"))
10389 '("[ ]" "[X]"))))
10390 nval)
10391 (unless allowed
10392 (error "Allowed values for this property have not been defined"))
10393 (if previous (setq allowed (reverse allowed)))
10394 (if (member value allowed)
10395 (setq nval (car (cdr (member value allowed)))))
10396 (setq nval (or nval (car allowed)))
10397 (if (equal nval value)
10398 (error "Only one allowed value for this property"))
10399 (org-at-property-p)
10400 (replace-match (concat " :" key ": " nval) t t)
10401 (org-indent-line-function)
10402 (beginning-of-line 1)
10403 (skip-chars-forward " \t")))
10405 (defun org-find-entry-with-id (ident)
10406 "Locate the entry that contains the ID property with exact value IDENT.
10407 IDENT can be a string, a symbol or a number, this function will search for
10408 the string representation of it.
10409 Return the position where this entry starts, or nil if there is no such entry."
10410 (let ((id (cond
10411 ((stringp ident) ident)
10412 ((symbol-name ident) (symbol-name ident))
10413 ((numberp ident) (number-to-string ident))
10414 (t (error "IDENT %s must be a string, symbol or number" ident))))
10415 (case-fold-search nil))
10416 (save-excursion
10417 (save-restriction
10418 (widen)
10419 (goto-char (point-min))
10420 (when (re-search-forward
10421 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10422 nil t)
10423 (org-back-to-heading)
10424 (point))))))
10426 ;;; Column View
10428 (defvar org-columns-overlays nil
10429 "Holds the list of current column overlays.")
10431 (defvar org-columns-current-fmt nil
10432 "Local variable, holds the currently active column format.")
10433 (defvar org-columns-current-fmt-compiled nil
10434 "Local variable, holds the currently active column format.
10435 This is the compiled version of the format.")
10436 (defvar org-columns-current-widths nil
10437 "Loval variable, holds the currently widths of fields.")
10438 (defvar org-columns-current-maxwidths nil
10439 "Loval variable, holds the currently active maximum column widths.")
10440 (defvar org-columns-begin-marker (make-marker)
10441 "Points to the position where last a column creation command was called.")
10442 (defvar org-columns-top-level-marker (make-marker)
10443 "Points to the position where current columns region starts.")
10445 (defvar org-columns-map (make-sparse-keymap)
10446 "The keymap valid in column display.")
10448 (defun org-columns-content ()
10449 "Switch to contents view while in columns view."
10450 (interactive)
10451 (org-overview)
10452 (org-content))
10454 (org-defkey org-columns-map "c" 'org-columns-content)
10455 (org-defkey org-columns-map "o" 'org-overview)
10456 (org-defkey org-columns-map "e" 'org-columns-edit-value)
10457 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
10458 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
10459 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
10460 (org-defkey org-columns-map "v" 'org-columns-show-value)
10461 (org-defkey org-columns-map "q" 'org-columns-quit)
10462 (org-defkey org-columns-map "r" 'org-columns-redo)
10463 (org-defkey org-columns-map "g" 'org-columns-redo)
10464 (org-defkey org-columns-map [left] 'backward-char)
10465 (org-defkey org-columns-map "\M-b" 'backward-char)
10466 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
10467 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
10468 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
10469 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
10470 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
10471 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
10472 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
10473 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
10474 (org-defkey org-columns-map "<" 'org-columns-narrow)
10475 (org-defkey org-columns-map ">" 'org-columns-widen)
10476 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
10477 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
10478 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
10479 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
10481 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
10482 '("Column"
10483 ["Edit property" org-columns-edit-value t]
10484 ["Next allowed value" org-columns-next-allowed-value t]
10485 ["Previous allowed value" org-columns-previous-allowed-value t]
10486 ["Show full value" org-columns-show-value t]
10487 ["Edit allowed values" org-columns-edit-allowed t]
10488 "--"
10489 ["Edit column attributes" org-columns-edit-attributes t]
10490 ["Increase column width" org-columns-widen t]
10491 ["Decrease column width" org-columns-narrow t]
10492 "--"
10493 ["Move column right" org-columns-move-right t]
10494 ["Move column left" org-columns-move-left t]
10495 ["Add column" org-columns-new t]
10496 ["Delete column" org-columns-delete t]
10497 "--"
10498 ["CONTENTS" org-columns-content t]
10499 ["OVERVIEW" org-overview t]
10500 ["Refresh columns display" org-columns-redo t]
10501 "--"
10502 ["Open link" org-columns-open-link t]
10503 "--"
10504 ["Quit" org-columns-quit t]))
10506 (defun org-columns-new-overlay (beg end &optional string face)
10507 "Create a new column overlay and add it to the list."
10508 (let ((ov (org-make-overlay beg end)))
10509 (org-overlay-put ov 'face (or face 'secondary-selection))
10510 (org-overlay-display ov string face)
10511 (push ov org-columns-overlays)
10512 ov))
10514 (defun org-columns-display-here (&optional props)
10515 "Overlay the current line with column display."
10516 (interactive)
10517 (let* ((fmt org-columns-current-fmt-compiled)
10518 (beg (point-at-bol))
10519 (level-face (save-excursion
10520 (beginning-of-line 1)
10521 (and (looking-at "\\(\\**\\)\\(\\* \\)")
10522 (org-get-level-face 2))))
10523 (color (list :foreground
10524 (face-attribute (or level-face 'default) :foreground)))
10525 props pom property ass width f string ov column val modval)
10526 ;; Check if the entry is in another buffer.
10527 (unless props
10528 (if (eq major-mode 'org-agenda-mode)
10529 (setq pom (or (get-text-property (point) 'org-hd-marker)
10530 (get-text-property (point) 'org-marker))
10531 props (if pom (org-entry-properties pom) nil))
10532 (setq props (org-entry-properties nil))))
10533 ;; Walk the format
10534 (while (setq column (pop fmt))
10535 (setq property (car column)
10536 ass (if (equal property "ITEM")
10537 (cons "ITEM"
10538 (save-match-data
10539 (org-no-properties
10540 (org-remove-tabs
10541 (buffer-substring-no-properties
10542 (point-at-bol) (point-at-eol))))))
10543 (assoc property props))
10544 width (or (cdr (assoc property org-columns-current-maxwidths))
10545 (nth 2 column)
10546 (length property))
10547 f (format "%%-%d.%ds | " width width)
10548 val (or (cdr ass) "")
10549 modval (if (equal property "ITEM")
10550 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
10551 string (format f (or modval val)))
10552 ;; Create the overlay
10553 (org-unmodified
10554 (setq ov (org-columns-new-overlay
10555 beg (setq beg (1+ beg)) string
10556 (list color 'org-column)))
10557 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
10558 (org-overlay-put ov 'keymap org-columns-map)
10559 (org-overlay-put ov 'org-columns-key property)
10560 (org-overlay-put ov 'org-columns-value (cdr ass))
10561 (org-overlay-put ov 'org-columns-value-modified modval)
10562 (org-overlay-put ov 'org-columns-pom pom)
10563 (org-overlay-put ov 'org-columns-format f))
10564 (if (or (not (char-after beg))
10565 (equal (char-after beg) ?\n))
10566 (let ((inhibit-read-only t))
10567 (save-excursion
10568 (goto-char beg)
10569 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
10570 ;; Make the rest of the line disappear.
10571 (org-unmodified
10572 (setq ov (org-columns-new-overlay beg (point-at-eol)))
10573 (org-overlay-put ov 'invisible t)
10574 (org-overlay-put ov 'keymap org-columns-map)
10575 (org-overlay-put ov 'intangible t)
10576 (push ov org-columns-overlays)
10577 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
10578 (org-overlay-put ov 'keymap org-columns-map)
10579 (push ov org-columns-overlays)
10580 (let ((inhibit-read-only t))
10581 (put-text-property (max (point-min) (1- (point-at-bol)))
10582 (min (point-max) (1+ (point-at-eol)))
10583 'read-only "Type `e' to edit property")))))
10585 (defvar org-columns-full-header-line-format nil
10586 "Fthe full header line format, will be shifted by horizontal scrolling." )
10587 (defvar org-previous-header-line-format nil
10588 "The header line format before column view was turned on.")
10589 (defvar org-columns-inhibit-recalculation nil
10590 "Inhibit recomputing of columns on column view startup.")
10593 (defvar header-line-format)
10594 (defvar org-columns-previous-hscroll 0)
10595 (defun org-columns-display-here-title ()
10596 "Overlay the newline before the current line with the table title."
10597 (interactive)
10598 (let ((fmt org-columns-current-fmt-compiled)
10599 string (title "")
10600 property width f column str widths)
10601 (while (setq column (pop fmt))
10602 (setq property (car column)
10603 str (or (nth 1 column) property)
10604 width (or (cdr (assoc property org-columns-current-maxwidths))
10605 (nth 2 column)
10606 (length str))
10607 widths (push width widths)
10608 f (format "%%-%d.%ds | " width width)
10609 string (format f str)
10610 title (concat title string)))
10611 (setq title (concat
10612 (org-add-props " " nil 'display '(space :align-to 0))
10613 (org-add-props title nil 'face '(:weight bold :underline t :inherit default))))
10614 (org-set-local 'org-previous-header-line-format header-line-format)
10615 (org-set-local 'org-columns-current-widths (nreverse widths))
10616 (setq org-columns-full-header-line-format title)
10617 (setq org-columns-previous-hscroll -1)
10618 ; (org-columns-hscoll-title)
10619 (org-add-hook 'post-command-hook 'org-columns-hscoll-title nil 'local)))
10621 (defun org-columns-hscoll-title ()
10622 "Set the header-line-format so that it scrolls along with the table."
10623 (sit-for .0001) ; need to force a redisplay to update window-hscroll
10624 (when (not (= (window-hscroll) org-columns-previous-hscroll))
10625 (setq header-line-format
10626 (concat (substring org-columns-full-header-line-format 0 1)
10627 (substring org-columns-full-header-line-format
10628 (1+ (window-hscroll))))
10629 org-columns-previous-hscroll (window-hscroll))
10630 (force-mode-line-update)))
10632 (defun org-columns-remove-overlays ()
10633 "Remove all currently active column overlays."
10634 (interactive)
10635 (when (marker-buffer org-columns-begin-marker)
10636 (with-current-buffer (marker-buffer org-columns-begin-marker)
10637 (when (local-variable-p 'org-previous-header-line-format)
10638 (setq header-line-format org-previous-header-line-format)
10639 (kill-local-variable 'org-previous-header-line-format)
10640 (remove-hook 'post-command-hook 'org-columns-hscoll-title 'local))
10641 (move-marker org-columns-begin-marker nil)
10642 (move-marker org-columns-top-level-marker nil)
10643 (org-unmodified
10644 (mapc 'org-delete-overlay org-columns-overlays)
10645 (setq org-columns-overlays nil)
10646 (let ((inhibit-read-only t))
10647 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
10649 (defun org-columns-cleanup-item (item fmt)
10650 "Remove from ITEM what is a column in the format FMT."
10651 (if (not org-complex-heading-regexp)
10652 item
10653 (when (string-match org-complex-heading-regexp item)
10654 (concat
10655 (org-add-props (concat (match-string 1 item) " ") nil
10656 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
10657 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
10658 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
10659 " " (match-string 4 item)
10660 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
10662 (defun org-columns-show-value ()
10663 "Show the full value of the property."
10664 (interactive)
10665 (let ((value (get-char-property (point) 'org-columns-value)))
10666 (message "Value is: %s" (or value ""))))
10668 (defun org-columns-quit ()
10669 "Remove the column overlays and in this way exit column editing."
10670 (interactive)
10671 (org-unmodified
10672 (org-columns-remove-overlays)
10673 (let ((inhibit-read-only t))
10674 (remove-text-properties (point-min) (point-max) '(read-only t))))
10675 (when (eq major-mode 'org-agenda-mode)
10676 (message
10677 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
10679 (defun org-columns-check-computed ()
10680 "Check if this column value is computed.
10681 If yes, throw an error indicating that changing it does not make sense."
10682 (let ((val (get-char-property (point) 'org-columns-value)))
10683 (when (and (stringp val)
10684 (get-char-property 0 'org-computed val))
10685 (error "This value is computed from the entry's children"))))
10687 (defun org-columns-todo (&optional arg)
10688 "Change the TODO state during column view."
10689 (interactive "P")
10690 (org-columns-edit-value "TODO"))
10692 (defun org-columns-set-tags-or-toggle (&optional arg)
10693 "Toggle checkbox at point, or set tags for current headline."
10694 (interactive "P")
10695 (if (string-match "\\`\\[[ xX-]\\]\\'"
10696 (get-char-property (point) 'org-columns-value))
10697 (org-columns-next-allowed-value)
10698 (org-columns-edit-value "TAGS")))
10700 (defun org-columns-edit-value (&optional key)
10701 "Edit the value of the property at point in column view.
10702 Where possible, use the standard interface for changing this line."
10703 (interactive)
10704 (org-columns-check-computed)
10705 (let* ((external-key key)
10706 (col (current-column))
10707 (key (or key (get-char-property (point) 'org-columns-key)))
10708 (value (get-char-property (point) 'org-columns-value))
10709 (bol (point-at-bol)) (eol (point-at-eol))
10710 (pom (or (get-text-property bol 'org-hd-marker)
10711 (point))) ; keep despite of compiler waring
10712 (line-overlays
10713 (delq nil (mapcar (lambda (x)
10714 (and (eq (overlay-buffer x) (current-buffer))
10715 (>= (overlay-start x) bol)
10716 (<= (overlay-start x) eol)
10718 org-columns-overlays)))
10719 nval eval allowed)
10720 (cond
10721 ((equal key "CLOCKSUM")
10722 (error "This special column cannot be edited"))
10723 ((equal key "ITEM")
10724 (setq eval '(org-with-point-at pom
10725 (org-edit-headline))))
10726 ((equal key "TODO")
10727 (setq eval '(org-with-point-at pom
10728 (let ((current-prefix-arg
10729 (if external-key current-prefix-arg '(4))))
10730 (call-interactively 'org-todo)))))
10731 ((equal key "PRIORITY")
10732 (setq eval '(org-with-point-at pom
10733 (call-interactively 'org-priority))))
10734 ((equal key "TAGS")
10735 (setq eval '(org-with-point-at pom
10736 (let ((org-fast-tag-selection-single-key
10737 (if (eq org-fast-tag-selection-single-key 'expert)
10738 t org-fast-tag-selection-single-key)))
10739 (call-interactively 'org-set-tags)))))
10740 ((equal key "DEADLINE")
10741 (setq eval '(org-with-point-at pom
10742 (call-interactively 'org-deadline))))
10743 ((equal key "SCHEDULED")
10744 (setq eval '(org-with-point-at pom
10745 (call-interactively 'org-schedule))))
10747 (setq allowed (org-property-get-allowed-values pom key 'table))
10748 (if allowed
10749 (setq nval (completing-read "Value: " allowed nil t))
10750 (setq nval (read-string "Edit: " value)))
10751 (setq nval (org-trim nval))
10752 (when (not (equal nval value))
10753 (setq eval '(org-entry-put pom key nval)))))
10754 (when eval
10755 (let ((inhibit-read-only t))
10756 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
10757 (unwind-protect
10758 (progn
10759 (setq org-columns-overlays
10760 (org-delete-all line-overlays org-columns-overlays))
10761 (mapc 'org-delete-overlay line-overlays)
10762 (org-columns-eval eval))
10763 (org-columns-display-here))))
10764 (move-to-column col)
10765 (if (and (org-mode-p)
10766 (nth 3 (assoc key org-columns-current-fmt-compiled)))
10767 (org-columns-update key))))
10769 (defun org-edit-headline () ; FIXME: this is not columns specific
10770 "Edit the current headline, the part without TODO keyword, TAGS."
10771 (org-back-to-heading)
10772 (when (looking-at org-todo-line-regexp)
10773 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
10774 (txt (match-string 3))
10775 (post "")
10776 txt2)
10777 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
10778 (setq post (match-string 0 txt)
10779 txt (substring txt 0 (match-beginning 0))))
10780 (setq txt2 (read-string "Edit: " txt))
10781 (when (not (equal txt txt2))
10782 (beginning-of-line 1)
10783 (insert pre txt2 post)
10784 (delete-region (point) (point-at-eol))
10785 (org-set-tags nil t)))))
10787 (defun org-columns-edit-allowed ()
10788 "Edit the list of allowed values for the current property."
10789 (interactive)
10790 (let* ((key (get-char-property (point) 'org-columns-key))
10791 (key1 (concat key "_ALL"))
10792 (allowed (org-entry-get (point) key1 t))
10793 nval)
10794 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
10795 (setq nval (read-string "Allowed: " allowed))
10796 (org-entry-put
10797 (cond ((marker-position org-entry-property-inherited-from)
10798 org-entry-property-inherited-from)
10799 ((marker-position org-columns-top-level-marker)
10800 org-columns-top-level-marker))
10801 key1 nval)))
10803 (defun org-columns-eval (form)
10804 (let (hidep)
10805 (save-excursion
10806 (beginning-of-line 1)
10807 ;; `next-line' is needed here, because it skips invisible line.
10808 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
10809 (setq hidep (org-on-heading-p 1)))
10810 (eval form)
10811 (and hidep (hide-entry))))
10813 (defun org-columns-previous-allowed-value ()
10814 "Switch to the previous allowed value for this column."
10815 (interactive)
10816 (org-columns-next-allowed-value t))
10818 (defun org-columns-next-allowed-value (&optional previous)
10819 "Switch to the next allowed value for this column."
10820 (interactive)
10821 (org-columns-check-computed)
10822 (let* ((col (current-column))
10823 (key (get-char-property (point) 'org-columns-key))
10824 (value (get-char-property (point) 'org-columns-value))
10825 (bol (point-at-bol)) (eol (point-at-eol))
10826 (pom (or (get-text-property bol 'org-hd-marker)
10827 (point))) ; keep despite of compiler waring
10828 (line-overlays
10829 (delq nil (mapcar (lambda (x)
10830 (and (eq (overlay-buffer x) (current-buffer))
10831 (>= (overlay-start x) bol)
10832 (<= (overlay-start x) eol)
10834 org-columns-overlays)))
10835 (allowed (or (org-property-get-allowed-values pom key)
10836 (and (memq
10837 (nth 4 (assoc key org-columns-current-fmt-compiled))
10838 '(checkbox checkbox-n-of-m checkbox-percent))
10839 '("[ ]" "[X]"))))
10840 nval)
10841 (when (equal key "ITEM")
10842 (error "Cannot edit item headline from here"))
10843 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
10844 (error "Allowed values for this property have not been defined"))
10845 (if (member key '("SCHEDULED" "DEADLINE"))
10846 (setq nval (if previous 'earlier 'later))
10847 (if previous (setq allowed (reverse allowed)))
10848 (if (member value allowed)
10849 (setq nval (car (cdr (member value allowed)))))
10850 (setq nval (or nval (car allowed)))
10851 (if (equal nval value)
10852 (error "Only one allowed value for this property")))
10853 (let ((inhibit-read-only t))
10854 (remove-text-properties (1- bol) eol '(read-only t))
10855 (unwind-protect
10856 (progn
10857 (setq org-columns-overlays
10858 (org-delete-all line-overlays org-columns-overlays))
10859 (mapc 'org-delete-overlay line-overlays)
10860 (org-columns-eval '(org-entry-put pom key nval)))
10861 (org-columns-display-here)))
10862 (move-to-column col)
10863 (if (and (org-mode-p)
10864 (nth 3 (assoc key org-columns-current-fmt-compiled)))
10865 (org-columns-update key))))
10867 (defun org-verify-version (task)
10868 (cond
10869 ((eq task 'columns)
10870 (if (or (featurep 'xemacs)
10871 (< emacs-major-version 22))
10872 (error "Emacs 22 is required for the columns feature")))))
10874 (defun org-columns-open-link (&optional arg)
10875 (interactive "P")
10876 (let ((value (get-char-property (point) 'org-columns-value)))
10877 (org-open-link-from-string value arg)))
10879 (defun org-open-link-from-string (s &optional arg)
10880 "Open a link in the string S, as if it was in Org-mode."
10881 (interactive)
10882 (with-temp-buffer
10883 (let ((org-inhibit-startup t))
10884 (org-mode)
10885 (insert s)
10886 (goto-char (point-min))
10887 (org-open-at-point arg))))
10889 (defun org-columns-get-format-and-top-level ()
10890 (let (fmt)
10891 (when (condition-case nil (org-back-to-heading) (error nil))
10892 (move-marker org-entry-property-inherited-from nil)
10893 (setq fmt (org-entry-get nil "COLUMNS" t)))
10894 (setq fmt (or fmt org-columns-default-format))
10895 (org-set-local 'org-columns-current-fmt fmt)
10896 (org-columns-compile-format fmt)
10897 (if (marker-position org-entry-property-inherited-from)
10898 (move-marker org-columns-top-level-marker
10899 org-entry-property-inherited-from)
10900 (move-marker org-columns-top-level-marker (point)))
10901 fmt))
10903 (defun org-columns ()
10904 "Turn on column view on an org-mode file."
10905 (interactive)
10906 (org-verify-version 'columns)
10907 (org-columns-remove-overlays)
10908 (move-marker org-columns-begin-marker (point))
10909 (let (beg end fmt cache maxwidths)
10910 (setq fmt (org-columns-get-format-and-top-level))
10911 (save-excursion
10912 (goto-char org-columns-top-level-marker)
10913 (setq beg (point))
10914 (unless org-columns-inhibit-recalculation
10915 (org-columns-compute-all))
10916 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
10917 (point-max)))
10918 ;; Get and cache the properties
10919 (goto-char beg)
10920 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
10921 (save-excursion
10922 (save-restriction
10923 (narrow-to-region beg end)
10924 (org-clock-sum))))
10925 (while (re-search-forward (concat "^" outline-regexp) end t)
10926 (push (cons (org-current-line) (org-entry-properties)) cache))
10927 (when cache
10928 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
10929 (org-set-local 'org-columns-current-maxwidths maxwidths)
10930 (org-columns-display-here-title)
10931 (mapc (lambda (x)
10932 (goto-line (car x))
10933 (org-columns-display-here (cdr x)))
10934 cache)))))
10936 (defun org-columns-new (&optional prop title width op fmt &rest rest)
10937 "Insert a new column, to the left of the current column."
10938 (interactive)
10939 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
10940 cell)
10941 (setq prop (completing-read
10942 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
10943 nil nil prop))
10944 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
10945 (setq width (read-string "Column width: " (if width (number-to-string width))))
10946 (if (string-match "\\S-" width)
10947 (setq width (string-to-number width))
10948 (setq width nil))
10949 (setq fmt (completing-read "Summary [none]: "
10950 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
10951 nil t))
10952 (if (string-match "\\S-" fmt)
10953 (setq fmt (intern fmt))
10954 (setq fmt nil))
10955 (if (eq fmt 'none) (setq fmt nil))
10956 (if editp
10957 (progn
10958 (setcar editp prop)
10959 (setcdr editp (list title width nil fmt)))
10960 (setq cell (nthcdr (1- (current-column))
10961 org-columns-current-fmt-compiled))
10962 (setcdr cell (cons (list prop title width nil fmt)
10963 (cdr cell))))
10964 (org-columns-store-format)
10965 (org-columns-redo)))
10967 (defun org-columns-delete ()
10968 "Delete the column at point from columns view."
10969 (interactive)
10970 (let* ((n (current-column))
10971 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
10972 (when (y-or-n-p
10973 (format "Are you sure you want to remove column \"%s\"? " title))
10974 (setq org-columns-current-fmt-compiled
10975 (delq (nth n org-columns-current-fmt-compiled)
10976 org-columns-current-fmt-compiled))
10977 (org-columns-store-format)
10978 (org-columns-redo)
10979 (if (>= (current-column) (length org-columns-current-fmt-compiled))
10980 (backward-char 1)))))
10982 (defun org-columns-edit-attributes ()
10983 "Edit the attributes of the current column."
10984 (interactive)
10985 (let* ((n (current-column))
10986 (info (nth n org-columns-current-fmt-compiled)))
10987 (apply 'org-columns-new info)))
10989 (defun org-columns-widen (arg)
10990 "Make the column wider by ARG characters."
10991 (interactive "p")
10992 (let* ((n (current-column))
10993 (entry (nth n org-columns-current-fmt-compiled))
10994 (width (or (nth 2 entry)
10995 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
10996 (setq width (max 1 (+ width arg)))
10997 (setcar (nthcdr 2 entry) width)
10998 (org-columns-store-format)
10999 (org-columns-redo)))
11001 (defun org-columns-narrow (arg)
11002 "Make the column nrrower by ARG characters."
11003 (interactive "p")
11004 (org-columns-widen (- arg)))
11006 (defun org-columns-move-right ()
11007 "Swap this column with the one to the right."
11008 (interactive)
11009 (let* ((n (current-column))
11010 (cell (nthcdr n org-columns-current-fmt-compiled))
11012 (when (>= n (1- (length org-columns-current-fmt-compiled)))
11013 (error "Cannot shift this column further to the right"))
11014 (setq e (car cell))
11015 (setcar cell (car (cdr cell)))
11016 (setcdr cell (cons e (cdr (cdr cell))))
11017 (org-columns-store-format)
11018 (org-columns-redo)
11019 (forward-char 1)))
11021 (defun org-columns-move-left ()
11022 "Swap this column with the one to the left."
11023 (interactive)
11024 (let* ((n (current-column)))
11025 (when (= n 0)
11026 (error "Cannot shift this column further to the left"))
11027 (backward-char 1)
11028 (org-columns-move-right)
11029 (backward-char 1)))
11031 (defun org-columns-store-format ()
11032 "Store the text version of the current columns format in appropriate place.
11033 This is either in the COLUMNS property of the node starting the current column
11034 display, or in the #+COLUMNS line of the current buffer."
11035 (let (fmt (cnt 0))
11036 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
11037 (org-set-local 'org-columns-current-fmt fmt)
11038 (if (marker-position org-columns-top-level-marker)
11039 (save-excursion
11040 (goto-char org-columns-top-level-marker)
11041 (if (and (org-at-heading-p)
11042 (org-entry-get nil "COLUMNS"))
11043 (org-entry-put nil "COLUMNS" fmt)
11044 (goto-char (point-min))
11045 ;; Overwrite all #+COLUMNS lines....
11046 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
11047 (setq cnt (1+ cnt))
11048 (replace-match (concat "#+COLUMNS: " fmt) t t))
11049 (unless (> cnt 0)
11050 (goto-char (point-min))
11051 (or (org-on-heading-p t) (outline-next-heading))
11052 (let ((inhibit-read-only t))
11053 (insert-before-markers "#+COLUMNS: " fmt "\n")))
11054 (org-set-local 'org-columns-default-format fmt))))))
11056 (defvar org-overriding-columns-format nil
11057 "When set, overrides any other definition.")
11058 (defvar org-agenda-view-columns-initially nil
11059 "When set, switch to columns view immediately after creating the agenda.")
11061 (defun org-agenda-columns ()
11062 "Turn on column view in the agenda."
11063 (interactive)
11064 (org-verify-version 'columns)
11065 (org-columns-remove-overlays)
11066 (move-marker org-columns-begin-marker (point))
11067 (let (fmt cache maxwidths m)
11068 (cond
11069 ((and (local-variable-p 'org-overriding-columns-format)
11070 org-overriding-columns-format)
11071 (setq fmt org-overriding-columns-format))
11072 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
11073 (setq fmt (org-entry-get m "COLUMNS" t)))
11074 ((and (boundp 'org-columns-current-fmt)
11075 (local-variable-p 'org-columns-current-fmt)
11076 org-columns-current-fmt)
11077 (setq fmt org-columns-current-fmt))
11078 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
11079 (setq m (get-text-property m 'org-hd-marker))
11080 (setq fmt (org-entry-get m "COLUMNS" t))))
11081 (setq fmt (or fmt org-columns-default-format))
11082 (org-set-local 'org-columns-current-fmt fmt)
11083 (org-columns-compile-format fmt)
11084 (save-excursion
11085 ;; Get and cache the properties
11086 (goto-char (point-min))
11087 (while (not (eobp))
11088 (when (setq m (or (get-text-property (point) 'org-hd-marker)
11089 (get-text-property (point) 'org-marker)))
11090 (push (cons (org-current-line) (org-entry-properties m)) cache))
11091 (beginning-of-line 2))
11092 (when cache
11093 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
11094 (org-set-local 'org-columns-current-maxwidths maxwidths)
11095 (org-columns-display-here-title)
11096 (mapc (lambda (x)
11097 (goto-line (car x))
11098 (org-columns-display-here (cdr x)))
11099 cache)))))
11101 (defun org-columns-get-autowidth-alist (s cache)
11102 "Derive the maximum column widths from the format and the cache."
11103 (let ((start 0) rtn)
11104 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
11105 (push (cons (match-string 1 s) 1) rtn)
11106 (setq start (match-end 0)))
11107 (mapc (lambda (x)
11108 (setcdr x (apply 'max
11109 (mapcar
11110 (lambda (y)
11111 (length (or (cdr (assoc (car x) (cdr y))) " ")))
11112 cache))))
11113 rtn)
11114 rtn))
11116 (defun org-columns-compute-all ()
11117 "Compute all columns that have operators defined."
11118 (org-unmodified
11119 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
11120 (let ((columns org-columns-current-fmt-compiled) col)
11121 (while (setq col (pop columns))
11122 (when (nth 3 col)
11123 (save-excursion
11124 (org-columns-compute (car col)))))))
11126 (defun org-columns-update (property)
11127 "Recompute PROPERTY, and update the columns display for it."
11128 (org-columns-compute property)
11129 (let (fmt val pos)
11130 (save-excursion
11131 (mapc (lambda (ov)
11132 (when (equal (org-overlay-get ov 'org-columns-key) property)
11133 (setq pos (org-overlay-start ov))
11134 (goto-char pos)
11135 (when (setq val (cdr (assoc property
11136 (get-text-property
11137 (point-at-bol) 'org-summaries))))
11138 (setq fmt (org-overlay-get ov 'org-columns-format))
11139 (org-overlay-put ov 'org-columns-value val)
11140 (org-overlay-put ov 'display (format fmt val)))))
11141 org-columns-overlays))))
11143 (defun org-columns-compute (property)
11144 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
11145 (interactive)
11146 (let* ((re (concat "^" outline-regexp))
11147 (lmax 30) ; Does anyone use deeper levels???
11148 (lsum (make-vector lmax 0))
11149 (lflag (make-vector lmax nil))
11150 (level 0)
11151 (ass (assoc property org-columns-current-fmt-compiled))
11152 (format (nth 4 ass))
11153 (printf (nth 5 ass))
11154 (beg org-columns-top-level-marker)
11155 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
11156 (save-excursion
11157 ;; Find the region to compute
11158 (goto-char beg)
11159 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
11160 (goto-char end)
11161 ;; Walk the tree from the back and do the computations
11162 (while (re-search-backward re beg t)
11163 (setq sumpos (match-beginning 0)
11164 last-level level
11165 level (org-outline-level)
11166 val (org-entry-get nil property)
11167 valflag (and val (string-match "\\S-" val)))
11168 (cond
11169 ((< level last-level)
11170 ;; put the sum of lower levels here as a property
11171 (setq sum (aref lsum last-level) ; current sum
11172 flag (aref lflag last-level) ; any valid entries from children?
11173 str (org-column-number-to-string sum format printf)
11174 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
11175 useval (if flag str1 (if valflag val ""))
11176 sum-alist (get-text-property sumpos 'org-summaries))
11177 (if (assoc property sum-alist)
11178 (setcdr (assoc property sum-alist) useval)
11179 (push (cons property useval) sum-alist)
11180 (org-unmodified
11181 (add-text-properties sumpos (1+ sumpos)
11182 (list 'org-summaries sum-alist))))
11183 (when val
11184 (org-entry-put nil property (if flag str val)))
11185 ;; add current to current level accumulator
11186 (when (or flag valflag)
11187 (aset lsum level (+ (aref lsum level)
11188 (if flag sum (org-column-string-to-number
11189 (if flag str val) format))))
11190 (aset lflag level t))
11191 ;; clear accumulators for deeper levels
11192 (loop for l from (1+ level) to (1- lmax) do
11193 (aset lsum l 0)
11194 (aset lflag l nil)))
11195 ((>= level last-level)
11196 ;; add what we have here to the accumulator for this level
11197 (aset lsum level (+ (aref lsum level)
11198 (org-column-string-to-number (or val "0") format)))
11199 (and valflag (aset lflag level t)))
11200 (t (error "This should not happen")))))))
11202 (defun org-columns-redo ()
11203 "Construct the column display again."
11204 (interactive)
11205 (message "Recomputing columns...")
11206 (save-excursion
11207 (if (marker-position org-columns-begin-marker)
11208 (goto-char org-columns-begin-marker))
11209 (org-columns-remove-overlays)
11210 (if (org-mode-p)
11211 (call-interactively 'org-columns)
11212 (call-interactively 'org-agenda-columns)))
11213 (message "Recomputing columns...done"))
11215 (defun org-columns-not-in-agenda ()
11216 (if (eq major-mode 'org-agenda-mode)
11217 (error "This command is only allowed in Org-mode buffers")))
11220 (defun org-string-to-number (s)
11221 "Convert string to number, and interpret hh:mm:ss."
11222 (if (not (string-match ":" s))
11223 (string-to-number s)
11224 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
11225 (while l
11226 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
11227 sum)))
11229 (defun org-column-number-to-string (n fmt &optional printf)
11230 "Convert a computed column number to a string value, according to FMT."
11231 (cond
11232 ((eq fmt 'add_times)
11233 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
11234 (format "%d:%02d" h m)))
11235 ((eq fmt 'checkbox)
11236 (cond ((= n (floor n)) "[X]")
11237 ((> n 1.) "[-]")
11238 (t "[ ]")))
11239 ((memq fmt '(checkbox-n-of-m checkbox-percent))
11240 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
11241 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
11242 (printf (format printf n))
11243 ((eq fmt 'currency)
11244 (format "%.2f" n))
11245 (t (number-to-string n))))
11247 (defun org-nofm-to-completion (n m &optional percent)
11248 (if (not percent)
11249 (format "[%d/%d]" n m)
11250 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
11252 (defun org-column-string-to-number (s fmt)
11253 "Convert a column value to a number that can be used for column computing."
11254 (cond
11255 ((string-match ":" s)
11256 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
11257 (while l
11258 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
11259 sum))
11260 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
11261 (if (equal s "[X]") 1. 0.000001))
11262 (t (string-to-number s))))
11264 (defun org-columns-uncompile-format (cfmt)
11265 "Turn the compiled columns format back into a string representation."
11266 (let ((rtn "") e s prop title op width fmt printf)
11267 (while (setq e (pop cfmt))
11268 (setq prop (car e)
11269 title (nth 1 e)
11270 width (nth 2 e)
11271 op (nth 3 e)
11272 fmt (nth 4 e)
11273 printf (nth 5 e))
11274 (cond
11275 ((eq fmt 'add_times) (setq op ":"))
11276 ((eq fmt 'checkbox) (setq op "X"))
11277 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
11278 ((eq fmt 'checkbox-percent) (setq op "X%"))
11279 ((eq fmt 'add_numbers) (setq op "+"))
11280 ((eq fmt 'currency) (setq op "$")))
11281 (if (and op printf) (setq op (concat op ";" printf)))
11282 (if (equal title prop) (setq title nil))
11283 (setq s (concat "%" (if width (number-to-string width))
11284 prop
11285 (if title (concat "(" title ")"))
11286 (if op (concat "{" op "}"))))
11287 (setq rtn (concat rtn " " s)))
11288 (org-trim rtn)))
11290 (defun org-columns-compile-format (fmt)
11291 "Turn a column format string into an alist of specifications.
11292 The alist has one entry for each column in the format. The elements of
11293 that list are:
11294 property the property
11295 title the title field for the columns
11296 width the column width in characters, can be nil for automatic
11297 operator the operator if any
11298 format the output format for computed results, derived from operator
11299 printf a printf format for computed values"
11300 (let ((start 0) width prop title op f printf)
11301 (setq org-columns-current-fmt-compiled nil)
11302 (while (string-match
11303 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
11304 fmt start)
11305 (setq start (match-end 0)
11306 width (match-string 1 fmt)
11307 prop (match-string 2 fmt)
11308 title (or (match-string 3 fmt) prop)
11309 op (match-string 4 fmt)
11310 f nil
11311 printf nil)
11312 (if width (setq width (string-to-number width)))
11313 (when (and op (string-match ";" op))
11314 (setq printf (substring op (match-end 0))
11315 op (substring op 0 (match-beginning 0))))
11316 (cond
11317 ((equal op "+") (setq f 'add_numbers))
11318 ((equal op "$") (setq f 'currency))
11319 ((equal op ":") (setq f 'add_times))
11320 ((equal op "X") (setq f 'checkbox))
11321 ((equal op "X/") (setq f 'checkbox-n-of-m))
11322 ((equal op "X%") (setq f 'checkbox-percent))
11324 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
11325 (setq org-columns-current-fmt-compiled
11326 (nreverse org-columns-current-fmt-compiled))))
11329 ;;; Dynamic block for Column view
11331 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
11332 "Get the column view of the current buffer or subtree.
11333 The first optional argument MAXLEVEL sets the level limit. A
11334 second optional argument SKIP-EMPTY-ROWS tells whether to skip
11335 empty rows, an empty row being one where all the column view
11336 specifiers except ITEM are empty. This function returns a list
11337 containing the title row and all other rows. Each row is a list
11338 of fields."
11339 (save-excursion
11340 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
11341 (n (length title)) row tbl)
11342 (goto-char (point-min))
11343 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
11344 (or (null maxlevel)
11345 (>= maxlevel
11346 (if org-odd-levels-only
11347 (/ (1+ (length (match-string 1))) 2)
11348 (length (match-string 1))))))
11349 (when (get-char-property (match-beginning 0) 'org-columns-key)
11350 (setq row nil)
11351 (loop for i from 0 to (1- n) do
11352 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
11353 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
11355 row))
11356 (setq row (nreverse row))
11357 (unless (and skip-empty-rows
11358 (eq 1 (length (delete "" (delete-dups row)))))
11359 (push row tbl))))
11360 (append (list title 'hline) (nreverse tbl)))))
11362 (defun org-dblock-write:columnview (params)
11363 "Write the column view table.
11364 PARAMS is a property list of parameters:
11366 :width enforce same column widths with <N> specifiers.
11367 :id the :ID: property of the entry where the columns view
11368 should be built, as a string. When `local', call locally.
11369 When `global' call column view with the cursor at the beginning
11370 of the buffer (usually this means that the whole buffer switches
11371 to column view).
11372 :hlines When t, insert a hline before each item. When a number, insert
11373 a hline before each level <= that number.
11374 :vlines When t, make each column a colgroup to enforce vertical lines.
11375 :maxlevel When set to a number, don't capture headlines below this level.
11376 :skip-empty-rows
11377 When t, skip rows where all specifiers other than ITEM are empty."
11378 (let ((pos (move-marker (make-marker) (point)))
11379 (hlines (plist-get params :hlines))
11380 (vlines (plist-get params :vlines))
11381 (maxlevel (plist-get params :maxlevel))
11382 (skip-empty-rows (plist-get params :skip-empty-rows))
11383 tbl id idpos nfields tmp)
11384 (save-excursion
11385 (save-restriction
11386 (when (setq id (plist-get params :id))
11387 (cond ((not id) nil)
11388 ((eq id 'global) (goto-char (point-min)))
11389 ((eq id 'local) nil)
11390 ((setq idpos (org-find-entry-with-id id))
11391 (goto-char idpos))
11392 (t (error "Cannot find entry with :ID: %s" id))))
11393 (org-columns)
11394 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
11395 (setq nfields (length (car tbl)))
11396 (org-columns-quit)))
11397 (goto-char pos)
11398 (move-marker pos nil)
11399 (when tbl
11400 (when (plist-get params :hlines)
11401 (setq tmp nil)
11402 (while tbl
11403 (if (eq (car tbl) 'hline)
11404 (push (pop tbl) tmp)
11405 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
11406 (if (and (not (eq (car tmp) 'hline))
11407 (or (eq hlines t)
11408 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
11409 (push 'hline tmp)))
11410 (push (pop tbl) tmp)))
11411 (setq tbl (nreverse tmp)))
11412 (when vlines
11413 (setq tbl (mapcar (lambda (x)
11414 (if (eq 'hline x) x (cons "" x)))
11415 tbl))
11416 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
11417 (setq pos (point))
11418 (insert (org-listtable-to-string tbl))
11419 (when (plist-get params :width)
11420 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
11421 org-columns-current-widths "|")))
11422 (goto-char pos)
11423 (org-table-align))))
11425 (defun org-listtable-to-string (tbl)
11426 "Convert a listtable TBL to a string that contains the Org-mode table.
11427 The table still need to be alligned. The resulting string has no leading
11428 and tailing newline characters."
11429 (mapconcat
11430 (lambda (x)
11431 (cond
11432 ((listp x)
11433 (concat "|" (mapconcat 'identity x "|") "|"))
11434 ((eq x 'hline) "|-|")
11435 (t (error "Garbage in listtable: %s" x))))
11436 tbl "\n"))
11438 (defun org-insert-columns-dblock ()
11439 "Create a dynamic block capturing a column view table."
11440 (interactive)
11441 (let ((defaults '(:name "columnview" :hlines 1))
11442 (id (completing-read
11443 "Capture columns (local, global, entry with :ID: property) [local]: "
11444 (append '(("global") ("local"))
11445 (mapcar 'list (org-property-values "ID"))))))
11446 (if (equal id "") (setq id 'local))
11447 (if (equal id "global") (setq id 'global))
11448 (setq defaults (append defaults (list :id id)))
11449 (org-create-dblock defaults)
11450 (org-update-dblock)))
11452 ;;;; Timestamps
11454 (defvar org-last-changed-timestamp nil)
11455 (defvar org-time-was-given) ; dynamically scoped parameter
11456 (defvar org-end-time-was-given) ; dynamically scoped parameter
11457 (defvar org-ts-what) ; dynamically scoped parameter
11459 (defun org-time-stamp (arg)
11460 "Prompt for a date/time and insert a time stamp.
11461 If the user specifies a time like HH:MM, or if this command is called
11462 with a prefix argument, the time stamp will contain date and time.
11463 Otherwise, only the date will be included. All parts of a date not
11464 specified by the user will be filled in from the current date/time.
11465 So if you press just return without typing anything, the time stamp
11466 will represent the current date/time. If there is already a timestamp
11467 at the cursor, it will be modified."
11468 (interactive "P")
11469 (let* ((ts nil)
11470 (default-time
11471 ;; Default time is either today, or, when entering a range,
11472 ;; the range start.
11473 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11474 (save-excursion
11475 (re-search-backward
11476 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11477 (- (point) 20) t)))
11478 (apply 'encode-time (org-parse-time-string (match-string 1)))
11479 (current-time)))
11480 (default-input (and ts (org-get-compact-tod ts)))
11481 org-time-was-given org-end-time-was-given time)
11482 (cond
11483 ((and (org-at-timestamp-p)
11484 (eq last-command 'org-time-stamp)
11485 (eq this-command 'org-time-stamp))
11486 (insert "--")
11487 (setq time (let ((this-command this-command))
11488 (org-read-date arg 'totime nil nil default-time default-input)))
11489 (org-insert-time-stamp time (or org-time-was-given arg)))
11490 ((org-at-timestamp-p)
11491 (setq time (let ((this-command this-command))
11492 (org-read-date arg 'totime nil nil default-time default-input)))
11493 (when (org-at-timestamp-p) ; just to get the match data
11494 (replace-match "")
11495 (setq org-last-changed-timestamp
11496 (org-insert-time-stamp
11497 time (or org-time-was-given arg)
11498 nil nil nil (list org-end-time-was-given))))
11499 (message "Timestamp updated"))
11501 (setq time (let ((this-command this-command))
11502 (org-read-date arg 'totime nil nil default-time default-input)))
11503 (org-insert-time-stamp time (or org-time-was-given arg)
11504 nil nil nil (list org-end-time-was-given))))))
11506 ;; FIXME: can we use this for something else????
11507 ;; like computing time differences?????
11508 (defun org-get-compact-tod (s)
11509 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11510 (let* ((t1 (match-string 1 s))
11511 (h1 (string-to-number (match-string 2 s)))
11512 (m1 (string-to-number (match-string 3 s)))
11513 (t2 (and (match-end 4) (match-string 5 s)))
11514 (h2 (and t2 (string-to-number (match-string 6 s))))
11515 (m2 (and t2 (string-to-number (match-string 7 s))))
11516 dh dm)
11517 (if (not t2)
11519 (setq dh (- h2 h1) dm (- m2 m1))
11520 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11521 (concat t1 "+" (number-to-string dh)
11522 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11524 (defun org-time-stamp-inactive (&optional arg)
11525 "Insert an inactive time stamp.
11526 An inactive time stamp is enclosed in square brackets instead of angle
11527 brackets. It is inactive in the sense that it does not trigger agenda entries,
11528 does not link to the calendar and cannot be changed with the S-cursor keys.
11529 So these are more for recording a certain time/date."
11530 (interactive "P")
11531 (let (org-time-was-given org-end-time-was-given time)
11532 (setq time (org-read-date arg 'totime))
11533 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
11534 nil nil (list org-end-time-was-given))))
11536 (defvar org-date-ovl (org-make-overlay 1 1))
11537 (org-overlay-put org-date-ovl 'face 'org-warning)
11538 (org-detach-overlay org-date-ovl)
11540 (defvar org-ans1) ; dynamically scoped parameter
11541 (defvar org-ans2) ; dynamically scoped parameter
11543 (defvar org-plain-time-of-day-regexp) ; defined below
11545 (defvar org-read-date-overlay nil)
11546 (defvar org-dcst nil) ; dynamically scoped
11548 (defun org-read-date (&optional with-time to-time from-string prompt
11549 default-time default-input)
11550 "Read a date, possibly a time, and make things smooth for the user.
11551 The prompt will suggest to enter an ISO date, but you can also enter anything
11552 which will at least partially be understood by `parse-time-string'.
11553 Unrecognized parts of the date will default to the current day, month, year,
11554 hour and minute. If this command is called to replace a timestamp at point,
11555 of to enter the second timestamp of a range, the default time is taken from the
11556 existing stamp. For example,
11557 3-2-5 --> 2003-02-05
11558 feb 15 --> currentyear-02-15
11559 sep 12 9 --> 2009-09-12
11560 12:45 --> today 12:45
11561 22 sept 0:34 --> currentyear-09-22 0:34
11562 12 --> currentyear-currentmonth-12
11563 Fri --> nearest Friday (today or later)
11564 etc.
11566 Furthermore you can specify a relative date by giving, as the *first* thing
11567 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11568 change in days weeks, months, years.
11569 With a single plus or minus, the date is relative to today. With a double
11570 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11571 +4d --> four days from today
11572 +4 --> same as above
11573 +2w --> two weeks from today
11574 ++5 --> five days from default date
11576 The function understands only English month and weekday abbreviations,
11577 but this can be configured with the variables `parse-time-months' and
11578 `parse-time-weekdays'.
11580 While prompting, a calendar is popped up - you can also select the
11581 date with the mouse (button 1). The calendar shows a period of three
11582 months. To scroll it to other months, use the keys `>' and `<'.
11583 If you don't like the calendar, turn it off with
11584 \(setq org-read-date-popup-calendar nil)
11586 With optional argument TO-TIME, the date will immediately be converted
11587 to an internal time.
11588 With an optional argument WITH-TIME, the prompt will suggest to also
11589 insert a time. Note that when WITH-TIME is not set, you can still
11590 enter a time, and this function will inform the calling routine about
11591 this change. The calling routine may then choose to change the format
11592 used to insert the time stamp into the buffer to include the time.
11593 With optional argument FROM-STRING, read from this string instead from
11594 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11595 the time/date that is used for everything that is not specified by the
11596 user."
11597 (require 'parse-time)
11598 (let* ((org-time-stamp-rounding-minutes
11599 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11600 (org-dcst org-display-custom-times)
11601 (ct (org-current-time))
11602 (def (or default-time ct))
11603 (defdecode (decode-time def))
11604 (dummy (progn
11605 (when (< (nth 2 defdecode) org-extend-today-until)
11606 (setcar (nthcdr 2 defdecode) -1)
11607 (setcar (nthcdr 1 defdecode) 59)
11608 (setq def (apply 'encode-time defdecode)
11609 defdecode (decode-time def)))))
11610 (calendar-move-hook nil)
11611 (view-diary-entries-initially nil)
11612 (view-calendar-holidays-initially nil)
11613 (timestr (format-time-string
11614 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11615 (prompt (concat (if prompt (concat prompt " ") "")
11616 (format "Date+time [%s]: " timestr)))
11617 ans (org-ans0 "") org-ans1 org-ans2 final)
11619 (cond
11620 (from-string (setq ans from-string))
11621 (org-read-date-popup-calendar
11622 (save-excursion
11623 (save-window-excursion
11624 (calendar)
11625 (calendar-forward-day (- (time-to-days def)
11626 (calendar-absolute-from-gregorian
11627 (calendar-current-date))))
11628 (org-eval-in-calendar nil t)
11629 (let* ((old-map (current-local-map))
11630 (map (copy-keymap calendar-mode-map))
11631 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11632 (org-defkey map (kbd "RET") 'org-calendar-select)
11633 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11634 'org-calendar-select-mouse)
11635 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11636 'org-calendar-select-mouse)
11637 (org-defkey minibuffer-local-map [(meta shift left)]
11638 (lambda () (interactive)
11639 (org-eval-in-calendar '(calendar-backward-month 1))))
11640 (org-defkey minibuffer-local-map [(meta shift right)]
11641 (lambda () (interactive)
11642 (org-eval-in-calendar '(calendar-forward-month 1))))
11643 (org-defkey minibuffer-local-map [(meta shift up)]
11644 (lambda () (interactive)
11645 (org-eval-in-calendar '(calendar-backward-year 1))))
11646 (org-defkey minibuffer-local-map [(meta shift down)]
11647 (lambda () (interactive)
11648 (org-eval-in-calendar '(calendar-forward-year 1))))
11649 (org-defkey minibuffer-local-map [(shift up)]
11650 (lambda () (interactive)
11651 (org-eval-in-calendar '(calendar-backward-week 1))))
11652 (org-defkey minibuffer-local-map [(shift down)]
11653 (lambda () (interactive)
11654 (org-eval-in-calendar '(calendar-forward-week 1))))
11655 (org-defkey minibuffer-local-map [(shift left)]
11656 (lambda () (interactive)
11657 (org-eval-in-calendar '(calendar-backward-day 1))))
11658 (org-defkey minibuffer-local-map [(shift right)]
11659 (lambda () (interactive)
11660 (org-eval-in-calendar '(calendar-forward-day 1))))
11661 (org-defkey minibuffer-local-map ">"
11662 (lambda () (interactive)
11663 (org-eval-in-calendar '(scroll-calendar-left 1))))
11664 (org-defkey minibuffer-local-map "<"
11665 (lambda () (interactive)
11666 (org-eval-in-calendar '(scroll-calendar-right 1))))
11667 (unwind-protect
11668 (progn
11669 (use-local-map map)
11670 (add-hook 'post-command-hook 'org-read-date-display)
11671 (setq org-ans0 (read-string prompt default-input nil nil))
11672 ;; org-ans0: from prompt
11673 ;; org-ans1: from mouse click
11674 ;; org-ans2: from calendar motion
11675 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11676 (remove-hook 'post-command-hook 'org-read-date-display)
11677 (use-local-map old-map)
11678 (when org-read-date-overlay
11679 (org-delete-overlay org-read-date-overlay)
11680 (setq org-read-date-overlay nil)))))))
11682 (t ; Naked prompt only
11683 (unwind-protect
11684 (setq ans (read-string prompt default-input nil timestr))
11685 (when org-read-date-overlay
11686 (org-delete-overlay org-read-date-overlay)
11687 (setq org-read-date-overlay nil)))))
11689 (setq final (org-read-date-analyze ans def defdecode))
11691 (if to-time
11692 (apply 'encode-time final)
11693 (if (and (boundp 'org-time-was-given) org-time-was-given)
11694 (format "%04d-%02d-%02d %02d:%02d"
11695 (nth 5 final) (nth 4 final) (nth 3 final)
11696 (nth 2 final) (nth 1 final))
11697 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11698 (defvar def)
11699 (defvar defdecode)
11700 (defvar with-time)
11701 (defun org-read-date-display ()
11702 "Display the currrent date prompt interpretation in the minibuffer."
11703 (when org-read-date-display-live
11704 (when org-read-date-overlay
11705 (org-delete-overlay org-read-date-overlay))
11706 (let ((p (point)))
11707 (end-of-line 1)
11708 (while (not (equal (buffer-substring
11709 (max (point-min) (- (point) 4)) (point))
11710 " "))
11711 (insert " "))
11712 (goto-char p))
11713 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11714 " " (or org-ans1 org-ans2)))
11715 (org-end-time-was-given nil)
11716 (f (org-read-date-analyze ans def defdecode))
11717 (fmts (if org-dcst
11718 org-time-stamp-custom-formats
11719 org-time-stamp-formats))
11720 (fmt (if (or with-time
11721 (and (boundp 'org-time-was-given) org-time-was-given))
11722 (cdr fmts)
11723 (car fmts)))
11724 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11725 (when (and org-end-time-was-given
11726 (string-match org-plain-time-of-day-regexp txt))
11727 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11728 org-end-time-was-given
11729 (substring txt (match-end 0)))))
11730 (setq org-read-date-overlay
11731 (make-overlay (1- (point-at-eol)) (point-at-eol)))
11732 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11734 (defun org-read-date-analyze (ans def defdecode)
11735 "Analyze the combined answer of the date prompt."
11736 ;; FIXME: cleanup and comment
11737 (let (delta deltan deltaw deltadef year month day
11738 hour minute second wday pm h2 m2 tl wday1
11739 iso-year iso-weekday iso-week iso-year iso-date)
11741 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11742 (setq ans (replace-match "" t t ans)
11743 deltan (car delta)
11744 deltaw (nth 1 delta)
11745 deltadef (nth 2 delta)))
11747 ;; Check if there is an iso week date in there
11748 ;; If yes, sore the info and ostpone interpreting it until the rest
11749 ;; of the parsing is done
11750 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11751 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11752 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11753 iso-week (string-to-number (match-string 2 ans)))
11754 (setq ans (replace-match "" t t ans)))
11756 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11757 (when (string-match
11758 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11759 (setq year (if (match-end 2)
11760 (string-to-number (match-string 2 ans))
11761 (string-to-number (format-time-string "%Y")))
11762 month (string-to-number (match-string 3 ans))
11763 day (string-to-number (match-string 4 ans)))
11764 (if (< year 100) (setq year (+ 2000 year)))
11765 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11766 t nil ans)))
11767 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11768 ;; If there is a time with am/pm, and *no* time without it, we convert
11769 ;; so that matching will be successful.
11770 (loop for i from 1 to 2 do ; twice, for end time as well
11771 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11772 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11773 (setq hour (string-to-number (match-string 1 ans))
11774 minute (if (match-end 3)
11775 (string-to-number (match-string 3 ans))
11777 pm (equal ?p
11778 (string-to-char (downcase (match-string 4 ans)))))
11779 (if (and (= hour 12) (not pm))
11780 (setq hour 0)
11781 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11782 (setq ans (replace-match (format "%02d:%02d" hour minute)
11783 t t ans))))
11785 ;; Check if a time range is given as a duration
11786 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11787 (setq hour (string-to-number (match-string 1 ans))
11788 h2 (+ hour (string-to-number (match-string 3 ans)))
11789 minute (string-to-number (match-string 2 ans))
11790 m2 (+ minute (if (match-end 5) (string-to-number
11791 (match-string 5 ans))0)))
11792 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11793 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11794 t t ans)))
11796 ;; Check if there is a time range
11797 (when (boundp 'org-end-time-was-given)
11798 (setq org-time-was-given nil)
11799 (when (and (string-match org-plain-time-of-day-regexp ans)
11800 (match-end 8))
11801 (setq org-end-time-was-given (match-string 8 ans))
11802 (setq ans (concat (substring ans 0 (match-beginning 7))
11803 (substring ans (match-end 7))))))
11805 (setq tl (parse-time-string ans)
11806 day (or (nth 3 tl) (nth 3 defdecode))
11807 month (or (nth 4 tl)
11808 (if (and org-read-date-prefer-future
11809 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11810 (1+ (nth 4 defdecode))
11811 (nth 4 defdecode)))
11812 year (or (nth 5 tl)
11813 (if (and org-read-date-prefer-future
11814 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11815 (1+ (nth 5 defdecode))
11816 (nth 5 defdecode)))
11817 hour (or (nth 2 tl) (nth 2 defdecode))
11818 minute (or (nth 1 tl) (nth 1 defdecode))
11819 second (or (nth 0 tl) 0)
11820 wday (nth 6 tl))
11822 ;; Special date definitions below
11823 (cond
11824 (iso-week
11825 ;; There was an iso week
11826 (setq year (or iso-year year)
11827 day (or iso-weekday wday 1)
11828 wday nil ; to make sure that the trigger below does not match
11829 iso-date (calendar-gregorian-from-absolute
11830 (calendar-absolute-from-iso
11831 (list iso-week day year))))
11832 ; FIXME: Should we also push ISO weeks into the future?
11833 ; (when (and org-read-date-prefer-future
11834 ; (not iso-year)
11835 ; (< (calendar-absolute-from-gregorian iso-date)
11836 ; (time-to-days (current-time))))
11837 ; (setq year (1+ year)
11838 ; iso-date (calendar-gregorian-from-absolute
11839 ; (calendar-absolute-from-iso
11840 ; (list iso-week day year)))))
11841 (setq month (car iso-date)
11842 year (nth 2 iso-date)
11843 day (nth 1 iso-date)))
11844 (deltan
11845 (unless deltadef
11846 (let ((now (decode-time (current-time))))
11847 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11848 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11849 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11850 ((equal deltaw "m") (setq month (+ month deltan)))
11851 ((equal deltaw "y") (setq year (+ year deltan)))))
11852 ((and wday (not (nth 3 tl)))
11853 ;; Weekday was given, but no day, so pick that day in the week
11854 ;; on or after the derived date.
11855 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11856 (unless (equal wday wday1)
11857 (setq day (+ day (% (- wday wday1 -7) 7))))))
11858 (if (and (boundp 'org-time-was-given)
11859 (nth 2 tl))
11860 (setq org-time-was-given t))
11861 (if (< year 100) (setq year (+ 2000 year)))
11862 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11863 (list second minute hour day month year)))
11865 (defvar parse-time-weekdays)
11867 (defun org-read-date-get-relative (s today default)
11868 "Check string S for special relative date string.
11869 TODAY and DEFAULT are internal times, for today and for a default.
11870 Return shift list (N what def-flag)
11871 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11872 N is the number of WHATs to shift.
11873 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11874 the DEFAULT date rather than TODAY."
11875 (when (string-match
11876 (concat
11877 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
11878 "\\([0-9]+\\)?"
11879 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11880 "\\([ \t]\\|$\\)") s)
11881 (let* ((dir (if (match-end 1)
11882 (string-to-char (substring (match-string 1 s) -1))
11883 ?+))
11884 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11885 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11886 (what (if (match-end 3) (match-string 3 s) "d"))
11887 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11888 (date (if rel default today))
11889 (wday (nth 6 (decode-time date)))
11890 delta)
11891 (if wday1
11892 (progn
11893 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11894 (if (= dir ?-) (setq delta (- delta 7)))
11895 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11896 (list delta "d" rel))
11897 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11899 (defun org-eval-in-calendar (form &optional keepdate)
11900 "Eval FORM in the calendar window and return to current window.
11901 Also, store the cursor date in variable org-ans2."
11902 (let ((sw (selected-window)))
11903 (select-window (get-buffer-window "*Calendar*"))
11904 (eval form)
11905 (when (and (not keepdate) (calendar-cursor-to-date))
11906 (let* ((date (calendar-cursor-to-date))
11907 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11908 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11909 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11910 (select-window sw)))
11912 ; ;; Update the prompt to show new default date
11913 ; (save-excursion
11914 ; (goto-char (point-min))
11915 ; (when (and org-ans2
11916 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
11917 ; (get-text-property (match-end 0) 'field))
11918 ; (let ((inhibit-read-only t))
11919 ; (replace-match (concat "[" org-ans2 "]") t t)
11920 ; (add-text-properties (point-min) (1+ (match-end 0))
11921 ; (text-properties-at (1+ (point-min)))))))))
11923 (defun org-calendar-select ()
11924 "Return to `org-read-date' with the date currently selected.
11925 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11926 (interactive)
11927 (when (calendar-cursor-to-date)
11928 (let* ((date (calendar-cursor-to-date))
11929 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11930 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11931 (if (active-minibuffer-window) (exit-minibuffer))))
11933 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11934 "Insert a date stamp for the date given by the internal TIME.
11935 WITH-HM means, use the stamp format that includes the time of the day.
11936 INACTIVE means use square brackets instead of angular ones, so that the
11937 stamp will not contribute to the agenda.
11938 PRE and POST are optional strings to be inserted before and after the
11939 stamp.
11940 The command returns the inserted time stamp."
11941 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11942 stamp)
11943 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11944 (insert-before-markers (or pre ""))
11945 (insert-before-markers (setq stamp (format-time-string fmt time)))
11946 (when (listp extra)
11947 (setq extra (car extra))
11948 (if (and (stringp extra)
11949 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11950 (setq extra (format "-%02d:%02d"
11951 (string-to-number (match-string 1 extra))
11952 (string-to-number (match-string 2 extra))))
11953 (setq extra nil)))
11954 (when extra
11955 (backward-char 1)
11956 (insert-before-markers extra)
11957 (forward-char 1))
11958 (insert-before-markers (or post ""))
11959 stamp))
11961 (defun org-toggle-time-stamp-overlays ()
11962 "Toggle the use of custom time stamp formats."
11963 (interactive)
11964 (setq org-display-custom-times (not org-display-custom-times))
11965 (unless org-display-custom-times
11966 (let ((p (point-min)) (bmp (buffer-modified-p)))
11967 (while (setq p (next-single-property-change p 'display))
11968 (if (and (get-text-property p 'display)
11969 (eq (get-text-property p 'face) 'org-date))
11970 (remove-text-properties
11971 p (setq p (next-single-property-change p 'display))
11972 '(display t))))
11973 (set-buffer-modified-p bmp)))
11974 (if (featurep 'xemacs)
11975 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11976 (org-restart-font-lock)
11977 (setq org-table-may-need-update t)
11978 (if org-display-custom-times
11979 (message "Time stamps are overlayed with custom format")
11980 (message "Time stamp overlays removed")))
11982 (defun org-display-custom-time (beg end)
11983 "Overlay modified time stamp format over timestamp between BED and END."
11984 (let* ((ts (buffer-substring beg end))
11985 t1 w1 with-hm tf time str w2 (off 0))
11986 (save-match-data
11987 (setq t1 (org-parse-time-string ts t))
11988 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11989 (setq off (- (match-end 0) (match-beginning 0)))))
11990 (setq end (- end off))
11991 (setq w1 (- end beg)
11992 with-hm (and (nth 1 t1) (nth 2 t1))
11993 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11994 time (org-fix-decoded-time t1)
11995 str (org-add-props
11996 (format-time-string
11997 (substring tf 1 -1) (apply 'encode-time time))
11998 nil 'mouse-face 'highlight)
11999 w2 (length str))
12000 (if (not (= w2 w1))
12001 (add-text-properties (1+ beg) (+ 2 beg)
12002 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12003 (if (featurep 'xemacs)
12004 (progn
12005 (put-text-property beg end 'invisible t)
12006 (put-text-property beg end 'end-glyph (make-glyph str)))
12007 (put-text-property beg end 'display str))))
12009 (defun org-translate-time (string)
12010 "Translate all timestamps in STRING to custom format.
12011 But do this only if the variable `org-display-custom-times' is set."
12012 (when org-display-custom-times
12013 (save-match-data
12014 (let* ((start 0)
12015 (re org-ts-regexp-both)
12016 t1 with-hm inactive tf time str beg end)
12017 (while (setq start (string-match re string start))
12018 (setq beg (match-beginning 0)
12019 end (match-end 0)
12020 t1 (save-match-data
12021 (org-parse-time-string (substring string beg end) t))
12022 with-hm (and (nth 1 t1) (nth 2 t1))
12023 inactive (equal (substring string beg (1+ beg)) "[")
12024 tf (funcall (if with-hm 'cdr 'car)
12025 org-time-stamp-custom-formats)
12026 time (org-fix-decoded-time t1)
12027 str (format-time-string
12028 (concat
12029 (if inactive "[" "<") (substring tf 1 -1)
12030 (if inactive "]" ">"))
12031 (apply 'encode-time time))
12032 string (replace-match str t t string)
12033 start (+ start (length str)))))))
12034 string)
12036 (defun org-fix-decoded-time (time)
12037 "Set 0 instead of nil for the first 6 elements of time.
12038 Don't touch the rest."
12039 (let ((n 0))
12040 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12042 (defun org-days-to-time (timestamp-string)
12043 "Difference between TIMESTAMP-STRING and now in days."
12044 (- (time-to-days (org-time-string-to-time timestamp-string))
12045 (time-to-days (current-time))))
12047 (defun org-deadline-close (timestamp-string &optional ndays)
12048 "Is the time in TIMESTAMP-STRING close to the current date?"
12049 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12050 (and (< (org-days-to-time timestamp-string) ndays)
12051 (not (org-entry-is-done-p))))
12053 (defun org-get-wdays (ts)
12054 "Get the deadline lead time appropriate for timestring TS."
12055 (cond
12056 ((<= org-deadline-warning-days 0)
12057 ;; 0 or negative, enforce this value no matter what
12058 (- org-deadline-warning-days))
12059 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
12060 ;; lead time is specified.
12061 (floor (* (string-to-number (match-string 1 ts))
12062 (cdr (assoc (match-string 2 ts)
12063 '(("d" . 1) ("w" . 7)
12064 ("m" . 30.4) ("y" . 365.25)))))))
12065 ;; go for the default.
12066 (t org-deadline-warning-days)))
12068 (defun org-calendar-select-mouse (ev)
12069 "Return to `org-read-date' with the date currently selected.
12070 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12071 (interactive "e")
12072 (mouse-set-point ev)
12073 (when (calendar-cursor-to-date)
12074 (let* ((date (calendar-cursor-to-date))
12075 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12076 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12077 (if (active-minibuffer-window) (exit-minibuffer))))
12079 (defun org-check-deadlines (ndays)
12080 "Check if there are any deadlines due or past due.
12081 A deadline is considered due if it happens within `org-deadline-warning-days'
12082 days from today's date. If the deadline appears in an entry marked DONE,
12083 it is not shown. The prefix arg NDAYS can be used to test that many
12084 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12085 (interactive "P")
12086 (let* ((org-warn-days
12087 (cond
12088 ((equal ndays '(4)) 100000)
12089 (ndays (prefix-numeric-value ndays))
12090 (t (abs org-deadline-warning-days))))
12091 (case-fold-search nil)
12092 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12093 (callback
12094 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12096 (message "%d deadlines past-due or due within %d days"
12097 (org-occur regexp nil callback)
12098 org-warn-days)))
12100 (defun org-check-before-date (date)
12101 "Check if there are deadlines or scheduled entries before DATE."
12102 (interactive (list (org-read-date)))
12103 (let ((case-fold-search nil)
12104 (regexp (concat "\\<\\(" org-deadline-string
12105 "\\|" org-scheduled-string
12106 "\\) *<\\([^>]+\\)>"))
12107 (callback
12108 (lambda () (time-less-p
12109 (org-time-string-to-time (match-string 2))
12110 (org-time-string-to-time date)))))
12111 (message "%d entries before %s"
12112 (org-occur regexp nil callback) date)))
12114 (defun org-evaluate-time-range (&optional to-buffer)
12115 "Evaluate a time range by computing the difference between start and end.
12116 Normally the result is just printed in the echo area, but with prefix arg
12117 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12118 If the time range is actually in a table, the result is inserted into the
12119 next column.
12120 For time difference computation, a year is assumed to be exactly 365
12121 days in order to avoid rounding problems."
12122 (interactive "P")
12124 (org-clock-update-time-maybe)
12125 (save-excursion
12126 (unless (org-at-date-range-p t)
12127 (goto-char (point-at-bol))
12128 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12129 (if (not (org-at-date-range-p t))
12130 (error "Not at a time-stamp range, and none found in current line")))
12131 (let* ((ts1 (match-string 1))
12132 (ts2 (match-string 2))
12133 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12134 (match-end (match-end 0))
12135 (time1 (org-time-string-to-time ts1))
12136 (time2 (org-time-string-to-time ts2))
12137 (t1 (time-to-seconds time1))
12138 (t2 (time-to-seconds time2))
12139 (diff (abs (- t2 t1)))
12140 (negative (< (- t2 t1) 0))
12141 ;; (ys (floor (* 365 24 60 60)))
12142 (ds (* 24 60 60))
12143 (hs (* 60 60))
12144 (fy "%dy %dd %02d:%02d")
12145 (fy1 "%dy %dd")
12146 (fd "%dd %02d:%02d")
12147 (fd1 "%dd")
12148 (fh "%02d:%02d")
12149 y d h m align)
12150 (if havetime
12151 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12153 d (floor (/ diff ds)) diff (mod diff ds)
12154 h (floor (/ diff hs)) diff (mod diff hs)
12155 m (floor (/ diff 60)))
12156 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12158 d (floor (+ (/ diff ds) 0.5))
12159 h 0 m 0))
12160 (if (not to-buffer)
12161 (message "%s" (org-make-tdiff-string y d h m))
12162 (if (org-at-table-p)
12163 (progn
12164 (goto-char match-end)
12165 (setq align t)
12166 (and (looking-at " *|") (goto-char (match-end 0))))
12167 (goto-char match-end))
12168 (if (looking-at
12169 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12170 (replace-match ""))
12171 (if negative (insert " -"))
12172 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12173 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12174 (insert " " (format fh h m))))
12175 (if align (org-table-align))
12176 (message "Time difference inserted")))))
12178 (defun org-make-tdiff-string (y d h m)
12179 (let ((fmt "")
12180 (l nil))
12181 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12182 l (push y l)))
12183 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12184 l (push d l)))
12185 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12186 l (push h l)))
12187 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12188 l (push m l)))
12189 (apply 'format fmt (nreverse l))))
12191 (defun org-time-string-to-time (s)
12192 (apply 'encode-time (org-parse-time-string s)))
12194 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12195 "Convert a time stamp to an absolute day number.
12196 If there is a specifyer for a cyclic time stamp, get the closest date to
12197 DAYNR.
12198 PREFER and SHOW_ALL are passed through to `org-closest-date'."
12199 (cond
12200 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12201 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12202 daynr
12203 (+ daynr 1000)))
12204 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12205 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12206 (time-to-days (current-time))) (match-string 0 s)
12207 prefer show-all))
12208 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12210 (defun org-time-from-absolute (d)
12211 "Return the time corresponding to date D.
12212 D may be an absolute day number, or a calendar-type list (month day year)."
12213 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12214 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12216 (defun org-calendar-holiday ()
12217 "List of holidays, for Diary display in Org-mode."
12218 (require 'holidays)
12219 (let ((hl (funcall
12220 (if (fboundp 'calendar-check-holidays)
12221 'calendar-check-holidays 'check-calendar-holidays) date)))
12222 (if hl (mapconcat 'identity hl "; "))))
12224 (defun org-diary-sexp-entry (sexp entry date)
12225 "Process a SEXP diary ENTRY for DATE."
12226 (require 'diary-lib)
12227 (let ((result (if calendar-debug-sexp
12228 (let ((stack-trace-on-error t))
12229 (eval (car (read-from-string sexp))))
12230 (condition-case nil
12231 (eval (car (read-from-string sexp)))
12232 (error
12233 (beep)
12234 (message "Bad sexp at line %d in %s: %s"
12235 (org-current-line)
12236 (buffer-file-name) sexp)
12237 (sleep-for 2))))))
12238 (cond ((stringp result) result)
12239 ((and (consp result)
12240 (stringp (cdr result))) (cdr result))
12241 (result entry)
12242 (t nil))))
12244 (defun org-diary-to-ical-string (frombuf)
12245 "Get iCalendar entries from diary entries in buffer FROMBUF.
12246 This uses the icalendar.el library."
12247 (let* ((tmpdir (if (featurep 'xemacs)
12248 (temp-directory)
12249 temporary-file-directory))
12250 (tmpfile (make-temp-name
12251 (expand-file-name "orgics" tmpdir)))
12252 buf rtn b e)
12253 (save-excursion
12254 (set-buffer frombuf)
12255 (icalendar-export-region (point-min) (point-max) tmpfile)
12256 (setq buf (find-buffer-visiting tmpfile))
12257 (set-buffer buf)
12258 (goto-char (point-min))
12259 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12260 (setq b (match-beginning 0)))
12261 (goto-char (point-max))
12262 (if (re-search-backward "^END:VEVENT" nil t)
12263 (setq e (match-end 0)))
12264 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12265 (kill-buffer buf)
12266 (kill-buffer frombuf)
12267 (delete-file tmpfile)
12268 rtn))
12270 (defun org-closest-date (start current change prefer show-all)
12271 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12272 When PREFER is `past' return a date that is either CURRENT or past.
12273 When PREFER is `future', return a date that is either CURRENT or future.
12274 When SHOW-ALL is nil, only return the current occurence of a time stamp."
12275 ;; Make the proper lists from the dates
12276 (catch 'exit
12277 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12278 dn dw sday cday n1 n2
12279 d m y y1 y2 date1 date2 nmonths nm ny m2)
12281 (setq start (org-date-to-gregorian start)
12282 current (org-date-to-gregorian
12283 (if show-all
12284 current
12285 (time-to-days (current-time))))
12286 sday (calendar-absolute-from-gregorian start)
12287 cday (calendar-absolute-from-gregorian current))
12289 (if (<= cday sday) (throw 'exit sday))
12291 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12292 (setq dn (string-to-number (match-string 1 change))
12293 dw (cdr (assoc (match-string 2 change) a1)))
12294 (error "Invalid change specifyer: %s" change))
12295 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12296 (cond
12297 ((eq dw 'day)
12298 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12299 n2 (+ n1 dn)))
12300 ((eq dw 'year)
12301 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12302 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12303 (setq date1 (list m d y1)
12304 n1 (calendar-absolute-from-gregorian date1)
12305 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12306 n2 (calendar-absolute-from-gregorian date2)))
12307 ((eq dw 'month)
12308 ;; approx number of month between the tow dates
12309 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12310 ;; How often does dn fit in there?
12311 (setq d (nth 1 start) m (car start) y (nth 2 start)
12312 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12313 m (+ m nm)
12314 ny (floor (/ m 12))
12315 y (+ y ny)
12316 m (- m (* ny 12)))
12317 (while (> m 12) (setq m (- m 12) y (1+ y)))
12318 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12319 (setq m2 (+ m dn) y2 y)
12320 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12321 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12322 (while (< n2 cday)
12323 (setq n1 n2 m m2 y y2)
12324 (setq m2 (+ m dn) y2 y)
12325 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12326 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12328 (if show-all
12329 (cond
12330 ((eq prefer 'past) n1)
12331 ((eq prefer 'future) (if (= cday n1) n1 n2))
12332 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12333 (cond
12334 ((eq prefer 'past) n1)
12335 ((eq prefer 'future) (if (= cday n1) n1 n2))
12336 (t (if (= cday n1) n1 n2)))))))
12338 (defun org-date-to-gregorian (date)
12339 "Turn any specification of DATE into a gregorian date for the calendar."
12340 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12341 ((and (listp date) (= (length date) 3)) date)
12342 ((stringp date)
12343 (setq date (org-parse-time-string date))
12344 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12345 ((listp date)
12346 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12348 (defun org-parse-time-string (s &optional nodefault)
12349 "Parse the standard Org-mode time string.
12350 This should be a lot faster than the normal `parse-time-string'.
12351 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12352 hour and minute fields will be nil if not given."
12353 (if (string-match org-ts-regexp0 s)
12354 (list 0
12355 (if (or (match-beginning 8) (not nodefault))
12356 (string-to-number (or (match-string 8 s) "0")))
12357 (if (or (match-beginning 7) (not nodefault))
12358 (string-to-number (or (match-string 7 s) "0")))
12359 (string-to-number (match-string 4 s))
12360 (string-to-number (match-string 3 s))
12361 (string-to-number (match-string 2 s))
12362 nil nil nil)
12363 (make-list 9 0)))
12365 (defun org-timestamp-up (&optional arg)
12366 "Increase the date item at the cursor by one.
12367 If the cursor is on the year, change the year. If it is on the month or
12368 the day, change that.
12369 With prefix ARG, change by that many units."
12370 (interactive "p")
12371 (org-timestamp-change (prefix-numeric-value arg)))
12373 (defun org-timestamp-down (&optional arg)
12374 "Decrease the date item at the cursor by one.
12375 If the cursor is on the year, change the year. If it is on the month or
12376 the day, change that.
12377 With prefix ARG, change by that many units."
12378 (interactive "p")
12379 (org-timestamp-change (- (prefix-numeric-value arg))))
12381 (defun org-timestamp-up-day (&optional arg)
12382 "Increase the date in the time stamp by one day.
12383 With prefix ARG, change that many days."
12384 (interactive "p")
12385 (if (and (not (org-at-timestamp-p t))
12386 (org-on-heading-p))
12387 (org-todo 'up)
12388 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12390 (defun org-timestamp-down-day (&optional arg)
12391 "Decrease the date in the time stamp by one day.
12392 With prefix ARG, change that many days."
12393 (interactive "p")
12394 (if (and (not (org-at-timestamp-p t))
12395 (org-on-heading-p))
12396 (org-todo 'down)
12397 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12399 (defun org-at-timestamp-p (&optional inactive-ok)
12400 "Determine if the cursor is in or at a timestamp."
12401 (interactive)
12402 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12403 (pos (point))
12404 (ans (or (looking-at tsr)
12405 (save-excursion
12406 (skip-chars-backward "^[<\n\r\t")
12407 (if (> (point) (point-min)) (backward-char 1))
12408 (and (looking-at tsr)
12409 (> (- (match-end 0) pos) -1))))))
12410 (and ans
12411 (boundp 'org-ts-what)
12412 (setq org-ts-what
12413 (cond
12414 ((= pos (match-beginning 0)) 'bracket)
12415 ((= pos (1- (match-end 0))) 'bracket)
12416 ((org-pos-in-match-range pos 2) 'year)
12417 ((org-pos-in-match-range pos 3) 'month)
12418 ((org-pos-in-match-range pos 7) 'hour)
12419 ((org-pos-in-match-range pos 8) 'minute)
12420 ((or (org-pos-in-match-range pos 4)
12421 (org-pos-in-match-range pos 5)) 'day)
12422 ((and (> pos (or (match-end 8) (match-end 5)))
12423 (< pos (match-end 0)))
12424 (- pos (or (match-end 8) (match-end 5))))
12425 (t 'day))))
12426 ans))
12428 (defun org-toggle-timestamp-type ()
12429 "Toggle the type (<active> or [inactive]) of a time stamp."
12430 (interactive)
12431 (when (org-at-timestamp-p t)
12432 (save-excursion
12433 (goto-char (match-beginning 0))
12434 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
12435 (goto-char (1- (match-end 0)))
12436 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
12437 (message "Timestamp is now %sactive"
12438 (if (equal (char-before) ?>) "in" ""))))
12440 (defun org-timestamp-change (n &optional what)
12441 "Change the date in the time stamp at point.
12442 The date will be changed by N times WHAT. WHAT can be `day', `month',
12443 `year', `minute', `second'. If WHAT is not given, the cursor position
12444 in the timestamp determines what will be changed."
12445 (let ((pos (point))
12446 with-hm inactive
12447 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12448 org-ts-what
12449 extra rem
12450 ts time time0)
12451 (if (not (org-at-timestamp-p t))
12452 (error "Not at a timestamp"))
12453 (if (and (not what) (eq org-ts-what 'bracket))
12454 (org-toggle-timestamp-type)
12455 (if (and (not what) (not (eq org-ts-what 'day))
12456 org-display-custom-times
12457 (get-text-property (point) 'display)
12458 (not (get-text-property (1- (point)) 'display)))
12459 (setq org-ts-what 'day))
12460 (setq org-ts-what (or what org-ts-what)
12461 inactive (= (char-after (match-beginning 0)) ?\[)
12462 ts (match-string 0))
12463 (replace-match "")
12464 (if (string-match
12465 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12467 (setq extra (match-string 1 ts)))
12468 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12469 (setq with-hm t))
12470 (setq time0 (org-parse-time-string ts))
12471 (when (and (eq org-ts-what 'minute)
12472 (eq current-prefix-arg nil))
12473 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12474 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12475 (setcar (cdr time0) (+ (nth 1 time0)
12476 (if (> n 0) (- rem) (- dm rem))))))
12477 (setq time
12478 (encode-time (or (car time0) 0)
12479 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12480 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12481 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12482 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12483 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12484 (nthcdr 6 time0)))
12485 (when (integerp org-ts-what)
12486 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12487 (if (eq what 'calendar)
12488 (let ((cal-date (org-get-date-from-calendar)))
12489 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12490 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12491 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12492 (setcar time0 (or (car time0) 0))
12493 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12494 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12495 (setq time (apply 'encode-time time0))))
12496 (setq org-last-changed-timestamp
12497 (org-insert-time-stamp time with-hm inactive nil nil extra))
12498 (org-clock-update-time-maybe)
12499 (goto-char pos)
12500 ;; Try to recenter the calendar window, if any
12501 (if (and org-calendar-follow-timestamp-change
12502 (get-buffer-window "*Calendar*" t)
12503 (memq org-ts-what '(day month year)))
12504 (org-recenter-calendar (time-to-days time))))))
12506 ;; FIXME: does not yet work for lead times
12507 (defun org-modify-ts-extra (s pos n dm)
12508 "Change the different parts of the lead-time and repeat fields in timestamp."
12509 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12510 ng h m new rem)
12511 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12512 (cond
12513 ((or (org-pos-in-match-range pos 2)
12514 (org-pos-in-match-range pos 3))
12515 (setq m (string-to-number (match-string 3 s))
12516 h (string-to-number (match-string 2 s)))
12517 (if (org-pos-in-match-range pos 2)
12518 (setq h (+ h n))
12519 (setq n (* dm (org-no-warnings (signum n))))
12520 (when (not (= 0 (setq rem (% m dm))))
12521 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12522 (setq m (+ m n)))
12523 (if (< m 0) (setq m (+ m 60) h (1- h)))
12524 (if (> m 59) (setq m (- m 60) h (1+ h)))
12525 (setq h (min 24 (max 0 h)))
12526 (setq ng 1 new (format "-%02d:%02d" h m)))
12527 ((org-pos-in-match-range pos 6)
12528 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12529 ((org-pos-in-match-range pos 5)
12530 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12532 ((org-pos-in-match-range pos 9)
12533 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12534 ((org-pos-in-match-range pos 8)
12535 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12537 (when ng
12538 (setq s (concat
12539 (substring s 0 (match-beginning ng))
12541 (substring s (match-end ng))))))
12544 (defun org-recenter-calendar (date)
12545 "If the calendar is visible, recenter it to DATE."
12546 (let* ((win (selected-window))
12547 (cwin (get-buffer-window "*Calendar*" t))
12548 (calendar-move-hook nil))
12549 (when cwin
12550 (select-window cwin)
12551 (calendar-goto-date (if (listp date) date
12552 (calendar-gregorian-from-absolute date)))
12553 (select-window win))))
12555 (defun org-goto-calendar (&optional arg)
12556 "Go to the Emacs calendar at the current date.
12557 If there is a time stamp in the current line, go to that date.
12558 A prefix ARG can be used to force the current date."
12559 (interactive "P")
12560 (let ((tsr org-ts-regexp) diff
12561 (calendar-move-hook nil)
12562 (view-calendar-holidays-initially nil)
12563 (view-diary-entries-initially nil))
12564 (if (or (org-at-timestamp-p)
12565 (save-excursion
12566 (beginning-of-line 1)
12567 (looking-at (concat ".*" tsr))))
12568 (let ((d1 (time-to-days (current-time)))
12569 (d2 (time-to-days
12570 (org-time-string-to-time (match-string 1)))))
12571 (setq diff (- d2 d1))))
12572 (calendar)
12573 (calendar-goto-today)
12574 (if (and diff (not arg)) (calendar-forward-day diff))))
12576 (defun org-get-date-from-calendar ()
12577 "Return a list (month day year) of date at point in calendar."
12578 (with-current-buffer "*Calendar*"
12579 (save-match-data
12580 (calendar-cursor-to-date))))
12582 (defun org-date-from-calendar ()
12583 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12584 If there is already a time stamp at the cursor position, update it."
12585 (interactive)
12586 (if (org-at-timestamp-p t)
12587 (org-timestamp-change 0 'calendar)
12588 (let ((cal-date (org-get-date-from-calendar)))
12589 (org-insert-time-stamp
12590 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12592 ;;; The clock for measuring work time.
12594 (defvar org-mode-line-string "")
12595 (put 'org-mode-line-string 'risky-local-variable t)
12597 (defvar org-mode-line-timer nil)
12598 (defvar org-clock-heading "")
12599 (defvar org-clock-start-time "")
12601 (defun org-update-mode-line ()
12602 (let* ((delta (- (time-to-seconds (current-time))
12603 (time-to-seconds org-clock-start-time)))
12604 (h (floor delta 3600))
12605 (m (floor (- delta (* 3600 h)) 60)))
12606 (setq org-mode-line-string
12607 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
12608 'help-echo "Org-mode clock is running"))
12609 (force-mode-line-update)))
12611 (defvar org-clock-marker (make-marker)
12612 "Marker recording the last clock-in.")
12613 (defvar org-clock-mode-line-entry nil
12614 "Information for the modeline about the running clock.")
12616 (defun org-clock-in ()
12617 "Start the clock on the current item.
12618 If necessary, clock-out of the currently active clock."
12619 (interactive)
12620 (org-clock-out t)
12621 (let (ts)
12622 (save-excursion
12623 (org-back-to-heading t)
12624 (when (and org-clock-in-switch-to-state
12625 (not (looking-at (concat outline-regexp "[ \t]*"
12626 org-clock-in-switch-to-state
12627 "\\>"))))
12628 (org-todo org-clock-in-switch-to-state))
12629 (if (and org-clock-heading-function
12630 (functionp org-clock-heading-function))
12631 (setq org-clock-heading (funcall org-clock-heading-function))
12632 (if (looking-at org-complex-heading-regexp)
12633 (setq org-clock-heading (match-string 4))
12634 (setq org-clock-heading "???")))
12635 (setq org-clock-heading (propertize org-clock-heading 'face nil))
12636 (org-clock-find-position)
12638 (insert "\n") (backward-char 1)
12639 (indent-relative)
12640 (insert org-clock-string " ")
12641 (setq org-clock-start-time (current-time))
12642 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12643 (move-marker org-clock-marker (point) (buffer-base-buffer))
12644 (or global-mode-string (setq global-mode-string '("")))
12645 (or (memq 'org-mode-line-string global-mode-string)
12646 (setq global-mode-string
12647 (append global-mode-string '(org-mode-line-string))))
12648 (org-update-mode-line)
12649 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
12650 (message "Clock started at %s" ts))))
12652 (defun org-clock-find-position ()
12653 "Find the location where the next clock line should be inserted."
12654 (org-back-to-heading t)
12655 (catch 'exit
12656 (let ((beg (save-excursion
12657 (beginning-of-line 2)
12658 (or (bolp) (newline))
12659 (point)))
12660 (end (progn (outline-next-heading) (point)))
12661 (re (concat "^[ \t]*" org-clock-string))
12662 (cnt 0)
12663 first last)
12664 (goto-char beg)
12665 (when (eobp) (newline) (setq end (max (point) end)))
12666 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
12667 ;; we seem to have a CLOCK drawer, so go there.
12668 (beginning-of-line 2)
12669 (throw 'exit t))
12670 ;; Lets count the CLOCK lines
12671 (goto-char beg)
12672 (while (re-search-forward re end t)
12673 (setq first (or first (match-beginning 0))
12674 last (match-beginning 0)
12675 cnt (1+ cnt)))
12676 (when (and (integerp org-clock-into-drawer)
12677 (>= (1+ cnt) org-clock-into-drawer))
12678 ;; Wrap current entries into a new drawer
12679 (goto-char last)
12680 (beginning-of-line 2)
12681 (if (org-at-item-p) (org-end-of-item))
12682 (insert ":END:\n")
12683 (beginning-of-line 0)
12684 (org-indent-line-function)
12685 (goto-char first)
12686 (insert ":CLOCK:\n")
12687 (beginning-of-line 0)
12688 (org-indent-line-function)
12689 (org-flag-drawer t)
12690 (beginning-of-line 2)
12691 (throw 'exit nil))
12693 (goto-char beg)
12694 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12695 (not (equal (match-string 1) org-clock-string)))
12696 ;; Planning info, skip to after it
12697 (beginning-of-line 2)
12698 (or (bolp) (newline)))
12699 (when (eq t org-clock-into-drawer)
12700 (insert ":CLOCK:\n:END:\n")
12701 (beginning-of-line -1)
12702 (org-indent-line-function)
12703 (org-flag-drawer t)
12704 (beginning-of-line 2)
12705 (org-indent-line-function)))))
12707 (defun org-clock-out (&optional fail-quietly)
12708 "Stop the currently running clock.
12709 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
12710 (interactive)
12711 (catch 'exit
12712 (if (not (marker-buffer org-clock-marker))
12713 (if fail-quietly (throw 'exit t) (error "No active clock")))
12714 (let (ts te s h m)
12715 (save-excursion
12716 (set-buffer (marker-buffer org-clock-marker))
12717 (goto-char org-clock-marker)
12718 (beginning-of-line 1)
12719 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12720 (equal (match-string 1) org-clock-string))
12721 (setq ts (match-string 2))
12722 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
12723 (goto-char (match-end 0))
12724 (delete-region (point) (point-at-eol))
12725 (insert "--")
12726 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12727 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
12728 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
12729 h (floor (/ s 3600))
12730 s (- s (* 3600 h))
12731 m (floor (/ s 60))
12732 s (- s (* 60 s)))
12733 (insert " => " (format "%2d:%02d" h m))
12734 (move-marker org-clock-marker nil)
12735 (when org-log-note-clock-out
12736 (org-add-log-setup 'clock-out))
12737 (when org-mode-line-timer
12738 (cancel-timer org-mode-line-timer)
12739 (setq org-mode-line-timer nil))
12740 (setq global-mode-string
12741 (delq 'org-mode-line-string global-mode-string))
12742 (force-mode-line-update)
12743 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
12745 (defun org-clock-cancel ()
12746 "Cancel the running clock be removing the start timestamp."
12747 (interactive)
12748 (if (not (marker-buffer org-clock-marker))
12749 (error "No active clock"))
12750 (save-excursion
12751 (set-buffer (marker-buffer org-clock-marker))
12752 (goto-char org-clock-marker)
12753 (delete-region (1- (point-at-bol)) (point-at-eol)))
12754 (setq global-mode-string
12755 (delq 'org-mode-line-string global-mode-string))
12756 (force-mode-line-update)
12757 (message "Clock canceled"))
12759 (defun org-clock-goto (&optional delete-windows)
12760 "Go to the currently clocked-in entry."
12761 (interactive "P")
12762 (if (not (marker-buffer org-clock-marker))
12763 (error "No active clock"))
12764 (switch-to-buffer-other-window
12765 (marker-buffer org-clock-marker))
12766 (if delete-windows (delete-other-windows))
12767 (goto-char org-clock-marker)
12768 (org-show-entry)
12769 (org-back-to-heading)
12770 (recenter))
12772 (defvar org-clock-file-total-minutes nil
12773 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
12774 (make-variable-buffer-local 'org-clock-file-total-minutes)
12776 (defun org-clock-sum (&optional tstart tend)
12777 "Sum the times for each subtree.
12778 Puts the resulting times in minutes as a text property on each headline."
12779 (interactive)
12780 (let* ((bmp (buffer-modified-p))
12781 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
12782 org-clock-string
12783 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
12784 (lmax 30)
12785 (ltimes (make-vector lmax 0))
12786 (t1 0)
12787 (level 0)
12788 ts te dt
12789 time)
12790 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
12791 (save-excursion
12792 (goto-char (point-max))
12793 (while (re-search-backward re nil t)
12794 (cond
12795 ((match-end 2)
12796 ;; Two time stamps
12797 (setq ts (match-string 2)
12798 te (match-string 3)
12799 ts (time-to-seconds
12800 (apply 'encode-time (org-parse-time-string ts)))
12801 te (time-to-seconds
12802 (apply 'encode-time (org-parse-time-string te)))
12803 ts (if tstart (max ts tstart) ts)
12804 te (if tend (min te tend) te)
12805 dt (- te ts)
12806 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
12807 ((match-end 4)
12808 ;; A naket time
12809 (setq t1 (+ t1 (string-to-number (match-string 5))
12810 (* 60 (string-to-number (match-string 4))))))
12811 (t ;; A headline
12812 (setq level (- (match-end 1) (match-beginning 1)))
12813 (when (or (> t1 0) (> (aref ltimes level) 0))
12814 (loop for l from 0 to level do
12815 (aset ltimes l (+ (aref ltimes l) t1)))
12816 (setq t1 0 time (aref ltimes level))
12817 (loop for l from level to (1- lmax) do
12818 (aset ltimes l 0))
12819 (goto-char (match-beginning 0))
12820 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
12821 (setq org-clock-file-total-minutes (aref ltimes 0)))
12822 (set-buffer-modified-p bmp)))
12824 (defun org-clock-display (&optional total-only)
12825 "Show subtree times in the entire buffer.
12826 If TOTAL-ONLY is non-nil, only show the total time for the entire file
12827 in the echo area."
12828 (interactive)
12829 (org-remove-clock-overlays)
12830 (let (time h m p)
12831 (org-clock-sum)
12832 (unless total-only
12833 (save-excursion
12834 (goto-char (point-min))
12835 (while (or (and (equal (setq p (point)) (point-min))
12836 (get-text-property p :org-clock-minutes))
12837 (setq p (next-single-property-change
12838 (point) :org-clock-minutes)))
12839 (goto-char p)
12840 (when (setq time (get-text-property p :org-clock-minutes))
12841 (org-put-clock-overlay time (funcall outline-level))))
12842 (setq h (/ org-clock-file-total-minutes 60)
12843 m (- org-clock-file-total-minutes (* 60 h)))
12844 ;; Arrange to remove the overlays upon next change.
12845 (when org-remove-highlights-with-change
12846 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
12847 nil 'local))))
12848 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
12850 (defvar org-clock-overlays nil)
12851 (make-variable-buffer-local 'org-clock-overlays)
12853 (defun org-put-clock-overlay (time &optional level)
12854 "Put an overlays on the current line, displaying TIME.
12855 If LEVEL is given, prefix time with a corresponding number of stars.
12856 This creates a new overlay and stores it in `org-clock-overlays', so that it
12857 will be easy to remove."
12858 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
12859 (l (if level (org-get-valid-level level 0) 0))
12860 (off 0)
12861 ov tx)
12862 (move-to-column c)
12863 (unless (eolp) (skip-chars-backward "^ \t"))
12864 (skip-chars-backward " \t")
12865 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
12866 tx (concat (buffer-substring (1- (point)) (point))
12867 (make-string (+ off (max 0 (- c (current-column)))) ?.)
12868 (org-add-props (format "%s %2d:%02d%s"
12869 (make-string l ?*) h m
12870 (make-string (- 16 l) ?\ ))
12871 '(face secondary-selection))
12872 ""))
12873 (if (not (featurep 'xemacs))
12874 (org-overlay-put ov 'display tx)
12875 (org-overlay-put ov 'invisible t)
12876 (org-overlay-put ov 'end-glyph (make-glyph tx)))
12877 (push ov org-clock-overlays)))
12879 (defun org-remove-clock-overlays (&optional beg end noremove)
12880 "Remove the occur highlights from the buffer.
12881 BEG and END are ignored. If NOREMOVE is nil, remove this function
12882 from the `before-change-functions' in the current buffer."
12883 (interactive)
12884 (unless org-inhibit-highlight-removal
12885 (mapc 'org-delete-overlay org-clock-overlays)
12886 (setq org-clock-overlays nil)
12887 (unless noremove
12888 (remove-hook 'before-change-functions
12889 'org-remove-clock-overlays 'local))))
12891 (defun org-clock-out-if-current ()
12892 "Clock out if the current entry contains the running clock.
12893 This is used to stop the clock after a TODO entry is marked DONE,
12894 and is only done if the variable `org-clock-out-when-done' is not nil."
12895 (when (and org-clock-out-when-done
12896 (member state org-done-keywords)
12897 (equal (marker-buffer org-clock-marker) (current-buffer))
12898 (< (point) org-clock-marker)
12899 (> (save-excursion (outline-next-heading) (point))
12900 org-clock-marker))
12901 ;; Clock out, but don't accept a logging message for this.
12902 (let ((org-log-note-clock-out nil))
12903 (org-clock-out))))
12905 (add-hook 'org-after-todo-state-change-hook
12906 'org-clock-out-if-current)
12908 (defun org-check-running-clock ()
12909 "Check if the current buffer contains the running clock.
12910 If yes, offer to stop it and to save the buffer with the changes."
12911 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
12912 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
12913 (buffer-name))))
12914 (org-clock-out)
12915 (when (y-or-n-p "Save changed buffer?")
12916 (save-buffer))))
12918 (defun org-clock-report (&optional arg)
12919 "Create a table containing a report about clocked time.
12920 If the cursor is inside an existing clocktable block, then the table
12921 will be updated. If not, a new clocktable will be inserted.
12922 When called with a prefix argument, move to the first clock table in the
12923 buffer and update it."
12924 (interactive "P")
12925 (org-remove-clock-overlays)
12926 (when arg
12927 (org-find-dblock "clocktable")
12928 (org-show-entry))
12929 (if (org-in-clocktable-p)
12930 (goto-char (org-in-clocktable-p))
12931 (org-create-dblock (list :name "clocktable"
12932 :maxlevel 2 :scope 'file)))
12933 (org-update-dblock))
12935 (defun org-in-clocktable-p ()
12936 "Check if the cursor is in a clocktable."
12937 (let ((pos (point)) start)
12938 (save-excursion
12939 (end-of-line 1)
12940 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
12941 (setq start (match-beginning 0))
12942 (re-search-forward "^#\\+END:.*" nil t)
12943 (>= (match-end 0) pos)
12944 start))))
12946 (defun org-clock-update-time-maybe ()
12947 "If this is a CLOCK line, update it and return t.
12948 Otherwise, return nil."
12949 (interactive)
12950 (save-excursion
12951 (beginning-of-line 1)
12952 (skip-chars-forward " \t")
12953 (when (looking-at org-clock-string)
12954 (let ((re (concat "[ \t]*" org-clock-string
12955 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
12956 "\\([ \t]*=>.*\\)?"))
12957 ts te h m s)
12958 (if (not (looking-at re))
12960 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
12961 (end-of-line 1)
12962 (setq ts (match-string 1)
12963 te (match-string 2))
12964 (setq s (- (time-to-seconds
12965 (apply 'encode-time (org-parse-time-string te)))
12966 (time-to-seconds
12967 (apply 'encode-time (org-parse-time-string ts))))
12968 h (floor (/ s 3600))
12969 s (- s (* 3600 h))
12970 m (floor (/ s 60))
12971 s (- s (* 60 s)))
12972 (insert " => " (format "%2d:%02d" h m))
12973 t)))))
12975 (defun org-clock-special-range (key &optional time as-strings)
12976 "Return two times bordering a special time range.
12977 Key is a symbol specifying the range and can be one of `today', `yesterday',
12978 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
12979 A week starts Monday 0:00 and ends Sunday 24:00.
12980 The range is determined relative to TIME. TIME defaults to the current time.
12981 The return value is a cons cell with two internal times like the ones
12982 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
12983 the returned times will be formatted strings."
12984 (let* ((tm (decode-time (or time (current-time))))
12985 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
12986 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
12987 (dow (nth 6 tm))
12988 s1 m1 h1 d1 month1 y1 diff ts te fm)
12989 (cond
12990 ((eq key 'today)
12991 (setq h 0 m 0 h1 24 m1 0))
12992 ((eq key 'yesterday)
12993 (setq d (1- d) h 0 m 0 h1 24 m1 0))
12994 ((eq key 'thisweek)
12995 (setq diff (if (= dow 0) 6 (1- dow))
12996 m 0 h 0 d (- d diff) d1 (+ 7 d)))
12997 ((eq key 'lastweek)
12998 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
12999 m 0 h 0 d (- d diff) d1 (+ 7 d)))
13000 ((eq key 'thismonth)
13001 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
13002 ((eq key 'lastmonth)
13003 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
13004 ((eq key 'thisyear)
13005 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
13006 ((eq key 'lastyear)
13007 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
13008 (t (error "No such time block %s" key)))
13009 (setq ts (encode-time s m h d month y)
13010 te (encode-time (or s1 s) (or m1 m) (or h1 h)
13011 (or d1 d) (or month1 month) (or y1 y)))
13012 (setq fm (cdr org-time-stamp-formats))
13013 (if as-strings
13014 (cons (format-time-string fm ts) (format-time-string fm te))
13015 (cons ts te))))
13017 (defun org-dblock-write:clocktable (params)
13018 "Write the standard clocktable."
13019 (catch 'exit
13020 (let* ((hlchars '((1 . "*") (2 . "/")))
13021 (ins (make-marker))
13022 (total-time nil)
13023 (scope (plist-get params :scope))
13024 (tostring (plist-get params :tostring))
13025 (multifile (plist-get params :multifile))
13026 (header (plist-get params :header))
13027 (maxlevel (or (plist-get params :maxlevel) 3))
13028 (step (plist-get params :step))
13029 (emph (plist-get params :emphasize))
13030 (ts (plist-get params :tstart))
13031 (te (plist-get params :tend))
13032 (block (plist-get params :block))
13033 (link (plist-get params :link))
13034 ipos time h m p level hlc hdl
13035 cc beg end pos tbl)
13036 (when step
13037 (org-clocktable-steps params)
13038 (throw 'exit nil))
13039 (when block
13040 (setq cc (org-clock-special-range block nil t)
13041 ts (car cc) te (cdr cc)))
13042 (if ts (setq ts (time-to-seconds
13043 (apply 'encode-time (org-parse-time-string ts)))))
13044 (if te (setq te (time-to-seconds
13045 (apply 'encode-time (org-parse-time-string te)))))
13046 (move-marker ins (point))
13047 (setq ipos (point))
13049 ;; Get the right scope
13050 (setq pos (point))
13051 (save-restriction
13052 (cond
13053 ((not scope))
13054 ((eq scope 'file) (widen))
13055 ((eq scope 'subtree) (org-narrow-to-subtree))
13056 ((eq scope 'tree)
13057 (while (org-up-heading-safe))
13058 (org-narrow-to-subtree))
13059 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
13060 (symbol-name scope)))
13061 (setq level (string-to-number (match-string 1 (symbol-name scope))))
13062 (catch 'exit
13063 (while (org-up-heading-safe)
13064 (looking-at outline-regexp)
13065 (if (<= (org-reduced-level (funcall outline-level)) level)
13066 (throw 'exit nil))))
13067 (org-narrow-to-subtree))
13068 ((or (listp scope) (eq scope 'agenda))
13069 (let* ((files (if (listp scope) scope (org-agenda-files)))
13070 (scope 'agenda)
13071 (p1 (copy-sequence params))
13072 file)
13073 (plist-put p1 :tostring t)
13074 (plist-put p1 :multifile t)
13075 (plist-put p1 :scope 'file)
13076 (org-prepare-agenda-buffers files)
13077 (while (setq file (pop files))
13078 (with-current-buffer (find-buffer-visiting file)
13079 (push (org-clocktable-add-file
13080 file (org-dblock-write:clocktable p1)) tbl)
13081 (setq total-time (+ (or total-time 0)
13082 org-clock-file-total-minutes)))))))
13083 (goto-char pos)
13085 (unless (eq scope 'agenda)
13086 (org-clock-sum ts te)
13087 (goto-char (point-min))
13088 (while (setq p (next-single-property-change (point) :org-clock-minutes))
13089 (goto-char p)
13090 (when (setq time (get-text-property p :org-clock-minutes))
13091 (save-excursion
13092 (beginning-of-line 1)
13093 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
13094 (setq level (org-reduced-level
13095 (- (match-end 1) (match-beginning 1))))
13096 (<= level maxlevel))
13097 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
13098 hdl (if (not link)
13099 (match-string 2)
13100 (org-make-link-string
13101 (format "file:%s::%s"
13102 (buffer-file-name)
13103 (save-match-data
13104 (org-make-org-heading-search-string
13105 (match-string 2))))
13106 (match-string 2)))
13107 h (/ time 60)
13108 m (- time (* 60 h)))
13109 (if (and (not multifile) (= level 1)) (push "|-" tbl))
13110 (push (concat
13111 "| " (int-to-string level) "|" hlc hdl hlc " |"
13112 (make-string (1- level) ?|)
13113 hlc (format "%d:%02d" h m) hlc
13114 " |") tbl))))))
13115 (setq tbl (nreverse tbl))
13116 (if tostring
13117 (if tbl (mapconcat 'identity tbl "\n") nil)
13118 (goto-char ins)
13119 (insert-before-markers
13120 (or header
13121 (concat
13122 "Clock summary at ["
13123 (substring
13124 (format-time-string (cdr org-time-stamp-formats))
13125 1 -1)
13126 "]."
13127 (if block
13128 (format " Considered range is /%s/." block)
13130 "\n\n"))
13131 (if (eq scope 'agenda) "|File" "")
13132 "|L|Headline|Time|\n")
13133 (setq total-time (or total-time org-clock-file-total-minutes)
13134 h (/ total-time 60)
13135 m (- total-time (* 60 h)))
13136 (insert-before-markers
13137 "|-\n|"
13138 (if (eq scope 'agenda) "|" "")
13140 "*Total time*| "
13141 (format "*%d:%02d*" h m)
13142 "|\n|-\n")
13143 (setq tbl (delq nil tbl))
13144 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
13145 (equal (substring (car tbl) 0 2) "|-"))
13146 (pop tbl))
13147 (insert-before-markers (mapconcat
13148 'identity (delq nil tbl)
13149 (if (eq scope 'agenda) "\n|-\n" "\n")))
13150 (backward-delete-char 1)
13151 (goto-char ipos)
13152 (skip-chars-forward "^|")
13153 (org-table-align))))))
13155 (defun org-clocktable-steps (params)
13156 (let* ((p1 (copy-sequence params))
13157 (ts (plist-get p1 :tstart))
13158 (te (plist-get p1 :tend))
13159 (step0 (plist-get p1 :step))
13160 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
13161 (block (plist-get p1 :block))
13163 (when block
13164 (setq cc (org-clock-special-range block nil t)
13165 ts (car cc) te (cdr cc)))
13166 (if ts (setq ts (time-to-seconds
13167 (apply 'encode-time (org-parse-time-string ts)))))
13168 (if te (setq te (time-to-seconds
13169 (apply 'encode-time (org-parse-time-string te)))))
13170 (plist-put p1 :header "")
13171 (plist-put p1 :step nil)
13172 (plist-put p1 :block nil)
13173 (while (< ts te)
13174 (or (bolp) (insert "\n"))
13175 (plist-put p1 :tstart (format-time-string
13176 (car org-time-stamp-formats)
13177 (seconds-to-time ts)))
13178 (plist-put p1 :tend (format-time-string
13179 (car org-time-stamp-formats)
13180 (seconds-to-time (setq ts (+ ts step)))))
13181 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
13182 (plist-get p1 :tstart) "\n")
13183 (org-dblock-write:clocktable p1)
13184 (re-search-forward "#\\+END:")
13185 (end-of-line 0))))
13188 (defun org-clocktable-add-file (file table)
13189 (if table
13190 (let ((lines (org-split-string table "\n"))
13191 (ff (file-name-nondirectory file)))
13192 (mapconcat 'identity
13193 (mapcar (lambda (x)
13194 (if (string-match org-table-dataline-regexp x)
13195 (concat "|" ff x)
13197 lines)
13198 "\n"))))
13200 ;; FIXME: I don't think anybody uses this, ask David
13201 (defun org-collect-clock-time-entries ()
13202 "Return an internal list with clocking information.
13203 This list has one entry for each CLOCK interval.
13204 FIXME: describe the elements."
13205 (interactive)
13206 (let ((re (concat "^[ \t]*" org-clock-string
13207 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
13208 rtn beg end next cont level title total closedp leafp
13209 clockpos titlepos h m donep)
13210 (save-excursion
13211 (org-clock-sum)
13212 (goto-char (point-min))
13213 (while (re-search-forward re nil t)
13214 (setq clockpos (match-beginning 0)
13215 beg (match-string 1) end (match-string 2)
13216 cont (match-end 0))
13217 (setq beg (apply 'encode-time (org-parse-time-string beg))
13218 end (apply 'encode-time (org-parse-time-string end)))
13219 (org-back-to-heading t)
13220 (setq donep (org-entry-is-done-p))
13221 (setq titlepos (point)
13222 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
13223 h (/ total 60) m (- total (* 60 h))
13224 total (cons h m))
13225 (looking-at "\\(\\*+\\) +\\(.*\\)")
13226 (setq level (- (match-end 1) (match-beginning 1))
13227 title (org-match-string-no-properties 2))
13228 (save-excursion (outline-next-heading) (setq next (point)))
13229 (setq closedp (re-search-forward org-closed-time-regexp next t))
13230 (goto-char next)
13231 (setq leafp (and (looking-at "^\\*+ ")
13232 (<= (- (match-end 0) (point)) level)))
13233 (push (list beg end clockpos closedp donep
13234 total title titlepos level leafp)
13235 rtn)
13236 (goto-char cont)))
13237 (nreverse rtn)))
13239 ;;;; Agenda files
13241 (defun org-agenda-files (&optional unrestricted)
13242 "Get the list of agenda files.
13243 Optional UNRESTRICTED means return the full list even if a restriction
13244 is currently in place."
13245 (let ((files
13246 (cond
13247 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13248 ((stringp org-agenda-files) (org-read-agenda-file-list))
13249 ((listp org-agenda-files) org-agenda-files)
13250 (t (error "Invalid value of `org-agenda-files'")))))
13251 (setq files (apply 'append
13252 (mapcar (lambda (f)
13253 (if (file-directory-p f)
13254 (directory-files f t
13255 org-agenda-file-regexp)
13256 (list f)))
13257 files)))
13258 (if org-agenda-skip-unavailable-files
13259 (delq nil
13260 (mapcar (function
13261 (lambda (file)
13262 (and (file-readable-p file) file)))
13263 files))
13264 files))) ; `org-check-agenda-file' will remove them from the list
13266 (defun org-edit-agenda-file-list ()
13267 "Edit the list of agenda files.
13268 Depending on setup, this either uses customize to edit the variable
13269 `org-agenda-files', or it visits the file that is holding the list. In the
13270 latter case, the buffer is set up in a way that saving it automatically kills
13271 the buffer and restores the previous window configuration."
13272 (interactive)
13273 (if (stringp org-agenda-files)
13274 (let ((cw (current-window-configuration)))
13275 (find-file org-agenda-files)
13276 (org-set-local 'org-window-configuration cw)
13277 (org-add-hook 'after-save-hook
13278 (lambda ()
13279 (set-window-configuration
13280 (prog1 org-window-configuration
13281 (kill-buffer (current-buffer))))
13282 (org-install-agenda-files-menu)
13283 (message "New agenda file list installed"))
13284 nil 'local)
13285 (message "%s" (substitute-command-keys
13286 "Edit list and finish with \\[save-buffer]")))
13287 (customize-variable 'org-agenda-files)))
13289 (defun org-store-new-agenda-file-list (list)
13290 "Set new value for the agenda file list and save it correcly."
13291 (if (stringp org-agenda-files)
13292 (let ((f org-agenda-files) b)
13293 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13294 (with-temp-file f
13295 (insert (mapconcat 'identity list "\n") "\n")))
13296 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13297 (setq org-agenda-files list)
13298 (customize-save-variable 'org-agenda-files org-agenda-files))))
13300 (defun org-read-agenda-file-list ()
13301 "Read the list of agenda files from a file."
13302 (when (stringp org-agenda-files)
13303 (with-temp-buffer
13304 (insert-file-contents org-agenda-files)
13305 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13308 ;;;###autoload
13309 (defun org-cycle-agenda-files ()
13310 "Cycle through the files in `org-agenda-files'.
13311 If the current buffer visits an agenda file, find the next one in the list.
13312 If the current buffer does not, find the first agenda file."
13313 (interactive)
13314 (let* ((fs (org-agenda-files t))
13315 (files (append fs (list (car fs))))
13316 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13317 file)
13318 (unless files (error "No agenda files"))
13319 (catch 'exit
13320 (while (setq file (pop files))
13321 (if (equal (file-truename file) tcf)
13322 (when (car files)
13323 (find-file (car files))
13324 (throw 'exit t))))
13325 (find-file (car fs)))
13326 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13328 (defun org-agenda-file-to-front (&optional to-end)
13329 "Move/add the current file to the top of the agenda file list.
13330 If the file is not present in the list, it is added to the front. If it is
13331 present, it is moved there. With optional argument TO-END, add/move to the
13332 end of the list."
13333 (interactive "P")
13334 (let ((org-agenda-skip-unavailable-files nil)
13335 (file-alist (mapcar (lambda (x)
13336 (cons (file-truename x) x))
13337 (org-agenda-files t)))
13338 (ctf (file-truename buffer-file-name))
13339 x had)
13340 (setq x (assoc ctf file-alist) had x)
13342 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13343 (if to-end
13344 (setq file-alist (append (delq x file-alist) (list x)))
13345 (setq file-alist (cons x (delq x file-alist))))
13346 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13347 (org-install-agenda-files-menu)
13348 (message "File %s to %s of agenda file list"
13349 (if had "moved" "added") (if to-end "end" "front"))))
13351 (defun org-remove-file (&optional file)
13352 "Remove current file from the list of files in variable `org-agenda-files'.
13353 These are the files which are being checked for agenda entries.
13354 Optional argument FILE means, use this file instead of the current."
13355 (interactive)
13356 (let* ((org-agenda-skip-unavailable-files nil)
13357 (file (or file buffer-file-name))
13358 (true-file (file-truename file))
13359 (afile (abbreviate-file-name file))
13360 (files (delq nil (mapcar
13361 (lambda (x)
13362 (if (equal true-file
13363 (file-truename x))
13364 nil x))
13365 (org-agenda-files t)))))
13366 (if (not (= (length files) (length (org-agenda-files t))))
13367 (progn
13368 (org-store-new-agenda-file-list files)
13369 (org-install-agenda-files-menu)
13370 (message "Removed file: %s" afile))
13371 (message "File was not in list: %s (not removed)" afile))))
13373 (defun org-file-menu-entry (file)
13374 (vector file (list 'find-file file) t))
13376 (defun org-check-agenda-file (file)
13377 "Make sure FILE exists. If not, ask user what to do."
13378 (when (not (file-exists-p file))
13379 (message "non-existent file %s. [R]emove from list or [A]bort?"
13380 (abbreviate-file-name file))
13381 (let ((r (downcase (read-char-exclusive))))
13382 (cond
13383 ((equal r ?r)
13384 (org-remove-file file)
13385 (throw 'nextfile t))
13386 (t (error "Abort"))))))
13388 (defun org-get-agenda-file-buffer (file)
13389 "Get a buffer visiting FILE. If the buffer needs to be created, add
13390 it to the list of buffers which might be released later."
13391 (let ((buf (org-find-base-buffer-visiting file)))
13392 (if buf
13393 buf ; just return it
13394 ;; Make a new buffer and remember it
13395 (setq buf (find-file-noselect file))
13396 (if buf (push buf org-agenda-new-buffers))
13397 buf)))
13399 (defun org-release-buffers (blist)
13400 "Release all buffers in list, asking the user for confirmation when needed.
13401 When a buffer is unmodified, it is just killed. When modified, it is saved
13402 \(if the user agrees) and then killed."
13403 (let (buf file)
13404 (while (setq buf (pop blist))
13405 (setq file (buffer-file-name buf))
13406 (when (and (buffer-modified-p buf)
13407 file
13408 (y-or-n-p (format "Save file %s? " file)))
13409 (with-current-buffer buf (save-buffer)))
13410 (kill-buffer buf))))
13412 (defun org-prepare-agenda-buffers (files)
13413 "Create buffers for all agenda files, protect archived trees and comments."
13414 (interactive)
13415 (let ((pa '(:org-archived t))
13416 (pc '(:org-comment t))
13417 (pall '(:org-archived t :org-comment t))
13418 (inhibit-read-only t)
13419 (rea (concat ":" org-archive-tag ":"))
13420 bmp file re)
13421 (save-excursion
13422 (save-restriction
13423 (while (setq file (pop files))
13424 (if (bufferp file)
13425 (set-buffer file)
13426 (org-check-agenda-file file)
13427 (set-buffer (org-get-agenda-file-buffer file)))
13428 (widen)
13429 (setq bmp (buffer-modified-p))
13430 (org-refresh-category-properties)
13431 (setq org-todo-keywords-for-agenda
13432 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13433 (setq org-done-keywords-for-agenda
13434 (append org-done-keywords-for-agenda org-done-keywords))
13435 (save-excursion
13436 (remove-text-properties (point-min) (point-max) pall)
13437 (when org-agenda-skip-archived-trees
13438 (goto-char (point-min))
13439 (while (re-search-forward rea nil t)
13440 (if (org-on-heading-p t)
13441 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13442 (goto-char (point-min))
13443 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13444 (while (re-search-forward re nil t)
13445 (add-text-properties
13446 (match-beginning 0) (org-end-of-subtree t) pc)))
13447 (set-buffer-modified-p bmp))))))
13449 ;;;; Embedded LaTeX
13451 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13452 "Keymap for the minor `org-cdlatex-mode'.")
13454 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13455 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13456 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13457 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13458 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13460 (defvar org-cdlatex-texmathp-advice-is-done nil
13461 "Flag remembering if we have applied the advice to texmathp already.")
13463 (define-minor-mode org-cdlatex-mode
13464 "Toggle the minor `org-cdlatex-mode'.
13465 This mode supports entering LaTeX environment and math in LaTeX fragments
13466 in Org-mode.
13467 \\{org-cdlatex-mode-map}"
13468 nil " OCDL" nil
13469 (when org-cdlatex-mode (require 'cdlatex))
13470 (unless org-cdlatex-texmathp-advice-is-done
13471 (setq org-cdlatex-texmathp-advice-is-done t)
13472 (defadvice texmathp (around org-math-always-on activate)
13473 "Always return t in org-mode buffers.
13474 This is because we want to insert math symbols without dollars even outside
13475 the LaTeX math segments. If Orgmode thinks that point is actually inside
13476 en embedded LaTeX fragement, let texmathp do its job.
13477 \\[org-cdlatex-mode-map]"
13478 (interactive)
13479 (let (p)
13480 (cond
13481 ((not (org-mode-p)) ad-do-it)
13482 ((eq this-command 'cdlatex-math-symbol)
13483 (setq ad-return-value t
13484 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13486 (let ((p (org-inside-LaTeX-fragment-p)))
13487 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13488 (setq ad-return-value t
13489 texmathp-why '("Org-mode embedded math" . 0))
13490 (if p ad-do-it)))))))))
13492 (defun turn-on-org-cdlatex ()
13493 "Unconditionally turn on `org-cdlatex-mode'."
13494 (org-cdlatex-mode 1))
13496 (defun org-inside-LaTeX-fragment-p ()
13497 "Test if point is inside a LaTeX fragment.
13498 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13499 sequence appearing also before point.
13500 Even though the matchers for math are configurable, this function assumes
13501 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13502 delimiters are skipped when they have been removed by customization.
13503 The return value is nil, or a cons cell with the delimiter and
13504 and the position of this delimiter.
13506 This function does a reasonably good job, but can locally be fooled by
13507 for example currency specifications. For example it will assume being in
13508 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13509 fragments that are properly closed, but during editing, we have to live
13510 with the uncertainty caused by missing closing delimiters. This function
13511 looks only before point, not after."
13512 (catch 'exit
13513 (let ((pos (point))
13514 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13515 (lim (progn
13516 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13517 (point)))
13518 dd-on str (start 0) m re)
13519 (goto-char pos)
13520 (when dodollar
13521 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13522 re (nth 1 (assoc "$" org-latex-regexps)))
13523 (while (string-match re str start)
13524 (cond
13525 ((= (match-end 0) (length str))
13526 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13527 ((= (match-end 0) (- (length str) 5))
13528 (throw 'exit nil))
13529 (t (setq start (match-end 0))))))
13530 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13531 (goto-char pos)
13532 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13533 (and (match-beginning 2) (throw 'exit nil))
13534 ;; count $$
13535 (while (re-search-backward "\\$\\$" lim t)
13536 (setq dd-on (not dd-on)))
13537 (goto-char pos)
13538 (if dd-on (cons "$$" m))))))
13541 (defun org-try-cdlatex-tab ()
13542 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13543 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13544 - inside a LaTeX fragment, or
13545 - after the first word in a line, where an abbreviation expansion could
13546 insert a LaTeX environment."
13547 (when org-cdlatex-mode
13548 (cond
13549 ((save-excursion
13550 (skip-chars-backward "a-zA-Z0-9*")
13551 (skip-chars-backward " \t")
13552 (bolp))
13553 (cdlatex-tab) t)
13554 ((org-inside-LaTeX-fragment-p)
13555 (cdlatex-tab) t)
13556 (t nil))))
13558 (defun org-cdlatex-underscore-caret (&optional arg)
13559 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13560 Revert to the normal definition outside of these fragments."
13561 (interactive "P")
13562 (if (org-inside-LaTeX-fragment-p)
13563 (call-interactively 'cdlatex-sub-superscript)
13564 (let (org-cdlatex-mode)
13565 (call-interactively (key-binding (vector last-input-event))))))
13567 (defun org-cdlatex-math-modify (&optional arg)
13568 "Execute `cdlatex-math-modify' in LaTeX fragments.
13569 Revert to the normal definition outside of these fragments."
13570 (interactive "P")
13571 (if (org-inside-LaTeX-fragment-p)
13572 (call-interactively 'cdlatex-math-modify)
13573 (let (org-cdlatex-mode)
13574 (call-interactively (key-binding (vector last-input-event))))))
13576 (defvar org-latex-fragment-image-overlays nil
13577 "List of overlays carrying the images of latex fragments.")
13578 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13580 (defun org-remove-latex-fragment-image-overlays ()
13581 "Remove all overlays with LaTeX fragment images in current buffer."
13582 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13583 (setq org-latex-fragment-image-overlays nil))
13585 (defun org-preview-latex-fragment (&optional subtree)
13586 "Preview the LaTeX fragment at point, or all locally or globally.
13587 If the cursor is in a LaTeX fragment, create the image and overlay
13588 it over the source code. If there is no fragment at point, display
13589 all fragments in the current text, from one headline to the next. With
13590 prefix SUBTREE, display all fragments in the current subtree. With a
13591 double prefix `C-u C-u', or when the cursor is before the first headline,
13592 display all fragments in the buffer.
13593 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13594 (interactive "P")
13595 (org-remove-latex-fragment-image-overlays)
13596 (save-excursion
13597 (save-restriction
13598 (let (beg end at msg)
13599 (cond
13600 ((or (equal subtree '(16))
13601 (not (save-excursion
13602 (re-search-backward (concat "^" outline-regexp) nil t))))
13603 (setq beg (point-min) end (point-max)
13604 msg "Creating images for buffer...%s"))
13605 ((equal subtree '(4))
13606 (org-back-to-heading)
13607 (setq beg (point) end (org-end-of-subtree t)
13608 msg "Creating images for subtree...%s"))
13610 (if (setq at (org-inside-LaTeX-fragment-p))
13611 (goto-char (max (point-min) (- (cdr at) 2)))
13612 (org-back-to-heading))
13613 (setq beg (point) end (progn (outline-next-heading) (point))
13614 msg (if at "Creating image...%s"
13615 "Creating images for entry...%s"))))
13616 (message msg "")
13617 (narrow-to-region beg end)
13618 (goto-char beg)
13619 (org-format-latex
13620 (concat "ltxpng/" (file-name-sans-extension
13621 (file-name-nondirectory
13622 buffer-file-name)))
13623 default-directory 'overlays msg at 'forbuffer)
13624 (message msg "done. Use `C-c C-c' to remove images.")))))
13626 (defvar org-latex-regexps
13627 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13628 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13629 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13630 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
13631 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13632 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13633 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13634 "Regular expressions for matching embedded LaTeX.")
13636 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13637 "Replace LaTeX fragments with links to an image, and produce images."
13638 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13639 (let* ((prefixnodir (file-name-nondirectory prefix))
13640 (absprefix (expand-file-name prefix dir))
13641 (todir (file-name-directory absprefix))
13642 (opt org-format-latex-options)
13643 (matchers (plist-get opt :matchers))
13644 (re-list org-latex-regexps)
13645 (cnt 0) txt link beg end re e checkdir
13646 m n block linkfile movefile ov)
13647 ;; Check if there are old images files with this prefix, and remove them
13648 (when (file-directory-p todir)
13649 (mapc 'delete-file
13650 (directory-files
13651 todir 'full
13652 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13653 ;; Check the different regular expressions
13654 (while (setq e (pop re-list))
13655 (setq m (car e) re (nth 1 e) n (nth 2 e)
13656 block (if (nth 3 e) "\n\n" ""))
13657 (when (member m matchers)
13658 (goto-char (point-min))
13659 (while (re-search-forward re nil t)
13660 (when (or (not at) (equal (cdr at) (match-beginning n)))
13661 (setq txt (match-string n)
13662 beg (match-beginning n) end (match-end n)
13663 cnt (1+ cnt)
13664 linkfile (format "%s_%04d.png" prefix cnt)
13665 movefile (format "%s_%04d.png" absprefix cnt)
13666 link (concat block "[[file:" linkfile "]]" block))
13667 (if msg (message msg cnt))
13668 (goto-char beg)
13669 (unless checkdir ; make sure the directory exists
13670 (setq checkdir t)
13671 (or (file-directory-p todir) (make-directory todir)))
13672 (org-create-formula-image
13673 txt movefile opt forbuffer)
13674 (if overlays
13675 (progn
13676 (setq ov (org-make-overlay beg end))
13677 (if (featurep 'xemacs)
13678 (progn
13679 (org-overlay-put ov 'invisible t)
13680 (org-overlay-put
13681 ov 'end-glyph
13682 (make-glyph (vector 'png :file movefile))))
13683 (org-overlay-put
13684 ov 'display
13685 (list 'image :type 'png :file movefile :ascent 'center)))
13686 (push ov org-latex-fragment-image-overlays)
13687 (goto-char end))
13688 (delete-region beg end)
13689 (insert link))))))))
13691 ;; This function borrows from Ganesh Swami's latex2png.el
13692 (defun org-create-formula-image (string tofile options buffer)
13693 (let* ((tmpdir (if (featurep 'xemacs)
13694 (temp-directory)
13695 temporary-file-directory))
13696 (texfilebase (make-temp-name
13697 (expand-file-name "orgtex" tmpdir)))
13698 (texfile (concat texfilebase ".tex"))
13699 (dvifile (concat texfilebase ".dvi"))
13700 (pngfile (concat texfilebase ".png"))
13701 (fnh (face-attribute 'default :height nil))
13702 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13703 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13704 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13705 "Black"))
13706 (bg (or (plist-get options (if buffer :background :html-background))
13707 "Transparent")))
13708 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13709 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13710 (with-temp-file texfile
13711 (insert org-format-latex-header
13712 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13713 (let ((dir default-directory))
13714 (condition-case nil
13715 (progn
13716 (cd tmpdir)
13717 (call-process "latex" nil nil nil texfile))
13718 (error nil))
13719 (cd dir))
13720 (if (not (file-exists-p dvifile))
13721 (progn (message "Failed to create dvi file from %s" texfile) nil)
13722 (call-process "dvipng" nil nil nil
13723 "-E" "-fg" fg "-bg" bg
13724 "-D" dpi
13725 ;;"-x" scale "-y" scale
13726 "-T" "tight"
13727 "-o" pngfile
13728 dvifile)
13729 (if (not (file-exists-p pngfile))
13730 (progn (message "Failed to create png file from %s" texfile) nil)
13731 ;; Use the requested file name and clean up
13732 (copy-file pngfile tofile 'replace)
13733 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13734 (delete-file (concat texfilebase e)))
13735 pngfile))))
13737 (defun org-dvipng-color (attr)
13738 "Return an rgb color specification for dvipng."
13739 (apply 'format "rgb %s %s %s"
13740 (mapcar 'org-normalize-color
13741 (color-values (face-attribute 'default attr nil)))))
13743 (defun org-normalize-color (value)
13744 "Return string to be used as color value for an RGB component."
13745 (format "%g" (/ value 65535.0)))
13748 ;;;; Key bindings
13750 ;; Make `C-c C-x' a prefix key
13751 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13753 ;; TAB key with modifiers
13754 (org-defkey org-mode-map "\C-i" 'org-cycle)
13755 (org-defkey org-mode-map [(tab)] 'org-cycle)
13756 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13757 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13758 (org-defkey org-mode-map "\M-\t" 'org-complete)
13759 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13760 ;; The following line is necessary under Suse GNU/Linux
13761 (unless (featurep 'xemacs)
13762 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13763 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13764 (define-key org-mode-map [backtab] 'org-shifttab)
13766 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13767 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13768 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13770 ;; Cursor keys with modifiers
13771 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13772 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13773 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13774 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13776 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13777 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13778 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13779 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13781 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13782 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13783 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13784 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13786 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13787 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13789 ;;; Extra keys for tty access.
13790 ;; We only set them when really needed because otherwise the
13791 ;; menus don't show the simple keys
13793 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13794 (not window-system))
13795 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13796 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13797 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13798 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13799 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13800 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13801 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13802 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13803 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13804 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13805 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13806 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13807 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13808 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13809 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13810 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13811 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13812 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13813 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13814 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13815 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13816 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13818 ;; All the other keys
13820 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13821 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13822 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
13823 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13824 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13825 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13826 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13827 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13828 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13829 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13830 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13831 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13832 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13833 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13834 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13835 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13836 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13837 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13838 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
13839 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13840 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13841 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13842 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13843 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13844 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13845 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13846 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13847 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13848 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13849 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13850 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13851 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13852 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13853 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13854 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13855 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13856 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13857 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13858 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13859 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13860 (org-defkey org-mode-map "\C-c^" 'org-sort)
13861 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13862 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13863 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13864 (org-defkey org-mode-map "\C-m" 'org-return)
13865 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13866 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13867 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13868 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13869 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13870 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
13871 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13872 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13873 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13874 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13875 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
13876 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13877 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13878 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13879 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13880 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13882 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
13883 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13884 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13885 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13887 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13888 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13889 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13890 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13891 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13892 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13893 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13894 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13895 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13896 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13897 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13898 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
13900 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13902 (when (featurep 'xemacs)
13903 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13905 (defvar org-table-auto-blank-field) ; defined in org-table.el
13906 (defun org-self-insert-command (N)
13907 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13908 If the cursor is in a table looking at whitespace, the whitespace is
13909 overwritten, and the table is not marked as requiring realignment."
13910 (interactive "p")
13911 (if (and (org-table-p)
13912 (progn
13913 ;; check if we blank the field, and if that triggers align
13914 (and (featurep 'org-table) org-table-auto-blank-field
13915 (member last-command
13916 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13917 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13918 ;; got extra space, this field does not determine column width
13919 (let (org-table-may-need-update) (org-table-blank-field))
13920 ;; no extra space, this field may determine column width
13921 (org-table-blank-field)))
13923 (eq N 1)
13924 (looking-at "[^|\n]* |"))
13925 (let (org-table-may-need-update)
13926 (goto-char (1- (match-end 0)))
13927 (delete-backward-char 1)
13928 (goto-char (match-beginning 0))
13929 (self-insert-command N))
13930 (setq org-table-may-need-update t)
13931 (self-insert-command N)
13932 (org-fix-tags-on-the-fly)))
13934 (defun org-fix-tags-on-the-fly ()
13935 (when (and (equal (char-after (point-at-bol)) ?*)
13936 (org-on-heading-p))
13937 (org-align-tags-here org-tags-column)))
13939 (defun org-delete-backward-char (N)
13940 "Like `delete-backward-char', insert whitespace at field end in tables.
13941 When deleting backwards, in tables this function will insert whitespace in
13942 front of the next \"|\" separator, to keep the table aligned. The table will
13943 still be marked for re-alignment if the field did fill the entire column,
13944 because, in this case the deletion might narrow the column."
13945 (interactive "p")
13946 (if (and (org-table-p)
13947 (eq N 1)
13948 (string-match "|" (buffer-substring (point-at-bol) (point)))
13949 (looking-at ".*?|"))
13950 (let ((pos (point))
13951 (noalign (looking-at "[^|\n\r]* |"))
13952 (c org-table-may-need-update))
13953 (backward-delete-char N)
13954 (skip-chars-forward "^|")
13955 (insert " ")
13956 (goto-char (1- pos))
13957 ;; noalign: if there were two spaces at the end, this field
13958 ;; does not determine the width of the column.
13959 (if noalign (setq org-table-may-need-update c)))
13960 (backward-delete-char N)
13961 (org-fix-tags-on-the-fly)))
13963 (defun org-delete-char (N)
13964 "Like `delete-char', but insert whitespace at field end in tables.
13965 When deleting characters, in tables this function will insert whitespace in
13966 front of the next \"|\" separator, to keep the table aligned. The table will
13967 still be marked for re-alignment if the field did fill the entire column,
13968 because, in this case the deletion might narrow the column."
13969 (interactive "p")
13970 (if (and (org-table-p)
13971 (not (bolp))
13972 (not (= (char-after) ?|))
13973 (eq N 1))
13974 (if (looking-at ".*?|")
13975 (let ((pos (point))
13976 (noalign (looking-at "[^|\n\r]* |"))
13977 (c org-table-may-need-update))
13978 (replace-match (concat
13979 (substring (match-string 0) 1 -1)
13980 " |"))
13981 (goto-char pos)
13982 ;; noalign: if there were two spaces at the end, this field
13983 ;; does not determine the width of the column.
13984 (if noalign (setq org-table-may-need-update c)))
13985 (delete-char N))
13986 (delete-char N)
13987 (org-fix-tags-on-the-fly)))
13989 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13990 (put 'org-self-insert-command 'delete-selection t)
13991 (put 'orgtbl-self-insert-command 'delete-selection t)
13992 (put 'org-delete-char 'delete-selection 'supersede)
13993 (put 'org-delete-backward-char 'delete-selection 'supersede)
13995 ;; Make `flyspell-mode' delay after some commands
13996 (put 'org-self-insert-command 'flyspell-delayed t)
13997 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13998 (put 'org-delete-char 'flyspell-delayed t)
13999 (put 'org-delete-backward-char 'flyspell-delayed t)
14001 ;; Make pabbrev-mode expand after org-mode commands
14002 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14003 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
14005 ;; How to do this: Measure non-white length of current string
14006 ;; If equal to column width, we should realign.
14008 (defun org-remap (map &rest commands)
14009 "In MAP, remap the functions given in COMMANDS.
14010 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14011 (let (new old)
14012 (while commands
14013 (setq old (pop commands) new (pop commands))
14014 (if (fboundp 'command-remapping)
14015 (org-defkey map (vector 'remap old) new)
14016 (substitute-key-definition old new map global-map)))))
14018 (when (eq org-enable-table-editor 'optimized)
14019 ;; If the user wants maximum table support, we need to hijack
14020 ;; some standard editing functions
14021 (org-remap org-mode-map
14022 'self-insert-command 'org-self-insert-command
14023 'delete-char 'org-delete-char
14024 'delete-backward-char 'org-delete-backward-char)
14025 (org-defkey org-mode-map "|" 'org-force-self-insert))
14027 (defun org-shiftcursor-error ()
14028 "Throw an error because Shift-Cursor command was applied in wrong context."
14029 (error "This command is active in special context like tables, headlines or timestamps"))
14031 (defun org-shifttab (&optional arg)
14032 "Global visibility cycling or move to previous table field.
14033 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14034 on context.
14035 See the individual commands for more information."
14036 (interactive "P")
14037 (cond
14038 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14039 (arg (message "Content view to level: ")
14040 (org-content (prefix-numeric-value arg))
14041 (setq org-cycle-global-status 'overview))
14042 (t (call-interactively 'org-global-cycle))))
14044 (defun org-shiftmetaleft ()
14045 "Promote subtree or delete table column.
14046 Calls `org-promote-subtree', `org-outdent-item',
14047 or `org-table-delete-column', depending on context.
14048 See the individual commands for more information."
14049 (interactive)
14050 (cond
14051 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14052 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14053 ((org-at-item-p) (call-interactively 'org-outdent-item))
14054 (t (org-shiftcursor-error))))
14056 (defun org-shiftmetaright ()
14057 "Demote subtree or insert table column.
14058 Calls `org-demote-subtree', `org-indent-item',
14059 or `org-table-insert-column', depending on context.
14060 See the individual commands for more information."
14061 (interactive)
14062 (cond
14063 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14064 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14065 ((org-at-item-p) (call-interactively 'org-indent-item))
14066 (t (org-shiftcursor-error))))
14068 (defun org-shiftmetaup (&optional arg)
14069 "Move subtree up or kill table row.
14070 Calls `org-move-subtree-up' or `org-table-kill-row' or
14071 `org-move-item-up' depending on context. See the individual commands
14072 for more information."
14073 (interactive "P")
14074 (cond
14075 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14076 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14077 ((org-at-item-p) (call-interactively 'org-move-item-up))
14078 (t (org-shiftcursor-error))))
14079 (defun org-shiftmetadown (&optional arg)
14080 "Move subtree down or insert table row.
14081 Calls `org-move-subtree-down' or `org-table-insert-row' or
14082 `org-move-item-down', depending on context. See the individual
14083 commands for more information."
14084 (interactive "P")
14085 (cond
14086 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14087 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14088 ((org-at-item-p) (call-interactively 'org-move-item-down))
14089 (t (org-shiftcursor-error))))
14091 (defun org-metaleft (&optional arg)
14092 "Promote heading or move table column to left.
14093 Calls `org-do-promote' or `org-table-move-column', depending on context.
14094 With no specific context, calls the Emacs default `backward-word'.
14095 See the individual commands for more information."
14096 (interactive "P")
14097 (cond
14098 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14099 ((or (org-on-heading-p) (org-region-active-p))
14100 (call-interactively 'org-do-promote))
14101 ((org-at-item-p) (call-interactively 'org-outdent-item))
14102 (t (call-interactively 'backward-word))))
14104 (defun org-metaright (&optional arg)
14105 "Demote subtree or move table column to right.
14106 Calls `org-do-demote' or `org-table-move-column', depending on context.
14107 With no specific context, calls the Emacs default `forward-word'.
14108 See the individual commands for more information."
14109 (interactive "P")
14110 (cond
14111 ((org-at-table-p) (call-interactively 'org-table-move-column))
14112 ((or (org-on-heading-p) (org-region-active-p))
14113 (call-interactively 'org-do-demote))
14114 ((org-at-item-p) (call-interactively 'org-indent-item))
14115 (t (call-interactively 'forward-word))))
14117 (defun org-metaup (&optional arg)
14118 "Move subtree up or move table row up.
14119 Calls `org-move-subtree-up' or `org-table-move-row' or
14120 `org-move-item-up', depending on context. See the individual commands
14121 for more information."
14122 (interactive "P")
14123 (cond
14124 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14125 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14126 ((org-at-item-p) (call-interactively 'org-move-item-up))
14127 (t (transpose-lines 1) (beginning-of-line -1))))
14129 (defun org-metadown (&optional arg)
14130 "Move subtree down or move table row down.
14131 Calls `org-move-subtree-down' or `org-table-move-row' or
14132 `org-move-item-down', depending on context. See the individual
14133 commands for more information."
14134 (interactive "P")
14135 (cond
14136 ((org-at-table-p) (call-interactively 'org-table-move-row))
14137 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14138 ((org-at-item-p) (call-interactively 'org-move-item-down))
14139 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14141 (defun org-shiftup (&optional arg)
14142 "Increase item in timestamp or increase priority of current headline.
14143 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14144 depending on context. See the individual commands for more information."
14145 (interactive "P")
14146 (cond
14147 ((org-at-timestamp-p t)
14148 (call-interactively (if org-edit-timestamp-down-means-later
14149 'org-timestamp-down 'org-timestamp-up)))
14150 ((org-on-heading-p) (call-interactively 'org-priority-up))
14151 ((org-at-item-p) (call-interactively 'org-previous-item))
14152 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
14154 (defun org-shiftdown (&optional arg)
14155 "Decrease item in timestamp or decrease priority of current headline.
14156 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14157 depending on context. See the individual commands for more information."
14158 (interactive "P")
14159 (cond
14160 ((org-at-timestamp-p t)
14161 (call-interactively (if org-edit-timestamp-down-means-later
14162 'org-timestamp-up 'org-timestamp-down)))
14163 ((org-on-heading-p) (call-interactively 'org-priority-down))
14164 (t (call-interactively 'org-next-item))))
14166 (defun org-shiftright ()
14167 "Next TODO keyword or timestamp one day later, depending on context."
14168 (interactive)
14169 (cond
14170 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14171 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
14172 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
14173 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
14174 (t (org-shiftcursor-error))))
14176 (defun org-shiftleft ()
14177 "Previous TODO keyword or timestamp one day earlier, depending on context."
14178 (interactive)
14179 (cond
14180 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14181 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
14182 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
14183 ((org-at-property-p)
14184 (call-interactively 'org-property-previous-allowed-value))
14185 (t (org-shiftcursor-error))))
14187 (defun org-shiftcontrolright ()
14188 "Switch to next TODO set."
14189 (interactive)
14190 (cond
14191 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
14192 (t (org-shiftcursor-error))))
14194 (defun org-shiftcontrolleft ()
14195 "Switch to previous TODO set."
14196 (interactive)
14197 (cond
14198 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
14199 (t (org-shiftcursor-error))))
14201 (defun org-ctrl-c-ret ()
14202 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14203 (interactive)
14204 (cond
14205 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14206 (t (call-interactively 'org-insert-heading))))
14208 (defun org-copy-special ()
14209 "Copy region in table or copy current subtree.
14210 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14211 See the individual commands for more information."
14212 (interactive)
14213 (call-interactively
14214 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14216 (defun org-cut-special ()
14217 "Cut region in table or cut current subtree.
14218 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14219 See the individual commands for more information."
14220 (interactive)
14221 (call-interactively
14222 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14224 (defun org-paste-special (arg)
14225 "Paste rectangular region into table, or past subtree relative to level.
14226 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14227 See the individual commands for more information."
14228 (interactive "P")
14229 (if (org-at-table-p)
14230 (org-table-paste-rectangle)
14231 (org-paste-subtree arg)))
14233 (defun org-ctrl-c-ctrl-c (&optional arg)
14234 "Set tags in headline, or update according to changed information at point.
14236 This command does many different things, depending on context:
14238 - If the cursor is in a headline, prompt for tags and insert them
14239 into the current line, aligned to `org-tags-column'. When called
14240 with prefix arg, realign all tags in the current buffer.
14242 - If the cursor is in one of the special #+KEYWORD lines, this
14243 triggers scanning the buffer for these lines and updating the
14244 information.
14246 - If the cursor is inside a table, realign the table. This command
14247 works even if the automatic table editor has been turned off.
14249 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14250 the entire table.
14252 - If the cursor is a the beginning of a dynamic block, update it.
14254 - If the cursor is inside a table created by the table.el package,
14255 activate that table.
14257 - If the current buffer is a remember buffer, close note and file it.
14258 with a prefix argument, file it without further interaction to the default
14259 location.
14261 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14262 links in this buffer.
14264 - If the cursor is on a numbered item in a plain list, renumber the
14265 ordered list.
14267 - If the cursor is on a checkbox, toggle it."
14268 (interactive "P")
14269 (let ((org-enable-table-editor t))
14270 (cond
14271 ((or org-clock-overlays
14272 org-occur-highlights
14273 org-latex-fragment-image-overlays)
14274 (org-remove-clock-overlays)
14275 (org-remove-occur-highlights)
14276 (org-remove-latex-fragment-image-overlays)
14277 (message "Temporary highlights/overlays removed from current buffer"))
14278 ((and (local-variable-p 'org-finish-function (current-buffer))
14279 (fboundp org-finish-function))
14280 (funcall org-finish-function))
14281 ((org-at-property-p)
14282 (call-interactively 'org-property-action))
14283 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14284 ((org-on-heading-p) (call-interactively 'org-set-tags))
14285 ((org-at-table.el-p)
14286 (require 'table)
14287 (beginning-of-line 1)
14288 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14289 (call-interactively 'table-recognize-table))
14290 ((org-at-table-p)
14291 (org-table-maybe-eval-formula)
14292 (if arg
14293 (call-interactively 'org-table-recalculate)
14294 (org-table-maybe-recalculate-line))
14295 (call-interactively 'org-table-align))
14296 ((org-at-item-checkbox-p)
14297 (call-interactively 'org-toggle-checkbox))
14298 ((org-at-item-p)
14299 (call-interactively 'org-maybe-renumber-ordered-list))
14300 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14301 ;; Dynamic block
14302 (beginning-of-line 1)
14303 (org-update-dblock))
14304 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14305 (cond
14306 ((equal (match-string 1) "TBLFM")
14307 ;; Recalculate the table before this line
14308 (save-excursion
14309 (beginning-of-line 1)
14310 (skip-chars-backward " \r\n\t")
14311 (if (org-at-table-p)
14312 (org-call-with-arg 'org-table-recalculate t))))
14314 (call-interactively 'org-mode-restart))))
14315 (t (error "C-c C-c can do nothing useful at this location.")))))
14317 (defun org-mode-restart ()
14318 "Restart Org-mode, to scan again for special lines.
14319 Also updates the keyword regular expressions."
14320 (interactive)
14321 (let ((org-inhibit-startup t)) (org-mode))
14322 (message "Org-mode restarted to refresh keyword and special line setup"))
14324 (defun org-kill-note-or-show-branches ()
14325 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14326 (interactive)
14327 (if (not org-finish-function)
14328 (call-interactively 'show-branches)
14329 (let ((org-note-abort t))
14330 (funcall org-finish-function))))
14332 (defun org-return (&optional indent)
14333 "Goto next table row or insert a newline.
14334 Calls `org-table-next-row' or `newline', depending on context.
14335 See the individual commands for more information."
14336 (interactive)
14337 (cond
14338 ((bobp) (if indent (newline-and-indent) (newline)))
14339 ((and (org-at-heading-p)
14340 (looking-at
14341 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14342 (org-show-entry)
14343 (end-of-line 1)
14344 (newline))
14345 ((org-at-table-p)
14346 (org-table-justify-field-maybe)
14347 (call-interactively 'org-table-next-row))
14348 (t (if indent (newline-and-indent) (newline)))))
14350 (defun org-return-indent ()
14351 "Goto next table row or insert a newline and indent.
14352 Calls `org-table-next-row' or `newline-and-indent', depending on
14353 context. See the individual commands for more information."
14354 (interactive)
14355 (org-return t))
14357 (defun org-ctrl-c-star ()
14358 "Compute table, or change heading status of lines.
14359 Calls `org-table-recalculate' or `org-toggle-region-headlines',
14360 depending on context. This will also turn a plain list item or a normal
14361 line into a subheading."
14362 (interactive)
14363 (cond
14364 ((org-at-table-p)
14365 (call-interactively 'org-table-recalculate))
14366 ((org-region-active-p)
14367 ;; Convert all lines in region to list items
14368 (call-interactively 'org-toggle-region-headings))
14369 ((org-on-heading-p)
14370 (org-toggle-region-headings (point-at-bol)
14371 (min (1+ (point-at-eol)) (point-max))))
14372 ((org-at-item-p)
14373 ;; Convert to heading
14374 (let ((level (save-match-data
14375 (save-excursion
14376 (condition-case nil
14377 (progn
14378 (org-back-to-heading t)
14379 (funcall outline-level))
14380 (error 0))))))
14381 (replace-match
14382 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
14383 (t (org-toggle-region-headings (point-at-bol)
14384 (min (1+ (point-at-eol)) (point-max))))))
14386 (defun org-ctrl-c-minus ()
14387 "Insert separator line in table or modify bullet status of line.
14388 Also turns a plain line or a region of lines into list items.
14389 Calls `org-table-insert-hline', `org-toggle-region-items', or
14390 `org-cycle-list-bullet', depending on context."
14391 (interactive)
14392 (cond
14393 ((org-at-table-p)
14394 (call-interactively 'org-table-insert-hline))
14395 ((org-on-heading-p)
14396 ;; Convert to item
14397 (save-excursion
14398 (beginning-of-line 1)
14399 (if (looking-at "\\*+ ")
14400 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
14401 ((org-region-active-p)
14402 ;; Convert all lines in region to list items
14403 (call-interactively 'org-toggle-region-items))
14404 ((org-in-item-p)
14405 (call-interactively 'org-cycle-list-bullet))
14406 (t (org-toggle-region-items (point-at-bol)
14407 (min (1+ (point-at-eol)) (point-max))))))
14409 (defun org-toggle-region-items (beg end)
14410 "Convert all lines in region to list items.
14411 If the first line is already an item, convert all list items in the region
14412 to normal lines."
14413 (interactive "r")
14414 (let (l2 l)
14415 (save-excursion
14416 (goto-char end)
14417 (setq l2 (org-current-line))
14418 (goto-char beg)
14419 (beginning-of-line 1)
14420 (setq l (1- (org-current-line)))
14421 (if (org-at-item-p)
14422 ;; We already have items, de-itemize
14423 (while (< (setq l (1+ l)) l2)
14424 (when (org-at-item-p)
14425 (goto-char (match-beginning 2))
14426 (delete-region (match-beginning 2) (match-end 2))
14427 (and (looking-at "[ \t]+") (replace-match "")))
14428 (beginning-of-line 2))
14429 (while (< (setq l (1+ l)) l2)
14430 (unless (org-at-item-p)
14431 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14432 (replace-match "\\1- \\2")))
14433 (beginning-of-line 2))))))
14435 (defun org-toggle-region-headings (beg end)
14436 "Convert all lines in region to list items.
14437 If the first line is already an item, convert all list items in the region
14438 to normal lines."
14439 (interactive "r")
14440 (let (l2 l)
14441 (save-excursion
14442 (goto-char end)
14443 (setq l2 (org-current-line))
14444 (goto-char beg)
14445 (beginning-of-line 1)
14446 (setq l (1- (org-current-line)))
14447 (if (org-on-heading-p)
14448 ;; We already have headlines, de-star them
14449 (while (< (setq l (1+ l)) l2)
14450 (when (org-on-heading-p t)
14451 (and (looking-at outline-regexp) (replace-match "")))
14452 (beginning-of-line 2))
14453 (let* ((stars (save-excursion
14454 (re-search-backward org-complex-heading-regexp nil t)
14455 (or (match-string 1) "*")))
14456 (add-stars (if org-odd-levels-only "**" "*"))
14457 (rpl (concat stars add-stars " \\2")))
14458 (while (< (setq l (1+ l)) l2)
14459 (unless (org-on-heading-p)
14460 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14461 (replace-match rpl)))
14462 (beginning-of-line 2)))))))
14464 (defun org-meta-return (&optional arg)
14465 "Insert a new heading or wrap a region in a table.
14466 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14467 See the individual commands for more information."
14468 (interactive "P")
14469 (cond
14470 ((org-at-table-p)
14471 (call-interactively 'org-table-wrap-region))
14472 (t (call-interactively 'org-insert-heading))))
14474 ;;; Menu entries
14476 ;; Define the Org-mode menus
14477 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14478 '("Tbl"
14479 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
14480 ["Next Field" org-cycle (org-at-table-p)]
14481 ["Previous Field" org-shifttab (org-at-table-p)]
14482 ["Next Row" org-return (org-at-table-p)]
14483 "--"
14484 ["Blank Field" org-table-blank-field (org-at-table-p)]
14485 ["Edit Field" org-table-edit-field (org-at-table-p)]
14486 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14487 "--"
14488 ("Column"
14489 ["Move Column Left" org-metaleft (org-at-table-p)]
14490 ["Move Column Right" org-metaright (org-at-table-p)]
14491 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14492 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14493 ("Row"
14494 ["Move Row Up" org-metaup (org-at-table-p)]
14495 ["Move Row Down" org-metadown (org-at-table-p)]
14496 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14497 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14498 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14499 "--"
14500 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14501 ("Rectangle"
14502 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14503 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14504 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14505 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14506 "--"
14507 ("Calculate"
14508 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14509 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14510 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
14511 "--"
14512 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14513 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14514 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14515 "--"
14516 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14517 "--"
14518 ["Sum Column/Rectangle" org-table-sum
14519 (or (org-at-table-p) (org-region-active-p))]
14520 ["Which Column?" org-table-current-column (org-at-table-p)])
14521 ["Debug Formulas"
14522 org-table-toggle-formula-debugger
14523 :style toggle :selected org-table-formula-debug]
14524 ["Show Col/Row Numbers"
14525 org-table-toggle-coordinate-overlays
14526 :style toggle :selected org-table-overlay-coordinates]
14527 "--"
14528 ["Create" org-table-create (and (not (org-at-table-p))
14529 org-enable-table-editor)]
14530 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14531 ["Import from File" org-table-import (not (org-at-table-p))]
14532 ["Export to File" org-table-export (org-at-table-p)]
14533 "--"
14534 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14536 (easy-menu-define org-org-menu org-mode-map "Org menu"
14537 '("Org"
14538 ("Show/Hide"
14539 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
14540 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
14541 ["Sparse Tree" org-occur t]
14542 ["Reveal Context" org-reveal t]
14543 ["Show All" show-all t]
14544 "--"
14545 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14546 "--"
14547 ["New Heading" org-insert-heading t]
14548 ("Navigate Headings"
14549 ["Up" outline-up-heading t]
14550 ["Next" outline-next-visible-heading t]
14551 ["Previous" outline-previous-visible-heading t]
14552 ["Next Same Level" outline-forward-same-level t]
14553 ["Previous Same Level" outline-backward-same-level t]
14554 "--"
14555 ["Jump" org-goto t])
14556 ("Edit Structure"
14557 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14558 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14559 "--"
14560 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14561 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14562 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14563 "--"
14564 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14565 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14566 ["Demote Heading" org-metaright (not (org-at-table-p))]
14567 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14568 "--"
14569 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14570 "--"
14571 ["Convert to odd levels" org-convert-to-odd-levels t]
14572 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14573 ("Editing"
14574 ["Emphasis..." org-emphasize t])
14575 ("Archive"
14576 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14577 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14578 ; :active t :keys "C-u C-c C-x C-a"]
14579 ["Sparse trees open ARCHIVE trees"
14580 (setq org-sparse-tree-open-archived-trees
14581 (not org-sparse-tree-open-archived-trees))
14582 :style toggle :selected org-sparse-tree-open-archived-trees]
14583 ["Cycling opens ARCHIVE trees"
14584 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14585 :style toggle :selected org-cycle-open-archived-trees]
14586 ["Agenda includes ARCHIVE trees"
14587 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
14588 :style toggle :selected (not org-agenda-skip-archived-trees)]
14589 "--"
14590 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14591 ; ["Check and Move Children" (org-archive-subtree '(4))
14592 ; :active t :keys "C-u C-c C-x C-s"]
14594 "--"
14595 ("TODO Lists"
14596 ["TODO/DONE/-" org-todo t]
14597 ("Select keyword"
14598 ["Next keyword" org-shiftright (org-on-heading-p)]
14599 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14600 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14601 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14602 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14603 ["Show TODO Tree" org-show-todo-tree t]
14604 ["Global TODO list" org-todo-list t]
14605 "--"
14606 ["Set Priority" org-priority t]
14607 ["Priority Up" org-shiftup t]
14608 ["Priority Down" org-shiftdown t])
14609 ("TAGS and Properties"
14610 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
14611 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
14612 "--"
14613 ["Set property" 'org-set-property t]
14614 ["Column view of properties" org-columns t]
14615 ["Insert Column View DBlock" org-insert-columns-dblock t])
14616 ("Dates and Scheduling"
14617 ["Timestamp" org-time-stamp t]
14618 ["Timestamp (inactive)" org-time-stamp-inactive t]
14619 ("Change Date"
14620 ["1 Day Later" org-shiftright t]
14621 ["1 Day Earlier" org-shiftleft t]
14622 ["1 ... Later" org-shiftup t]
14623 ["1 ... Earlier" org-shiftdown t])
14624 ["Compute Time Range" org-evaluate-time-range t]
14625 ["Schedule Item" org-schedule t]
14626 ["Deadline" org-deadline t]
14627 "--"
14628 ["Custom time format" org-toggle-time-stamp-overlays
14629 :style radio :selected org-display-custom-times]
14630 "--"
14631 ["Goto Calendar" org-goto-calendar t]
14632 ["Date from Calendar" org-date-from-calendar t])
14633 ("Logging work"
14634 ["Clock in" org-clock-in t]
14635 ["Clock out" org-clock-out t]
14636 ["Clock cancel" org-clock-cancel t]
14637 ["Goto running clock" org-clock-goto t]
14638 ["Display times" org-clock-display t]
14639 ["Create clock table" org-clock-report t]
14640 "--"
14641 ["Record DONE time"
14642 (progn (setq org-log-done (not org-log-done))
14643 (message "Switching to %s will %s record a timestamp"
14644 (car org-done-keywords)
14645 (if org-log-done "automatically" "not")))
14646 :style toggle :selected org-log-done])
14647 "--"
14648 ["Agenda Command..." org-agenda t]
14649 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14650 ("File List for Agenda")
14651 ("Special views current file"
14652 ["TODO Tree" org-show-todo-tree t]
14653 ["Check Deadlines" org-check-deadlines t]
14654 ["Timeline" org-timeline t]
14655 ["Tags Tree" org-tags-sparse-tree t])
14656 "--"
14657 ("Hyperlinks"
14658 ["Store Link (Global)" org-store-link t]
14659 ["Insert Link" org-insert-link t]
14660 ["Follow Link" org-open-at-point t]
14661 "--"
14662 ["Next link" org-next-link t]
14663 ["Previous link" org-previous-link t]
14664 "--"
14665 ["Descriptive Links"
14666 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14667 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
14668 ["Literal Links"
14669 (progn
14670 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14671 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
14672 "--"
14673 ["Export/Publish..." org-export t]
14674 ("LaTeX"
14675 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14676 :selected org-cdlatex-mode]
14677 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14678 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14679 ["Modify math symbol" org-cdlatex-math-modify
14680 (org-inside-LaTeX-fragment-p)]
14681 ["Export LaTeX fragments as images"
14682 (if (featurep 'org-exp)
14683 (setq org-export-with-LaTeX-fragments
14684 (not org-export-with-LaTeX-fragments))
14685 (require 'org-exp))
14686 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14687 org-export-with-LaTeX-fragments)])
14688 "--"
14689 ("Documentation"
14690 ["Show Version" org-version t]
14691 ["Info Documentation" org-info t])
14692 ("Customize"
14693 ["Browse Org Group" org-customize t]
14694 "--"
14695 ["Expand This Menu" org-create-customize-menu
14696 (fboundp 'customize-menu-create)])
14697 "--"
14698 ["Refresh setup" org-mode-restart t]
14701 (defun org-info (&optional node)
14702 "Read documentation for Org-mode in the info system.
14703 With optional NODE, go directly to that node."
14704 (interactive)
14705 (info (format "(org)%s" (or node ""))))
14707 (defun org-install-agenda-files-menu ()
14708 (let ((bl (buffer-list)))
14709 (save-excursion
14710 (while bl
14711 (set-buffer (pop bl))
14712 (if (org-mode-p) (setq bl nil)))
14713 (when (org-mode-p)
14714 (easy-menu-change
14715 '("Org") "File List for Agenda"
14716 (append
14717 (list
14718 ["Edit File List" (org-edit-agenda-file-list) t]
14719 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14720 ["Remove Current File from List" org-remove-file t]
14721 ["Cycle through agenda files" org-cycle-agenda-files t]
14722 ["Occur in all agenda files" org-occur-in-agenda-files t]
14723 "--")
14724 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14726 ;;;; Documentation
14728 (defun org-customize ()
14729 "Call the customize function with org as argument."
14730 (interactive)
14731 (customize-browse 'org))
14733 (defun org-create-customize-menu ()
14734 "Create a full customization menu for Org-mode, insert it into the menu."
14735 (interactive)
14736 (if (fboundp 'customize-menu-create)
14737 (progn
14738 (easy-menu-change
14739 '("Org") "Customize"
14740 `(["Browse Org group" org-customize t]
14741 "--"
14742 ,(customize-menu-create 'org)
14743 ["Set" Custom-set t]
14744 ["Save" Custom-save t]
14745 ["Reset to Current" Custom-reset-current t]
14746 ["Reset to Saved" Custom-reset-saved t]
14747 ["Reset to Standard Settings" Custom-reset-standard t]))
14748 (message "\"Org\"-menu now contains full customization menu"))
14749 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14751 ;;;; Miscellaneous stuff
14753 ;;; Generally useful functions
14755 (defun org-force-self-insert (N)
14756 "Needed to enforce self-insert under remapping."
14757 (interactive "p")
14758 (self-insert-command N))
14760 (defun org-string-width (s)
14761 "Compute width of string, ignoring invisible characters.
14762 This ignores character with invisibility property `org-link', and also
14763 characters with property `org-cwidth', because these will become invisible
14764 upon the next fontification round."
14765 (let (b l)
14766 (when (or (eq t buffer-invisibility-spec)
14767 (assq 'org-link buffer-invisibility-spec))
14768 (while (setq b (text-property-any 0 (length s)
14769 'invisible 'org-link s))
14770 (setq s (concat (substring s 0 b)
14771 (substring s (or (next-single-property-change
14772 b 'invisible s) (length s)))))))
14773 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14774 (setq s (concat (substring s 0 b)
14775 (substring s (or (next-single-property-change
14776 b 'org-cwidth s) (length s))))))
14777 (setq l (string-width s) b -1)
14778 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14779 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14783 (defun org-trim (s)
14784 "Remove whitespace at beginning and end of string."
14785 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14786 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14789 (defun org-wrap (string &optional width lines)
14790 "Wrap string to either a number of lines, or a width in characters.
14791 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14792 that costs. If there is a word longer than WIDTH, the text is actually
14793 wrapped to the length of that word.
14794 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14795 many lines, whatever width that takes.
14796 The return value is a list of lines, without newlines at the end."
14797 (let* ((words (org-split-string string "[ \t\n]+"))
14798 (maxword (apply 'max (mapcar 'org-string-width words)))
14799 w ll)
14800 (cond (width
14801 (org-do-wrap words (max maxword width)))
14802 (lines
14803 (setq w maxword)
14804 (setq ll (org-do-wrap words maxword))
14805 (if (<= (length ll) lines)
14807 (setq ll words)
14808 (while (> (length ll) lines)
14809 (setq w (1+ w))
14810 (setq ll (org-do-wrap words w)))
14811 ll))
14812 (t (error "Cannot wrap this")))))
14814 (defun org-do-wrap (words width)
14815 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14816 (let (lines line)
14817 (while words
14818 (setq line (pop words))
14819 (while (and words (< (+ (length line) (length (car words))) width))
14820 (setq line (concat line " " (pop words))))
14821 (setq lines (push line lines)))
14822 (nreverse lines)))
14824 (defun org-split-string (string &optional separators)
14825 "Splits STRING into substrings at SEPARATORS.
14826 No empty strings are returned if there are matches at the beginning
14827 and end of string."
14828 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14829 (start 0)
14830 notfirst
14831 (list nil))
14832 (while (and (string-match rexp string
14833 (if (and notfirst
14834 (= start (match-beginning 0))
14835 (< start (length string)))
14836 (1+ start) start))
14837 (< (match-beginning 0) (length string)))
14838 (setq notfirst t)
14839 (or (eq (match-beginning 0) 0)
14840 (and (eq (match-beginning 0) (match-end 0))
14841 (eq (match-beginning 0) start))
14842 (setq list
14843 (cons (substring string start (match-beginning 0))
14844 list)))
14845 (setq start (match-end 0)))
14846 (or (eq start (length string))
14847 (setq list
14848 (cons (substring string start)
14849 list)))
14850 (nreverse list)))
14852 (defun org-context ()
14853 "Return a list of contexts of the current cursor position.
14854 If several contexts apply, all are returned.
14855 Each context entry is a list with a symbol naming the context, and
14856 two positions indicating start and end of the context. Possible
14857 contexts are:
14859 :headline anywhere in a headline
14860 :headline-stars on the leading stars in a headline
14861 :todo-keyword on a TODO keyword (including DONE) in a headline
14862 :tags on the TAGS in a headline
14863 :priority on the priority cookie in a headline
14864 :item on the first line of a plain list item
14865 :item-bullet on the bullet/number of a plain list item
14866 :checkbox on the checkbox in a plain list item
14867 :table in an org-mode table
14868 :table-special on a special filed in a table
14869 :table-table in a table.el table
14870 :link on a hyperlink
14871 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14872 :target on a <<target>>
14873 :radio-target on a <<<radio-target>>>
14874 :latex-fragment on a LaTeX fragment
14875 :latex-preview on a LaTeX fragment with overlayed preview image
14877 This function expects the position to be visible because it uses font-lock
14878 faces as a help to recognize the following contexts: :table-special, :link,
14879 and :keyword."
14880 (let* ((f (get-text-property (point) 'face))
14881 (faces (if (listp f) f (list f)))
14882 (p (point)) clist o)
14883 ;; First the large context
14884 (cond
14885 ((org-on-heading-p t)
14886 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14887 (when (progn
14888 (beginning-of-line 1)
14889 (looking-at org-todo-line-tags-regexp))
14890 (push (org-point-in-group p 1 :headline-stars) clist)
14891 (push (org-point-in-group p 2 :todo-keyword) clist)
14892 (push (org-point-in-group p 4 :tags) clist))
14893 (goto-char p)
14894 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14895 (if (looking-at "\\[#[A-Z0-9]\\]")
14896 (push (org-point-in-group p 0 :priority) clist)))
14898 ((org-at-item-p)
14899 (push (org-point-in-group p 2 :item-bullet) clist)
14900 (push (list :item (point-at-bol)
14901 (save-excursion (org-end-of-item) (point)))
14902 clist)
14903 (and (org-at-item-checkbox-p)
14904 (push (org-point-in-group p 0 :checkbox) clist)))
14906 ((org-at-table-p)
14907 (push (list :table (org-table-begin) (org-table-end)) clist)
14908 (if (memq 'org-formula faces)
14909 (push (list :table-special
14910 (previous-single-property-change p 'face)
14911 (next-single-property-change p 'face)) clist)))
14912 ((org-at-table-p 'any)
14913 (push (list :table-table) clist)))
14914 (goto-char p)
14916 ;; Now the small context
14917 (cond
14918 ((org-at-timestamp-p)
14919 (push (org-point-in-group p 0 :timestamp) clist))
14920 ((memq 'org-link faces)
14921 (push (list :link
14922 (previous-single-property-change p 'face)
14923 (next-single-property-change p 'face)) clist))
14924 ((memq 'org-special-keyword faces)
14925 (push (list :keyword
14926 (previous-single-property-change p 'face)
14927 (next-single-property-change p 'face)) clist))
14928 ((org-on-target-p)
14929 (push (org-point-in-group p 0 :target) clist)
14930 (goto-char (1- (match-beginning 0)))
14931 (if (looking-at org-radio-target-regexp)
14932 (push (org-point-in-group p 0 :radio-target) clist))
14933 (goto-char p))
14934 ((setq o (car (delq nil
14935 (mapcar
14936 (lambda (x)
14937 (if (memq x org-latex-fragment-image-overlays) x))
14938 (org-overlays-at (point))))))
14939 (push (list :latex-fragment
14940 (org-overlay-start o) (org-overlay-end o)) clist)
14941 (push (list :latex-preview
14942 (org-overlay-start o) (org-overlay-end o)) clist))
14943 ((org-inside-LaTeX-fragment-p)
14944 ;; FIXME: positions wrong.
14945 (push (list :latex-fragment (point) (point)) clist)))
14947 (setq clist (nreverse (delq nil clist)))
14948 clist))
14950 ;; FIXME: Compare with at-regexp-p Do we need both?
14951 (defun org-in-regexp (re &optional nlines visually)
14952 "Check if point is inside a match of regexp.
14953 Normally only the current line is checked, but you can include NLINES extra
14954 lines both before and after point into the search.
14955 If VISUALLY is set, require that the cursor is not after the match but
14956 really on, so that the block visually is on the match."
14957 (catch 'exit
14958 (let ((pos (point))
14959 (eol (point-at-eol (+ 1 (or nlines 0))))
14960 (inc (if visually 1 0)))
14961 (save-excursion
14962 (beginning-of-line (- 1 (or nlines 0)))
14963 (while (re-search-forward re eol t)
14964 (if (and (<= (match-beginning 0) pos)
14965 (>= (+ inc (match-end 0)) pos))
14966 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14968 (defun org-at-regexp-p (regexp)
14969 "Is point inside a match of REGEXP in the current line?"
14970 (catch 'exit
14971 (save-excursion
14972 (let ((pos (point)) (end (point-at-eol)))
14973 (beginning-of-line 1)
14974 (while (re-search-forward regexp end t)
14975 (if (and (<= (match-beginning 0) pos)
14976 (>= (match-end 0) pos))
14977 (throw 'exit t)))
14978 nil))))
14980 (defun org-occur-in-agenda-files (regexp &optional nlines)
14981 "Call `multi-occur' with buffers for all agenda files."
14982 (interactive "sOrg-files matching: \np")
14983 (let* ((files (org-agenda-files))
14984 (tnames (mapcar 'file-truename files))
14985 (extra org-agenda-text-search-extra-files)
14987 (while (setq f (pop extra))
14988 (unless (member (file-truename f) tnames)
14989 (add-to-list 'files f 'append)
14990 (add-to-list 'tnames (file-truename f) 'append)))
14991 (multi-occur
14992 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14993 regexp)))
14995 (if (boundp 'occur-mode-find-occurrence-hook)
14996 ;; Emacs 23
14997 (add-hook 'occur-mode-find-occurrence-hook
14998 (lambda ()
14999 (when (org-mode-p)
15000 (org-reveal))))
15001 ;; Emacs 22
15002 (defadvice occur-mode-goto-occurrence
15003 (after org-occur-reveal activate)
15004 (and (org-mode-p) (org-reveal)))
15005 (defadvice occur-mode-goto-occurrence-other-window
15006 (after org-occur-reveal activate)
15007 (and (org-mode-p) (org-reveal)))
15008 (defadvice occur-mode-display-occurrence
15009 (after org-occur-reveal activate)
15010 (when (org-mode-p)
15011 (let ((pos (occur-mode-find-occurrence)))
15012 (with-current-buffer (marker-buffer pos)
15013 (save-excursion
15014 (goto-char pos)
15015 (org-reveal)))))))
15017 (defun org-uniquify (list)
15018 "Remove duplicate elements from LIST."
15019 (let (res)
15020 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15021 res))
15023 (defun org-delete-all (elts list)
15024 "Remove all elements in ELTS from LIST."
15025 (while elts
15026 (setq list (delete (pop elts) list)))
15027 list)
15029 (defun org-back-over-empty-lines ()
15030 "Move backwards over witespace, to the beginning of the first empty line.
15031 Returns the number of empty lines passed."
15032 (let ((pos (point)))
15033 (skip-chars-backward " \t\n\r")
15034 (beginning-of-line 2)
15035 (goto-char (min (point) pos))
15036 (count-lines (point) pos)))
15038 (defun org-skip-whitespace ()
15039 (skip-chars-forward " \t\n\r"))
15041 (defun org-point-in-group (point group &optional context)
15042 "Check if POINT is in match-group GROUP.
15043 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15044 match. If the match group does ot exist or point is not inside it,
15045 return nil."
15046 (and (match-beginning group)
15047 (>= point (match-beginning group))
15048 (<= point (match-end group))
15049 (if context
15050 (list context (match-beginning group) (match-end group))
15051 t)))
15053 (defun org-switch-to-buffer-other-window (&rest args)
15054 "Switch to buffer in a second window on the current frame.
15055 In particular, do not allow pop-up frames."
15056 (let (pop-up-frames special-display-buffer-names special-display-regexps
15057 special-display-function)
15058 (apply 'switch-to-buffer-other-window args)))
15060 (defun org-combine-plists (&rest plists)
15061 "Create a single property list from all plists in PLISTS.
15062 The process starts by copying the first list, and then setting properties
15063 from the other lists. Settings in the last list are the most significant
15064 ones and overrule settings in the other lists."
15065 (let ((rtn (copy-sequence (pop plists)))
15066 p v ls)
15067 (while plists
15068 (setq ls (pop plists))
15069 (while ls
15070 (setq p (pop ls) v (pop ls))
15071 (setq rtn (plist-put rtn p v))))
15072 rtn))
15074 (defun org-move-line-down (arg)
15075 "Move the current line down. With prefix argument, move it past ARG lines."
15076 (interactive "p")
15077 (let ((col (current-column))
15078 beg end pos)
15079 (beginning-of-line 1) (setq beg (point))
15080 (beginning-of-line 2) (setq end (point))
15081 (beginning-of-line (+ 1 arg))
15082 (setq pos (move-marker (make-marker) (point)))
15083 (insert (delete-and-extract-region beg end))
15084 (goto-char pos)
15085 (move-to-column col)))
15087 (defun org-move-line-up (arg)
15088 "Move the current line up. With prefix argument, move it past ARG lines."
15089 (interactive "p")
15090 (let ((col (current-column))
15091 beg end pos)
15092 (beginning-of-line 1) (setq beg (point))
15093 (beginning-of-line 2) (setq end (point))
15094 (beginning-of-line (- arg))
15095 (setq pos (move-marker (make-marker) (point)))
15096 (insert (delete-and-extract-region beg end))
15097 (goto-char pos)
15098 (move-to-column col)))
15100 (defun org-replace-escapes (string table)
15101 "Replace %-escapes in STRING with values in TABLE.
15102 TABLE is an association list with keys like \"%a\" and string values.
15103 The sequences in STRING may contain normal field width and padding information,
15104 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15105 so values can contain further %-escapes if they are define later in TABLE."
15106 (let ((case-fold-search nil)
15107 e re rpl)
15108 (while (setq e (pop table))
15109 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15110 (while (string-match re string)
15111 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15112 (cdr e)))
15113 (setq string (replace-match rpl t t string))))
15114 string))
15117 (defun org-sublist (list start end)
15118 "Return a section of LIST, from START to END.
15119 Counting starts at 1."
15120 (let (rtn (c start))
15121 (setq list (nthcdr (1- start) list))
15122 (while (and list (<= c end))
15123 (push (pop list) rtn)
15124 (setq c (1+ c)))
15125 (nreverse rtn)))
15127 (defun org-find-base-buffer-visiting (file)
15128 "Like `find-buffer-visiting' but alway return the base buffer and
15129 not an indirect buffer."
15130 (let ((buf (find-buffer-visiting file)))
15131 (if buf
15132 (or (buffer-base-buffer buf) buf)
15133 nil)))
15135 (defun org-image-file-name-regexp ()
15136 "Return regexp matching the file names of images."
15137 (if (fboundp 'image-file-name-regexp)
15138 (image-file-name-regexp)
15139 (let ((image-file-name-extensions
15140 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15141 "xbm" "xpm" "pbm" "pgm" "ppm")))
15142 (concat "\\."
15143 (regexp-opt (nconc (mapcar 'upcase
15144 image-file-name-extensions)
15145 image-file-name-extensions)
15147 "\\'"))))
15149 (defun org-file-image-p (file)
15150 "Return non-nil if FILE is an image."
15151 (save-match-data
15152 (string-match (org-image-file-name-regexp) file)))
15154 ;;; Paragraph filling stuff.
15155 ;; We want this to be just right, so use the full arsenal.
15157 (defun org-indent-line-function ()
15158 "Indent line like previous, but further if previous was headline or item."
15159 (interactive)
15160 (let* ((pos (point))
15161 (itemp (org-at-item-p))
15162 column bpos bcol tpos tcol bullet btype bullet-type)
15163 ;; Find the previous relevant line
15164 (beginning-of-line 1)
15165 (cond
15166 ((looking-at "#") (setq column 0))
15167 ((looking-at "\\*+ ") (setq column 0))
15169 (beginning-of-line 0)
15170 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
15171 (beginning-of-line 0))
15172 (cond
15173 ((looking-at "\\*+[ \t]+")
15174 (goto-char (match-end 0))
15175 (setq column (current-column)))
15176 ((org-in-item-p)
15177 (org-beginning-of-item)
15178 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15179 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
15180 (setq bpos (match-beginning 1) tpos (match-end 0)
15181 bcol (progn (goto-char bpos) (current-column))
15182 tcol (progn (goto-char tpos) (current-column))
15183 bullet (match-string 1)
15184 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15185 (if (not itemp)
15186 (setq column tcol)
15187 (goto-char pos)
15188 (beginning-of-line 1)
15189 (if (looking-at "\\S-")
15190 (progn
15191 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15192 (setq bullet (match-string 1)
15193 btype (if (string-match "[0-9]" bullet) "n" bullet))
15194 (setq column (if (equal btype bullet-type) bcol tcol)))
15195 (setq column (org-get-indentation)))))
15196 (t (setq column (org-get-indentation))))))
15197 (goto-char pos)
15198 (if (<= (current-column) (current-indentation))
15199 (indent-line-to column)
15200 (save-excursion (indent-line-to column)))
15201 (setq column (current-column))
15202 (beginning-of-line 1)
15203 (if (looking-at
15204 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15205 (replace-match (concat "\\1" (format org-property-format
15206 (match-string 2) (match-string 3)))
15207 t nil))
15208 (move-to-column column)))
15210 (defun org-set-autofill-regexps ()
15211 (interactive)
15212 ;; In the paragraph separator we include headlines, because filling
15213 ;; text in a line directly attached to a headline would otherwise
15214 ;; fill the headline as well.
15215 (org-set-local 'comment-start-skip "^#+[ \t]*")
15216 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15217 ;; The paragraph starter includes hand-formatted lists.
15218 (org-set-local 'paragraph-start
15219 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15220 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15221 ;; But only if the user has not turned off tables or fixed-width regions
15222 (org-set-local
15223 'auto-fill-inhibit-regexp
15224 (concat "\\*+ \\|#\\+"
15225 "\\|[ \t]*" org-keyword-time-regexp
15226 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15227 (concat
15228 "\\|[ \t]*["
15229 (if org-enable-table-editor "|" "")
15230 (if org-enable-fixed-width-editor ":" "")
15231 "]"))))
15232 ;; We use our own fill-paragraph function, to make sure that tables
15233 ;; and fixed-width regions are not wrapped. That function will pass
15234 ;; through to `fill-paragraph' when appropriate.
15235 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15236 ; Adaptive filling: To get full control, first make sure that
15237 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15238 (org-set-local 'adaptive-fill-regexp "\000")
15239 (org-set-local 'adaptive-fill-function
15240 'org-adaptive-fill-function)
15241 (org-set-local
15242 'align-mode-rules-list
15243 '((org-in-buffer-settings
15244 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15245 (modes . '(org-mode))))))
15247 (defun org-fill-paragraph (&optional justify)
15248 "Re-align a table, pass through to fill-paragraph if no table."
15249 (let ((table-p (org-at-table-p))
15250 (table.el-p (org-at-table.el-p)))
15251 (cond ((and (equal (char-after (point-at-bol)) ?*)
15252 (save-excursion (goto-char (point-at-bol))
15253 (looking-at outline-regexp)))
15254 t) ; skip headlines
15255 (table.el-p t) ; skip table.el tables
15256 (table-p (org-table-align) t) ; align org-mode tables
15257 (t nil)))) ; call paragraph-fill
15259 ;; For reference, this is the default value of adaptive-fill-regexp
15260 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15262 (defun org-adaptive-fill-function ()
15263 "Return a fill prefix for org-mode files.
15264 In particular, this makes sure hanging paragraphs for hand-formatted lists
15265 work correctly."
15266 (cond ((looking-at "#[ \t]+")
15267 (match-string 0))
15268 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
15269 (save-excursion
15270 (goto-char (match-end 0))
15271 (make-string (current-column) ?\ )))
15272 (t nil)))
15274 ;;; Other stuff.
15276 (defun org-toggle-fixed-width-section (arg)
15277 "Toggle the fixed-width export.
15278 If there is no active region, the QUOTE keyword at the current headline is
15279 inserted or removed. When present, it causes the text between this headline
15280 and the next to be exported as fixed-width text, and unmodified.
15281 If there is an active region, this command adds or removes a colon as the
15282 first character of this line. If the first character of a line is a colon,
15283 this line is also exported in fixed-width font."
15284 (interactive "P")
15285 (let* ((cc 0)
15286 (regionp (org-region-active-p))
15287 (beg (if regionp (region-beginning) (point)))
15288 (end (if regionp (region-end)))
15289 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15290 (case-fold-search nil)
15291 (re "[ \t]*\\(:\\)")
15292 off)
15293 (if regionp
15294 (save-excursion
15295 (goto-char beg)
15296 (setq cc (current-column))
15297 (beginning-of-line 1)
15298 (setq off (looking-at re))
15299 (while (> nlines 0)
15300 (setq nlines (1- nlines))
15301 (beginning-of-line 1)
15302 (cond
15303 (arg
15304 (move-to-column cc t)
15305 (insert ":\n")
15306 (forward-line -1))
15307 ((and off (looking-at re))
15308 (replace-match "" t t nil 1))
15309 ((not off) (move-to-column cc t) (insert ":")))
15310 (forward-line 1)))
15311 (save-excursion
15312 (org-back-to-heading)
15313 (if (looking-at (concat outline-regexp
15314 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15315 (replace-match "" t t nil 1)
15316 (if (looking-at outline-regexp)
15317 (progn
15318 (goto-char (match-end 0))
15319 (insert org-quote-string " "))))))))
15321 ;;;; Functions extending outline functionality
15323 (defun org-beginning-of-line (&optional arg)
15324 "Go to the beginning of the current line. If that is invisible, continue
15325 to a visible line beginning. This makes the function of C-a more intuitive.
15326 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15327 first attempt, and only move to after the tags when the cursor is already
15328 beyond the end of the headline."
15329 (interactive "P")
15330 (let ((pos (point)))
15331 (beginning-of-line 1)
15332 (if (bobp)
15334 (backward-char 1)
15335 (if (org-invisible-p)
15336 (while (and (not (bobp)) (org-invisible-p))
15337 (backward-char 1)
15338 (beginning-of-line 1))
15339 (forward-char 1)))
15340 (when org-special-ctrl-a/e
15341 (cond
15342 ((and (looking-at org-todo-line-regexp)
15343 (= (char-after (match-end 1)) ?\ ))
15344 (goto-char
15345 (if (eq org-special-ctrl-a/e t)
15346 (cond ((> pos (match-beginning 3)) (match-beginning 3))
15347 ((= pos (point)) (match-beginning 3))
15348 (t (point)))
15349 (cond ((> pos (point)) (point))
15350 ((not (eq last-command this-command)) (point))
15351 (t (match-beginning 3))))))
15352 ((org-at-item-p)
15353 (goto-char
15354 (if (eq org-special-ctrl-a/e t)
15355 (cond ((> pos (match-end 4)) (match-end 4))
15356 ((= pos (point)) (match-end 4))
15357 (t (point)))
15358 (cond ((> pos (point)) (point))
15359 ((not (eq last-command this-command)) (point))
15360 (t (match-end 4))))))))))
15362 (defun org-end-of-line (&optional arg)
15363 "Go to the end of the line.
15364 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15365 first attempt, and only move to after the tags when the cursor is already
15366 beyond the end of the headline."
15367 (interactive "P")
15368 (if (or (not org-special-ctrl-a/e)
15369 (not (org-on-heading-p)))
15370 (end-of-line arg)
15371 (let ((pos (point)))
15372 (beginning-of-line 1)
15373 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15374 (if (eq org-special-ctrl-a/e t)
15375 (if (or (< pos (match-beginning 1))
15376 (= pos (match-end 0)))
15377 (goto-char (match-beginning 1))
15378 (goto-char (match-end 0)))
15379 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15380 (goto-char (match-end 0))
15381 (goto-char (match-beginning 1))))
15382 (end-of-line arg)))))
15384 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15385 (define-key org-mode-map "\C-e" 'org-end-of-line)
15387 (defun org-kill-line (&optional arg)
15388 "Kill line, to tags or end of line."
15389 (interactive "P")
15390 (cond
15391 ((or (not org-special-ctrl-k)
15392 (bolp)
15393 (not (org-on-heading-p)))
15394 (call-interactively 'kill-line))
15395 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15396 (kill-region (point) (match-beginning 1))
15397 (org-set-tags nil t))
15398 (t (kill-region (point) (point-at-eol)))))
15400 (define-key org-mode-map "\C-k" 'org-kill-line)
15402 (defun org-invisible-p ()
15403 "Check if point is at a character currently not visible."
15404 ;; Early versions of noutline don't have `outline-invisible-p'.
15405 (if (fboundp 'outline-invisible-p)
15406 (outline-invisible-p)
15407 (get-char-property (point) 'invisible)))
15409 (defun org-invisible-p2 ()
15410 "Check if point is at a character currently not visible."
15411 (save-excursion
15412 (if (and (eolp) (not (bobp))) (backward-char 1))
15413 ;; Early versions of noutline don't have `outline-invisible-p'.
15414 (if (fboundp 'outline-invisible-p)
15415 (outline-invisible-p)
15416 (get-char-property (point) 'invisible))))
15418 (defalias 'org-back-to-heading 'outline-back-to-heading)
15419 (defalias 'org-on-heading-p 'outline-on-heading-p)
15420 (defalias 'org-at-heading-p 'outline-on-heading-p)
15421 (defun org-at-heading-or-item-p ()
15422 (or (org-on-heading-p) (org-at-item-p)))
15424 (defun org-on-target-p ()
15425 (or (org-in-regexp org-radio-target-regexp)
15426 (org-in-regexp org-target-regexp)))
15428 (defun org-up-heading-all (arg)
15429 "Move to the heading line of which the present line is a subheading.
15430 This function considers both visible and invisible heading lines.
15431 With argument, move up ARG levels."
15432 (if (fboundp 'outline-up-heading-all)
15433 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15434 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15436 (defun org-up-heading-safe ()
15437 "Move to the heading line of which the present line is a subheading.
15438 This version will not throw an error. It will return the level of the
15439 headline found, or nil if no higher level is found."
15440 (let ((pos (point)) start-level level
15441 (re (concat "^" outline-regexp)))
15442 (catch 'exit
15443 (outline-back-to-heading t)
15444 (setq start-level (funcall outline-level))
15445 (if (equal start-level 1) (throw 'exit nil))
15446 (while (re-search-backward re nil t)
15447 (setq level (funcall outline-level))
15448 (if (< level start-level) (throw 'exit level)))
15449 nil)))
15451 (defun org-first-sibling-p ()
15452 "Is this heading the first child of its parents?"
15453 (interactive)
15454 (let ((re (concat "^" outline-regexp))
15455 level l)
15456 (unless (org-at-heading-p t)
15457 (error "Not at a heading"))
15458 (setq level (funcall outline-level))
15459 (save-excursion
15460 (if (not (re-search-backward re nil t))
15462 (setq l (funcall outline-level))
15463 (< l level)))))
15465 (defun org-goto-sibling (&optional previous)
15466 "Goto the next sibling, even if it is invisible.
15467 When PREVIOUS is set, go to the previous sibling instead. Returns t
15468 when a sibling was found. When none is found, return nil and don't
15469 move point."
15470 (let ((fun (if previous 're-search-backward 're-search-forward))
15471 (pos (point))
15472 (re (concat "^" outline-regexp))
15473 level l)
15474 (when (condition-case nil (org-back-to-heading t) (error nil))
15475 (setq level (funcall outline-level))
15476 (catch 'exit
15477 (or previous (forward-char 1))
15478 (while (funcall fun re nil t)
15479 (setq l (funcall outline-level))
15480 (when (< l level) (goto-char pos) (throw 'exit nil))
15481 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15482 (goto-char pos)
15483 nil))))
15485 (defun org-show-siblings ()
15486 "Show all siblings of the current headline."
15487 (save-excursion
15488 (while (org-goto-sibling) (org-flag-heading nil)))
15489 (save-excursion
15490 (while (org-goto-sibling 'previous)
15491 (org-flag-heading nil))))
15493 (defun org-show-hidden-entry ()
15494 "Show an entry where even the heading is hidden."
15495 (save-excursion
15496 (org-show-entry)))
15498 (defun org-flag-heading (flag &optional entry)
15499 "Flag the current heading. FLAG non-nil means make invisible.
15500 When ENTRY is non-nil, show the entire entry."
15501 (save-excursion
15502 (org-back-to-heading t)
15503 ;; Check if we should show the entire entry
15504 (if entry
15505 (progn
15506 (org-show-entry)
15507 (save-excursion
15508 (and (outline-next-heading)
15509 (org-flag-heading nil))))
15510 (outline-flag-region (max (point-min) (1- (point)))
15511 (save-excursion (outline-end-of-heading) (point))
15512 flag))))
15514 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15515 ;; This is an exact copy of the original function, but it uses
15516 ;; `org-back-to-heading', to make it work also in invisible
15517 ;; trees. And is uses an invisible-OK argument.
15518 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15519 (org-back-to-heading invisible-OK)
15520 (let ((first t)
15521 (level (funcall outline-level)))
15522 (while (and (not (eobp))
15523 (or first (> (funcall outline-level) level)))
15524 (setq first nil)
15525 (outline-next-heading))
15526 (unless to-heading
15527 (if (memq (preceding-char) '(?\n ?\^M))
15528 (progn
15529 ;; Go to end of line before heading
15530 (forward-char -1)
15531 (if (memq (preceding-char) '(?\n ?\^M))
15532 ;; leave blank line before heading
15533 (forward-char -1))))))
15534 (point))
15536 (defun org-show-subtree ()
15537 "Show everything after this heading at deeper levels."
15538 (outline-flag-region
15539 (point)
15540 (save-excursion
15541 (outline-end-of-subtree) (outline-next-heading) (point))
15542 nil))
15544 (defun org-show-entry ()
15545 "Show the body directly following this heading.
15546 Show the heading too, if it is currently invisible."
15547 (interactive)
15548 (save-excursion
15549 (condition-case nil
15550 (progn
15551 (org-back-to-heading t)
15552 (outline-flag-region
15553 (max (point-min) (1- (point)))
15554 (save-excursion
15555 (re-search-forward
15556 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15557 (or (match-beginning 1) (point-max)))
15558 nil))
15559 (error nil))))
15561 (defun org-make-options-regexp (kwds)
15562 "Make a regular expression for keyword lines."
15563 (concat
15565 "#?[ \t]*\\+\\("
15566 (mapconcat 'regexp-quote kwds "\\|")
15567 "\\):[ \t]*"
15568 "\\(.+\\)"))
15570 ;; Make isearch reveal the necessary context
15571 (defun org-isearch-end ()
15572 "Reveal context after isearch exits."
15573 (when isearch-success ; only if search was successful
15574 (if (featurep 'xemacs)
15575 ;; Under XEmacs, the hook is run in the correct place,
15576 ;; we directly show the context.
15577 (org-show-context 'isearch)
15578 ;; In Emacs the hook runs *before* restoring the overlays.
15579 ;; So we have to use a one-time post-command-hook to do this.
15580 ;; (Emacs 22 has a special variable, see function `org-mode')
15581 (unless (and (boundp 'isearch-mode-end-hook-quit)
15582 isearch-mode-end-hook-quit)
15583 ;; Only when the isearch was not quitted.
15584 (org-add-hook 'post-command-hook 'org-isearch-post-command
15585 'append 'local)))))
15587 (defun org-isearch-post-command ()
15588 "Remove self from hook, and show context."
15589 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15590 (org-show-context 'isearch))
15593 ;;;; Integration with and fixes for other packages
15595 ;;; Imenu support
15597 (defvar org-imenu-markers nil
15598 "All markers currently used by Imenu.")
15599 (make-variable-buffer-local 'org-imenu-markers)
15601 (defun org-imenu-new-marker (&optional pos)
15602 "Return a new marker for use by Imenu, and remember the marker."
15603 (let ((m (make-marker)))
15604 (move-marker m (or pos (point)))
15605 (push m org-imenu-markers)
15608 (defun org-imenu-get-tree ()
15609 "Produce the index for Imenu."
15610 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15611 (setq org-imenu-markers nil)
15612 (let* ((n org-imenu-depth)
15613 (re (concat "^" outline-regexp))
15614 (subs (make-vector (1+ n) nil))
15615 (last-level 0)
15616 m tree level head)
15617 (save-excursion
15618 (save-restriction
15619 (widen)
15620 (goto-char (point-max))
15621 (while (re-search-backward re nil t)
15622 (setq level (org-reduced-level (funcall outline-level)))
15623 (when (<= level n)
15624 (looking-at org-complex-heading-regexp)
15625 (setq head (org-match-string-no-properties 4)
15626 m (org-imenu-new-marker))
15627 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15628 (if (>= level last-level)
15629 (push (cons head m) (aref subs level))
15630 (push (cons head (aref subs (1+ level))) (aref subs level))
15631 (loop for i from (1+ level) to n do (aset subs i nil)))
15632 (setq last-level level)))))
15633 (aref subs 1)))
15635 (eval-after-load "imenu"
15636 '(progn
15637 (add-hook 'imenu-after-jump-hook
15638 (lambda () (org-show-context 'org-goto)))))
15640 ;; Speedbar support
15642 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15643 "Overlay marking the agenda restriction line in speedbar.")
15644 (org-overlay-put org-speedbar-restriction-lock-overlay
15645 'face 'org-agenda-restriction-lock)
15646 (org-overlay-put org-speedbar-restriction-lock-overlay
15647 'help-echo "Agendas are currently limited to this item.")
15648 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15650 (defun org-speedbar-set-agenda-restriction ()
15651 "Restrict future agenda commands to the location at point in speedbar.
15652 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15653 (interactive)
15654 (let (p m tp np dir txt w)
15655 (cond
15656 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15657 'org-imenu t))
15658 (setq m (get-text-property p 'org-imenu-marker))
15659 (save-excursion
15660 (save-restriction
15661 (set-buffer (marker-buffer m))
15662 (goto-char m)
15663 (org-agenda-set-restriction-lock 'subtree))))
15664 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15665 'speedbar-function 'speedbar-find-file))
15666 (setq tp (previous-single-property-change
15667 (1+ p) 'speedbar-function)
15668 np (next-single-property-change
15669 tp 'speedbar-function)
15670 dir (speedbar-line-directory)
15671 txt (buffer-substring-no-properties (or tp (point-min))
15672 (or np (point-max))))
15673 (save-excursion
15674 (save-restriction
15675 (set-buffer (find-file-noselect
15676 (let ((default-directory dir))
15677 (expand-file-name txt))))
15678 (unless (org-mode-p)
15679 (error "Cannot restrict to non-Org-mode file"))
15680 (org-agenda-set-restriction-lock 'file))))
15681 (t (error "Don't know how to restrict Org-mode's agenda")))
15682 (org-move-overlay org-speedbar-restriction-lock-overlay
15683 (point-at-bol) (point-at-eol))
15684 (setq current-prefix-arg nil)
15685 (org-agenda-maybe-redo)))
15687 (eval-after-load "speedbar"
15688 '(progn
15689 (speedbar-add-supported-extension ".org")
15690 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15691 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15692 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15693 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15694 (add-hook 'speedbar-visiting-tag-hook
15695 (lambda () (org-show-context 'org-goto)))))
15698 ;;; Fixes and Hacks
15700 ;; Make flyspell not check words in links, to not mess up our keymap
15701 (defun org-mode-flyspell-verify ()
15702 "Don't let flyspell put overlays at active buttons."
15703 (not (get-text-property (point) 'keymap)))
15705 ;; Make `bookmark-jump' show the jump location if it was hidden.
15706 (eval-after-load "bookmark"
15707 '(if (boundp 'bookmark-after-jump-hook)
15708 ;; We can use the hook
15709 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15710 ;; Hook not available, use advice
15711 (defadvice bookmark-jump (after org-make-visible activate)
15712 "Make the position visible."
15713 (org-bookmark-jump-unhide))))
15715 (defun org-bookmark-jump-unhide ()
15716 "Unhide the current position, to show the bookmark location."
15717 (and (org-mode-p)
15718 (or (org-invisible-p)
15719 (save-excursion (goto-char (max (point-min) (1- (point))))
15720 (org-invisible-p)))
15721 (org-show-context 'bookmark-jump)))
15723 ;; Make session.el ignore our circular variable
15724 (eval-after-load "session"
15725 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15727 ;;;; Experimental code
15729 (defun org-closed-in-range ()
15730 "Sparse tree of items closed in a certain time range.
15731 Still experimental, may disappear in the future."
15732 (interactive)
15733 ;; Get the time interval from the user.
15734 (let* ((time1 (time-to-seconds
15735 (org-read-date nil 'to-time nil "Starting date: ")))
15736 (time2 (time-to-seconds
15737 (org-read-date nil 'to-time nil "End date:")))
15738 ;; callback function
15739 (callback (lambda ()
15740 (let ((time
15741 (time-to-seconds
15742 (apply 'encode-time
15743 (org-parse-time-string
15744 (match-string 1))))))
15745 ;; check if time in interval
15746 (and (>= time time1) (<= time time2))))))
15747 ;; make tree, check each match with the callback
15748 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15751 ;;;; Finish up
15753 (provide 'org)
15755 (run-hooks 'org-load-hook)
15757 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15758 ;;; org.el ends here
15761 (defun org-get-heading (&optional no-tags)
15762 "Return the heading of the current entry, without the stars."
15763 (save-excursion
15764 (org-back-to-heading t)
15765 (if (looking-at
15766 (if no-tags
15767 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
15768 "\\*+[ \t]+\\([^\r\n]*\\)"))
15769 (match-string 1) "")))
15771 (defun org-get-category (&optional pos)
15772 "Get the category applying to position POS."
15773 (get-text-property (or pos (point)) 'org-category))
15775 (defun org-get-tags-at (&optional pos)
15776 "Get a list of all headline tags applicable at POS.
15777 POS defaults to point. If tags are inherited, the list contains
15778 the targets in the same sequence as the headlines appear, i.e.
15779 sthe tags of the current headline come last."
15780 (interactive)
15781 (let (tags ltags lastpos parent)
15782 (save-excursion
15783 (save-restriction
15784 (widen)
15785 (goto-char (or pos (point)))
15786 (save-match-data
15787 (condition-case nil
15788 (progn
15789 (org-back-to-heading t)
15790 (while (not (equal lastpos (point)))
15791 (setq lastpos (point))
15792 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
15793 (setq ltags (org-split-string
15794 (org-match-string-no-properties 1) ":"))
15795 (setq tags (append (org-remove-uniherited-tags ltags)
15796 tags)))
15797 (or org-use-tag-inheritance (error ""))
15798 (org-up-heading-all 1)
15799 (setq parent t)))
15800 (error nil))))
15801 tags)))
15803 (defun org-days-to-iso-week (days)
15804 "Return the iso week number."
15805 (require 'cal-iso)
15806 (car (calendar-iso-from-absolute days)))
15808 (defun org-small-year-to-year (year)
15809 "Convert 2-digit years into 4-digit years.
15810 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15811 The year 2000 cannot be abbreviated. Any year lager than 99
15812 is retrned unchanged."
15813 (if (< year 38)
15814 (setq year (+ 2000 year))
15815 (if (< year 100)
15816 (setq year (+ 1900 year))))
15817 year)