release 6.01b
[org-mode.git] / lisp / org.el
blob1b74321360dff1ac9779d51475f5bd86ca7e2673
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.01b
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)
90 (require 'org-faces)
92 ;;;; Customization variables
94 ;;; Version
96 (defconst org-version "6.01b"
97 "The version number of the file org.el.")
99 (defun org-version (&optional here)
100 "Show the org-mode version in the echo area.
101 With prefix arg HERE, insert it at point."
102 (interactive "P")
103 (let ((version (format "Org-mode version %s" org-version)))
104 (message version)
105 (if here
106 (insert version))))
108 ;;; Compatibility constants
110 ;;; The custom variables
112 (defgroup org nil
113 "Outline-based notes management and organizer."
114 :tag "Org"
115 :group 'outlines
116 :group 'hypermedia
117 :group 'calendar)
119 (defcustom org-load-hook nil
120 "Hook that is run after org.el has been loaded."
121 :group 'org
122 :type 'hook)
124 (defvar org-modules) ; defined below
125 (defvar org-modules-loaded nil
126 "Have the modules been loaded already?")
128 (defun org-load-modules-maybe (&optional force)
129 "Load all extensions listed in `org-default-extensions'."
130 (when (or force (not org-modules-loaded))
131 (mapc (lambda (ext)
132 (condition-case nil (require ext)
133 (error (message "Problems while trying to load feature `%s'" ext))))
134 org-modules)
135 (setq org-modules-loaded t)))
137 (defun org-set-modules (var value)
138 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
139 (set var value)
140 (when (featurep 'org)
141 (org-load-modules-maybe 'force)))
143 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-infojs org-irc org-mew org-mhe org-rmail org-vm org-wl)
144 "Modules that should always be loaded together with org.el.
145 If a description starts with <C>, the file is not part of emacs
146 and loading it will require that you have downloaded and properly installed
147 the org-mode distribution.
149 You can also use this system to load external packages (i.e. neither Org
150 core modules, not modules from the CONTRIB directory). Just add symbols
151 to the end of the list. If the package is called org-xyz.e, then you need
152 to add the symbol `xyz', and the package must have a call to
154 (provide 'org-xyz)"
155 :group 'org
156 :set 'org-set-modules
157 :type
158 '(set :greedy t
159 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
160 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
161 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
162 (const :tag " info: Links to Info nodes" org-info)
163 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" org-infojs)
164 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
165 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
166 (const :tag " mew Links to Mew folders/messages" org-mew)
167 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
168 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
169 (const :tag " vm: Links to VM folders/messages" org-vm)
170 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
171 (const :tag " mouse: Additional mouse support" org-mouse)
173 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
174 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
175 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
176 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
177 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
178 (const :tag "C id: Global id's for identifying entries" org-id)
179 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
180 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
181 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
182 (const :tag "C mew: Support for links to messages in Mew" org-mew)
183 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
184 (const :tag "C registry: A registry for Org links" org-registry)
185 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
186 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
187 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
188 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
191 (defgroup org-startup nil
192 "Options concerning startup of Org-mode."
193 :tag "Org Startup"
194 :group 'org)
196 (defcustom org-startup-folded t
197 "Non-nil means, entering Org-mode will switch to OVERVIEW.
198 This can also be configured on a per-file basis by adding one of
199 the following lines anywhere in the buffer:
201 #+STARTUP: fold
202 #+STARTUP: nofold
203 #+STARTUP: content"
204 :group 'org-startup
205 :type '(choice
206 (const :tag "nofold: show all" nil)
207 (const :tag "fold: overview" t)
208 (const :tag "content: all headlines" content)))
210 (defcustom org-startup-truncated t
211 "Non-nil means, entering Org-mode will set `truncate-lines'.
212 This is useful since some lines containing links can be very long and
213 uninteresting. Also tables look terrible when wrapped."
214 :group 'org-startup
215 :type 'boolean)
217 (defcustom org-startup-align-all-tables nil
218 "Non-nil means, align all tables when visiting a file.
219 This is useful when the column width in tables is forced with <N> cookies
220 in table fields. Such tables will look correct only after the first re-align.
221 This can also be configured on a per-file basis by adding one of
222 the following lines anywhere in the buffer:
223 #+STARTUP: align
224 #+STARTUP: noalign"
225 :group 'org-startup
226 :type 'boolean)
228 (defcustom org-insert-mode-line-in-empty-file nil
229 "Non-nil means insert the first line setting Org-mode in empty files.
230 When the function `org-mode' is called interactively in an empty file, this
231 normally means that the file name does not automatically trigger Org-mode.
232 To ensure that the file will always be in Org-mode in the future, a
233 line enforcing Org-mode will be inserted into the buffer, if this option
234 has been set."
235 :group 'org-startup
236 :type 'boolean)
238 (defcustom org-replace-disputed-keys nil
239 "Non-nil means use alternative key bindings for some keys.
240 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
241 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
242 If you want to use Org-mode together with one of these other modes,
243 or more generally if you would like to move some Org-mode commands to
244 other keys, set this variable and configure the keys with the variable
245 `org-disputed-keys'.
247 This option is only relevant at load-time of Org-mode, and must be set
248 *before* org.el is loaded. Changing it requires a restart of Emacs to
249 become effective."
250 :group 'org-startup
251 :type 'boolean)
253 (if (fboundp 'defvaralias)
254 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
256 (defcustom org-disputed-keys
257 '(([(shift up)] . [(meta p)])
258 ([(shift down)] . [(meta n)])
259 ([(shift left)] . [(meta -)])
260 ([(shift right)] . [(meta +)])
261 ([(control shift right)] . [(meta shift +)])
262 ([(control shift left)] . [(meta shift -)]))
263 "Keys for which Org-mode and other modes compete.
264 This is an alist, cars are the default keys, second element specifies
265 the alternative to use when `org-replace-disputed-keys' is t.
267 Keys can be specified in any syntax supported by `define-key'.
268 The value of this option takes effect only at Org-mode's startup,
269 therefore you'll have to restart Emacs to apply it after changing."
270 :group 'org-startup
271 :type 'alist)
273 (defun org-key (key)
274 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
275 Or return the original if not disputed."
276 (if org-replace-disputed-keys
277 (let* ((nkey (key-description key))
278 (x (org-find-if (lambda (x)
279 (equal (key-description (car x)) nkey))
280 org-disputed-keys)))
281 (if x (cdr x) key))
282 key))
284 (defun org-find-if (predicate seq)
285 (catch 'exit
286 (while seq
287 (if (funcall predicate (car seq))
288 (throw 'exit (car seq))
289 (pop seq)))))
291 (defun org-defkey (keymap key def)
292 "Define a key, possibly translated, as returned by `org-key'."
293 (define-key keymap (org-key key) def))
295 (defcustom org-ellipsis nil
296 "The ellipsis to use in the Org-mode outline.
297 When nil, just use the standard three dots. When a string, use that instead,
298 When a face, use the standart 3 dots, but with the specified face.
299 The change affects only Org-mode (which will then use its own display table).
300 Changing this requires executing `M-x org-mode' in a buffer to become
301 effective."
302 :group 'org-startup
303 :type '(choice (const :tag "Default" nil)
304 (face :tag "Face" :value org-warning)
305 (string :tag "String" :value "...#")))
307 (defvar org-display-table nil
308 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
310 (defgroup org-keywords nil
311 "Keywords in Org-mode."
312 :tag "Org Keywords"
313 :group 'org)
315 (defcustom org-deadline-string "DEADLINE:"
316 "String to mark deadline entries.
317 A deadline is this string, followed by a time stamp. Should be a word,
318 terminated by a colon. You can insert a schedule keyword and
319 a timestamp with \\[org-deadline].
320 Changes become only effective after restarting Emacs."
321 :group 'org-keywords
322 :type 'string)
324 (defcustom org-scheduled-string "SCHEDULED:"
325 "String to mark scheduled TODO entries.
326 A schedule is this string, followed by a time stamp. Should be a word,
327 terminated by a colon. You can insert a schedule keyword and
328 a timestamp with \\[org-schedule].
329 Changes become only effective after restarting Emacs."
330 :group 'org-keywords
331 :type 'string)
333 (defcustom org-closed-string "CLOSED:"
334 "String used as the prefix for timestamps logging closing a TODO entry."
335 :group 'org-keywords
336 :type 'string)
338 (defcustom org-clock-string "CLOCK:"
339 "String used as prefix for timestamps clocking work hours on an item."
340 :group 'org-keywords
341 :type 'string)
343 (defcustom org-comment-string "COMMENT"
344 "Entries starting with this keyword will never be exported.
345 An entry can be toggled between COMMENT and normal with
346 \\[org-toggle-comment].
347 Changes become only effective after restarting Emacs."
348 :group 'org-keywords
349 :type 'string)
351 (defcustom org-quote-string "QUOTE"
352 "Entries starting with this keyword will be exported in fixed-width font.
353 Quoting applies only to the text in the entry following the headline, and does
354 not extend beyond the next headline, even if that is lower level.
355 An entry can be toggled between QUOTE and normal with
356 \\[org-toggle-fixed-width-section]."
357 :group 'org-keywords
358 :type 'string)
360 (defconst org-repeat-re
361 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
362 "Regular expression for specifying repeated events.
363 After a match, group 1 contains the repeat expression.")
365 (defgroup org-structure nil
366 "Options concerning the general structure of Org-mode files."
367 :tag "Org Structure"
368 :group 'org)
370 (defgroup org-reveal-location nil
371 "Options about how to make context of a location visible."
372 :tag "Org Reveal Location"
373 :group 'org-structure)
375 (defconst org-context-choice
376 '(choice
377 (const :tag "Always" t)
378 (const :tag "Never" nil)
379 (repeat :greedy t :tag "Individual contexts"
380 (cons
381 (choice :tag "Context"
382 (const agenda)
383 (const org-goto)
384 (const occur-tree)
385 (const tags-tree)
386 (const link-search)
387 (const mark-goto)
388 (const bookmark-jump)
389 (const isearch)
390 (const default))
391 (boolean))))
392 "Contexts for the reveal options.")
394 (defcustom org-show-hierarchy-above '((default . t))
395 "Non-nil means, show full hierarchy when revealing a location.
396 Org-mode often shows locations in an org-mode file which might have
397 been invisible before. When this is set, the hierarchy of headings
398 above the exposed location is shown.
399 Turning this off for example for sparse trees makes them very compact.
400 Instead of t, this can also be an alist specifying this option for different
401 contexts. Valid contexts are
402 agenda when exposing an entry from the agenda
403 org-goto when using the command `org-goto' on key C-c C-j
404 occur-tree when using the command `org-occur' on key C-c /
405 tags-tree when constructing a sparse tree based on tags matches
406 link-search when exposing search matches associated with a link
407 mark-goto when exposing the jump goal of a mark
408 bookmark-jump when exposing a bookmark location
409 isearch when exiting from an incremental search
410 default default for all contexts not set explicitly"
411 :group 'org-reveal-location
412 :type org-context-choice)
414 (defcustom org-show-following-heading '((default . nil))
415 "Non-nil means, show following heading when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the heading following the
418 match is shown.
419 Turning this off for example for sparse trees makes them very compact,
420 but makes it harder to edit the location of the match. In such a case,
421 use the command \\[org-reveal] to show more context.
422 Instead of t, this can also be an alist specifying this option for different
423 contexts. See `org-show-hierarchy-above' for valid contexts."
424 :group 'org-reveal-location
425 :type org-context-choice)
427 (defcustom org-show-siblings '((default . nil) (isearch t))
428 "Non-nil means, show all sibling heading when revealing a location.
429 Org-mode often shows locations in an org-mode file which might have
430 been invisible before. When this is set, the sibling of the current entry
431 heading are all made visible. If `org-show-hierarchy-above' is t,
432 the same happens on each level of the hierarchy above the current entry.
434 By default this is on for the isearch context, off for all other contexts.
435 Turning this off for example for sparse trees makes them very compact,
436 but makes it harder to edit the location of the match. In such a case,
437 use the command \\[org-reveal] to show more context.
438 Instead of t, this can also be an alist specifying this option for different
439 contexts. See `org-show-hierarchy-above' for valid contexts."
440 :group 'org-reveal-location
441 :type org-context-choice)
443 (defcustom org-show-entry-below '((default . nil))
444 "Non-nil means, show the entry below a headline when revealing a location.
445 Org-mode often shows locations in an org-mode file which might have
446 been invisible before. When this is set, the text below the headline that is
447 exposed is also shown.
449 By default this is off for all contexts.
450 Instead of t, this can also be an alist specifying this option for different
451 contexts. See `org-show-hierarchy-above' for valid contexts."
452 :group 'org-reveal-location
453 :type org-context-choice)
455 (defcustom org-indirect-buffer-display 'other-window
456 "How should indirect tree buffers be displayed?
457 This applies to indirect buffers created with the commands
458 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
459 Valid values are:
460 current-window Display in the current window
461 other-window Just display in another window.
462 dedicated-frame Create one new frame, and re-use it each time.
463 new-frame Make a new frame each time. Note that in this case
464 previously-made indirect buffers are kept, and you need to
465 kill these buffers yourself."
466 :group 'org-structure
467 :group 'org-agenda-windows
468 :type '(choice
469 (const :tag "In current window" current-window)
470 (const :tag "In current frame, other window" other-window)
471 (const :tag "Each time a new frame" new-frame)
472 (const :tag "One dedicated frame" dedicated-frame)))
474 (defgroup org-cycle nil
475 "Options concerning visibility cycling in Org-mode."
476 :tag "Org Cycle"
477 :group 'org-structure)
479 (defcustom org-drawers '("PROPERTIES" "CLOCK")
480 "Names of drawers. Drawers are not opened by cycling on the headline above.
481 Drawers only open with a TAB on the drawer line itself. A drawer looks like
482 this:
483 :DRAWERNAME:
484 .....
485 :END:
486 The drawer \"PROPERTIES\" is special for capturing properties through
487 the property API.
489 Drawers can be defined on the per-file basis with a line like:
491 #+DRAWERS: HIDDEN STATE PROPERTIES"
492 :group 'org-structure
493 :type '(repeat (string :tag "Drawer Name")))
495 (defcustom org-cycle-global-at-bob nil
496 "Cycle globally if cursor is at beginning of buffer and not at a headline.
497 This makes it possible to do global cycling without having to use S-TAB or
498 C-u TAB. For this special case to work, the first line of the buffer
499 must not be a headline - it may be empty ot some other text. When used in
500 this way, `org-cycle-hook' is disables temporarily, to make sure the
501 cursor stays at the beginning of the buffer.
502 When this option is nil, don't do anything special at the beginning
503 of the buffer."
504 :group 'org-cycle
505 :type 'boolean)
507 (defcustom org-cycle-emulate-tab t
508 "Where should `org-cycle' emulate TAB.
509 nil Never
510 white Only in completely white lines
511 whitestart Only at the beginning of lines, before the first non-white char
512 t Everywhere except in headlines
513 exc-hl-bol Everywhere except at the start of a headline
514 If TAB is used in a place where it does not emulate TAB, the current subtree
515 visibility is cycled."
516 :group 'org-cycle
517 :type '(choice (const :tag "Never" nil)
518 (const :tag "Only in completely white lines" white)
519 (const :tag "Before first char in a line" whitestart)
520 (const :tag "Everywhere except in headlines" t)
521 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
524 (defcustom org-cycle-separator-lines 2
525 "Number of empty lines needed to keep an empty line between collapsed trees.
526 If you leave an empty line between the end of a subtree and the following
527 headline, this empty line is hidden when the subtree is folded.
528 Org-mode will leave (exactly) one empty line visible if the number of
529 empty lines is equal or larger to the number given in this variable.
530 So the default 2 means, at least 2 empty lines after the end of a subtree
531 are needed to produce free space between a collapsed subtree and the
532 following headline.
534 Special case: when 0, never leave empty lines in collapsed view."
535 :group 'org-cycle
536 :type 'integer)
538 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
539 org-cycle-hide-drawers
540 org-cycle-show-empty-lines
541 org-optimize-window-after-visibility-change)
542 "Hook that is run after `org-cycle' has changed the buffer visibility.
543 The function(s) in this hook must accept a single argument which indicates
544 the new state that was set by the most recent `org-cycle' command. The
545 argument is a symbol. After a global state change, it can have the values
546 `overview', `content', or `all'. After a local state change, it can have
547 the values `folded', `children', or `subtree'."
548 :group 'org-cycle
549 :type 'hook)
551 (defgroup org-edit-structure nil
552 "Options concerning structure editing in Org-mode."
553 :tag "Org Edit Structure"
554 :group 'org-structure)
556 (defcustom org-odd-levels-only nil
557 "Non-nil means, skip even levels and only use odd levels for the outline.
558 This has the effect that two stars are being added/taken away in
559 promotion/demotion commands. It also influences how levels are
560 handled by the exporters.
561 Changing it requires restart of `font-lock-mode' to become effective
562 for fontification also in regions already fontified.
563 You may also set this on a per-file basis by adding one of the following
564 lines to the buffer:
566 #+STARTUP: odd
567 #+STARTUP: oddeven"
568 :group 'org-edit-structure
569 :group 'org-font-lock
570 :type 'boolean)
572 (defcustom org-adapt-indentation t
573 "Non-nil means, adapt indentation when promoting and demoting.
574 When this is set and the *entire* text in an entry is indented, the
575 indentation is increased by one space in a demotion command, and
576 decreased by one in a promotion command. If any line in the entry
577 body starts at column 0, indentation is not changed at all."
578 :group 'org-edit-structure
579 :type 'boolean)
581 (defcustom org-special-ctrl-a/e nil
582 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
583 When t, `C-a' will bring back the cursor to the beginning of the
584 headline text, i.e. after the stars and after a possible TODO keyword.
585 In an item, this will be the position after the bullet.
586 When the cursor is already at that position, another `C-a' will bring
587 it to the beginning of the line.
588 `C-e' will jump to the end of the headline, ignoring the presence of tags
589 in the headline. A second `C-e' will then jump to the true end of the
590 line, after any tags.
591 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
592 and only a directly following, identical keypress will bring the cursor
593 to the special positions."
594 :group 'org-edit-structure
595 :type '(choice
596 (const :tag "off" nil)
597 (const :tag "after bullet first" t)
598 (const :tag "border first" reversed)))
600 (if (fboundp 'defvaralias)
601 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
603 (defcustom org-special-ctrl-k nil
604 "Non-nil means `C-k' will behave specially in headlines.
605 When nil, `C-k' will call the default `kill-line' command.
606 When t, the following will happen while the cursor is in the headline:
608 - When the cursor is at the beginning of a headline, kill the entire
609 line and possible the folded subtree below the line.
610 - When in the middle of the headline text, kill the headline up to the tags.
611 - When after the headline text, kill the tags."
612 :group 'org-edit-structure
613 :type 'boolean)
615 (defcustom org-M-RET-may-split-line '((default . t))
616 "Non-nil means, M-RET will split the line at the cursor position.
617 When nil, it will go to the end of the line before making a
618 new line.
619 You may also set this option in a different way for different
620 contexts. Valid contexts are:
622 headline when creating a new headline
623 item when creating a new item
624 table in a table field
625 default the value to be used for all contexts not explicitly
626 customized"
627 :group 'org-structure
628 :group 'org-table
629 :type '(choice
630 (const :tag "Always" t)
631 (const :tag "Never" nil)
632 (repeat :greedy t :tag "Individual contexts"
633 (cons
634 (choice :tag "Context"
635 (const headline)
636 (const item)
637 (const table)
638 (const default))
639 (boolean)))))
642 (defcustom org-blank-before-new-entry '((heading . nil)
643 (plain-list-item . nil))
644 "Should `org-insert-heading' leave a blank line before new heading/item?
645 The value is an alist, with `heading' and `plain-list-item' as car,
646 and a boolean flag as cdr."
647 :group 'org-edit-structure
648 :type '(list
649 (cons (const heading) (boolean))
650 (cons (const plain-list-item) (boolean))))
652 (defcustom org-insert-heading-hook nil
653 "Hook being run after inserting a new heading."
654 :group 'org-edit-structure
655 :type 'hook)
657 (defcustom org-enable-fixed-width-editor t
658 "Non-nil means, lines starting with \":\" are treated as fixed-width.
659 This currently only means, they are never auto-wrapped.
660 When nil, such lines will be treated like ordinary lines.
661 See also the QUOTE keyword."
662 :group 'org-edit-structure
663 :type 'boolean)
665 (defcustom org-goto-auto-isearch t
666 "Non-nil means, typing characters in org-goto starts incremental search."
667 :group 'org-edit-structure
668 :type 'boolean)
670 (defgroup org-sparse-trees nil
671 "Options concerning sparse trees in Org-mode."
672 :tag "Org Sparse Trees"
673 :group 'org-structure)
675 (defcustom org-highlight-sparse-tree-matches t
676 "Non-nil means, highlight all matches that define a sparse tree.
677 The highlights will automatically disappear the next time the buffer is
678 changed by an edit command."
679 :group 'org-sparse-trees
680 :type 'boolean)
682 (defcustom org-remove-highlights-with-change t
683 "Non-nil means, any change to the buffer will remove temporary highlights.
684 Such highlights are created by `org-occur' and `org-clock-display'.
685 When nil, `C-c C-c needs to be used to get rid of the highlights.
686 The highlights created by `org-preview-latex-fragment' always need
687 `C-c C-c' to be removed."
688 :group 'org-sparse-trees
689 :group 'org-time
690 :type 'boolean)
693 (defcustom org-occur-hook '(org-first-headline-recenter)
694 "Hook that is run after `org-occur' has constructed a sparse tree.
695 This can be used to recenter the window to show as much of the structure
696 as possible."
697 :group 'org-sparse-trees
698 :type 'hook)
700 (defgroup org-plain-lists nil
701 "Options concerning plain lists in Org-mode."
702 :tag "Org Plain lists"
703 :group 'org-structure)
705 (defcustom org-cycle-include-plain-lists nil
706 "Non-nil means, include plain lists into visibility cycling.
707 This means that during cycling, plain list items will *temporarily* be
708 interpreted as outline headlines with a level given by 1000+i where i is the
709 indentation of the bullet. In all other operations, plain list items are
710 not seen as headlines. For example, you cannot assign a TODO keyword to
711 such an item."
712 :group 'org-plain-lists
713 :type 'boolean)
715 (defcustom org-plain-list-ordered-item-terminator t
716 "The character that makes a line with leading number an ordered list item.
717 Valid values are ?. and ?\). To get both terminators, use t. While
718 ?. may look nicer, it creates the danger that a line with leading
719 number may be incorrectly interpreted as an item. ?\) therefore is
720 the safe choice."
721 :group 'org-plain-lists
722 :type '(choice (const :tag "dot like in \"2.\"" ?.)
723 (const :tag "paren like in \"2)\"" ?\))
724 (const :tab "both" t)))
726 (defcustom org-empty-line-terminates-plain-lists nil
727 "Non-nil means, an empty line ends all plain list levels.
728 When nil, empty lines are part of the preceeding item."
729 :group 'org-plain-lists
730 :type 'boolean)
732 (defcustom org-auto-renumber-ordered-lists t
733 "Non-nil means, automatically renumber ordered plain lists.
734 Renumbering happens when the sequence have been changed with
735 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
736 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
737 :group 'org-plain-lists
738 :type 'boolean)
740 (defcustom org-provide-checkbox-statistics t
741 "Non-nil means, update checkbox statistics after insert and toggle.
742 When this is set, checkbox statistics is updated each time you either insert
743 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
744 with \\[org-ctrl-c-ctrl-c\\]."
745 :group 'org-plain-lists
746 :type 'boolean)
749 (defgroup org-imenu-and-speedbar nil
750 "Options concerning imenu and speedbar in Org-mode."
751 :tag "Org Imenu and Speedbar"
752 :group 'org-structure)
754 (defcustom org-imenu-depth 2
755 "The maximum level for Imenu access to Org-mode headlines.
756 This also applied for speedbar access."
757 :group 'org-imenu-and-speedbar
758 :type 'number)
760 (defgroup org-table nil
761 "Options concerning tables in Org-mode."
762 :tag "Org Table"
763 :group 'org)
765 (defcustom org-enable-table-editor 'optimized
766 "Non-nil means, lines starting with \"|\" are handled by the table editor.
767 When nil, such lines will be treated like ordinary lines.
769 When equal to the symbol `optimized', the table editor will be optimized to
770 do the following:
771 - Automatic overwrite mode in front of whitespace in table fields.
772 This makes the structure of the table stay in tact as long as the edited
773 field does not exceed the column width.
774 - Minimize the number of realigns. Normally, the table is aligned each time
775 TAB or RET are pressed to move to another field. With optimization this
776 happens only if changes to a field might have changed the column width.
777 Optimization requires replacing the functions `self-insert-command',
778 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
779 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
780 very good at guessing when a re-align will be necessary, but you can always
781 force one with \\[org-ctrl-c-ctrl-c].
783 If you would like to use the optimized version in Org-mode, but the
784 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
786 This variable can be used to turn on and off the table editor during a session,
787 but in order to toggle optimization, a restart is required.
789 See also the variable `org-table-auto-blank-field'."
790 :group 'org-table
791 :type '(choice
792 (const :tag "off" nil)
793 (const :tag "on" t)
794 (const :tag "on, optimized" optimized)))
796 (defcustom org-table-tab-recognizes-table.el t
797 "Non-nil means, TAB will automatically notice a table.el table.
798 When it sees such a table, it moves point into it and - if necessary -
799 calls `table-recognize-table'."
800 :group 'org-table-editing
801 :type 'boolean)
803 (defgroup org-link nil
804 "Options concerning links in Org-mode."
805 :tag "Org Link"
806 :group 'org)
808 (defvar org-link-abbrev-alist-local nil
809 "Buffer-local version of `org-link-abbrev-alist', which see.
810 The value of this is taken from the #+LINK lines.")
811 (make-variable-buffer-local 'org-link-abbrev-alist-local)
813 (defcustom org-link-abbrev-alist nil
814 "Alist of link abbreviations.
815 The car of each element is a string, to be replaced at the start of a link.
816 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
817 links in Org-mode buffers can have an optional tag after a double colon, e.g.
819 [[linkkey:tag][description]]
821 If REPLACE is a string, the tag will simply be appended to create the link.
822 If the string contains \"%s\", the tag will be inserted there.
824 REPLACE may also be a function that will be called with the tag as the
825 only argument to create the link, which should be returned as a string.
827 See the manual for examples."
828 :group 'org-link
829 :type 'alist)
831 (defcustom org-descriptive-links t
832 "Non-nil means, hide link part and only show description of bracket links.
833 Bracket links are like [[link][descritpion]]. This variable sets the initial
834 state in new org-mode buffers. The setting can then be toggled on a
835 per-buffer basis from the Org->Hyperlinks menu."
836 :group 'org-link
837 :type 'boolean)
839 (defcustom org-link-file-path-type 'adaptive
840 "How the path name in file links should be stored.
841 Valid values are:
843 relative Relative to the current directory, i.e. the directory of the file
844 into which the link is being inserted.
845 absolute Absolute path, if possible with ~ for home directory.
846 noabbrev Absolute path, no abbreviation of home directory.
847 adaptive Use relative path for files in the current directory and sub-
848 directories of it. For other files, use an absolute path."
849 :group 'org-link
850 :type '(choice
851 (const relative)
852 (const absolute)
853 (const noabbrev)
854 (const adaptive)))
856 (defcustom org-activate-links '(bracket angle plain radio tag date)
857 "Types of links that should be activated in Org-mode files.
858 This is a list of symbols, each leading to the activation of a certain link
859 type. In principle, it does not hurt to turn on most link types - there may
860 be a small gain when turning off unused link types. The types are:
862 bracket The recommended [[link][description]] or [[link]] links with hiding.
863 angular Links in angular brackes that may contain whitespace like
864 <bbdb:Carsten Dominik>.
865 plain Plain links in normal text, no whitespace, like http://google.com.
866 radio Text that is matched by a radio target, see manual for details.
867 tag Tag settings in a headline (link to tag search).
868 date Time stamps (link to calendar).
870 Changing this variable requires a restart of Emacs to become effective."
871 :group 'org-link
872 :type '(set (const :tag "Double bracket links (new style)" bracket)
873 (const :tag "Angular bracket links (old style)" angular)
874 (const :tag "Plain text links" plain)
875 (const :tag "Radio target matches" radio)
876 (const :tag "Tags" tag)
877 (const :tag "Timestamps" date)))
879 (defcustom org-make-link-description-function nil
880 "Function to use to generate link descriptions from links. If
881 nil the link location will be used. This function must take two
882 parameters; the first is the link and the second the description
883 org-insert-link has generated, and should return the description
884 to use."
885 :group 'org-link
886 :type 'function)
888 (defgroup org-link-store nil
889 "Options concerning storing links in Org-mode."
890 :tag "Org Store Link"
891 :group 'org-link)
893 (defcustom org-email-link-description-format "Email %c: %.30s"
894 "Format of the description part of a link to an email or usenet message.
895 The following %-excapes will be replaced by corresponding information:
897 %F full \"From\" field
898 %f name, taken from \"From\" field, address if no name
899 %T full \"To\" field
900 %t first name in \"To\" field, address if no name
901 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
902 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
903 %s subject
904 %m message-id.
906 You may use normal field width specification between the % and the letter.
907 This is for example useful to limit the length of the subject.
909 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
910 :group 'org-link-store
911 :type 'string)
913 (defcustom org-from-is-user-regexp
914 (let (r1 r2)
915 (when (and user-mail-address (not (string= user-mail-address "")))
916 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
917 (when (and user-full-name (not (string= user-full-name "")))
918 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
919 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
920 "Regexp mached against the \"From:\" header of an email or usenet message.
921 It should match if the message is from the user him/herself."
922 :group 'org-link-store
923 :type 'regexp)
925 (defcustom org-context-in-file-links t
926 "Non-nil means, file links from `org-store-link' contain context.
927 A search string will be added to the file name with :: as separator and
928 used to find the context when the link is activated by the command
929 `org-open-at-point'.
930 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
931 negates this setting for the duration of the command."
932 :group 'org-link-store
933 :type 'boolean)
935 (defcustom org-keep-stored-link-after-insertion nil
936 "Non-nil means, keep link in list for entire session.
938 The command `org-store-link' adds a link pointing to the current
939 location to an internal list. These links accumulate during a session.
940 The command `org-insert-link' can be used to insert links into any
941 Org-mode file (offering completion for all stored links). When this
942 option is nil, every link which has been inserted once using \\[org-insert-link]
943 will be removed from the list, to make completing the unused links
944 more efficient."
945 :group 'org-link-store
946 :type 'boolean)
948 (defgroup org-link-follow nil
949 "Options concerning following links in Org-mode."
950 :tag "Org Follow Link"
951 :group 'org-link)
953 (defcustom org-follow-link-hook nil
954 "Hook that is run after a link has been followed."
955 :group 'org-link-follow
956 :type 'hook)
958 (defcustom org-tab-follows-link nil
959 "Non-nil means, on links TAB will follow the link.
960 Needs to be set before org.el is loaded."
961 :group 'org-link-follow
962 :type 'boolean)
964 (defcustom org-return-follows-link nil
965 "Non-nil means, on links RET will follow the link.
966 Needs to be set before org.el is loaded."
967 :group 'org-link-follow
968 :type 'boolean)
970 (defcustom org-mouse-1-follows-link
971 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
972 "Non-nil means, mouse-1 on a link will follow the link.
973 A longer mouse click will still set point. Does not work on XEmacs.
974 Needs to be set before org.el is loaded."
975 :group 'org-link-follow
976 :type 'boolean)
978 (defcustom org-mark-ring-length 4
979 "Number of different positions to be recorded in the ring
980 Changing this requires a restart of Emacs to work correctly."
981 :group 'org-link-follow
982 :type 'interger)
984 (defcustom org-link-frame-setup
985 '((vm . vm-visit-folder-other-frame)
986 (gnus . gnus-other-frame)
987 (file . find-file-other-window))
988 "Setup the frame configuration for following links.
989 When following a link with Emacs, it may often be useful to display
990 this link in another window or frame. This variable can be used to
991 set this up for the different types of links.
992 For VM, use any of
993 `vm-visit-folder'
994 `vm-visit-folder-other-frame'
995 For Gnus, use any of
996 `gnus'
997 `gnus-other-frame'
998 For FILE, use any of
999 `find-file'
1000 `find-file-other-window'
1001 `find-file-other-frame'
1002 For the calendar, use the variable `calendar-setup'.
1003 For BBDB, it is currently only possible to display the matches in
1004 another window."
1005 :group 'org-link-follow
1006 :type '(list
1007 (cons (const vm)
1008 (choice
1009 (const vm-visit-folder)
1010 (const vm-visit-folder-other-window)
1011 (const vm-visit-folder-other-frame)))
1012 (cons (const gnus)
1013 (choice
1014 (const gnus)
1015 (const gnus-other-frame)))
1016 (cons (const file)
1017 (choice
1018 (const find-file)
1019 (const find-file-other-window)
1020 (const find-file-other-frame)))))
1022 (defcustom org-display-internal-link-with-indirect-buffer nil
1023 "Non-nil means, use indirect buffer to display infile links.
1024 Activating internal links (from one location in a file to another location
1025 in the same file) normally just jumps to the location. When the link is
1026 activated with a C-u prefix (or with mouse-3), the link is displayed in
1027 another window. When this option is set, the other window actually displays
1028 an indirect buffer clone of the current buffer, to avoid any visibility
1029 changes to the current buffer."
1030 :group 'org-link-follow
1031 :type 'boolean)
1033 (defcustom org-open-non-existing-files nil
1034 "Non-nil means, `org-open-file' will open non-existing files.
1035 When nil, an error will be generated."
1036 :group 'org-link-follow
1037 :type 'boolean)
1039 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1040 "Function and arguments to call for following mailto links.
1041 This is a list with the first element being a lisp function, and the
1042 remaining elements being arguments to the function. In string arguments,
1043 %a will be replaced by the address, and %s will be replaced by the subject
1044 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1045 :group 'org-link-follow
1046 :type '(choice
1047 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1048 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1049 (const :tag "message-mail" (message-mail "%a" "%s"))
1050 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1052 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1053 "Non-nil means, ask for confirmation before executing shell links.
1054 Shell links can be dangerous: just think about a link
1056 [[shell:rm -rf ~/*][Google Search]]
1058 This link would show up in your Org-mode document as \"Google Search\",
1059 but really it would remove your entire home directory.
1060 Therefore we advise against setting this variable to nil.
1061 Just change it to `y-or-n-p' of you want to confirm with a
1062 single keystroke rather than having to type \"yes\"."
1063 :group 'org-link-follow
1064 :type '(choice
1065 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1066 (const :tag "with y-or-n (faster)" y-or-n-p)
1067 (const :tag "no confirmation (dangerous)" nil)))
1069 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1070 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1071 Elisp links can be dangerous: just think about a link
1073 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1075 This link would show up in your Org-mode document as \"Google Search\",
1076 but really it would remove your entire home directory.
1077 Therefore we advise against setting this variable to nil.
1078 Just change it to `y-or-n-p' of you want to confirm with a
1079 single keystroke rather than having to type \"yes\"."
1080 :group 'org-link-follow
1081 :type '(choice
1082 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1083 (const :tag "with y-or-n (faster)" y-or-n-p)
1084 (const :tag "no confirmation (dangerous)" nil)))
1086 (defconst org-file-apps-defaults-gnu
1087 '((remote . emacs)
1088 (t . mailcap))
1089 "Default file applications on a UNIX or GNU/Linux system.
1090 See `org-file-apps'.")
1092 (defconst org-file-apps-defaults-macosx
1093 '((remote . emacs)
1094 (t . "open %s")
1095 ("ps" . "gv %s")
1096 ("ps.gz" . "gv %s")
1097 ("eps" . "gv %s")
1098 ("eps.gz" . "gv %s")
1099 ("dvi" . "xdvi %s")
1100 ("fig" . "xfig %s"))
1101 "Default file applications on a MacOS X system.
1102 The system \"open\" is known as a default, but we use X11 applications
1103 for some files for which the OS does not have a good default.
1104 See `org-file-apps'.")
1106 (defconst org-file-apps-defaults-windowsnt
1107 (list
1108 '(remote . emacs)
1109 (cons t
1110 (list (if (featurep 'xemacs)
1111 'mswindows-shell-execute
1112 'w32-shell-execute)
1113 "open" 'file)))
1114 "Default file applications on a Windows NT system.
1115 The system \"open\" is used for most files.
1116 See `org-file-apps'.")
1118 (defcustom org-file-apps
1120 ("txt" . emacs)
1121 ("tex" . emacs)
1122 ("ltx" . emacs)
1123 ("org" . emacs)
1124 ("el" . emacs)
1125 ("bib" . emacs)
1127 "External applications for opening `file:path' items in a document.
1128 Org-mode uses system defaults for different file types, but
1129 you can use this variable to set the application for a given file
1130 extension. The entries in this list are cons cells where the car identifies
1131 files and the cdr the corresponding command. Possible values for the
1132 file identifier are
1133 \"ext\" A string identifying an extension
1134 `directory' Matches a directory
1135 `remote' Matches a remote file, accessible through tramp or efs.
1136 Remote files most likely should be visited through Emacs
1137 because external applications cannot handle such paths.
1138 t Default for all remaining files
1140 Possible values for the command are:
1141 `emacs' The file will be visited by the current Emacs process.
1142 `default' Use the default application for this file type.
1143 string A command to be executed by a shell; %s will be replaced
1144 by the path to the file.
1145 sexp A Lisp form which will be evaluated. The file path will
1146 be available in the Lisp variable `file'.
1147 For more examples, see the system specific constants
1148 `org-file-apps-defaults-macosx'
1149 `org-file-apps-defaults-windowsnt'
1150 `org-file-apps-defaults-gnu'."
1151 :group 'org-link-follow
1152 :type '(repeat
1153 (cons (choice :value ""
1154 (string :tag "Extension")
1155 (const :tag "Default for unrecognized files" t)
1156 (const :tag "Remote file" remote)
1157 (const :tag "Links to a directory" directory))
1158 (choice :value ""
1159 (const :tag "Visit with Emacs" emacs)
1160 (const :tag "Use system default" default)
1161 (string :tag "Command")
1162 (sexp :tag "Lisp form")))))
1164 (defgroup org-refile nil
1165 "Options concerning refiling entries in Org-mode."
1166 :tag "Org Remember"
1167 :group 'org)
1169 (defcustom org-directory "~/org"
1170 "Directory with org files.
1171 This directory will be used as default to prompt for org files.
1172 Used by the hooks for remember.el."
1173 :group 'org-refile
1174 :group 'org-remember
1175 :type 'directory)
1177 (defcustom org-default-notes-file "~/.notes"
1178 "Default target for storing notes.
1179 Used by the hooks for remember.el. This can be a string, or nil to mean
1180 the value of `remember-data-file'.
1181 You can set this on a per-template basis with the variable
1182 `org-remember-templates'."
1183 :group 'org-refile
1184 :group 'org-remember
1185 :type '(choice
1186 (const :tag "Default from remember-data-file" nil)
1187 file))
1189 (defcustom org-goto-interface 'outline
1190 "The default interface to be used for `org-goto'.
1191 Allowed vaues are:
1192 outline The interface shows an outline of the relevant file
1193 and the correct heading is found by moving through
1194 the outline or by searching with incremental search.
1195 outline-path-completion Headlines in the current buffer are offered via
1196 completion."
1197 :group 'org-refile
1198 :type '(choice
1199 (const :tag "Outline" outline)
1200 (const :tag "Outline-path-completion" outline-path-completion)))
1202 (defcustom org-reverse-note-order nil
1203 "Non-nil means, store new notes at the beginning of a file or entry.
1204 When nil, new notes will be filed to the end of a file or entry.
1205 This can also be a list with cons cells of regular expressions that
1206 are matched against file names, and values."
1207 :group 'org-remember
1208 :type '(choice
1209 (const :tag "Reverse always" t)
1210 (const :tag "Reverse never" nil)
1211 (repeat :tag "By file name regexp"
1212 (cons regexp boolean))))
1214 (defcustom org-refile-targets nil
1215 "Targets for refiling entries with \\[org-refile].
1216 This is list of cons cells. Each cell contains:
1217 - a specification of the files to be considered, either a list of files,
1218 or a symbol whose function or variable value will be used to retrieve
1219 a file name or a list of file names. Nil means, refile to a different
1220 heading in the current buffer.
1221 - A specification of how to find candidate refile targets. This may be
1222 any of
1223 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1224 This tag has to be present in all target headlines, inheritance will
1225 not be considered.
1226 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1227 todo keyword.
1228 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1229 headlines that are refiling targets.
1230 - a cons cell (:level . N). Any headline of level N is considered a target.
1231 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1232 :group 'org-remember
1233 :type '(repeat
1234 (cons
1235 (choice :value org-agenda-files
1236 (const :tag "All agenda files" org-agenda-files)
1237 (const :tag "Current buffer" nil)
1238 (function) (variable) (file))
1239 (choice :tag "Identify target headline by"
1240 (cons :tag "Specific tag" (const :tag) (string))
1241 (cons :tag "TODO keyword" (const :todo) (string))
1242 (cons :tag "Regular expression" (const :regexp) (regexp))
1243 (cons :tag "Level number" (const :level) (integer))
1244 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1246 (defcustom org-refile-use-outline-path nil
1247 "Non-nil means, provide refile targets as paths.
1248 So a level 3 headline will be available as level1/level2/level3.
1249 When the value is `file', also include the file name (without directory)
1250 into the path. When `full-file-path', include the full file path."
1251 :group 'org-remember
1252 :type '(choice
1253 (const :tag "Not" nil)
1254 (const :tag "Yes" t)
1255 (const :tag "Start with file name" file)
1256 (const :tag "Start with full file path" full-file-path)))
1258 (defgroup org-todo nil
1259 "Options concerning TODO items in Org-mode."
1260 :tag "Org TODO"
1261 :group 'org)
1263 (defgroup org-progress nil
1264 "Options concerning Progress logging in Org-mode."
1265 :tag "Org Progress"
1266 :group 'org-time)
1268 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1269 "List of TODO entry keyword sequences and their interpretation.
1270 \\<org-mode-map>This is a list of sequences.
1272 Each sequence starts with a symbol, either `sequence' or `type',
1273 indicating if the keywords should be interpreted as a sequence of
1274 action steps, or as different types of TODO items. The first
1275 keywords are states requiring action - these states will select a headline
1276 for inclusion into the global TODO list Org-mode produces. If one of
1277 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1278 signify that no further action is necessary. If \"|\" is not found,
1279 the last keyword is treated as the only DONE state of the sequence.
1281 The command \\[org-todo] cycles an entry through these states, and one
1282 additional state where no keyword is present. For details about this
1283 cycling, see the manual.
1285 TODO keywords and interpretation can also be set on a per-file basis with
1286 the special #+SEQ_TODO and #+TYP_TODO lines.
1288 Each keyword can optionally specify a character for fast state selection
1289 \(in combination with the variable `org-use-fast-todo-selection')
1290 and specifiers for state change logging, using the same syntax
1291 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1292 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1293 indicates to record a time stamp each time this state is selected.
1295 Each keyword may also specify if a timestamp or a note should be
1296 recorded when entering or leaving the state, by adding additional
1297 characters in the parenthesis after the keyword. This looks like this:
1298 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1299 record only the time of the state change. With X and Y being either
1300 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1301 Y when leaving the state if and only if the *target* state does not
1302 define X. You may omit any of the fast-selection key or X or /Y,
1303 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1305 For backward compatibility, this variable may also be just a list
1306 of keywords - in this case the interptetation (sequence or type) will be
1307 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1308 :group 'org-todo
1309 :group 'org-keywords
1310 :type '(choice
1311 (repeat :tag "Old syntax, just keywords"
1312 (string :tag "Keyword"))
1313 (repeat :tag "New syntax"
1314 (cons
1315 (choice
1316 :tag "Interpretation"
1317 (const :tag "Sequence (cycling hits every state)" sequence)
1318 (const :tag "Type (cycling directly to DONE)" type))
1319 (repeat
1320 (string :tag "Keyword"))))))
1322 (defvar org-todo-keywords-1 nil
1323 "All TODO and DONE keywords active in a buffer.")
1324 (make-variable-buffer-local 'org-todo-keywords-1)
1325 (defvar org-todo-keywords-for-agenda nil)
1326 (defvar org-done-keywords-for-agenda nil)
1327 (defvar org-not-done-keywords nil)
1328 (make-variable-buffer-local 'org-not-done-keywords)
1329 (defvar org-done-keywords nil)
1330 (make-variable-buffer-local 'org-done-keywords)
1331 (defvar org-todo-heads nil)
1332 (make-variable-buffer-local 'org-todo-heads)
1333 (defvar org-todo-sets nil)
1334 (make-variable-buffer-local 'org-todo-sets)
1335 (defvar org-todo-log-states nil)
1336 (make-variable-buffer-local 'org-todo-log-states)
1337 (defvar org-todo-kwd-alist nil)
1338 (make-variable-buffer-local 'org-todo-kwd-alist)
1339 (defvar org-todo-key-alist nil)
1340 (make-variable-buffer-local 'org-todo-key-alist)
1341 (defvar org-todo-key-trigger nil)
1342 (make-variable-buffer-local 'org-todo-key-trigger)
1344 (defcustom org-todo-interpretation 'sequence
1345 "Controls how TODO keywords are interpreted.
1346 This variable is in principle obsolete and is only used for
1347 backward compatibility, if the interpretation of todo keywords is
1348 not given already in `org-todo-keywords'. See that variable for
1349 more information."
1350 :group 'org-todo
1351 :group 'org-keywords
1352 :type '(choice (const sequence)
1353 (const type)))
1355 (defcustom org-use-fast-todo-selection 'prefix
1356 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1357 This variable describes if and under what circumstances the cycling
1358 mechanism for TODO keywords will be replaced by a single-key, direct
1359 selection scheme.
1361 When nil, fast selection is never used.
1363 When the symbol `prefix', it will be used when `org-todo' is called with
1364 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1365 in an agenda buffer.
1367 When t, fast selection is used by default. In this case, the prefix
1368 argument forces cycling instead.
1370 In all cases, the special interface is only used if access keys have actually
1371 been assigned by the user, i.e. if keywords in the configuration are followed
1372 by a letter in parenthesis, like TODO(t)."
1373 :group 'org-todo
1374 :type '(choice
1375 (const :tag "Never" nil)
1376 (const :tag "By default" t)
1377 (const :tag "Only with C-u C-c C-t" prefix)))
1379 (defcustom org-after-todo-state-change-hook nil
1380 "Hook which is run after the state of a TODO item was changed.
1381 The new state (a string with a TODO keyword, or nil) is available in the
1382 Lisp variable `state'."
1383 :group 'org-todo
1384 :type 'hook)
1386 (defcustom org-log-done nil
1387 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1388 When equal to the list (done), also prompt for a closing note.
1389 This can also be configured on a per-file basis by adding one of
1390 the following lines anywhere in the buffer:
1392 #+STARTUP: logdone
1393 #+STARTUP: lognotedone
1394 #+STARTUP: nologdone"
1395 :group 'org-todo
1396 :group 'org-progress
1397 :type '(choice
1398 (const :tag "No logging" nil)
1399 (const :tag "Record CLOSED timestamp" time)
1400 (const :tag "Record CLOSED timestamp with closing note." note)))
1402 ;; Normalize old uses of org-log-done.
1403 (cond
1404 ((eq org-log-done t) (setq org-log-done 'time))
1405 ((and (listp org-log-done) (memq 'done org-log-done))
1406 (setq org-log-done 'note)))
1408 (defcustom org-log-note-clock-out nil
1409 "Non-nil means, recored a note when clocking out of an item.
1410 This can also be configured on a per-file basis by adding one of
1411 the following lines anywhere in the buffer:
1413 #+STARTUP: lognoteclock-out
1414 #+STARTUP: nolognoteclock-out"
1415 :group 'org-todo
1416 :group 'org-progress
1417 :type 'boolean)
1419 (defcustom org-log-done-with-time t
1420 "Non-nil means, the CLOSED time stamp will contain date and time.
1421 When nil, only the date will be recorded."
1422 :group 'org-progress
1423 :type 'boolean)
1425 (defcustom org-log-note-headings
1426 '((done . "CLOSING NOTE %t")
1427 (state . "State %-12s %t")
1428 (note . "Note taken on %t")
1429 (clock-out . ""))
1430 "Headings for notes added to entries.
1431 The value is an alist, with the car being a symbol indicating the note
1432 context, and the cdr is the heading to be used. The heading may also be the
1433 empty string.
1434 %t in the heading will be replaced by a time stamp.
1435 %s will be replaced by the new TODO state, in double quotes.
1436 %u will be replaced by the user name.
1437 %U will be replaced by the full user name."
1438 :group 'org-todo
1439 :group 'org-progress
1440 :type '(list :greedy t
1441 (cons (const :tag "Heading when closing an item" done) string)
1442 (cons (const :tag
1443 "Heading when changing todo state (todo sequence only)"
1444 state) string)
1445 (cons (const :tag "Heading when just taking a note" note) string)
1446 (cons (const :tag "Heading when clocking out" clock-out) string)))
1448 (unless (assq 'note org-log-note-headings)
1449 (push '(note . "%t") org-log-note-headings))
1451 (defcustom org-log-states-order-reversed t
1452 "Non-nil means, the latest state change note will be directly after heading.
1453 When nil, the notes will be orderer according to time."
1454 :group 'org-todo
1455 :group 'org-progress
1456 :type 'boolean)
1458 (defcustom org-log-repeat 'time
1459 "Non-nil means, record moving through the DONE state when triggering repeat.
1460 An auto-repeating tasks is immediately switched back to TODO when marked
1461 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1462 the TODO keyword definition, or recording a cloing note by setting
1463 `org-log-done', there will be no record of the task moving trhough DONE.
1464 This variable forces taking a note anyway. Possible values are:
1466 nil Don't force a record
1467 time Record a time stamp
1468 note Record a note
1470 This option can also be set with on a per-file-basis with
1472 #+STARTUP: logrepeat
1473 #+STARTUP: lognoterepeat
1474 #+STARTUP: nologrepeat
1476 You can have local logging settings for a subtree by setting the LOGGING
1477 property to one or more of these keywords."
1478 :group 'org-todo
1479 :group 'org-progress
1480 :type '(choice
1481 (const :tag "Don't force a record" nil)
1482 (const :tag "Force recording the DONE state" time)
1483 (const :tag "Force recording a note with the DONE state" note)))
1486 (defgroup org-priorities nil
1487 "Priorities in Org-mode."
1488 :tag "Org Priorities"
1489 :group 'org-todo)
1491 (defcustom org-highest-priority ?A
1492 "The highest priority of TODO items. A character like ?A, ?B etc.
1493 Must have a smaller ASCII number than `org-lowest-priority'."
1494 :group 'org-priorities
1495 :type 'character)
1497 (defcustom org-lowest-priority ?C
1498 "The lowest priority of TODO items. A character like ?A, ?B etc.
1499 Must have a larger ASCII number than `org-highest-priority'."
1500 :group 'org-priorities
1501 :type 'character)
1503 (defcustom org-default-priority ?B
1504 "The default priority of TODO items.
1505 This is the priority an item get if no explicit priority is given."
1506 :group 'org-priorities
1507 :type 'character)
1509 (defcustom org-priority-start-cycle-with-default t
1510 "Non-nil means, start with default priority when starting to cycle.
1511 When this is nil, the first step in the cycle will be (depending on the
1512 command used) one higher or lower that the default priority."
1513 :group 'org-priorities
1514 :type 'boolean)
1516 (defgroup org-time nil
1517 "Options concerning time stamps and deadlines in Org-mode."
1518 :tag "Org Time"
1519 :group 'org)
1521 (defcustom org-insert-labeled-timestamps-at-point nil
1522 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1523 When nil, these labeled time stamps are forces into the second line of an
1524 entry, just after the headline. When scheduling from the global TODO list,
1525 the time stamp will always be forced into the second line."
1526 :group 'org-time
1527 :type 'boolean)
1529 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1530 "Formats for `format-time-string' which are used for time stamps.
1531 It is not recommended to change this constant.")
1533 (defcustom org-time-stamp-rounding-minutes '(0 5)
1534 "Number of minutes to round time stamps to.
1535 These are two values, the first applies when first creating a time stamp.
1536 The second applies when changing it with the commands `S-up' and `S-down'.
1537 When changing the time stamp, this means that it will change in steps
1538 of N minutes, as given by the second value.
1540 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1541 numbers should be factors of 60, so for example 5, 10, 15.
1543 When this is larger than 1, you can still force an exact time-stamp by using
1544 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1545 and by using a prefix arg to `S-up/down' to specify the exact number
1546 of minutes to shift."
1547 :group 'org-time
1548 :get '(lambda (var) ; Make sure all entries have 5 elements
1549 (if (integerp (default-value var))
1550 (list (default-value var) 5)
1551 (default-value var)))
1552 :type '(list
1553 (integer :tag "when inserting times")
1554 (integer :tag "when modifying times")))
1556 ;; Normalize old customizations of this variable.
1557 (when (integerp org-time-stamp-rounding-minutes)
1558 (setq org-time-stamp-rounding-minutes
1559 (list org-time-stamp-rounding-minutes
1560 org-time-stamp-rounding-minutes)))
1562 (defcustom org-display-custom-times nil
1563 "Non-nil means, overlay custom formats over all time stamps.
1564 The formats are defined through the variable `org-time-stamp-custom-formats'.
1565 To turn this on on a per-file basis, insert anywhere in the file:
1566 #+STARTUP: customtime"
1567 :group 'org-time
1568 :set 'set-default
1569 :type 'sexp)
1570 (make-variable-buffer-local 'org-display-custom-times)
1572 (defcustom org-time-stamp-custom-formats
1573 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1574 "Custom formats for time stamps. See `format-time-string' for the syntax.
1575 These are overlayed over the default ISO format if the variable
1576 `org-display-custom-times' is set. Time like %H:%M should be at the
1577 end of the second format."
1578 :group 'org-time
1579 :type 'sexp)
1581 (defun org-time-stamp-format (&optional long inactive)
1582 "Get the right format for a time string."
1583 (let ((f (if long (cdr org-time-stamp-formats)
1584 (car org-time-stamp-formats))))
1585 (if inactive
1586 (concat "[" (substring f 1 -1) "]")
1587 f)))
1589 (defcustom org-deadline-warning-days 14
1590 "No. of days before expiration during which a deadline becomes active.
1591 This variable governs the display in sparse trees and in the agenda.
1592 When 0 or negative, it means use this number (the absolute value of it)
1593 even if a deadline has a different individual lead time specified."
1594 :group 'org-time
1595 :group 'org-agenda-daily/weekly
1596 :type 'number)
1598 (defcustom org-read-date-prefer-future t
1599 "Non-nil means, assume future for incomplete date input from user.
1600 This affects the following situations:
1601 1. The user gives a day, but no month.
1602 For example, if today is the 15th, and you enter \"3\", Org-mode will
1603 read this as the third of *next* month. However, if you enter \"17\",
1604 it will be considered as *this* month.
1605 2. The user gives a month but not a year.
1606 For example, if it is april and you enter \"feb 2\", this will be read
1607 as feb 2, *next* year. \"May 5\", however, will be this year.
1609 Currently this does not work for ISO week specifications.
1611 When this option is nil, the current month and year will always be used
1612 as defaults."
1613 :group 'org-time
1614 :type 'boolean)
1616 (defcustom org-read-date-display-live t
1617 "Non-nil means, display current interpretation of date prompt live.
1618 This display will be in an overlay, in the minibuffer."
1619 :group 'org-time
1620 :type 'boolean)
1622 (defcustom org-read-date-popup-calendar t
1623 "Non-nil means, pop up a calendar when prompting for a date.
1624 In the calendar, the date can be selected with mouse-1. However, the
1625 minibuffer will also be active, and you can simply enter the date as well.
1626 When nil, only the minibuffer will be available."
1627 :group 'org-time
1628 :type 'boolean)
1629 (if (fboundp 'defvaralias)
1630 (defvaralias 'org-popup-calendar-for-date-prompt
1631 'org-read-date-popup-calendar))
1633 (defcustom org-extend-today-until 0
1634 "The hour when your day really ends.
1635 This has influence for the following applications:
1636 - When switching the agenda to \"today\". It it is still earlier than
1637 the time given here, the day recognized as TODAY is actually yesterday.
1638 - When a date is read from the user and it is still before the time given
1639 here, the current date and time will be assumed to be yesterday, 23:59.
1641 FIXME:
1642 IMPORTANT: This is still a very experimental feature, it may disappear
1643 again or it may be extended to mean more things."
1644 :group 'org-time
1645 :type 'number)
1647 (defcustom org-edit-timestamp-down-means-later nil
1648 "Non-nil means, S-down will increase the time in a time stamp.
1649 When nil, S-up will increase."
1650 :group 'org-time
1651 :type 'boolean)
1653 (defcustom org-calendar-follow-timestamp-change t
1654 "Non-nil means, make the calendar window follow timestamp changes.
1655 When a timestamp is modified and the calendar window is visible, it will be
1656 moved to the new date."
1657 :group 'org-time
1658 :type 'boolean)
1660 (defgroup org-tags nil
1661 "Options concerning tags in Org-mode."
1662 :tag "Org Tags"
1663 :group 'org)
1665 (defcustom org-tag-alist nil
1666 "List of tags allowed in Org-mode files.
1667 When this list is nil, Org-mode will base TAG input on what is already in the
1668 buffer.
1669 The value of this variable is an alist, the car of each entry must be a
1670 keyword as a string, the cdr may be a character that is used to select
1671 that tag through the fast-tag-selection interface.
1672 See the manual for details."
1673 :group 'org-tags
1674 :type '(repeat
1675 (choice
1676 (cons (string :tag "Tag name")
1677 (character :tag "Access char"))
1678 (const :tag "Start radio group" (:startgroup))
1679 (const :tag "End radio group" (:endgroup)))))
1681 (defcustom org-use-fast-tag-selection 'auto
1682 "Non-nil means, use fast tag selection scheme.
1683 This is a special interface to select and deselect tags with single keys.
1684 When nil, fast selection is never used.
1685 When the symbol `auto', fast selection is used if and only if selection
1686 characters for tags have been configured, either through the variable
1687 `org-tag-alist' or through a #+TAGS line in the buffer.
1688 When t, fast selection is always used and selection keys are assigned
1689 automatically if necessary."
1690 :group 'org-tags
1691 :type '(choice
1692 (const :tag "Always" t)
1693 (const :tag "Never" nil)
1694 (const :tag "When selection characters are configured" 'auto)))
1696 (defcustom org-fast-tag-selection-single-key nil
1697 "Non-nil means, fast tag selection exits after first change.
1698 When nil, you have to press RET to exit it.
1699 During fast tag selection, you can toggle this flag with `C-c'.
1700 This variable can also have the value `expert'. In this case, the window
1701 displaying the tags menu is not even shown, until you press C-c again."
1702 :group 'org-tags
1703 :type '(choice
1704 (const :tag "No" nil)
1705 (const :tag "Yes" t)
1706 (const :tag "Expert" expert)))
1708 (defvar org-fast-tag-selection-include-todo nil
1709 "Non-nil means, fast tags selection interface will also offer TODO states.
1710 This is an undocumented feature, you should not rely on it.")
1712 (defcustom org-tags-column -80
1713 "The column to which tags should be indented in a headline.
1714 If this number is positive, it specifies the column. If it is negative,
1715 it means that the tags should be flushright to that column. For example,
1716 -80 works well for a normal 80 character screen."
1717 :group 'org-tags
1718 :type 'integer)
1720 (defcustom org-auto-align-tags t
1721 "Non-nil means, realign tags after pro/demotion of TODO state change.
1722 These operations change the length of a headline and therefore shift
1723 the tags around. With this options turned on, after each such operation
1724 the tags are again aligned to `org-tags-column'."
1725 :group 'org-tags
1726 :type 'boolean)
1728 (defcustom org-use-tag-inheritance t
1729 "Non-nil means, tags in levels apply also for sublevels.
1730 When nil, only the tags directly given in a specific line apply there.
1731 If you turn off this option, you very likely want to turn on the
1732 companion option `org-tags-match-list-sublevels'.
1734 This may also be a list of tags that should be inherited, or a regexp that
1735 matches tags that should be inherited."
1736 :group 'org-tags
1737 :type '(choice
1738 (const :tag "Not" nil)
1739 (const :tag "Always" t)
1740 (repeat :tag "Specific tags" (string :tag "Tag"))
1741 (regexp :tag "Tags matched by regexp")))
1743 (defun org-tag-inherit-p (tag)
1744 "Check if TAG is one that should be inherited."
1745 (cond
1746 ((eq org-use-tag-inheritance t) t)
1747 ((not org-use-tag-inheritance) nil)
1748 ((stringp org-use-tag-inheritance)
1749 (string-match org-use-tag-inheritance tag))
1750 ((listp org-use-tag-inheritance)
1751 (member tag org-use-tag-inheritance))
1752 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1754 (defcustom org-tags-match-list-sublevels nil
1755 "Non-nil means list also sublevels of headlines matching tag search.
1756 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1757 the sublevels of a headline matching a tag search often also match
1758 the same search. Listing all of them can create very long lists.
1759 Setting this variable to nil causes subtrees of a match to be skipped.
1760 This option is off by default, because inheritance in on. If you turn
1761 inheritance off, you very likely want to turn this option on.
1763 As a special case, if the tag search is restricted to TODO items, the
1764 value of this variable is ignored and sublevels are always checked, to
1765 make sure all corresponding TODO items find their way into the list."
1766 :group 'org-tags
1767 :type 'boolean)
1769 (defvar org-tags-history nil
1770 "History of minibuffer reads for tags.")
1771 (defvar org-last-tags-completion-table nil
1772 "The last used completion table for tags.")
1773 (defvar org-after-tags-change-hook nil
1774 "Hook that is run after the tags in a line have changed.")
1776 (defgroup org-properties nil
1777 "Options concerning properties in Org-mode."
1778 :tag "Org Properties"
1779 :group 'org)
1781 (defcustom org-property-format "%-10s %s"
1782 "How property key/value pairs should be formatted by `indent-line'.
1783 When `indent-line' hits a property definition, it will format the line
1784 according to this format, mainly to make sure that the values are
1785 lined-up with respect to each other."
1786 :group 'org-properties
1787 :type 'string)
1789 (defcustom org-use-property-inheritance nil
1790 "Non-nil means, properties apply also for sublevels.
1792 This setting is chiefly used during property searches. Turning it on can
1793 cause significant overhead when doing a search, which is why it is not
1794 on by default.
1796 When nil, only the properties directly given in the current entry count.
1797 When t, every property is inherited. The value may also be a list of
1798 properties that should have inheritance, or a regular expression matching
1799 properties that should be inherited.
1801 However, note that some special properties use inheritance under special
1802 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1803 and the properties ending in \"_ALL\" when they are used as descriptor
1804 for valid values of a property.
1806 Note for programmers:
1807 When querying an entry with `org-entry-get', you can control if inheritance
1808 should be used. By default, `org-entry-get' looks only at the local
1809 properties. You can request inheritance by setting the inherit argument
1810 to t (to force inheritance) or to `selective' (to respect the setting
1811 in this variable)."
1812 :group 'org-properties
1813 :type '(choice
1814 (const :tag "Not" nil)
1815 (const :tag "Always" t)
1816 (repeat :tag "Specific properties" (string :tag "Property"))
1817 (regexp :tag "Properties matched by regexp")))
1819 (defun org-property-inherit-p (property)
1820 "Check if PROPERTY is one that should be inherited."
1821 (cond
1822 ((eq org-use-property-inheritance t) t)
1823 ((not org-use-property-inheritance) nil)
1824 ((stringp org-use-property-inheritance)
1825 (string-match org-use-property-inheritance property))
1826 ((listp org-use-property-inheritance)
1827 (member property org-use-property-inheritance))
1828 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1830 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1831 "The default column format, if no other format has been defined.
1832 This variable can be set on the per-file basis by inserting a line
1834 #+COLUMNS: %25ITEM ....."
1835 :group 'org-properties
1836 :type 'string)
1838 (defcustom org-global-properties nil
1839 "List of property/value pairs that can be inherited by any entry.
1840 You can set buffer-local values for this by adding lines like
1842 #+PROPERTY: NAME VALUE"
1843 :group 'org-properties
1844 :type '(repeat
1845 (cons (string :tag "Property")
1846 (string :tag "Value"))))
1848 (defvar org-local-properties nil
1849 "List of property/value pairs that can be inherited by any entry.
1850 Valid for the current buffer.
1851 This variable is populated from #+PROPERTY lines.")
1853 (defgroup org-agenda nil
1854 "Options concerning agenda views in Org-mode."
1855 :tag "Org Agenda"
1856 :group 'org)
1858 (defvar org-category nil
1859 "Variable used by org files to set a category for agenda display.
1860 Such files should use a file variable to set it, for example
1862 # -*- mode: org; org-category: \"ELisp\"
1864 or contain a special line
1866 #+CATEGORY: ELisp
1868 If the file does not specify a category, then file's base name
1869 is used instead.")
1870 (make-variable-buffer-local 'org-category)
1872 (defcustom org-agenda-files nil
1873 "The files to be used for agenda display.
1874 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1875 \\[org-remove-file]. You can also use customize to edit the list.
1877 If an entry is a directory, all files in that directory that are matched by
1878 `org-agenda-file-regexp' will be part of the file list.
1880 If the value of the variable is not a list but a single file name, then
1881 the list of agenda files is actually stored and maintained in that file, one
1882 agenda file per line."
1883 :group 'org-agenda
1884 :type '(choice
1885 (repeat :tag "List of files and directories" file)
1886 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1888 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1889 "Regular expression to match files for `org-agenda-files'.
1890 If any element in the list in that variable contains a directory instead
1891 of a normal file, all files in that directory that are matched by this
1892 regular expression will be included."
1893 :group 'org-agenda
1894 :type 'regexp)
1896 (defcustom org-agenda-text-search-extra-files nil
1897 "List of extra files to be searched by text search commands.
1898 These files will be search in addition to the agenda files bu the
1899 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1900 Note that these files will only be searched for text search commands,
1901 not for the other agenda views like todo lists, tag earches or the weekly
1902 agenda. This variable is intended to list notes and possibly archive files
1903 that should also be searched by these two commands."
1904 :group 'org-agenda
1905 :type '(repeat file))
1907 (if (fboundp 'defvaralias)
1908 (defvaralias 'org-agenda-multi-occur-extra-files
1909 'org-agenda-text-search-extra-files))
1911 (defcustom org-agenda-skip-unavailable-files nil
1912 "t means to just skip non-reachable files in `org-agenda-files'.
1913 Nil means to remove them, after a query, from the list."
1914 :group 'org-agenda
1915 :type 'boolean)
1917 (defcustom org-calendar-to-agenda-key [?c]
1918 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1919 The command `org-calendar-goto-agenda' will be bound to this key. The
1920 default is the character `c' because then `c' can be used to switch back and
1921 forth between agenda and calendar."
1922 :group 'org-agenda
1923 :type 'sexp)
1925 (eval-after-load "calendar"
1926 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1927 'org-calendar-goto-agenda))
1929 (defgroup org-latex nil
1930 "Options for embedding LaTeX code into Org-mode."
1931 :tag "Org LaTeX"
1932 :group 'org)
1934 (defcustom org-format-latex-options
1935 '(:foreground default :background default :scale 1.0
1936 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1937 :matchers ("begin" "$" "$$" "\\(" "\\["))
1938 "Options for creating images from LaTeX fragments.
1939 This is a property list with the following properties:
1940 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1941 `default' means use the forground of the default face.
1942 :background the background color, or \"Transparent\".
1943 `default' means use the background of the default face.
1944 :scale a scaling factor for the size of the images
1945 :html-foreground, :html-background, :html-scale
1946 The same numbers for HTML export.
1947 :matchers a list indicating which matchers should be used to
1948 find LaTeX fragments. Valid members of this list are:
1949 \"begin\" find environments
1950 \"$\" find math expressions surrounded by $...$
1951 \"$$\" find math expressions surrounded by $$....$$
1952 \"\\(\" find math expressions surrounded by \\(...\\)
1953 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1954 :group 'org-latex
1955 :type 'plist)
1957 (defcustom org-format-latex-header "\\documentclass{article}
1958 \\usepackage{fullpage} % do not remove
1959 \\usepackage{amssymb}
1960 \\usepackage[usenames]{color}
1961 \\usepackage{amsmath}
1962 \\usepackage{latexsym}
1963 \\usepackage[mathscr]{eucal}
1964 \\pagestyle{empty} % do not remove"
1965 "The document header used for processing LaTeX fragments."
1966 :group 'org-latex
1967 :type 'string)
1970 (defgroup org-font-lock nil
1971 "Font-lock settings for highlighting in Org-mode."
1972 :tag "Org Font Lock"
1973 :group 'org)
1975 (defcustom org-level-color-stars-only nil
1976 "Non-nil means fontify only the stars in each headline.
1977 When nil, the entire headline is fontified.
1978 Changing it requires restart of `font-lock-mode' to become effective
1979 also in regions already fontified."
1980 :group 'org-font-lock
1981 :type 'boolean)
1983 (defcustom org-hide-leading-stars nil
1984 "Non-nil means, hide the first N-1 stars in a headline.
1985 This works by using the face `org-hide' for these stars. This
1986 face is white for a light background, and black for a dark
1987 background. You may have to customize the face `org-hide' to
1988 make this work.
1989 Changing it requires restart of `font-lock-mode' to become effective
1990 also in regions already fontified.
1991 You may also set this on a per-file basis by adding one of the following
1992 lines to the buffer:
1994 #+STARTUP: hidestars
1995 #+STARTUP: showstars"
1996 :group 'org-font-lock
1997 :type 'boolean)
1999 (defcustom org-fontify-done-headline nil
2000 "Non-nil means, change the face of a headline if it is marked DONE.
2001 Normally, only the TODO/DONE keyword indicates the state of a headline.
2002 When this is non-nil, the headline after the keyword is set to the
2003 `org-headline-done' as an additional indication."
2004 :group 'org-font-lock
2005 :type 'boolean)
2007 (defcustom org-fontify-emphasized-text t
2008 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2009 Changing this variable requires a restart of Emacs to take effect."
2010 :group 'org-font-lock
2011 :type 'boolean)
2013 (defcustom org-highlight-latex-fragments-and-specials nil
2014 "Non-nil means, fontify what is treated specially by the exporters."
2015 :group 'org-font-lock
2016 :type 'boolean)
2018 (defcustom org-hide-emphasis-markers nil
2019 "Non-nil mean font-lock should hide the emphasis marker characters."
2020 :group 'org-font-lock
2021 :type 'boolean)
2023 (defvar org-emph-re nil
2024 "Regular expression for matching emphasis.")
2025 (defvar org-verbatim-re nil
2026 "Regular expression for matching verbatim text.")
2027 (defvar org-emphasis-regexp-components) ; defined just below
2028 (defvar org-emphasis-alist) ; defined just below
2029 (defun org-set-emph-re (var val)
2030 "Set variable and compute the emphasis regular expression."
2031 (set var val)
2032 (when (and (boundp 'org-emphasis-alist)
2033 (boundp 'org-emphasis-regexp-components)
2034 org-emphasis-alist org-emphasis-regexp-components)
2035 (let* ((e org-emphasis-regexp-components)
2036 (pre (car e))
2037 (post (nth 1 e))
2038 (border (nth 2 e))
2039 (body (nth 3 e))
2040 (nl (nth 4 e))
2041 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2042 (body1 (concat body "*?"))
2043 (markers (mapconcat 'car org-emphasis-alist ""))
2044 (vmarkers (mapconcat
2045 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2046 org-emphasis-alist "")))
2047 ;; make sure special characters appear at the right position in the class
2048 (if (string-match "\\^" markers)
2049 (setq markers (concat (replace-match "" t t markers) "^")))
2050 (if (string-match "-" markers)
2051 (setq markers (concat (replace-match "" t t markers) "-")))
2052 (if (string-match "\\^" vmarkers)
2053 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2054 (if (string-match "-" vmarkers)
2055 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2056 (if (> nl 0)
2057 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2058 (int-to-string nl) "\\}")))
2059 ;; Make the regexp
2060 (setq org-emph-re
2061 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2062 "\\("
2063 "\\([" markers "]\\)"
2064 "\\("
2065 "[^" border "]\\|"
2066 "[^" border (if (and nil stacked) markers) "]"
2067 body1
2068 "[^" border (if (and nil stacked) markers) "]"
2069 "\\)"
2070 "\\3\\)"
2071 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2072 (setq org-verbatim-re
2073 (concat "\\([" pre "]\\|^\\)"
2074 "\\("
2075 "\\([" vmarkers "]\\)"
2076 "\\("
2077 "[^" border "]\\|"
2078 "[^" border "]"
2079 body1
2080 "[^" border "]"
2081 "\\)"
2082 "\\3\\)"
2083 "\\([" post "]\\|$\\)")))))
2085 (defcustom org-emphasis-regexp-components
2086 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2087 "Components used to build the regular expression for emphasis.
2088 This is a list with 6 entries. Terminology: In an emphasis string
2089 like \" *strong word* \", we call the initial space PREMATCH, the final
2090 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2091 and \"trong wor\" is the body. The different components in this variable
2092 specify what is allowed/forbidden in each part:
2094 pre Chars allowed as prematch. Beginning of line will be allowed too.
2095 post Chars allowed as postmatch. End of line will be allowed too.
2096 border The chars *forbidden* as border characters.
2097 body-regexp A regexp like \".\" to match a body character. Don't use
2098 non-shy groups here, and don't allow newline here.
2099 newline The maximum number of newlines allowed in an emphasis exp.
2101 Use customize to modify this, or restart Emacs after changing it."
2102 :group 'org-font-lock
2103 :set 'org-set-emph-re
2104 :type '(list
2105 (sexp :tag "Allowed chars in pre ")
2106 (sexp :tag "Allowed chars in post ")
2107 (sexp :tag "Forbidden chars in border ")
2108 (sexp :tag "Regexp for body ")
2109 (integer :tag "number of newlines allowed")
2110 (option (boolean :tag "Stacking (DISABLED) "))))
2112 (defcustom org-emphasis-alist
2113 '(("*" bold "<b>" "</b>")
2114 ("/" italic "<i>" "</i>")
2115 ("_" underline "<u>" "</u>")
2116 ("=" org-code "<code>" "</code>" verbatim)
2117 ("~" org-verbatim "" "" verbatim)
2118 ("+" (:strike-through t) "<del>" "</del>")
2120 "Special syntax for emphasized text.
2121 Text starting and ending with a special character will be emphasized, for
2122 example *bold*, _underlined_ and /italic/. This variable sets the marker
2123 characters, the face to be used by font-lock for highlighting in Org-mode
2124 Emacs buffers, and the HTML tags to be used for this.
2125 Use customize to modify this, or restart Emacs after changing it."
2126 :group 'org-font-lock
2127 :set 'org-set-emph-re
2128 :type '(repeat
2129 (list
2130 (string :tag "Marker character")
2131 (choice
2132 (face :tag "Font-lock-face")
2133 (plist :tag "Face property list"))
2134 (string :tag "HTML start tag")
2135 (string :tag "HTML end tag")
2136 (option (const verbatim)))))
2138 ;;; Miscellaneous options
2140 (defgroup org-completion nil
2141 "Completion in Org-mode."
2142 :tag "Org Completion"
2143 :group 'org)
2145 (defcustom org-completion-fallback-command 'hippie-expand
2146 "The expansion command called by \\[org-complete] in normal context.
2147 Normal means, no org-mode-specific context."
2148 :group 'org-completion
2149 :type 'function)
2151 ;;; Functions and variables from ther packages
2152 ;; Declared here to avoid compiler warnings
2154 ;; XEmacs only
2155 (defvar outline-mode-menu-heading)
2156 (defvar outline-mode-menu-show)
2157 (defvar outline-mode-menu-hide)
2158 (defvar zmacs-regions) ; XEmacs regions
2160 ;; Emacs only
2161 (defvar mark-active)
2163 ;; Various packages
2164 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
2165 (declare-function calendar-forward-day "cal-move" (arg))
2166 (declare-function calendar-goto-date "cal-move" (date))
2167 (declare-function calendar-goto-today "cal-move" ())
2168 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
2169 (defvar calc-embedded-close-formula)
2170 (defvar calc-embedded-open-formula)
2171 (declare-function cdlatex-tab "ext:cdlatex" ())
2172 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2173 (defvar font-lock-unfontify-region-function)
2174 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2175 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2176 (defvar iswitchb-temp-buflist)
2177 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2178 (declare-function org-agenda-skip "org-agenda" ())
2179 (declare-function org-format-agenda-item "org-agenda"
2180 (extra txt &optional category tags dotime noprefix remove-re))
2181 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2182 (declare-function org-agenda-change-all-lines "org-agenda"
2183 (newhead hdmarker &optional fixface))
2184 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2185 (declare-function org-agenda-maybe-redo "org-agenda" ())
2186 (declare-function parse-time-string "parse-time" (string))
2187 (declare-function remember "remember" (&optional initial))
2188 (declare-function remember-buffer-desc "remember" ())
2189 (declare-function remember-finalize "remember" ())
2190 (defvar remember-save-after-remembering)
2191 (defvar remember-data-file)
2192 (defvar remember-register)
2193 (defvar remember-buffer)
2194 (defvar remember-handler-functions)
2195 (defvar remember-annotation-functions)
2196 (defvar texmathp-why)
2197 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2198 (declare-function table--at-cell-p "table" (position &optional object at-column))
2200 (defvar w3m-current-url)
2201 (defvar w3m-current-title)
2203 (defvar org-latex-regexps)
2205 ;;; Autoload and prepare some org modules
2207 ;; Some table stuff that needs to be defined here, because it is used
2208 ;; by the functions setting up org-mode or checking for table context.
2210 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2211 "Detects an org-type or table-type table.")
2212 (defconst org-table-line-regexp "^[ \t]*|"
2213 "Detects an org-type table line.")
2214 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2215 "Detects an org-type table line.")
2216 (defconst org-table-hline-regexp "^[ \t]*|-"
2217 "Detects an org-type table hline.")
2218 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2219 "Detects a table-type table hline.")
2220 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2221 "Searching from within a table (any type) this finds the first line
2222 outside the table.")
2224 ;; Autoload the functions in org-table.el that are needed by functions here.
2226 (eval-and-compile
2227 (org-autoload "org-table"
2228 '(org-table-align org-table-begin org-table-blank-field
2229 org-table-convert org-table-convert-region org-table-copy-down
2230 org-table-copy-region org-table-create
2231 org-table-create-or-convert-from-region
2232 org-table-create-with-table.el org-table-current-dline
2233 org-table-cut-region org-table-delete-column org-table-edit-field
2234 org-table-edit-formulas org-table-end org-table-eval-formula
2235 org-table-export org-table-field-info
2236 org-table-get-stored-formulas org-table-goto-column
2237 org-table-hline-and-move org-table-import org-table-insert-column
2238 org-table-insert-hline org-table-insert-row org-table-iterate
2239 org-table-justify-field-maybe org-table-kill-row
2240 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2241 org-table-move-column org-table-move-column-left
2242 org-table-move-column-right org-table-move-row
2243 org-table-move-row-down org-table-move-row-up
2244 org-table-next-field org-table-next-row org-table-paste-rectangle
2245 org-table-previous-field org-table-recalculate
2246 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2247 org-table-toggle-coordinate-overlays
2248 org-table-toggle-formula-debugger org-table-wrap-region
2249 orgtbl-mode turn-on-orgtbl)))
2251 (defun org-at-table-p (&optional table-type)
2252 "Return t if the cursor is inside an org-type table.
2253 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2254 (if org-enable-table-editor
2255 (save-excursion
2256 (beginning-of-line 1)
2257 (looking-at (if table-type org-table-any-line-regexp
2258 org-table-line-regexp)))
2259 nil))
2260 (defsubst org-table-p () (org-at-table-p))
2262 (defun org-at-table.el-p ()
2263 "Return t if and only if we are at a table.el table."
2264 (and (org-at-table-p 'any)
2265 (save-excursion
2266 (goto-char (org-table-begin 'any))
2267 (looking-at org-table1-hline-regexp))))
2268 (defun org-table-recognize-table.el ()
2269 "If there is a table.el table nearby, recognize it and move into it."
2270 (if org-table-tab-recognizes-table.el
2271 (if (org-at-table.el-p)
2272 (progn
2273 (beginning-of-line 1)
2274 (if (looking-at org-table-dataline-regexp)
2276 (if (looking-at org-table1-hline-regexp)
2277 (progn
2278 (beginning-of-line 2)
2279 (if (looking-at org-table-any-border-regexp)
2280 (beginning-of-line -1)))))
2281 (if (re-search-forward "|" (org-table-end t) t)
2282 (progn
2283 (require 'table)
2284 (if (table--at-cell-p (point))
2286 (message "recognizing table.el table...")
2287 (table-recognize-table)
2288 (message "recognizing table.el table...done")))
2289 (error "This should not happen..."))
2291 nil)
2292 nil))
2294 (defun org-at-table-hline-p ()
2295 "Return t if the cursor is inside a hline in a table."
2296 (if org-enable-table-editor
2297 (save-excursion
2298 (beginning-of-line 1)
2299 (looking-at org-table-hline-regexp))
2300 nil))
2302 (defvar org-table-clean-did-remove-column nil)
2304 (defun org-table-map-tables (function)
2305 "Apply FUNCTION to the start of all tables in the buffer."
2306 (save-excursion
2307 (save-restriction
2308 (widen)
2309 (goto-char (point-min))
2310 (while (re-search-forward org-table-any-line-regexp nil t)
2311 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2312 (beginning-of-line 1)
2313 (if (looking-at org-table-line-regexp)
2314 (save-excursion (funcall function)))
2315 (re-search-forward org-table-any-border-regexp nil 1))))
2316 (message "Mapping tables: done"))
2318 ;; Declare and autoload functions from org-exp.el
2320 (declare-function org-default-export-plist "org-exp")
2321 (declare-function org-infile-export-plist "org-exp")
2322 (declare-function org-get-current-options "org-exp")
2323 (eval-and-compile
2324 (org-autoload "org-exp"
2325 '(org-export org-export-as-ascii org-export-visible
2326 org-insert-export-options-template org-export-as-html-and-open
2327 org-export-as-html-batch org-export-as-html-to-buffer
2328 org-replace-region-by-html org-export-region-as-html
2329 org-export-as-html org-export-icalendar-this-file
2330 org-export-icalendar-all-agenda-files
2331 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2333 ;; Declare and autoload functions from org-exp.el
2335 (eval-and-compile
2336 (org-autoload "org-exp"
2337 '(org-agenda org-agenda-list org-search-view
2338 org-todo-list org-tags-view org-agenda-list-stuck-projects
2339 org-diary org-agenda-to-appt)))
2341 ;; Autoload org-remember
2343 (eval-and-compile
2344 (org-autoload "org-remember"
2345 '(org-remember-insinuate org-remember-annotation
2346 org-remember-apply-template org-remember org-remember-handler)))
2348 ;; Autoload org-clock.el
2350 (defvar org-clock-marker (make-marker)
2351 "Marker recording the last clock-in.")
2353 (eval-and-compile
2354 (org-autoload
2355 "org-clock"
2356 '(org-clock-in org-clock-out org-clock-cancel
2357 org-clock-goto org-clock-sum org-clock-display
2358 org-remove-clock-overlays org-clock-report
2359 org-clocktable-shift org-dblock-write:clocktable
2360 org-get-clocktable)))
2362 (defun org-clock-update-time-maybe ()
2363 "If this is a CLOCK line, update it and return t.
2364 Otherwise, return nil."
2365 (interactive)
2366 (save-excursion
2367 (beginning-of-line 1)
2368 (skip-chars-forward " \t")
2369 (when (looking-at org-clock-string)
2370 (let ((re (concat "[ \t]*" org-clock-string
2371 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2372 "\\([ \t]*=>.*\\)?"))
2373 ts te h m s)
2374 (if (not (looking-at re))
2376 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2377 (end-of-line 1)
2378 (setq ts (match-string 1)
2379 te (match-string 2))
2380 (setq s (- (time-to-seconds
2381 (apply 'encode-time (org-parse-time-string te)))
2382 (time-to-seconds
2383 (apply 'encode-time (org-parse-time-string ts))))
2384 h (floor (/ s 3600))
2385 s (- s (* 3600 h))
2386 m (floor (/ s 60))
2387 s (- s (* 60 s)))
2388 (insert " => " (format "%2d:%02d" h m))
2389 t)))))
2391 (defun org-check-running-clock ()
2392 "Check if the current buffer contains the running clock.
2393 If yes, offer to stop it and to save the buffer with the changes."
2394 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2395 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2396 (buffer-name))))
2397 (org-clock-out)
2398 (when (y-or-n-p "Save changed buffer?")
2399 (save-buffer))))
2401 (defun org-clocktable-try-shift (dir n)
2402 "Check if this line starts a clock table, if yes, shift the time block."
2403 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2404 (org-clocktable-shift dir n)))
2406 ;; Autoload archiving code
2407 ;; The stuff that is needed for cycling and tags has to be defined here.
2409 (defgroup org-archive nil
2410 "Options concerning archiving in Org-mode."
2411 :tag "Org Archive"
2412 :group 'org-structure)
2414 (defcustom org-archive-tag "ARCHIVE"
2415 "The tag that marks a subtree as archived.
2416 An archived subtree does not open during visibility cycling, and does
2417 not contribute to the agenda listings.
2418 After changing this, font-lock must be restarted in the relevant buffers to
2419 get the proper fontification."
2420 :group 'org-archive
2421 :group 'org-keywords
2422 :type 'string)
2424 (defcustom org-agenda-skip-archived-trees t
2425 "Non-nil means, the agenda will skip any items located in archived trees.
2426 An archived tree is a tree marked with the tag ARCHIVE."
2427 :group 'org-archive
2428 :group 'org-agenda-skip
2429 :type 'boolean)
2431 (defcustom org-cycle-open-archived-trees nil
2432 "Non-nil means, `org-cycle' will open archived trees.
2433 An archived tree is a tree marked with the tag ARCHIVE.
2434 When nil, archived trees will stay folded. You can still open them with
2435 normal outline commands like `show-all', but not with the cycling commands."
2436 :group 'org-archive
2437 :group 'org-cycle
2438 :type 'boolean)
2440 (defcustom org-sparse-tree-open-archived-trees nil
2441 "Non-nil means sparse tree construction shows matches in archived trees.
2442 When nil, matches in these trees are highlighted, but the trees are kept in
2443 collapsed state."
2444 :group 'org-archive
2445 :group 'org-sparse-trees
2446 :type 'boolean)
2448 (defun org-cycle-hide-archived-subtrees (state)
2449 "Re-hide all archived subtrees after a visibility state change."
2450 (when (and (not org-cycle-open-archived-trees)
2451 (not (memq state '(overview folded))))
2452 (save-excursion
2453 (let* ((globalp (memq state '(contents all)))
2454 (beg (if globalp (point-min) (point)))
2455 (end (if globalp (point-max) (org-end-of-subtree t))))
2456 (org-hide-archived-subtrees beg end)
2457 (goto-char beg)
2458 (if (looking-at (concat ".*:" org-archive-tag ":"))
2459 (message "%s" (substitute-command-keys
2460 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2462 (defun org-force-cycle-archived ()
2463 "Cycle subtree even if it is archived."
2464 (interactive)
2465 (setq this-command 'org-cycle)
2466 (let ((org-cycle-open-archived-trees t))
2467 (call-interactively 'org-cycle)))
2469 (defun org-hide-archived-subtrees (beg end)
2470 "Re-hide all archived subtrees after a visibility state change."
2471 (save-excursion
2472 (let* ((re (concat ":" org-archive-tag ":")))
2473 (goto-char beg)
2474 (while (re-search-forward re end t)
2475 (and (org-on-heading-p) (hide-subtree))
2476 (org-end-of-subtree t)))))
2478 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2480 (org-autoload "org-archive"
2481 '(org-archive-subtree org-archive-to-archive-sibling org-toggle-archive-tag))
2483 ;; Autoload Column View Code
2485 (declare-function org-columns-number-to-string "org-colview")
2486 (declare-function org-columns-get-format-and-top-level "org-colview")
2487 (declare-function org-columns-compute "org-colview")
2489 (org-autoload "org-colview"
2490 '(org-columns-number-to-string org-columns-get-format-and-top-level
2491 org-columns-compute org-agenda-columns org-columns-remove-overlays
2492 org-columns org-insert-columns-dblock))
2494 ;;; Variables for pre-computed regular expressions, all buffer local
2496 (defvar org-drawer-regexp nil
2497 "Matches first line of a hidden block.")
2498 (make-variable-buffer-local 'org-drawer-regexp)
2499 (defvar org-todo-regexp nil
2500 "Matches any of the TODO state keywords.")
2501 (make-variable-buffer-local 'org-todo-regexp)
2502 (defvar org-not-done-regexp nil
2503 "Matches any of the TODO state keywords except the last one.")
2504 (make-variable-buffer-local 'org-not-done-regexp)
2505 (defvar org-todo-line-regexp nil
2506 "Matches a headline and puts TODO state into group 2 if present.")
2507 (make-variable-buffer-local 'org-todo-line-regexp)
2508 (defvar org-complex-heading-regexp nil
2509 "Matches a headline and puts everything into groups:
2510 group 1: the stars
2511 group 2: The todo keyword, maybe
2512 group 3: Priority cookie
2513 group 4: True headline
2514 group 5: Tags")
2515 (make-variable-buffer-local 'org-complex-heading-regexp)
2516 (defvar org-todo-line-tags-regexp nil
2517 "Matches a headline and puts TODO state into group 2 if present.
2518 Also put tags into group 4 if tags are present.")
2519 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2520 (defvar org-nl-done-regexp nil
2521 "Matches newline followed by a headline with the DONE keyword.")
2522 (make-variable-buffer-local 'org-nl-done-regexp)
2523 (defvar org-looking-at-done-regexp nil
2524 "Matches the DONE keyword a point.")
2525 (make-variable-buffer-local 'org-looking-at-done-regexp)
2526 (defvar org-ds-keyword-length 12
2527 "Maximum length of the Deadline and SCHEDULED keywords.")
2528 (make-variable-buffer-local 'org-ds-keyword-length)
2529 (defvar org-deadline-regexp nil
2530 "Matches the DEADLINE keyword.")
2531 (make-variable-buffer-local 'org-deadline-regexp)
2532 (defvar org-deadline-time-regexp nil
2533 "Matches the DEADLINE keyword together with a time stamp.")
2534 (make-variable-buffer-local 'org-deadline-time-regexp)
2535 (defvar org-deadline-line-regexp nil
2536 "Matches the DEADLINE keyword and the rest of the line.")
2537 (make-variable-buffer-local 'org-deadline-line-regexp)
2538 (defvar org-scheduled-regexp nil
2539 "Matches the SCHEDULED keyword.")
2540 (make-variable-buffer-local 'org-scheduled-regexp)
2541 (defvar org-scheduled-time-regexp nil
2542 "Matches the SCHEDULED keyword together with a time stamp.")
2543 (make-variable-buffer-local 'org-scheduled-time-regexp)
2544 (defvar org-closed-time-regexp nil
2545 "Matches the CLOSED keyword together with a time stamp.")
2546 (make-variable-buffer-local 'org-closed-time-regexp)
2548 (defvar org-keyword-time-regexp nil
2549 "Matches any of the 4 keywords, together with the time stamp.")
2550 (make-variable-buffer-local 'org-keyword-time-regexp)
2551 (defvar org-keyword-time-not-clock-regexp nil
2552 "Matches any of the 3 keywords, together with the time stamp.")
2553 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2554 (defvar org-maybe-keyword-time-regexp nil
2555 "Matches a timestamp, possibly preceeded by a keyword.")
2556 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2557 (defvar org-planning-or-clock-line-re nil
2558 "Matches a line with planning or clock info.")
2559 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2561 (defconst org-plain-time-of-day-regexp
2562 (concat
2563 "\\(\\<[012]?[0-9]"
2564 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2565 "\\(--?"
2566 "\\(\\<[012]?[0-9]"
2567 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2568 "\\)?")
2569 "Regular expression to match a plain time or time range.
2570 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2571 groups carry important information:
2572 0 the full match
2573 1 the first time, range or not
2574 8 the second time, if it is a range.")
2576 (defconst org-plain-time-extension-regexp
2577 (concat
2578 "\\(\\<[012]?[0-9]"
2579 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2580 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2581 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2582 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2583 groups carry important information:
2584 0 the full match
2585 7 hours of duration
2586 9 minutes of duration")
2588 (defconst org-stamp-time-of-day-regexp
2589 (concat
2590 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2591 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2592 "\\(--?"
2593 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2594 "Regular expression to match a timestamp time or time range.
2595 After a match, the following groups carry important information:
2596 0 the full match
2597 1 date plus weekday, for backreferencing to make sure both times on same day
2598 2 the first time, range or not
2599 4 the second time, if it is a range.")
2601 (defconst org-startup-options
2602 '(("fold" org-startup-folded t)
2603 ("overview" org-startup-folded t)
2604 ("nofold" org-startup-folded nil)
2605 ("showall" org-startup-folded nil)
2606 ("content" org-startup-folded content)
2607 ("hidestars" org-hide-leading-stars t)
2608 ("showstars" org-hide-leading-stars nil)
2609 ("odd" org-odd-levels-only t)
2610 ("oddeven" org-odd-levels-only nil)
2611 ("align" org-startup-align-all-tables t)
2612 ("noalign" org-startup-align-all-tables nil)
2613 ("customtime" org-display-custom-times t)
2614 ("logdone" org-log-done time)
2615 ("lognotedone" org-log-done note)
2616 ("nologdone" org-log-done nil)
2617 ("lognoteclock-out" org-log-note-clock-out t)
2618 ("nolognoteclock-out" org-log-note-clock-out nil)
2619 ("logrepeat" org-log-repeat state)
2620 ("lognoterepeat" org-log-repeat note)
2621 ("nologrepeat" org-log-repeat nil)
2622 ("constcgs" constants-unit-system cgs)
2623 ("constSI" constants-unit-system SI))
2624 "Variable associated with STARTUP options for org-mode.
2625 Each element is a list of three items: The startup options as written
2626 in the #+STARTUP line, the corresponding variable, and the value to
2627 set this variable to if the option is found. An optional forth element PUSH
2628 means to push this value onto the list in the variable.")
2630 (defun org-set-regexps-and-options ()
2631 "Precompute regular expressions for current buffer."
2632 (when (org-mode-p)
2633 (org-set-local 'org-todo-kwd-alist nil)
2634 (org-set-local 'org-todo-key-alist nil)
2635 (org-set-local 'org-todo-key-trigger nil)
2636 (org-set-local 'org-todo-keywords-1 nil)
2637 (org-set-local 'org-done-keywords nil)
2638 (org-set-local 'org-todo-heads nil)
2639 (org-set-local 'org-todo-sets nil)
2640 (org-set-local 'org-todo-log-states nil)
2641 (let ((re (org-make-options-regexp
2642 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2643 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2644 "CONSTANTS" "PROPERTY" "DRAWERS")))
2645 (splitre "[ \t]+")
2646 kwds kws0 kwsa key log value cat arch tags const links hw dws
2647 tail sep kws1 prio props drawers)
2648 (save-excursion
2649 (save-restriction
2650 (widen)
2651 (goto-char (point-min))
2652 (while (re-search-forward re nil t)
2653 (setq key (match-string 1) value (org-match-string-no-properties 2))
2654 (cond
2655 ((equal key "CATEGORY")
2656 (if (string-match "[ \t]+$" value)
2657 (setq value (replace-match "" t t value)))
2658 (setq cat value))
2659 ((member key '("SEQ_TODO" "TODO"))
2660 (push (cons 'sequence (org-split-string value splitre)) kwds))
2661 ((equal key "TYP_TODO")
2662 (push (cons 'type (org-split-string value splitre)) kwds))
2663 ((equal key "TAGS")
2664 (setq tags (append tags (org-split-string value splitre))))
2665 ((equal key "COLUMNS")
2666 (org-set-local 'org-columns-default-format value))
2667 ((equal key "LINK")
2668 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2669 (push (cons (match-string 1 value)
2670 (org-trim (match-string 2 value)))
2671 links)))
2672 ((equal key "PRIORITIES")
2673 (setq prio (org-split-string value " +")))
2674 ((equal key "PROPERTY")
2675 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2676 (push (cons (match-string 1 value) (match-string 2 value))
2677 props)))
2678 ((equal key "DRAWERS")
2679 (setq drawers (org-split-string value splitre)))
2680 ((equal key "CONSTANTS")
2681 (setq const (append const (org-split-string value splitre))))
2682 ((equal key "STARTUP")
2683 (let ((opts (org-split-string value splitre))
2684 l var val)
2685 (while (setq l (pop opts))
2686 (when (setq l (assoc l org-startup-options))
2687 (setq var (nth 1 l) val (nth 2 l))
2688 (if (not (nth 3 l))
2689 (set (make-local-variable var) val)
2690 (if (not (listp (symbol-value var)))
2691 (set (make-local-variable var) nil))
2692 (set (make-local-variable var) (symbol-value var))
2693 (add-to-list var val))))))
2694 ((equal key "ARCHIVE")
2695 (string-match " *$" value)
2696 (setq arch (replace-match "" t t value))
2697 (remove-text-properties 0 (length arch)
2698 '(face t fontified t) arch)))
2700 (when cat
2701 (org-set-local 'org-category (intern cat))
2702 (push (cons "CATEGORY" cat) props))
2703 (when prio
2704 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2705 (setq prio (mapcar 'string-to-char prio))
2706 (org-set-local 'org-highest-priority (nth 0 prio))
2707 (org-set-local 'org-lowest-priority (nth 1 prio))
2708 (org-set-local 'org-default-priority (nth 2 prio)))
2709 (and props (org-set-local 'org-local-properties (nreverse props)))
2710 (and drawers (org-set-local 'org-drawers drawers))
2711 (and arch (org-set-local 'org-archive-location arch))
2712 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2713 ;; Process the TODO keywords
2714 (unless kwds
2715 ;; Use the global values as if they had been given locally.
2716 (setq kwds (default-value 'org-todo-keywords))
2717 (if (stringp (car kwds))
2718 (setq kwds (list (cons org-todo-interpretation
2719 (default-value 'org-todo-keywords)))))
2720 (setq kwds (reverse kwds)))
2721 (setq kwds (nreverse kwds))
2722 (let (inter kws kw)
2723 (while (setq kws (pop kwds))
2724 (setq inter (pop kws) sep (member "|" kws)
2725 kws0 (delete "|" (copy-sequence kws))
2726 kwsa nil
2727 kws1 (mapcar
2728 (lambda (x)
2729 ;; 1 2
2730 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2731 (progn
2732 (setq kw (match-string 1 x)
2733 key (and (match-end 2) (match-string 2 x))
2734 log (org-extract-log-state-settings x))
2735 (push (cons kw (and key (string-to-char key))) kwsa)
2736 (and log (push log org-todo-log-states))
2738 (error "Invalid TODO keyword %s" x)))
2739 kws0)
2740 kwsa (if kwsa (append '((:startgroup))
2741 (nreverse kwsa)
2742 '((:endgroup))))
2743 hw (car kws1)
2744 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2745 tail (list inter hw (car dws) (org-last dws)))
2746 (add-to-list 'org-todo-heads hw 'append)
2747 (push kws1 org-todo-sets)
2748 (setq org-done-keywords (append org-done-keywords dws nil))
2749 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2750 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2751 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2752 (setq org-todo-sets (nreverse org-todo-sets)
2753 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2754 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2755 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2756 ;; Process the constants
2757 (when const
2758 (let (e cst)
2759 (while (setq e (pop const))
2760 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2761 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2762 (setq org-table-formula-constants-local cst)))
2764 ;; Process the tags.
2765 (when tags
2766 (let (e tgs)
2767 (while (setq e (pop tags))
2768 (cond
2769 ((equal e "{") (push '(:startgroup) tgs))
2770 ((equal e "}") (push '(:endgroup) tgs))
2771 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2772 (push (cons (match-string 1 e)
2773 (string-to-char (match-string 2 e)))
2774 tgs))
2775 (t (push (list e) tgs))))
2776 (org-set-local 'org-tag-alist nil)
2777 (while (setq e (pop tgs))
2778 (or (and (stringp (car e))
2779 (assoc (car e) org-tag-alist))
2780 (push e org-tag-alist))))))
2782 ;; Compute the regular expressions and other local variables
2783 (if (not org-done-keywords)
2784 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2785 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2786 (length org-scheduled-string)
2787 (length org-clock-string)
2788 (length org-closed-string)))
2789 org-drawer-regexp
2790 (concat "^[ \t]*:\\("
2791 (mapconcat 'regexp-quote org-drawers "\\|")
2792 "\\):[ \t]*$")
2793 org-not-done-keywords
2794 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2795 org-todo-regexp
2796 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2797 "\\|") "\\)\\>")
2798 org-not-done-regexp
2799 (concat "\\<\\("
2800 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2801 "\\)\\>")
2802 org-todo-line-regexp
2803 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2804 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2805 "\\)\\>\\)?[ \t]*\\(.*\\)")
2806 org-complex-heading-regexp
2807 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2808 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2809 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2810 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2811 org-nl-done-regexp
2812 (concat "\n\\*+[ \t]+"
2813 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2814 "\\)" "\\>")
2815 org-todo-line-tags-regexp
2816 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2817 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2818 (org-re
2819 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2820 org-looking-at-done-regexp
2821 (concat "^" "\\(?:"
2822 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2823 "\\>")
2824 org-deadline-regexp (concat "\\<" org-deadline-string)
2825 org-deadline-time-regexp
2826 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2827 org-deadline-line-regexp
2828 (concat "\\<\\(" org-deadline-string "\\).*")
2829 org-scheduled-regexp
2830 (concat "\\<" org-scheduled-string)
2831 org-scheduled-time-regexp
2832 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2833 org-closed-time-regexp
2834 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2835 org-keyword-time-regexp
2836 (concat "\\<\\(" org-scheduled-string
2837 "\\|" org-deadline-string
2838 "\\|" org-closed-string
2839 "\\|" org-clock-string "\\)"
2840 " *[[<]\\([^]>]+\\)[]>]")
2841 org-keyword-time-not-clock-regexp
2842 (concat "\\<\\(" org-scheduled-string
2843 "\\|" org-deadline-string
2844 "\\|" org-closed-string
2845 "\\)"
2846 " *[[<]\\([^]>]+\\)[]>]")
2847 org-maybe-keyword-time-regexp
2848 (concat "\\(\\<\\(" org-scheduled-string
2849 "\\|" org-deadline-string
2850 "\\|" org-closed-string
2851 "\\|" org-clock-string "\\)\\)?"
2852 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2853 org-planning-or-clock-line-re
2854 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2855 "\\|" org-deadline-string
2856 "\\|" org-closed-string "\\|" org-clock-string
2857 "\\)\\>\\)")
2859 (org-compute-latex-and-specials-regexp)
2860 (org-set-font-lock-defaults)))
2862 (defun org-extract-log-state-settings (x)
2863 "Extract the log state setting from a TODO keyword string.
2864 This will extract info from a string like \"WAIT(w@/!)\"."
2865 (let (kw key log1 log2)
2866 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2867 (setq kw (match-string 1 x)
2868 key (and (match-end 2) (match-string 2 x))
2869 log1 (and (match-end 3) (match-string 3 x))
2870 log2 (and (match-end 4) (match-string 4 x)))
2871 (and (or log1 log2)
2872 (list kw
2873 (and log1 (if (equal log1 "!") 'time 'note))
2874 (and log2 (if (equal log2 "!") 'time 'note)))))))
2876 (defun org-remove-keyword-keys (list)
2877 "Remove a pair of parenthesis at the end of each string in LIST."
2878 (mapcar (lambda (x)
2879 (if (string-match "(.*)$" x)
2880 (substring x 0 (match-beginning 0))
2882 list))
2884 ;; FIXME: this could be done much better, using second characters etc.
2885 (defun org-assign-fast-keys (alist)
2886 "Assign fast keys to a keyword-key alist.
2887 Respect keys that are already there."
2888 (let (new e k c c1 c2 (char ?a))
2889 (while (setq e (pop alist))
2890 (cond
2891 ((equal e '(:startgroup)) (push e new))
2892 ((equal e '(:endgroup)) (push e new))
2894 (setq k (car e) c2 nil)
2895 (if (cdr e)
2896 (setq c (cdr e))
2897 ;; automatically assign a character.
2898 (setq c1 (string-to-char
2899 (downcase (substring
2900 k (if (= (string-to-char k) ?@) 1 0)))))
2901 (if (or (rassoc c1 new) (rassoc c1 alist))
2902 (while (or (rassoc char new) (rassoc char alist))
2903 (setq char (1+ char)))
2904 (setq c2 c1))
2905 (setq c (or c2 char)))
2906 (push (cons k c) new))))
2907 (nreverse new)))
2909 ;;; Some variables used in various places
2911 (defvar org-window-configuration nil
2912 "Used in various places to store a window configuration.")
2913 (defvar org-finish-function nil
2914 "Function to be called when `C-c C-c' is used.
2915 This is for getting out of special buffers like remember.")
2918 ;; FIXME: Occasionally check by commenting these, to make sure
2919 ;; no other functions uses these, forgetting to let-bind them.
2920 (defvar entry)
2921 (defvar state)
2922 (defvar last-state)
2923 (defvar date)
2924 (defvar description)
2926 ;; Defined somewhere in this file, but used before definition.
2927 (defvar org-html-entities)
2928 (defvar org-struct-menu)
2929 (defvar org-org-menu)
2930 (defvar org-tbl-menu)
2931 (defvar org-agenda-keymap)
2933 ;;;; Define the Org-mode
2935 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2936 (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."))
2939 ;; We use a before-change function to check if a table might need
2940 ;; an update.
2941 (defvar org-table-may-need-update t
2942 "Indicates that a table might need an update.
2943 This variable is set by `org-before-change-function'.
2944 `org-table-align' sets it back to nil.")
2945 (defun org-before-change-function (beg end)
2946 "Every change indicates that a table might need an update."
2947 (setq org-table-may-need-update t))
2948 (defvar org-mode-map)
2949 (defvar org-mode-hook nil)
2950 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2951 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2952 (defvar org-table-buffer-is-an nil)
2953 (defconst org-outline-regexp "\\*+ ")
2955 ;;;###autoload
2956 (define-derived-mode org-mode outline-mode "Org"
2957 "Outline-based notes management and organizer, alias
2958 \"Carsten's outline-mode for keeping track of everything.\"
2960 Org-mode develops organizational tasks around a NOTES file which
2961 contains information about projects as plain text. Org-mode is
2962 implemented on top of outline-mode, which is ideal to keep the content
2963 of large files well structured. It supports ToDo items, deadlines and
2964 time stamps, which magically appear in the diary listing of the Emacs
2965 calendar. Tables are easily created with a built-in table editor.
2966 Plain text URL-like links connect to websites, emails (VM), Usenet
2967 messages (Gnus), BBDB entries, and any files related to the project.
2968 For printing and sharing of notes, an Org-mode file (or a part of it)
2969 can be exported as a structured ASCII or HTML file.
2971 The following commands are available:
2973 \\{org-mode-map}"
2975 ;; Get rid of Outline menus, they are not needed
2976 ;; Need to do this here because define-derived-mode sets up
2977 ;; the keymap so late. Still, it is a waste to call this each time
2978 ;; we switch another buffer into org-mode.
2979 (if (featurep 'xemacs)
2980 (when (boundp 'outline-mode-menu-heading)
2981 ;; Assume this is Greg's port, it used easymenu
2982 (easy-menu-remove outline-mode-menu-heading)
2983 (easy-menu-remove outline-mode-menu-show)
2984 (easy-menu-remove outline-mode-menu-hide))
2985 (define-key org-mode-map [menu-bar headings] 'undefined)
2986 (define-key org-mode-map [menu-bar hide] 'undefined)
2987 (define-key org-mode-map [menu-bar show] 'undefined))
2989 (org-load-modules-maybe)
2990 (easy-menu-add org-org-menu)
2991 (easy-menu-add org-tbl-menu)
2992 (org-install-agenda-files-menu)
2993 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2994 (org-add-to-invisibility-spec '(org-cwidth))
2995 (when (featurep 'xemacs)
2996 (org-set-local 'line-move-ignore-invisible t))
2997 (org-set-local 'outline-regexp org-outline-regexp)
2998 (org-set-local 'outline-level 'org-outline-level)
2999 (when (and org-ellipsis
3000 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3001 (fboundp 'make-glyph-code))
3002 (unless org-display-table
3003 (setq org-display-table (make-display-table)))
3004 (set-display-table-slot
3005 org-display-table 4
3006 (vconcat (mapcar
3007 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3008 org-ellipsis)))
3009 (if (stringp org-ellipsis) org-ellipsis "..."))))
3010 (setq buffer-display-table org-display-table))
3011 (org-set-regexps-and-options)
3012 ;; Calc embedded
3013 (org-set-local 'calc-embedded-open-mode "# ")
3014 (modify-syntax-entry ?# "<")
3015 (modify-syntax-entry ?@ "w")
3016 (if org-startup-truncated (setq truncate-lines t))
3017 (org-set-local 'font-lock-unfontify-region-function
3018 'org-unfontify-region)
3019 ;; Activate before-change-function
3020 (org-set-local 'org-table-may-need-update t)
3021 (org-add-hook 'before-change-functions 'org-before-change-function nil
3022 'local)
3023 ;; Check for running clock before killing a buffer
3024 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3025 ;; Paragraphs and auto-filling
3026 (org-set-autofill-regexps)
3027 (setq indent-line-function 'org-indent-line-function)
3028 (org-update-radio-target-regexp)
3030 ;; Comment characters
3031 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3032 (org-set-local 'comment-padding " ")
3034 ;; Align options lines
3035 (org-set-local
3036 'align-mode-rules-list
3037 '((org-in-buffer-settings
3038 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3039 (modes . '(org-mode)))))
3041 ;; Imenu
3042 (org-set-local 'imenu-create-index-function
3043 'org-imenu-get-tree)
3045 ;; Make isearch reveal context
3046 (if (or (featurep 'xemacs)
3047 (not (boundp 'outline-isearch-open-invisible-function)))
3048 ;; Emacs 21 and XEmacs make use of the hook
3049 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3050 ;; Emacs 22 deals with this through a special variable
3051 (org-set-local 'outline-isearch-open-invisible-function
3052 (lambda (&rest ignore) (org-show-context 'isearch))))
3054 ;; If empty file that did not turn on org-mode automatically, make it to.
3055 (if (and org-insert-mode-line-in-empty-file
3056 (interactive-p)
3057 (= (point-min) (point-max)))
3058 (insert "# -*- mode: org -*-\n\n"))
3060 (unless org-inhibit-startup
3061 (when org-startup-align-all-tables
3062 (let ((bmp (buffer-modified-p)))
3063 (org-table-map-tables 'org-table-align)
3064 (set-buffer-modified-p bmp)))
3065 (org-cycle-hide-drawers 'all)
3066 (cond
3067 ((eq org-startup-folded t)
3068 (org-cycle '(4)))
3069 ((eq org-startup-folded 'content)
3070 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3071 (org-cycle '(4)) (org-cycle '(4)))))))
3073 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3075 (defun org-current-time ()
3076 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3077 (if (> (car org-time-stamp-rounding-minutes) 1)
3078 (let ((r (car org-time-stamp-rounding-minutes))
3079 (time (decode-time)))
3080 (apply 'encode-time
3081 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3082 (nthcdr 2 time))))
3083 (current-time)))
3085 ;;;; Font-Lock stuff, including the activators
3087 (defvar org-mouse-map (make-sparse-keymap))
3088 (org-defkey org-mouse-map
3089 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3090 (org-defkey org-mouse-map
3091 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3092 (when org-mouse-1-follows-link
3093 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3094 (when org-tab-follows-link
3095 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3096 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3097 (when org-return-follows-link
3098 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3099 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3101 (require 'font-lock)
3103 (defconst org-non-link-chars "]\t\n\r<>")
3104 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3105 "shell" "elisp"))
3106 (defvar org-link-types-re nil
3107 "Matches a link that has a url-like prefix like \"http:\"")
3108 (defvar org-link-re-with-space nil
3109 "Matches a link with spaces, optional angular brackets around it.")
3110 (defvar org-link-re-with-space2 nil
3111 "Matches a link with spaces, optional angular brackets around it.")
3112 (defvar org-angle-link-re nil
3113 "Matches link with angular brackets, spaces are allowed.")
3114 (defvar org-plain-link-re nil
3115 "Matches plain link, without spaces.")
3116 (defvar org-bracket-link-regexp nil
3117 "Matches a link in double brackets.")
3118 (defvar org-bracket-link-analytic-regexp nil
3119 "Regular expression used to analyze links.
3120 Here is what the match groups contain after a match:
3121 1: http:
3122 2: http
3123 3: path
3124 4: [desc]
3125 5: desc")
3126 (defvar org-any-link-re nil
3127 "Regular expression matching any link.")
3129 (defun org-make-link-regexps ()
3130 "Update the link regular expressions.
3131 This should be called after the variable `org-link-types' has changed."
3132 (setq org-link-types-re
3133 (concat
3134 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3135 org-link-re-with-space
3136 (concat
3137 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3138 "\\([^" org-non-link-chars " ]"
3139 "[^" org-non-link-chars "]*"
3140 "[^" org-non-link-chars " ]\\)>?")
3141 org-link-re-with-space2
3142 (concat
3143 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3144 "\\([^" org-non-link-chars " ]"
3145 "[^]\t\n\r]*"
3146 "[^" org-non-link-chars " ]\\)>?")
3147 org-angle-link-re
3148 (concat
3149 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3150 "\\([^" org-non-link-chars " ]"
3151 "[^" org-non-link-chars "]*"
3152 "\\)>")
3153 org-plain-link-re
3154 (concat
3155 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3156 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3157 org-bracket-link-regexp
3158 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3159 org-bracket-link-analytic-regexp
3160 (concat
3161 "\\[\\["
3162 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3163 "\\([^]]+\\)"
3164 "\\]"
3165 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3166 "\\]")
3167 org-any-link-re
3168 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3169 org-angle-link-re "\\)\\|\\("
3170 org-plain-link-re "\\)")))
3172 (org-make-link-regexps)
3174 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3175 "Regular expression for fast time stamp matching.")
3176 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3177 "Regular expression for fast time stamp matching.")
3178 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3179 "Regular expression matching time strings for analysis.
3180 This one does not require the space after the date, so it can be used
3181 on a string that terminates immediately after the date.")
3182 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3183 "Regular expression matching time strings for analysis.")
3184 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3185 "Regular expression matching time stamps, with groups.")
3186 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3187 "Regular expression matching time stamps (also [..]), with groups.")
3188 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3189 "Regular expression matching a time stamp range.")
3190 (defconst org-tr-regexp-both
3191 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3192 "Regular expression matching a time stamp range.")
3193 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3194 org-ts-regexp "\\)?")
3195 "Regular expression matching a time stamp or time stamp range.")
3196 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3197 org-ts-regexp-both "\\)?")
3198 "Regular expression matching a time stamp or time stamp range.
3199 The time stamps may be either active or inactive.")
3201 (defvar org-emph-face nil)
3203 (defun org-do-emphasis-faces (limit)
3204 "Run through the buffer and add overlays to links."
3205 (let (rtn)
3206 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3207 (if (not (= (char-after (match-beginning 3))
3208 (char-after (match-beginning 4))))
3209 (progn
3210 (setq rtn t)
3211 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3212 'face
3213 (nth 1 (assoc (match-string 3)
3214 org-emphasis-alist)))
3215 (add-text-properties (match-beginning 2) (match-end 2)
3216 '(font-lock-multiline t))
3217 (when org-hide-emphasis-markers
3218 (add-text-properties (match-end 4) (match-beginning 5)
3219 '(invisible org-link))
3220 (add-text-properties (match-beginning 3) (match-end 3)
3221 '(invisible org-link)))))
3222 (backward-char 1))
3223 rtn))
3225 (defun org-emphasize (&optional char)
3226 "Insert or change an emphasis, i.e. a font like bold or italic.
3227 If there is an active region, change that region to a new emphasis.
3228 If there is no region, just insert the marker characters and position
3229 the cursor between them.
3230 CHAR should be either the marker character, or the first character of the
3231 HTML tag associated with that emphasis. If CHAR is a space, the means
3232 to remove the emphasis of the selected region.
3233 If char is not given (for example in an interactive call) it
3234 will be prompted for."
3235 (interactive)
3236 (let ((eal org-emphasis-alist) e det
3237 (erc org-emphasis-regexp-components)
3238 (prompt "")
3239 (string "") beg end move tag c s)
3240 (if (org-region-active-p)
3241 (setq beg (region-beginning) end (region-end)
3242 string (buffer-substring beg end))
3243 (setq move t))
3245 (while (setq e (pop eal))
3246 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3247 c (aref tag 0))
3248 (push (cons c (string-to-char (car e))) det)
3249 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3250 (substring tag 1)))))
3251 (unless char
3252 (message "%s" (concat "Emphasis marker or tag:" prompt))
3253 (setq char (read-char-exclusive)))
3254 (setq char (or (cdr (assoc char det)) char))
3255 (if (equal char ?\ )
3256 (setq s "" move nil)
3257 (unless (assoc (char-to-string char) org-emphasis-alist)
3258 (error "No such emphasis marker: \"%c\"" char))
3259 (setq s (char-to-string char)))
3260 (while (and (> (length string) 1)
3261 (equal (substring string 0 1) (substring string -1))
3262 (assoc (substring string 0 1) org-emphasis-alist))
3263 (setq string (substring string 1 -1)))
3264 (setq string (concat s string s))
3265 (if beg (delete-region beg end))
3266 (unless (or (bolp)
3267 (string-match (concat "[" (nth 0 erc) "\n]")
3268 (char-to-string (char-before (point)))))
3269 (insert " "))
3270 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3271 (char-to-string (char-after (point))))
3272 (insert " ") (backward-char 1))
3273 (insert string)
3274 (and move (backward-char 1))))
3276 (defconst org-nonsticky-props
3277 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3280 (defun org-activate-plain-links (limit)
3281 "Run through the buffer and add overlays to links."
3282 (catch 'exit
3283 (let (f)
3284 (while (re-search-forward org-plain-link-re limit t)
3285 (setq f (get-text-property (match-beginning 0) 'face))
3286 (if (or (eq f 'org-tag)
3287 (and (listp f) (memq 'org-tag f)))
3289 (add-text-properties (match-beginning 0) (match-end 0)
3290 (list 'mouse-face 'highlight
3291 'rear-nonsticky org-nonsticky-props
3292 'keymap org-mouse-map
3294 (throw 'exit t))))))
3296 (defun org-activate-code (limit)
3297 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3298 (unless (get-text-property (match-beginning 1) 'face)
3299 (remove-text-properties (match-beginning 0) (match-end 0)
3300 '(display t invisible t intangible t))
3301 t)))
3303 (defun org-activate-angle-links (limit)
3304 "Run through the buffer and add overlays to links."
3305 (if (re-search-forward org-angle-link-re limit t)
3306 (progn
3307 (add-text-properties (match-beginning 0) (match-end 0)
3308 (list 'mouse-face 'highlight
3309 'rear-nonsticky org-nonsticky-props
3310 'keymap org-mouse-map
3312 t)))
3314 (defun org-activate-bracket-links (limit)
3315 "Run through the buffer and add overlays to bracketed links."
3316 (if (re-search-forward org-bracket-link-regexp limit t)
3317 (let* ((help (concat "LINK: "
3318 (org-match-string-no-properties 1)))
3319 ;; FIXME: above we should remove the escapes.
3320 ;; but that requires another match, protecting match data,
3321 ;; a lot of overhead for font-lock.
3322 (ip (org-maybe-intangible
3323 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3324 'keymap org-mouse-map 'mouse-face 'highlight
3325 'font-lock-multiline t 'help-echo help)))
3326 (vp (list 'rear-nonsticky org-nonsticky-props
3327 'keymap org-mouse-map 'mouse-face 'highlight
3328 ' font-lock-multiline t 'help-echo help)))
3329 ;; We need to remove the invisible property here. Table narrowing
3330 ;; may have made some of this invisible.
3331 (remove-text-properties (match-beginning 0) (match-end 0)
3332 '(invisible nil))
3333 (if (match-end 3)
3334 (progn
3335 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3336 (add-text-properties (match-beginning 3) (match-end 3) vp)
3337 (add-text-properties (match-end 3) (match-end 0) ip))
3338 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3339 (add-text-properties (match-beginning 1) (match-end 1) vp)
3340 (add-text-properties (match-end 1) (match-end 0) ip))
3341 t)))
3343 (defun org-activate-dates (limit)
3344 "Run through the buffer and add overlays to dates."
3345 (if (re-search-forward org-tsr-regexp-both limit t)
3346 (progn
3347 (add-text-properties (match-beginning 0) (match-end 0)
3348 (list 'mouse-face 'highlight
3349 'rear-nonsticky org-nonsticky-props
3350 'keymap org-mouse-map))
3351 (when org-display-custom-times
3352 (if (match-end 3)
3353 (org-display-custom-time (match-beginning 3) (match-end 3)))
3354 (org-display-custom-time (match-beginning 1) (match-end 1)))
3355 t)))
3357 (defvar org-target-link-regexp nil
3358 "Regular expression matching radio targets in plain text.")
3359 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3360 "Regular expression matching a link target.")
3361 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3362 "Regular expression matching a radio target.")
3363 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3364 "Regular expression matching any target.")
3366 (defun org-activate-target-links (limit)
3367 "Run through the buffer and add overlays to target matches."
3368 (when org-target-link-regexp
3369 (let ((case-fold-search t))
3370 (if (re-search-forward org-target-link-regexp limit t)
3371 (progn
3372 (add-text-properties (match-beginning 0) (match-end 0)
3373 (list 'mouse-face 'highlight
3374 'rear-nonsticky org-nonsticky-props
3375 'keymap org-mouse-map
3376 'help-echo "Radio target link"
3377 'org-linked-text t))
3378 t)))))
3380 (defun org-update-radio-target-regexp ()
3381 "Find all radio targets in this file and update the regular expression."
3382 (interactive)
3383 (when (memq 'radio org-activate-links)
3384 (setq org-target-link-regexp
3385 (org-make-target-link-regexp (org-all-targets 'radio)))
3386 (org-restart-font-lock)))
3388 (defun org-hide-wide-columns (limit)
3389 (let (s e)
3390 (setq s (text-property-any (point) (or limit (point-max))
3391 'org-cwidth t))
3392 (when s
3393 (setq e (next-single-property-change s 'org-cwidth))
3394 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3395 (goto-char e)
3396 t)))
3398 (defvar org-latex-and-specials-regexp nil
3399 "Regular expression for highlighting export special stuff.")
3400 (defvar org-match-substring-regexp)
3401 (defvar org-match-substring-with-braces-regexp)
3402 (defvar org-export-html-special-string-regexps)
3404 (defun org-compute-latex-and-specials-regexp ()
3405 "Compute regular expression for stuff treated specially by exporters."
3406 (if (not org-highlight-latex-fragments-and-specials)
3407 (org-set-local 'org-latex-and-specials-regexp nil)
3408 (require 'org-exp)
3409 (let*
3410 ((matchers (plist-get org-format-latex-options :matchers))
3411 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3412 org-latex-regexps)))
3413 (options (org-combine-plists (org-default-export-plist)
3414 (org-infile-export-plist)))
3415 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3416 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3417 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3418 (org-export-html-expand (plist-get options :expand-quoted-html))
3419 (org-export-with-special-strings (plist-get options :special-strings))
3420 (re-sub
3421 (cond
3422 ((equal org-export-with-sub-superscripts '{})
3423 (list org-match-substring-with-braces-regexp))
3424 (org-export-with-sub-superscripts
3425 (list org-match-substring-regexp))
3426 (t nil)))
3427 (re-latex
3428 (if org-export-with-LaTeX-fragments
3429 (mapcar (lambda (x) (nth 1 x)) latexs)))
3430 (re-macros
3431 (if org-export-with-TeX-macros
3432 (list (concat "\\\\"
3433 (regexp-opt
3434 (append (mapcar 'car org-html-entities)
3435 (if (boundp 'org-latex-entities)
3436 org-latex-entities nil))
3437 'words))) ; FIXME
3439 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3440 (re-special (if org-export-with-special-strings
3441 (mapcar (lambda (x) (car x))
3442 org-export-html-special-string-regexps)))
3443 (re-rest
3444 (delq nil
3445 (list
3446 (if org-export-html-expand "@<[^>\n]+>")
3447 ))))
3448 (org-set-local
3449 'org-latex-and-specials-regexp
3450 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3451 re-rest) "\\|")))))
3453 (defun org-do-latex-and-special-faces (limit)
3454 "Run through the buffer and add overlays to links."
3455 (when org-latex-and-specials-regexp
3456 (let (rtn d)
3457 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3458 limit t))
3459 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3460 'face))
3461 '(org-code org-verbatim underline)))
3462 (progn
3463 (setq rtn t
3464 d (cond ((member (char-after (1+ (match-beginning 0)))
3465 '(?_ ?^)) 1)
3466 (t 0)))
3467 (font-lock-prepend-text-property
3468 (+ d (match-beginning 0)) (match-end 0)
3469 'face 'org-latex-and-export-specials)
3470 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3471 '(font-lock-multiline t)))))
3472 rtn)))
3474 (defun org-restart-font-lock ()
3475 "Restart font-lock-mode, to force refontification."
3476 (when (and (boundp 'font-lock-mode) font-lock-mode)
3477 (font-lock-mode -1)
3478 (font-lock-mode 1)))
3480 (defun org-all-targets (&optional radio)
3481 "Return a list of all targets in this file.
3482 With optional argument RADIO, only find radio targets."
3483 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3484 rtn)
3485 (save-excursion
3486 (goto-char (point-min))
3487 (while (re-search-forward re nil t)
3488 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3489 rtn)))
3491 (defun org-make-target-link-regexp (targets)
3492 "Make regular expression matching all strings in TARGETS.
3493 The regular expression finds the targets also if there is a line break
3494 between words."
3495 (and targets
3496 (concat
3497 "\\<\\("
3498 (mapconcat
3499 (lambda (x)
3500 (while (string-match " +" x)
3501 (setq x (replace-match "\\s-+" t t x)))
3503 targets
3504 "\\|")
3505 "\\)\\>")))
3507 (defun org-activate-tags (limit)
3508 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3509 (progn
3510 (add-text-properties (match-beginning 1) (match-end 1)
3511 (list 'mouse-face 'highlight
3512 'rear-nonsticky org-nonsticky-props
3513 'keymap org-mouse-map))
3514 t)))
3516 (defun org-outline-level ()
3517 (save-excursion
3518 (looking-at outline-regexp)
3519 (if (match-beginning 1)
3520 (+ (org-get-string-indentation (match-string 1)) 1000)
3521 (1- (- (match-end 0) (match-beginning 0))))))
3523 (defvar org-font-lock-keywords nil)
3525 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
3526 "Regular expression matching a property line.")
3528 (defun org-set-font-lock-defaults ()
3529 (let* ((em org-fontify-emphasized-text)
3530 (lk org-activate-links)
3531 (org-font-lock-extra-keywords
3532 (list
3533 ;; Headlines
3534 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3535 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3536 ;; Table lines
3537 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3538 (1 'org-table t))
3539 ;; Table internals
3540 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3541 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3542 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3543 ;; Drawers
3544 (list org-drawer-regexp '(0 'org-special-keyword t))
3545 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3546 ;; Properties
3547 (list org-property-re
3548 '(1 'org-special-keyword t)
3549 '(3 'org-property-value t))
3550 (if org-format-transports-properties-p
3551 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3552 ;; Links
3553 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3554 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3555 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3556 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3557 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3558 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3559 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3560 '(org-hide-wide-columns (0 nil append))
3561 ;; TODO lines
3562 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3563 '(1 (org-get-todo-face 1) t))
3564 ;; DONE
3565 (if org-fontify-done-headline
3566 (list (concat "^[*]+ +\\<\\("
3567 (mapconcat 'regexp-quote org-done-keywords "\\|")
3568 "\\)\\(.*\\)")
3569 '(2 'org-headline-done t))
3570 nil)
3571 ;; Priorities
3572 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3573 ;; Special keywords
3574 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3575 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3576 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3577 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3578 ;; Emphasis
3579 (if em
3580 (if (featurep 'xemacs)
3581 '(org-do-emphasis-faces (0 nil append))
3582 '(org-do-emphasis-faces)))
3583 ;; Checkboxes
3584 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3585 2 'bold prepend)
3586 (if org-provide-checkbox-statistics
3587 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3588 (0 (org-get-checkbox-statistics-face) t)))
3589 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3590 '(1 'org-archived prepend))
3591 ;; Specials
3592 '(org-do-latex-and-special-faces)
3593 ;; Code
3594 '(org-activate-code (1 'org-code t))
3595 ;; COMMENT
3596 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3597 "\\|" org-quote-string "\\)\\>")
3598 '(1 'org-special-keyword t))
3599 '("^#.*" (0 'font-lock-comment-face t))
3601 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3602 ;; Now set the full font-lock-keywords
3603 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3604 (org-set-local 'font-lock-defaults
3605 '(org-font-lock-keywords t nil nil backward-paragraph))
3606 (kill-local-variable 'font-lock-keywords) nil))
3608 (defvar org-m nil)
3609 (defvar org-l nil)
3610 (defvar org-f nil)
3611 (defun org-get-level-face (n)
3612 "Get the right face for match N in font-lock matching of healdines."
3613 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3614 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3615 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3616 (cond
3617 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3618 ((eq n 2) org-f)
3619 (t (if org-level-color-stars-only nil org-f))))
3621 (defun org-get-todo-face (kwd)
3622 "Get the right face for a TODO keyword KWD.
3623 If KWD is a number, get the corresponding match group."
3624 (if (numberp kwd) (setq kwd (match-string kwd)))
3625 (or (cdr (assoc kwd org-todo-keyword-faces))
3626 (and (member kwd org-done-keywords) 'org-done)
3627 'org-todo))
3629 (defun org-unfontify-region (beg end &optional maybe_loudly)
3630 "Remove fontification and activation overlays from links."
3631 (font-lock-default-unfontify-region beg end)
3632 (let* ((buffer-undo-list t)
3633 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3634 (inhibit-modification-hooks t)
3635 deactivate-mark buffer-file-name buffer-file-truename)
3636 (remove-text-properties beg end
3637 '(mouse-face t keymap t org-linked-text t
3638 invisible t intangible t))))
3640 ;;;; Visibility cycling, including org-goto and indirect buffer
3642 ;;; Cycling
3644 (defvar org-cycle-global-status nil)
3645 (make-variable-buffer-local 'org-cycle-global-status)
3646 (defvar org-cycle-subtree-status nil)
3647 (make-variable-buffer-local 'org-cycle-subtree-status)
3649 ;;;###autoload
3650 (defun org-cycle (&optional arg)
3651 "Visibility cycling for Org-mode.
3653 - When this function is called with a prefix argument, rotate the entire
3654 buffer through 3 states (global cycling)
3655 1. OVERVIEW: Show only top-level headlines.
3656 2. CONTENTS: Show all headlines of all levels, but no body text.
3657 3. SHOW ALL: Show everything.
3659 - When point is at the beginning of a headline, rotate the subtree started
3660 by this line through 3 different states (local cycling)
3661 1. FOLDED: Only the main headline is shown.
3662 2. CHILDREN: The main headline and the direct children are shown.
3663 From this state, you can move to one of the children
3664 and zoom in further.
3665 3. SUBTREE: Show the entire subtree, including body text.
3667 - When there is a numeric prefix, go up to a heading with level ARG, do
3668 a `show-subtree' and return to the previous cursor position. If ARG
3669 is negative, go up that many levels.
3671 - When point is not at the beginning of a headline, execute
3672 `indent-relative', like TAB normally does. See the option
3673 `org-cycle-emulate-tab' for details.
3675 - Special case: if point is at the beginning of the buffer and there is
3676 no headline in line 1, this function will act as if called with prefix arg.
3677 But only if also the variable `org-cycle-global-at-bob' is t."
3678 (interactive "P")
3679 (org-load-modules-maybe)
3680 (let* ((outline-regexp
3681 (if (and (org-mode-p) org-cycle-include-plain-lists)
3682 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3683 outline-regexp))
3684 (bob-special (and org-cycle-global-at-bob (bobp)
3685 (not (looking-at outline-regexp))))
3686 (org-cycle-hook
3687 (if bob-special
3688 (delq 'org-optimize-window-after-visibility-change
3689 (copy-sequence org-cycle-hook))
3690 org-cycle-hook))
3691 (pos (point)))
3693 (if (or bob-special (equal arg '(4)))
3694 ;; special case: use global cycling
3695 (setq arg t))
3697 (cond
3699 ((org-at-table-p 'any)
3700 ;; Enter the table or move to the next field in the table
3701 (or (org-table-recognize-table.el)
3702 (progn
3703 (if arg (org-table-edit-field t)
3704 (org-table-justify-field-maybe)
3705 (call-interactively 'org-table-next-field)))))
3707 ((eq arg t) ;; Global cycling
3709 (cond
3710 ((and (eq last-command this-command)
3711 (eq org-cycle-global-status 'overview))
3712 ;; We just created the overview - now do table of contents
3713 ;; This can be slow in very large buffers, so indicate action
3714 (message "CONTENTS...")
3715 (org-content)
3716 (message "CONTENTS...done")
3717 (setq org-cycle-global-status 'contents)
3718 (run-hook-with-args 'org-cycle-hook 'contents))
3720 ((and (eq last-command this-command)
3721 (eq org-cycle-global-status 'contents))
3722 ;; We just showed the table of contents - now show everything
3723 (show-all)
3724 (message "SHOW ALL")
3725 (setq org-cycle-global-status 'all)
3726 (run-hook-with-args 'org-cycle-hook 'all))
3729 ;; Default action: go to overview
3730 (org-overview)
3731 (message "OVERVIEW")
3732 (setq org-cycle-global-status 'overview)
3733 (run-hook-with-args 'org-cycle-hook 'overview))))
3735 ((and org-drawers org-drawer-regexp
3736 (save-excursion
3737 (beginning-of-line 1)
3738 (looking-at org-drawer-regexp)))
3739 ;; Toggle block visibility
3740 (org-flag-drawer
3741 (not (get-char-property (match-end 0) 'invisible))))
3743 ((integerp arg)
3744 ;; Show-subtree, ARG levels up from here.
3745 (save-excursion
3746 (org-back-to-heading)
3747 (outline-up-heading (if (< arg 0) (- arg)
3748 (- (funcall outline-level) arg)))
3749 (org-show-subtree)))
3751 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3752 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3753 ;; At a heading: rotate between three different views
3754 (org-back-to-heading)
3755 (let ((goal-column 0) eoh eol eos)
3756 ;; First, some boundaries
3757 (save-excursion
3758 (org-back-to-heading)
3759 (save-excursion
3760 (beginning-of-line 2)
3761 (while (and (not (eobp)) ;; this is like `next-line'
3762 (get-char-property (1- (point)) 'invisible))
3763 (beginning-of-line 2)) (setq eol (point)))
3764 (outline-end-of-heading) (setq eoh (point))
3765 (org-end-of-subtree t)
3766 (unless (eobp)
3767 (skip-chars-forward " \t\n")
3768 (beginning-of-line 1) ; in case this is an item
3770 (setq eos (1- (point))))
3771 ;; Find out what to do next and set `this-command'
3772 (cond
3773 ((= eos eoh)
3774 ;; Nothing is hidden behind this heading
3775 (message "EMPTY ENTRY")
3776 (setq org-cycle-subtree-status nil)
3777 (save-excursion
3778 (goto-char eos)
3779 (outline-next-heading)
3780 (if (org-invisible-p) (org-flag-heading nil))))
3781 ((or (>= eol eos)
3782 (not (string-match "\\S-" (buffer-substring eol eos))))
3783 ;; Entire subtree is hidden in one line: open it
3784 (org-show-entry)
3785 (show-children)
3786 (message "CHILDREN")
3787 (save-excursion
3788 (goto-char eos)
3789 (outline-next-heading)
3790 (if (org-invisible-p) (org-flag-heading nil)))
3791 (setq org-cycle-subtree-status 'children)
3792 (run-hook-with-args 'org-cycle-hook 'children))
3793 ((and (eq last-command this-command)
3794 (eq org-cycle-subtree-status 'children))
3795 ;; We just showed the children, now show everything.
3796 (org-show-subtree)
3797 (message "SUBTREE")
3798 (setq org-cycle-subtree-status 'subtree)
3799 (run-hook-with-args 'org-cycle-hook 'subtree))
3801 ;; Default action: hide the subtree.
3802 (hide-subtree)
3803 (message "FOLDED")
3804 (setq org-cycle-subtree-status 'folded)
3805 (run-hook-with-args 'org-cycle-hook 'folded)))))
3807 ;; TAB emulation
3808 (buffer-read-only (org-back-to-heading))
3810 ((org-try-cdlatex-tab))
3812 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3813 (or (not (bolp))
3814 (not (looking-at outline-regexp))))
3815 (call-interactively (global-key-binding "\t")))
3817 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3818 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3819 (or (and (eq org-cycle-emulate-tab 'white)
3820 (= (match-end 0) (point-at-eol)))
3821 (and (eq org-cycle-emulate-tab 'whitestart)
3822 (>= (match-end 0) pos))))
3824 (eq org-cycle-emulate-tab t))
3825 (call-interactively (global-key-binding "\t")))
3827 (t (save-excursion
3828 (org-back-to-heading)
3829 (org-cycle))))))
3831 ;;;###autoload
3832 (defun org-global-cycle (&optional arg)
3833 "Cycle the global visibility. For details see `org-cycle'."
3834 (interactive "P")
3835 (let ((org-cycle-include-plain-lists
3836 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3837 (if (integerp arg)
3838 (progn
3839 (show-all)
3840 (hide-sublevels arg)
3841 (setq org-cycle-global-status 'contents))
3842 (org-cycle '(4)))))
3844 (defun org-overview ()
3845 "Switch to overview mode, shoing only top-level headlines.
3846 Really, this shows all headlines with level equal or greater than the level
3847 of the first headline in the buffer. This is important, because if the
3848 first headline is not level one, then (hide-sublevels 1) gives confusing
3849 results."
3850 (interactive)
3851 (let ((level (save-excursion
3852 (goto-char (point-min))
3853 (if (re-search-forward (concat "^" outline-regexp) nil t)
3854 (progn
3855 (goto-char (match-beginning 0))
3856 (funcall outline-level))))))
3857 (and level (hide-sublevels level))))
3859 (defun org-content (&optional arg)
3860 "Show all headlines in the buffer, like a table of contents.
3861 With numerical argument N, show content up to level N."
3862 (interactive "P")
3863 (save-excursion
3864 ;; Visit all headings and show their offspring
3865 (and (integerp arg) (org-overview))
3866 (goto-char (point-max))
3867 (catch 'exit
3868 (while (and (progn (condition-case nil
3869 (outline-previous-visible-heading 1)
3870 (error (goto-char (point-min))))
3872 (looking-at outline-regexp))
3873 (if (integerp arg)
3874 (show-children (1- arg))
3875 (show-branches))
3876 (if (bobp) (throw 'exit nil))))))
3879 (defun org-optimize-window-after-visibility-change (state)
3880 "Adjust the window after a change in outline visibility.
3881 This function is the default value of the hook `org-cycle-hook'."
3882 (when (get-buffer-window (current-buffer))
3883 (cond
3884 ; ((eq state 'overview) (org-first-headline-recenter 1))
3885 ; ((eq state 'overview) (org-beginning-of-line))
3886 ((eq state 'content) nil)
3887 ((eq state 'all) nil)
3888 ((eq state 'folded) nil)
3889 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3890 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3892 (defun org-compact-display-after-subtree-move ()
3893 (let (beg end)
3894 (save-excursion
3895 (if (org-up-heading-safe)
3896 (progn
3897 (hide-subtree)
3898 (show-entry)
3899 (show-children)
3900 (org-cycle-show-empty-lines 'children)
3901 (org-cycle-hide-drawers 'children))
3902 (org-overview)))))
3904 (defun org-cycle-show-empty-lines (state)
3905 "Show empty lines above all visible headlines.
3906 The region to be covered depends on STATE when called through
3907 `org-cycle-hook'. Lisp program can use t for STATE to get the
3908 entire buffer covered. Note that an empty line is only shown if there
3909 are at least `org-cycle-separator-lines' empty lines before the headeline."
3910 (when (> org-cycle-separator-lines 0)
3911 (save-excursion
3912 (let* ((n org-cycle-separator-lines)
3913 (re (cond
3914 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3915 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3916 (t (let ((ns (number-to-string (- n 2))))
3917 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3918 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3919 beg end)
3920 (cond
3921 ((memq state '(overview contents t))
3922 (setq beg (point-min) end (point-max)))
3923 ((memq state '(children folded))
3924 (setq beg (point) end (progn (org-end-of-subtree t t)
3925 (beginning-of-line 2)
3926 (point)))))
3927 (when beg
3928 (goto-char beg)
3929 (while (re-search-forward re end t)
3930 (if (not (get-char-property (match-end 1) 'invisible))
3931 (outline-flag-region
3932 (match-beginning 1) (match-end 1) nil)))))))
3933 ;; Never hide empty lines at the end of the file.
3934 (save-excursion
3935 (goto-char (point-max))
3936 (outline-previous-heading)
3937 (outline-end-of-heading)
3938 (if (and (looking-at "[ \t\n]+")
3939 (= (match-end 0) (point-max)))
3940 (outline-flag-region (point) (match-end 0) nil))))
3942 (defun org-cycle-hide-drawers (state)
3943 "Re-hide all drawers after a visibility state change."
3944 (when (and (org-mode-p)
3945 (not (memq state '(overview folded))))
3946 (save-excursion
3947 (let* ((globalp (memq state '(contents all)))
3948 (beg (if globalp (point-min) (point)))
3949 (end (if globalp (point-max) (org-end-of-subtree t))))
3950 (goto-char beg)
3951 (while (re-search-forward org-drawer-regexp end t)
3952 (org-flag-drawer t))))))
3954 (defun org-flag-drawer (flag)
3955 (save-excursion
3956 (beginning-of-line 1)
3957 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
3958 (let ((b (match-end 0))
3959 (outline-regexp org-outline-regexp))
3960 (if (re-search-forward
3961 "^[ \t]*:END:"
3962 (save-excursion (outline-next-heading) (point)) t)
3963 (outline-flag-region b (point-at-eol) flag)
3964 (error ":END: line missing"))))))
3968 (defun org-subtree-end-visible-p ()
3969 "Is the end of the current subtree visible?"
3970 (pos-visible-in-window-p
3971 (save-excursion (org-end-of-subtree t) (point))))
3973 (defun org-first-headline-recenter (&optional N)
3974 "Move cursor to the first headline and recenter the headline.
3975 Optional argument N means, put the headline into the Nth line of the window."
3976 (goto-char (point-min))
3977 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3978 (beginning-of-line)
3979 (recenter (prefix-numeric-value N))))
3981 ;;; Org-goto
3983 (defvar org-goto-window-configuration nil)
3984 (defvar org-goto-marker nil)
3985 (defvar org-goto-map
3986 (let ((map (make-sparse-keymap)))
3987 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
3988 (while (setq cmd (pop cmds))
3989 (substitute-key-definition cmd cmd map global-map)))
3990 (suppress-keymap map)
3991 (org-defkey map "\C-m" 'org-goto-ret)
3992 (org-defkey map [(return)] 'org-goto-ret)
3993 (org-defkey map [(left)] 'org-goto-left)
3994 (org-defkey map [(right)] 'org-goto-right)
3995 (org-defkey map [(control ?g)] 'org-goto-quit)
3996 (org-defkey map "\C-i" 'org-cycle)
3997 (org-defkey map [(tab)] 'org-cycle)
3998 (org-defkey map [(down)] 'outline-next-visible-heading)
3999 (org-defkey map [(up)] 'outline-previous-visible-heading)
4000 (if org-goto-auto-isearch
4001 (if (fboundp 'define-key-after)
4002 (define-key-after map [t] 'org-goto-local-auto-isearch)
4003 nil)
4004 (org-defkey map "q" 'org-goto-quit)
4005 (org-defkey map "n" 'outline-next-visible-heading)
4006 (org-defkey map "p" 'outline-previous-visible-heading)
4007 (org-defkey map "f" 'outline-forward-same-level)
4008 (org-defkey map "b" 'outline-backward-same-level)
4009 (org-defkey map "u" 'outline-up-heading))
4010 (org-defkey map "/" 'org-occur)
4011 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4012 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4013 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4014 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4015 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4016 map))
4018 (defconst org-goto-help
4019 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4020 RET=jump to location [Q]uit and return to previous location
4021 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4023 (defvar org-goto-start-pos) ; dynamically scoped parameter
4025 (defun org-goto (&optional alternative-interface)
4026 "Look up a different location in the current file, keeping current visibility.
4028 When you want look-up or go to a different location in a document, the
4029 fastest way is often to fold the entire buffer and then dive into the tree.
4030 This method has the disadvantage, that the previous location will be folded,
4031 which may not be what you want.
4033 This command works around this by showing a copy of the current buffer
4034 in an indirect buffer, in overview mode. You can dive into the tree in
4035 that copy, use org-occur and incremental search to find a location.
4036 When pressing RET or `Q', the command returns to the original buffer in
4037 which the visibility is still unchanged. After RET is will also jump to
4038 the location selected in the indirect buffer and expose the
4039 the headline hierarchy above."
4040 (interactive "P")
4041 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4042 (org-refile-use-outline-path t)
4043 (interface
4044 (if (not alternative-interface)
4045 org-goto-interface
4046 (if (eq org-goto-interface 'outline)
4047 'outline-path-completion
4048 'outline)))
4049 (org-goto-start-pos (point))
4050 (selected-point
4051 (if (eq interface 'outline)
4052 (car (org-get-location (current-buffer) org-goto-help))
4053 (nth 3 (org-refile-get-location "Goto: ")))))
4054 (if selected-point
4055 (progn
4056 (org-mark-ring-push org-goto-start-pos)
4057 (goto-char selected-point)
4058 (if (or (org-invisible-p) (org-invisible-p2))
4059 (org-show-context 'org-goto)))
4060 (message "Quit"))))
4062 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4063 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4064 (defvar org-goto-local-auto-isearch-map) ; defined below
4066 (defun org-get-location (buf help)
4067 "Let the user select a location in the Org-mode buffer BUF.
4068 This function uses a recursive edit. It returns the selected position
4069 or nil."
4070 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4071 (isearch-hide-immediately nil)
4072 (isearch-search-fun-function
4073 (lambda () 'org-goto-local-search-forward-headings))
4074 (org-goto-selected-point org-goto-exit-command))
4075 (save-excursion
4076 (save-window-excursion
4077 (delete-other-windows)
4078 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4079 (switch-to-buffer
4080 (condition-case nil
4081 (make-indirect-buffer (current-buffer) "*org-goto*")
4082 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4083 (with-output-to-temp-buffer "*Help*"
4084 (princ help))
4085 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4086 (setq buffer-read-only nil)
4087 (let ((org-startup-truncated t)
4088 (org-startup-folded nil)
4089 (org-startup-align-all-tables nil))
4090 (org-mode)
4091 (org-overview))
4092 (setq buffer-read-only t)
4093 (if (and (boundp 'org-goto-start-pos)
4094 (integer-or-marker-p org-goto-start-pos))
4095 (let ((org-show-hierarchy-above t)
4096 (org-show-siblings t)
4097 (org-show-following-heading t))
4098 (goto-char org-goto-start-pos)
4099 (and (org-invisible-p) (org-show-context)))
4100 (goto-char (point-min)))
4101 (org-beginning-of-line)
4102 (message "Select location and press RET")
4103 (use-local-map org-goto-map)
4104 (recursive-edit)
4106 (kill-buffer "*org-goto*")
4107 (cons org-goto-selected-point org-goto-exit-command)))
4109 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4110 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4111 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4112 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4114 (defun org-goto-local-search-forward-headings (string bound noerror)
4115 "Search and make sure that anu matches are in headlines."
4116 (catch 'return
4117 (while (search-forward string bound noerror)
4118 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4119 (and (member :headline context)
4120 (not (member :tags context))))
4121 (throw 'return (point))))))
4123 (defun org-goto-local-auto-isearch ()
4124 "Start isearch."
4125 (interactive)
4126 (goto-char (point-min))
4127 (let ((keys (this-command-keys)))
4128 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4129 (isearch-mode t)
4130 (isearch-process-search-char (string-to-char keys)))))
4132 (defun org-goto-ret (&optional arg)
4133 "Finish `org-goto' by going to the new location."
4134 (interactive "P")
4135 (setq org-goto-selected-point (point)
4136 org-goto-exit-command 'return)
4137 (throw 'exit nil))
4139 (defun org-goto-left ()
4140 "Finish `org-goto' by going to the new location."
4141 (interactive)
4142 (if (org-on-heading-p)
4143 (progn
4144 (beginning-of-line 1)
4145 (setq org-goto-selected-point (point)
4146 org-goto-exit-command 'left)
4147 (throw 'exit nil))
4148 (error "Not on a heading")))
4150 (defun org-goto-right ()
4151 "Finish `org-goto' by going to the new location."
4152 (interactive)
4153 (if (org-on-heading-p)
4154 (progn
4155 (setq org-goto-selected-point (point)
4156 org-goto-exit-command 'right)
4157 (throw 'exit nil))
4158 (error "Not on a heading")))
4160 (defun org-goto-quit ()
4161 "Finish `org-goto' without cursor motion."
4162 (interactive)
4163 (setq org-goto-selected-point nil)
4164 (setq org-goto-exit-command 'quit)
4165 (throw 'exit nil))
4167 ;;; Indirect buffer display of subtrees
4169 (defvar org-indirect-dedicated-frame nil
4170 "This is the frame being used for indirect tree display.")
4171 (defvar org-last-indirect-buffer nil)
4173 (defun org-tree-to-indirect-buffer (&optional arg)
4174 "Create indirect buffer and narrow it to current subtree.
4175 With numerical prefix ARG, go up to this level and then take that tree.
4176 If ARG is negative, go up that many levels.
4177 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4178 indirect buffer previously made with this command, to avoid proliferation of
4179 indirect buffers. However, when you call the command with a `C-u' prefix, or
4180 when `org-indirect-buffer-display' is `new-frame', the last buffer
4181 is kept so that you can work with several indirect buffers at the same time.
4182 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4183 requests that a new frame be made for the new buffer, so that the dedicated
4184 frame is not changed."
4185 (interactive "P")
4186 (let ((cbuf (current-buffer))
4187 (cwin (selected-window))
4188 (pos (point))
4189 beg end level heading ibuf)
4190 (save-excursion
4191 (org-back-to-heading t)
4192 (when (numberp arg)
4193 (setq level (org-outline-level))
4194 (if (< arg 0) (setq arg (+ level arg)))
4195 (while (> (setq level (org-outline-level)) arg)
4196 (outline-up-heading 1 t)))
4197 (setq beg (point)
4198 heading (org-get-heading))
4199 (org-end-of-subtree t) (setq end (point)))
4200 (if (and (buffer-live-p org-last-indirect-buffer)
4201 (not (eq org-indirect-buffer-display 'new-frame))
4202 (not arg))
4203 (kill-buffer org-last-indirect-buffer))
4204 (setq ibuf (org-get-indirect-buffer cbuf)
4205 org-last-indirect-buffer ibuf)
4206 (cond
4207 ((or (eq org-indirect-buffer-display 'new-frame)
4208 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4209 (select-frame (make-frame))
4210 (delete-other-windows)
4211 (switch-to-buffer ibuf)
4212 (org-set-frame-title heading))
4213 ((eq org-indirect-buffer-display 'dedicated-frame)
4214 (raise-frame
4215 (select-frame (or (and org-indirect-dedicated-frame
4216 (frame-live-p org-indirect-dedicated-frame)
4217 org-indirect-dedicated-frame)
4218 (setq org-indirect-dedicated-frame (make-frame)))))
4219 (delete-other-windows)
4220 (switch-to-buffer ibuf)
4221 (org-set-frame-title (concat "Indirect: " heading)))
4222 ((eq org-indirect-buffer-display 'current-window)
4223 (switch-to-buffer ibuf))
4224 ((eq org-indirect-buffer-display 'other-window)
4225 (pop-to-buffer ibuf))
4226 (t (error "Invalid value.")))
4227 (if (featurep 'xemacs)
4228 (save-excursion (org-mode) (turn-on-font-lock)))
4229 (narrow-to-region beg end)
4230 (show-all)
4231 (goto-char pos)
4232 (and (window-live-p cwin) (select-window cwin))))
4234 (defun org-get-indirect-buffer (&optional buffer)
4235 (setq buffer (or buffer (current-buffer)))
4236 (let ((n 1) (base (buffer-name buffer)) bname)
4237 (while (buffer-live-p
4238 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4239 (setq n (1+ n)))
4240 (condition-case nil
4241 (make-indirect-buffer buffer bname 'clone)
4242 (error (make-indirect-buffer buffer bname)))))
4244 (defun org-set-frame-title (title)
4245 "Set the title of the current frame to the string TITLE."
4246 ;; FIXME: how to name a single frame in XEmacs???
4247 (unless (featurep 'xemacs)
4248 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4250 ;;;; Structure editing
4252 ;;; Inserting headlines
4254 (defun org-insert-heading (&optional force-heading)
4255 "Insert a new heading or item with same depth at point.
4256 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4257 If point is at the beginning of a headline, insert a sibling before the
4258 current headline. If point is not at the beginning, do not split the line,
4259 but create the new hedline after the current line."
4260 (interactive "P")
4261 (if (= (buffer-size) 0)
4262 (insert "\n* ")
4263 (when (or force-heading (not (org-insert-item)))
4264 (let* ((head (save-excursion
4265 (condition-case nil
4266 (progn
4267 (org-back-to-heading)
4268 (match-string 0))
4269 (error "*"))))
4270 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4271 pos)
4272 (cond
4273 ((and (org-on-heading-p) (bolp)
4274 (or (bobp)
4275 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4276 ;; insert before the current line
4277 (open-line (if blank 2 1)))
4278 ((and (bolp)
4279 (or (bobp)
4280 (save-excursion
4281 (backward-char 1) (not (org-invisible-p)))))
4282 ;; insert right here
4283 nil)
4285 ;; in the middle of the line
4286 (org-show-entry)
4287 (let ((split
4288 (org-get-alist-option org-M-RET-may-split-line 'headline))
4289 tags pos)
4290 (if (org-on-heading-p)
4291 (progn
4292 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4293 (setq tags (and (match-end 2) (match-string 2)))
4294 (and (match-end 1)
4295 (delete-region (match-beginning 1) (match-end 1)))
4296 (setq pos (point-at-bol))
4297 (or split (end-of-line 1))
4298 (delete-horizontal-space)
4299 (newline (if blank 2 1))
4300 (when tags
4301 (save-excursion
4302 (goto-char pos)
4303 (end-of-line 1)
4304 (insert " " tags)
4305 (org-set-tags nil 'align))))
4306 (or split (end-of-line 1))
4307 (newline (if blank 2 1))))))
4308 (insert head) (just-one-space)
4309 (setq pos (point))
4310 (end-of-line 1)
4311 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4312 (run-hooks 'org-insert-heading-hook)))))
4314 (defun org-get-heading (&optional no-tags)
4315 "Return the heading of the current entry, without the stars."
4316 (save-excursion
4317 (org-back-to-heading t)
4318 (if (looking-at
4319 (if no-tags
4320 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4321 "\\*+[ \t]+\\([^\r\n]*\\)"))
4322 (match-string 1) "")))
4324 (defun org-insert-heading-after-current ()
4325 "Insert a new heading with same level as current, after current subtree."
4326 (interactive)
4327 (org-back-to-heading)
4328 (org-insert-heading)
4329 (org-move-subtree-down)
4330 (end-of-line 1))
4332 (defun org-insert-todo-heading (arg)
4333 "Insert a new heading with the same level and TODO state as current heading.
4334 If the heading has no TODO state, or if the state is DONE, use the first
4335 state (TODO by default). Also with prefix arg, force first state."
4336 (interactive "P")
4337 (when (not (org-insert-item 'checkbox))
4338 (org-insert-heading)
4339 (save-excursion
4340 (org-back-to-heading)
4341 (outline-previous-heading)
4342 (looking-at org-todo-line-regexp))
4343 (if (or arg
4344 (not (match-beginning 2))
4345 (member (match-string 2) org-done-keywords))
4346 (insert (car org-todo-keywords-1) " ")
4347 (insert (match-string 2) " "))))
4349 (defun org-insert-subheading (arg)
4350 "Insert a new subheading and demote it.
4351 Works for outline headings and for plain lists alike."
4352 (interactive "P")
4353 (org-insert-heading arg)
4354 (cond
4355 ((org-on-heading-p) (org-do-demote))
4356 ((org-at-item-p) (org-indent-item 1))))
4358 (defun org-insert-todo-subheading (arg)
4359 "Insert a new subheading with TODO keyword or checkbox and demote it.
4360 Works for outline headings and for plain lists alike."
4361 (interactive "P")
4362 (org-insert-todo-heading arg)
4363 (cond
4364 ((org-on-heading-p) (org-do-demote))
4365 ((org-at-item-p) (org-indent-item 1))))
4367 ;;; Promotion and Demotion
4369 (defun org-promote-subtree ()
4370 "Promote the entire subtree.
4371 See also `org-promote'."
4372 (interactive)
4373 (save-excursion
4374 (org-map-tree 'org-promote))
4375 (org-fix-position-after-promote))
4377 (defun org-demote-subtree ()
4378 "Demote the entire subtree. See `org-demote'.
4379 See also `org-promote'."
4380 (interactive)
4381 (save-excursion
4382 (org-map-tree 'org-demote))
4383 (org-fix-position-after-promote))
4386 (defun org-do-promote ()
4387 "Promote the current heading higher up the tree.
4388 If the region is active in `transient-mark-mode', promote all headings
4389 in the region."
4390 (interactive)
4391 (save-excursion
4392 (if (org-region-active-p)
4393 (org-map-region 'org-promote (region-beginning) (region-end))
4394 (org-promote)))
4395 (org-fix-position-after-promote))
4397 (defun org-do-demote ()
4398 "Demote the current heading lower down the tree.
4399 If the region is active in `transient-mark-mode', demote all headings
4400 in the region."
4401 (interactive)
4402 (save-excursion
4403 (if (org-region-active-p)
4404 (org-map-region 'org-demote (region-beginning) (region-end))
4405 (org-demote)))
4406 (org-fix-position-after-promote))
4408 (defun org-fix-position-after-promote ()
4409 "Make sure that after pro/demotion cursor position is right."
4410 (let ((pos (point)))
4411 (when (save-excursion
4412 (beginning-of-line 1)
4413 (looking-at org-todo-line-regexp)
4414 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4415 (cond ((eobp) (insert " "))
4416 ((eolp) (insert " "))
4417 ((equal (char-after) ?\ ) (forward-char 1))))))
4419 (defun org-reduced-level (l)
4420 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4422 (defun org-get-valid-level (level &optional change)
4423 "Rectify a level change under the influence of `org-odd-levels-only'
4424 LEVEL is a current level, CHANGE is by how much the level should be
4425 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4426 even level numbers will become the next higher odd number."
4427 (if org-odd-levels-only
4428 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4429 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4430 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4431 (max 1 (+ level change))))
4433 (if (boundp 'define-obsolete-function-alias)
4434 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4435 (define-obsolete-function-alias 'org-get-legal-level
4436 'org-get-valid-level)
4437 (define-obsolete-function-alias 'org-get-legal-level
4438 'org-get-valid-level "23.1")))
4440 (defun org-promote ()
4441 "Promote the current heading higher up the tree.
4442 If the region is active in `transient-mark-mode', promote all headings
4443 in the region."
4444 (org-back-to-heading t)
4445 (let* ((level (save-match-data (funcall outline-level)))
4446 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4447 (diff (abs (- level (length up-head) -1))))
4448 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4449 (replace-match up-head nil t)
4450 ;; Fixup tag positioning
4451 (and org-auto-align-tags (org-set-tags nil t))
4452 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4454 (defun org-demote ()
4455 "Demote the current heading lower down the tree.
4456 If the region is active in `transient-mark-mode', demote all headings
4457 in the region."
4458 (org-back-to-heading t)
4459 (let* ((level (save-match-data (funcall outline-level)))
4460 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4461 (diff (abs (- level (length down-head) -1))))
4462 (replace-match down-head nil t)
4463 ;; Fixup tag positioning
4464 (and org-auto-align-tags (org-set-tags nil t))
4465 (if org-adapt-indentation (org-fixup-indentation diff))))
4467 (defun org-map-tree (fun)
4468 "Call FUN for every heading underneath the current one."
4469 (org-back-to-heading)
4470 (let ((level (funcall outline-level)))
4471 (save-excursion
4472 (funcall fun)
4473 (while (and (progn
4474 (outline-next-heading)
4475 (> (funcall outline-level) level))
4476 (not (eobp)))
4477 (funcall fun)))))
4479 (defun org-map-region (fun beg end)
4480 "Call FUN for every heading between BEG and END."
4481 (let ((org-ignore-region t))
4482 (save-excursion
4483 (setq end (copy-marker end))
4484 (goto-char beg)
4485 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4486 (< (point) end))
4487 (funcall fun))
4488 (while (and (progn
4489 (outline-next-heading)
4490 (< (point) end))
4491 (not (eobp)))
4492 (funcall fun)))))
4494 (defun org-fixup-indentation (diff)
4495 "Change the indentation in the current entry by DIFF
4496 However, if any line in the current entry has no indentation, or if it
4497 would end up with no indentation after the change, nothing at all is done."
4498 (save-excursion
4499 (let ((end (save-excursion (outline-next-heading)
4500 (point-marker)))
4501 (prohibit (if (> diff 0)
4502 "^\\S-"
4503 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4504 col)
4505 (unless (save-excursion (end-of-line 1)
4506 (re-search-forward prohibit end t))
4507 (while (and (< (point) end)
4508 (re-search-forward "^[ \t]+" end t))
4509 (goto-char (match-end 0))
4510 (setq col (current-column))
4511 (if (< diff 0) (replace-match ""))
4512 (indent-to (+ diff col))))
4513 (move-marker end nil))))
4515 (defun org-convert-to-odd-levels ()
4516 "Convert an org-mode file with all levels allowed to one with odd levels.
4517 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4518 level 5 etc."
4519 (interactive)
4520 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4521 (let ((org-odd-levels-only nil) n)
4522 (save-excursion
4523 (goto-char (point-min))
4524 (while (re-search-forward "^\\*\\*+ " nil t)
4525 (setq n (- (length (match-string 0)) 2))
4526 (while (>= (setq n (1- n)) 0)
4527 (org-demote))
4528 (end-of-line 1))))))
4531 (defun org-convert-to-oddeven-levels ()
4532 "Convert an org-mode file with only odd levels to one with odd and even levels.
4533 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4534 section with an even level, conversion would destroy the structure of the file. An error
4535 is signaled in this case."
4536 (interactive)
4537 (goto-char (point-min))
4538 ;; First check if there are no even levels
4539 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4540 (org-show-context t)
4541 (error "Not all levels are odd in this file. Conversion not possible."))
4542 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4543 (let ((org-odd-levels-only nil) n)
4544 (save-excursion
4545 (goto-char (point-min))
4546 (while (re-search-forward "^\\*\\*+ " nil t)
4547 (setq n (/ (1- (length (match-string 0))) 2))
4548 (while (>= (setq n (1- n)) 0)
4549 (org-promote))
4550 (end-of-line 1))))))
4552 (defun org-tr-level (n)
4553 "Make N odd if required."
4554 (if org-odd-levels-only (1+ (/ n 2)) n))
4556 ;;; Vertical tree motion, cutting and pasting of subtrees
4558 (defun org-move-subtree-up (&optional arg)
4559 "Move the current subtree up past ARG headlines of the same level."
4560 (interactive "p")
4561 (org-move-subtree-down (- (prefix-numeric-value arg))))
4563 (defun org-move-subtree-down (&optional arg)
4564 "Move the current subtree down past ARG headlines of the same level."
4565 (interactive "p")
4566 (setq arg (prefix-numeric-value arg))
4567 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4568 'outline-get-last-sibling))
4569 (ins-point (make-marker))
4570 (cnt (abs arg))
4571 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4572 ;; Select the tree
4573 (org-back-to-heading)
4574 (setq beg0 (point))
4575 (save-excursion
4576 (setq ne-beg (org-back-over-empty-lines))
4577 (setq beg (point)))
4578 (save-match-data
4579 (save-excursion (outline-end-of-heading)
4580 (setq folded (org-invisible-p)))
4581 (outline-end-of-subtree))
4582 (outline-next-heading)
4583 (setq ne-end (org-back-over-empty-lines))
4584 (setq end (point))
4585 (goto-char beg0)
4586 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4587 ;; include less whitespace
4588 (save-excursion
4589 (goto-char beg)
4590 (forward-line (- ne-beg ne-end))
4591 (setq beg (point))))
4592 ;; Find insertion point, with error handling
4593 (while (> cnt 0)
4594 (or (and (funcall movfunc) (looking-at outline-regexp))
4595 (progn (goto-char beg0)
4596 (error "Cannot move past superior level or buffer limit")))
4597 (setq cnt (1- cnt)))
4598 (if (> arg 0)
4599 ;; Moving forward - still need to move over subtree
4600 (progn (org-end-of-subtree t t)
4601 (save-excursion
4602 (org-back-over-empty-lines)
4603 (or (bolp) (newline)))))
4604 (setq ne-ins (org-back-over-empty-lines))
4605 (move-marker ins-point (point))
4606 (setq txt (buffer-substring beg end))
4607 (delete-region beg end)
4608 (outline-flag-region (1- beg) beg nil)
4609 (outline-flag-region (1- (point)) (point) nil)
4610 (insert txt)
4611 (or (bolp) (insert "\n"))
4612 (setq ins-end (point))
4613 (goto-char ins-point)
4614 (org-skip-whitespace)
4615 (when (and (< arg 0)
4616 (org-first-sibling-p)
4617 (> ne-ins ne-beg))
4618 ;; Move whitespace back to beginning
4619 (save-excursion
4620 (goto-char ins-end)
4621 (let ((kill-whole-line t))
4622 (kill-line (- ne-ins ne-beg)) (point)))
4623 (insert (make-string (- ne-ins ne-beg) ?\n)))
4624 (move-marker ins-point nil)
4625 (org-compact-display-after-subtree-move)
4626 (unless folded
4627 (org-show-entry)
4628 (show-children)
4629 (org-cycle-hide-drawers 'children))))
4631 (defvar org-subtree-clip ""
4632 "Clipboard for cut and paste of subtrees.
4633 This is actually only a copy of the kill, because we use the normal kill
4634 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4636 (defvar org-subtree-clip-folded nil
4637 "Was the last copied subtree folded?
4638 This is used to fold the tree back after pasting.")
4640 (defun org-cut-subtree (&optional n)
4641 "Cut the current subtree into the clipboard.
4642 With prefix arg N, cut this many sequential subtrees.
4643 This is a short-hand for marking the subtree and then cutting it."
4644 (interactive "p")
4645 (org-copy-subtree n 'cut))
4647 (defun org-copy-subtree (&optional n cut)
4648 "Cut the current subtree into the clipboard.
4649 With prefix arg N, cut this many sequential subtrees.
4650 This is a short-hand for marking the subtree and then copying it.
4651 If CUT is non-nil, actually cut the subtree."
4652 (interactive "p")
4653 (let (beg end folded (beg0 (point)))
4654 (if (interactive-p)
4655 (org-back-to-heading nil) ; take what looks like a subtree
4656 (org-back-to-heading t)) ; take what is really there
4657 (org-back-over-empty-lines)
4658 (setq beg (point))
4659 (skip-chars-forward " \t\r\n")
4660 (save-match-data
4661 (save-excursion (outline-end-of-heading)
4662 (setq folded (org-invisible-p)))
4663 (condition-case nil
4664 (outline-forward-same-level (1- n))
4665 (error nil))
4666 (org-end-of-subtree t t))
4667 (org-back-over-empty-lines)
4668 (setq end (point))
4669 (goto-char beg0)
4670 (when (> end beg)
4671 (setq org-subtree-clip-folded folded)
4672 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4673 (setq org-subtree-clip (current-kill 0))
4674 (message "%s: Subtree(s) with %d characters"
4675 (if cut "Cut" "Copied")
4676 (length org-subtree-clip)))))
4678 (defun org-paste-subtree (&optional level tree)
4679 "Paste the clipboard as a subtree, with modification of headline level.
4680 The entire subtree is promoted or demoted in order to match a new headline
4681 level. By default, the new level is derived from the visible headings
4682 before and after the insertion point, and taken to be the inferior headline
4683 level of the two. So if the previous visible heading is level 3 and the
4684 next is level 4 (or vice versa), level 4 will be used for insertion.
4685 This makes sure that the subtree remains an independent subtree and does
4686 not swallow low level entries.
4688 You can also force a different level, either by using a numeric prefix
4689 argument, or by inserting the heading marker by hand. For example, if the
4690 cursor is after \"*****\", then the tree will be shifted to level 5.
4692 If you want to insert the tree as is, just use \\[yank].
4694 If optional TREE is given, use this text instead of the kill ring."
4695 (interactive "P")
4696 (unless (org-kill-is-subtree-p tree)
4697 (error "%s"
4698 (substitute-command-keys
4699 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4700 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4701 (^re (concat "^\\(" outline-regexp "\\)"))
4702 (re (concat "\\(" outline-regexp "\\)"))
4703 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4705 (old-level (if (string-match ^re txt)
4706 (- (match-end 0) (match-beginning 0) 1)
4707 -1))
4708 (force-level (cond (level (prefix-numeric-value level))
4709 ((string-match
4710 ^re_ (buffer-substring (point-at-bol) (point)))
4711 (- (match-end 1) (match-beginning 1)))
4712 (t nil)))
4713 (previous-level (save-excursion
4714 (condition-case nil
4715 (progn
4716 (outline-previous-visible-heading 1)
4717 (if (looking-at re)
4718 (- (match-end 0) (match-beginning 0) 1)
4720 (error 1))))
4721 (next-level (save-excursion
4722 (condition-case nil
4723 (progn
4724 (or (looking-at outline-regexp)
4725 (outline-next-visible-heading 1))
4726 (if (looking-at re)
4727 (- (match-end 0) (match-beginning 0) 1)
4729 (error 1))))
4730 (new-level (or force-level (max previous-level next-level)))
4731 (shift (if (or (= old-level -1)
4732 (= new-level -1)
4733 (= old-level new-level))
4735 (- new-level old-level)))
4736 (delta (if (> shift 0) -1 1))
4737 (func (if (> shift 0) 'org-demote 'org-promote))
4738 (org-odd-levels-only nil)
4739 beg end)
4740 ;; Remove the forced level indicator
4741 (if force-level
4742 (delete-region (point-at-bol) (point)))
4743 ;; Paste
4744 (beginning-of-line 1)
4745 (org-back-over-empty-lines)
4746 (setq beg (point))
4747 (insert-before-markers txt)
4748 (unless (string-match "\n\\'" txt) (insert "\n"))
4749 (setq end (point))
4750 (goto-char beg)
4751 (skip-chars-forward " \t\n\r")
4752 (setq beg (point))
4753 ;; Shift if necessary
4754 (unless (= shift 0)
4755 (save-restriction
4756 (narrow-to-region beg end)
4757 (while (not (= shift 0))
4758 (org-map-region func (point-min) (point-max))
4759 (setq shift (+ delta shift)))
4760 (goto-char (point-min))))
4761 (when (interactive-p)
4762 (message "Clipboard pasted as level %d subtree" new-level))
4763 (if (and kill-ring
4764 (eq org-subtree-clip (current-kill 0))
4765 org-subtree-clip-folded)
4766 ;; The tree was folded before it was killed/copied
4767 (hide-subtree))))
4769 (defun org-kill-is-subtree-p (&optional txt)
4770 "Check if the current kill is an outline subtree, or a set of trees.
4771 Returns nil if kill does not start with a headline, or if the first
4772 headline level is not the largest headline level in the tree.
4773 So this will actually accept several entries of equal levels as well,
4774 which is OK for `org-paste-subtree'.
4775 If optional TXT is given, check this string instead of the current kill."
4776 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4777 (start-level (and kill
4778 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4779 org-outline-regexp "\\)")
4780 kill)
4781 (- (match-end 2) (match-beginning 2) 1)))
4782 (re (concat "^" org-outline-regexp))
4783 (start (1+ (match-beginning 2))))
4784 (if (not start-level)
4785 (progn
4786 nil) ;; does not even start with a heading
4787 (catch 'exit
4788 (while (setq start (string-match re kill (1+ start)))
4789 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4790 (throw 'exit nil)))
4791 t))))
4793 (defun org-narrow-to-subtree ()
4794 "Narrow buffer to the current subtree."
4795 (interactive)
4796 (save-excursion
4797 (save-match-data
4798 (narrow-to-region
4799 (progn (org-back-to-heading) (point))
4800 (progn (org-end-of-subtree t t) (point))))))
4803 ;;; Outline Sorting
4805 (defun org-sort (with-case)
4806 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4807 Optional argument WITH-CASE means sort case-sensitively."
4808 (interactive "P")
4809 (if (org-at-table-p)
4810 (org-call-with-arg 'org-table-sort-lines with-case)
4811 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4813 (defun org-sort-remove-invisible (s)
4814 (remove-text-properties 0 (length s) org-rm-props s)
4815 (while (string-match org-bracket-link-regexp s)
4816 (setq s (replace-match (if (match-end 2)
4817 (match-string 3 s)
4818 (match-string 1 s)) t t s)))
4821 (defvar org-priority-regexp) ; defined later in the file
4823 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4824 "Sort entries on a certain level of an outline tree.
4825 If there is an active region, the entries in the region are sorted.
4826 Else, if the cursor is before the first entry, sort the top-level items.
4827 Else, the children of the entry at point are sorted.
4829 Sorting can be alphabetically, numerically, and by date/time as given by
4830 the first time stamp in the entry. The command prompts for the sorting
4831 type unless it has been given to the function through the SORTING-TYPE
4832 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4833 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4834 called with point at the beginning of the record. It must return either
4835 a string or a number that should serve as the sorting key for that record.
4837 Comparing entries ignores case by default. However, with an optional argument
4838 WITH-CASE, the sorting considers case as well."
4839 (interactive "P")
4840 (let ((case-func (if with-case 'identity 'downcase))
4841 start beg end stars re re2
4842 txt what tmp plain-list-p)
4843 ;; Find beginning and end of region to sort
4844 (cond
4845 ((org-region-active-p)
4846 ;; we will sort the region
4847 (setq end (region-end)
4848 what "region")
4849 (goto-char (region-beginning))
4850 (if (not (org-on-heading-p)) (outline-next-heading))
4851 (setq start (point)))
4852 ((org-at-item-p)
4853 ;; we will sort this plain list
4854 (org-beginning-of-item-list) (setq start (point))
4855 (org-end-of-item-list) (setq end (point))
4856 (goto-char start)
4857 (setq plain-list-p t
4858 what "plain list"))
4859 ((or (org-on-heading-p)
4860 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4861 ;; we will sort the children of the current headline
4862 (org-back-to-heading)
4863 (setq start (point)
4864 end (progn (org-end-of-subtree t t)
4865 (org-back-over-empty-lines)
4866 (point))
4867 what "children")
4868 (goto-char start)
4869 (show-subtree)
4870 (outline-next-heading))
4872 ;; we will sort the top-level entries in this file
4873 (goto-char (point-min))
4874 (or (org-on-heading-p) (outline-next-heading))
4875 (setq start (point) end (point-max) what "top-level")
4876 (goto-char start)
4877 (show-all)))
4879 (setq beg (point))
4880 (if (>= beg end) (error "Nothing to sort"))
4882 (unless plain-list-p
4883 (looking-at "\\(\\*+\\)")
4884 (setq stars (match-string 1)
4885 re (concat "^" (regexp-quote stars) " +")
4886 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4887 txt (buffer-substring beg end))
4888 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4889 (if (and (not (equal stars "*")) (string-match re2 txt))
4890 (error "Region to sort contains a level above the first entry")))
4892 (unless sorting-type
4893 (message
4894 (if plain-list-p
4895 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
4896 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty todo[o]rder [f]unc A/N/T/P/O/F means reversed:")
4897 what)
4898 (setq sorting-type (read-char-exclusive))
4900 (and (= (downcase sorting-type) ?f)
4901 (setq getkey-func
4902 (completing-read "Sort using function: "
4903 obarray 'fboundp t nil nil))
4904 (setq getkey-func (intern getkey-func)))
4906 (and (= (downcase sorting-type) ?r)
4907 (setq property
4908 (completing-read "Property: "
4909 (mapcar 'list (org-buffer-property-keys t))
4910 nil t))))
4912 (message "Sorting entries...")
4914 (save-restriction
4915 (narrow-to-region start end)
4917 (let ((dcst (downcase sorting-type))
4918 (now (current-time)))
4919 (sort-subr
4920 (/= dcst sorting-type)
4921 ;; This function moves to the beginning character of the "record" to
4922 ;; be sorted.
4923 (if plain-list-p
4924 (lambda nil
4925 (if (org-at-item-p) t (goto-char (point-max))))
4926 (lambda nil
4927 (if (re-search-forward re nil t)
4928 (goto-char (match-beginning 0))
4929 (goto-char (point-max)))))
4930 ;; This function moves to the last character of the "record" being
4931 ;; sorted.
4932 (if plain-list-p
4933 'org-end-of-item
4934 (lambda nil
4935 (save-match-data
4936 (condition-case nil
4937 (outline-forward-same-level 1)
4938 (error
4939 (goto-char (point-max)))))))
4941 ;; This function returns the value that gets sorted against.
4942 (if plain-list-p
4943 (lambda nil
4944 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
4945 (cond
4946 ((= dcst ?n)
4947 (string-to-number (buffer-substring (match-end 0)
4948 (point-at-eol))))
4949 ((= dcst ?a)
4950 (buffer-substring (match-end 0) (point-at-eol)))
4951 ((= dcst ?t)
4952 (if (re-search-forward org-ts-regexp
4953 (point-at-eol) t)
4954 (org-time-string-to-time (match-string 0))
4955 now))
4956 ((= dcst ?f)
4957 (if getkey-func
4958 (progn
4959 (setq tmp (funcall getkey-func))
4960 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
4961 tmp)
4962 (error "Invalid key function `%s'" getkey-func)))
4963 (t (error "Invalid sorting type `%c'" sorting-type)))))
4964 (lambda nil
4965 (cond
4966 ((= dcst ?n)
4967 (if (looking-at outline-regexp)
4968 (string-to-number (buffer-substring (match-end 0)
4969 (point-at-eol)))
4970 nil))
4971 ((= dcst ?a)
4972 (funcall case-func (buffer-substring (point-at-bol)
4973 (point-at-eol))))
4974 ((= dcst ?t)
4975 (if (re-search-forward org-ts-regexp
4976 (save-excursion
4977 (forward-line 2)
4978 (point)) t)
4979 (org-time-string-to-time (match-string 0))
4980 now))
4981 ((= dcst ?p)
4982 (if (re-search-forward org-priority-regexp (point-at-eol) t)
4983 (string-to-char (match-string 2))
4984 org-default-priority))
4985 ((= dcst ?r)
4986 (or (org-entry-get nil property) ""))
4987 ((= dcst ?o)
4988 (if (looking-at org-complex-heading-regexp)
4989 (- 9999 (length (member (match-string 2)
4990 org-todo-keywords-1)))))
4991 ((= dcst ?f)
4992 (if getkey-func
4993 (progn
4994 (setq tmp (funcall getkey-func))
4995 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
4996 tmp)
4997 (error "Invalid key function `%s'" getkey-func)))
4998 (t (error "Invalid sorting type `%c'" sorting-type)))))
5000 (cond
5001 ((= dcst ?a) 'string<)
5002 ((= dcst ?t) 'time-less-p)
5003 (t nil)))))
5004 (message "Sorting entries...done")))
5006 (defun org-do-sort (table what &optional with-case sorting-type)
5007 "Sort TABLE of WHAT according to SORTING-TYPE.
5008 The user will be prompted for the SORTING-TYPE if the call to this
5009 function does not specify it. WHAT is only for the prompt, to indicate
5010 what is being sorted. The sorting key will be extracted from
5011 the car of the elements of the table.
5012 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5013 (unless sorting-type
5014 (message
5015 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5016 what)
5017 (setq sorting-type (read-char-exclusive)))
5018 (let ((dcst (downcase sorting-type))
5019 extractfun comparefun)
5020 ;; Define the appropriate functions
5021 (cond
5022 ((= dcst ?n)
5023 (setq extractfun 'string-to-number
5024 comparefun (if (= dcst sorting-type) '< '>)))
5025 ((= dcst ?a)
5026 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5027 (lambda(x) (downcase (org-sort-remove-invisible x))))
5028 comparefun (if (= dcst sorting-type)
5029 'string<
5030 (lambda (a b) (and (not (string< a b))
5031 (not (string= a b)))))))
5032 ((= dcst ?t)
5033 (setq extractfun
5034 (lambda (x)
5035 (if (string-match org-ts-regexp x)
5036 (time-to-seconds
5037 (org-time-string-to-time (match-string 0 x)))
5039 comparefun (if (= dcst sorting-type) '< '>)))
5040 (t (error "Invalid sorting type `%c'" sorting-type)))
5042 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5043 table)
5044 (lambda (a b) (funcall comparefun (car a) (car b))))))
5046 ;;;; Plain list items, including checkboxes
5048 ;;; Plain list items
5050 (defun org-at-item-p ()
5051 "Is point in a line starting a hand-formatted item?"
5052 (let ((llt org-plain-list-ordered-item-terminator))
5053 (save-excursion
5054 (goto-char (point-at-bol))
5055 (looking-at
5056 (cond
5057 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5058 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5059 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5060 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5062 (defun org-in-item-p ()
5063 "It the cursor inside a plain list item.
5064 Does not have to be the first line."
5065 (save-excursion
5066 (condition-case nil
5067 (progn
5068 (org-beginning-of-item)
5069 (org-at-item-p)
5071 (error nil))))
5073 (defun org-insert-item (&optional checkbox)
5074 "Insert a new item at the current level.
5075 Return t when things worked, nil when we are not in an item."
5076 (when (save-excursion
5077 (condition-case nil
5078 (progn
5079 (org-beginning-of-item)
5080 (org-at-item-p)
5081 (if (org-invisible-p) (error "Invisible item"))
5083 (error nil)))
5084 (let* ((bul (match-string 0))
5085 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5086 (match-end 0)))
5087 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5088 pos)
5089 (cond
5090 ((and (org-at-item-p) (<= (point) eow))
5091 ;; before the bullet
5092 (beginning-of-line 1)
5093 (open-line (if blank 2 1)))
5094 ((<= (point) eow)
5095 (beginning-of-line 1))
5097 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5098 (end-of-line 1)
5099 (delete-horizontal-space))
5100 (newline (if blank 2 1))))
5101 (insert bul (if checkbox "[ ]" ""))
5102 (just-one-space)
5103 (setq pos (point))
5104 (end-of-line 1)
5105 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5106 (org-maybe-renumber-ordered-list)
5107 (and checkbox (org-update-checkbox-count-maybe))
5110 ;;; Checkboxes
5112 (defun org-at-item-checkbox-p ()
5113 "Is point at a line starting a plain-list item with a checklet?"
5114 (and (org-at-item-p)
5115 (save-excursion
5116 (goto-char (match-end 0))
5117 (skip-chars-forward " \t")
5118 (looking-at "\\[[- X]\\]"))))
5120 (defun org-toggle-checkbox (&optional arg)
5121 "Toggle the checkbox in the current line."
5122 (interactive "P")
5123 (catch 'exit
5124 (let (beg end status (firstnew 'unknown))
5125 (cond
5126 ((org-region-active-p)
5127 (setq beg (region-beginning) end (region-end)))
5128 ((org-on-heading-p)
5129 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5130 ((org-at-item-checkbox-p)
5131 (let ((pos (point)))
5132 (replace-match
5133 (cond (arg "[-]")
5134 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5135 (t "[ ]"))
5136 t t)
5137 (goto-char pos))
5138 (throw 'exit t))
5139 (t (error "Not at a checkbox or heading, and no active region")))
5140 (save-excursion
5141 (goto-char beg)
5142 (while (< (point) end)
5143 (when (org-at-item-checkbox-p)
5144 (setq status (equal (match-string 0) "[X]"))
5145 (when (eq firstnew 'unknown)
5146 (setq firstnew (not status)))
5147 (replace-match
5148 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5149 (beginning-of-line 2)))))
5150 (org-update-checkbox-count-maybe))
5152 (defun org-update-checkbox-count-maybe ()
5153 "Update checkbox statistics unless turned off by user."
5154 (when org-provide-checkbox-statistics
5155 (org-update-checkbox-count)))
5157 (defun org-update-checkbox-count (&optional all)
5158 "Update the checkbox statistics in the current section.
5159 This will find all statistic cookies like [57%] and [6/12] and update them
5160 with the current numbers. With optional prefix argument ALL, do this for
5161 the whole buffer."
5162 (interactive "P")
5163 (save-excursion
5164 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5165 (beg (condition-case nil
5166 (progn (outline-back-to-heading) (point))
5167 (error (point-min))))
5168 (end (move-marker (make-marker)
5169 (progn (outline-next-heading) (point))))
5170 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5171 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5172 (re-find (concat re "\\|" re-box))
5173 beg-cookie end-cookie is-percent c-on c-off lim
5174 eline curr-ind next-ind continue-from startsearch
5175 (cstat 0)
5177 (when all
5178 (goto-char (point-min))
5179 (outline-next-heading)
5180 (setq beg (point) end (point-max)))
5181 (goto-char end)
5182 ;; find each statistic cookie
5183 (while (re-search-backward re-find beg t)
5184 (setq beg-cookie (match-beginning 1)
5185 end-cookie (match-end 1)
5186 cstat (+ cstat (if end-cookie 1 0))
5187 startsearch (point-at-eol)
5188 continue-from (point-at-bol)
5189 is-percent (match-beginning 2)
5190 lim (cond
5191 ((org-on-heading-p) (outline-next-heading) (point))
5192 ((org-at-item-p) (org-end-of-item) (point))
5193 (t nil))
5194 c-on 0
5195 c-off 0)
5196 (when lim
5197 ;; find first checkbox for this cookie and gather
5198 ;; statistics from all that are at this indentation level
5199 (goto-char startsearch)
5200 (if (re-search-forward re-box lim t)
5201 (progn
5202 (org-beginning-of-item)
5203 (setq curr-ind (org-get-indentation))
5204 (setq next-ind curr-ind)
5205 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5206 (save-excursion (end-of-line) (setq eline (point)))
5207 (if (re-search-forward re-box eline t)
5208 (if (member (match-string 2) '("[ ]" "[-]"))
5209 (setq c-off (1+ c-off))
5210 (setq c-on (1+ c-on))
5213 (org-end-of-item)
5214 (setq next-ind (org-get-indentation))
5216 (goto-char continue-from)
5217 ;; update cookie
5218 (when end-cookie
5219 (delete-region beg-cookie end-cookie)
5220 (goto-char beg-cookie)
5221 (insert
5222 (if is-percent
5223 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5224 (format "[%d/%d]" c-on (+ c-on c-off)))))
5225 ;; update items checkbox if it has one
5226 (when (org-at-item-p)
5227 (org-beginning-of-item)
5228 (when (and (> (+ c-on c-off) 0)
5229 (re-search-forward re-box (point-at-eol) t))
5230 (setq beg-cookie (match-beginning 2)
5231 end-cookie (match-end 2))
5232 (delete-region beg-cookie end-cookie)
5233 (goto-char beg-cookie)
5234 (cond ((= c-off 0) (insert "[X]"))
5235 ((= c-on 0) (insert "[ ]"))
5236 (t (insert "[-]")))
5238 (goto-char continue-from))
5239 (when (interactive-p)
5240 (message "Checkbox satistics updated %s (%d places)"
5241 (if all "in entire file" "in current outline entry") cstat)))))
5243 (defun org-get-checkbox-statistics-face ()
5244 "Select the face for checkbox statistics.
5245 The face will be `org-done' when all relevant boxes are checked. Otherwise
5246 it will be `org-todo'."
5247 (if (match-end 1)
5248 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5249 (if (and (> (match-end 2) (match-beginning 2))
5250 (equal (match-string 2) (match-string 3)))
5251 'org-done
5252 'org-todo)))
5254 (defun org-get-indentation (&optional line)
5255 "Get the indentation of the current line, interpreting tabs.
5256 When LINE is given, assume it represents a line and compute its indentation."
5257 (if line
5258 (if (string-match "^ *" (org-remove-tabs line))
5259 (match-end 0))
5260 (save-excursion
5261 (beginning-of-line 1)
5262 (skip-chars-forward " \t")
5263 (current-column))))
5265 (defun org-remove-tabs (s &optional width)
5266 "Replace tabulators in S with spaces.
5267 Assumes that s is a single line, starting in column 0."
5268 (setq width (or width tab-width))
5269 (while (string-match "\t" s)
5270 (setq s (replace-match
5271 (make-string
5272 (- (* width (/ (+ (match-beginning 0) width) width))
5273 (match-beginning 0)) ?\ )
5274 t t s)))
5277 (defun org-fix-indentation (line ind)
5278 "Fix indentation in LINE.
5279 IND is a cons cell with target and minimum indentation.
5280 If the current indenation in LINE is smaller than the minimum,
5281 leave it alone. If it is larger than ind, set it to the target."
5282 (let* ((l (org-remove-tabs line))
5283 (i (org-get-indentation l))
5284 (i1 (car ind)) (i2 (cdr ind)))
5285 (if (>= i i2) (setq l (substring line i2)))
5286 (if (> i1 0)
5287 (concat (make-string i1 ?\ ) l)
5288 l)))
5290 (defun org-beginning-of-item ()
5291 "Go to the beginning of the current hand-formatted item.
5292 If the cursor is not in an item, throw an error."
5293 (interactive)
5294 (let ((pos (point))
5295 (limit (save-excursion
5296 (condition-case nil
5297 (progn
5298 (org-back-to-heading)
5299 (beginning-of-line 2) (point))
5300 (error (point-min)))))
5301 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5302 ind ind1)
5303 (if (org-at-item-p)
5304 (beginning-of-line 1)
5305 (beginning-of-line 1)
5306 (skip-chars-forward " \t")
5307 (setq ind (current-column))
5308 (if (catch 'exit
5309 (while t
5310 (beginning-of-line 0)
5311 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5313 (if (looking-at "[ \t]*$")
5314 (setq ind1 ind-empty)
5315 (skip-chars-forward " \t")
5316 (setq ind1 (current-column)))
5317 (if (< ind1 ind)
5318 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5320 (goto-char pos)
5321 (error "Not in an item")))))
5323 (defun org-end-of-item ()
5324 "Go to the end of the current hand-formatted item.
5325 If the cursor is not in an item, throw an error."
5326 (interactive)
5327 (let* ((pos (point))
5328 ind1
5329 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5330 (limit (save-excursion (outline-next-heading) (point)))
5331 (ind (save-excursion
5332 (org-beginning-of-item)
5333 (skip-chars-forward " \t")
5334 (current-column)))
5335 (end (catch 'exit
5336 (while t
5337 (beginning-of-line 2)
5338 (if (eobp) (throw 'exit (point)))
5339 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5340 (if (looking-at "[ \t]*$")
5341 (setq ind1 ind-empty)
5342 (skip-chars-forward " \t")
5343 (setq ind1 (current-column)))
5344 (if (<= ind1 ind)
5345 (throw 'exit (point-at-bol)))))))
5346 (if end
5347 (goto-char end)
5348 (goto-char pos)
5349 (error "Not in an item"))))
5351 (defun org-next-item ()
5352 "Move to the beginning of the next item in the current plain list.
5353 Error if not at a plain list, or if this is the last item in the list."
5354 (interactive)
5355 (let (ind ind1 (pos (point)))
5356 (org-beginning-of-item)
5357 (setq ind (org-get-indentation))
5358 (org-end-of-item)
5359 (setq ind1 (org-get-indentation))
5360 (unless (and (org-at-item-p) (= ind ind1))
5361 (goto-char pos)
5362 (error "On last item"))))
5364 (defun org-previous-item ()
5365 "Move to the beginning of the previous item in the current plain list.
5366 Error if not at a plain list, or if this is the first item in the list."
5367 (interactive)
5368 (let (beg ind ind1 (pos (point)))
5369 (org-beginning-of-item)
5370 (setq beg (point))
5371 (setq ind (org-get-indentation))
5372 (goto-char beg)
5373 (catch 'exit
5374 (while t
5375 (beginning-of-line 0)
5376 (if (looking-at "[ \t]*$")
5378 (if (<= (setq ind1 (org-get-indentation)) ind)
5379 (throw 'exit t)))))
5380 (condition-case nil
5381 (if (or (not (org-at-item-p))
5382 (< ind1 (1- ind)))
5383 (error "")
5384 (org-beginning-of-item))
5385 (error (goto-char pos)
5386 (error "On first item")))))
5388 (defun org-first-list-item-p ()
5389 "Is this heading the item in a plain list?"
5390 (unless (org-at-item-p)
5391 (error "Not at a plain list item"))
5392 (org-beginning-of-item)
5393 (= (point) (save-excursion (org-beginning-of-item-list))))
5395 (defun org-move-item-down ()
5396 "Move the plain list item at point down, i.e. swap with following item.
5397 Subitems (items with larger indentation) are considered part of the item,
5398 so this really moves item trees."
5399 (interactive)
5400 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5401 (org-beginning-of-item)
5402 (setq beg0 (point))
5403 (save-excursion
5404 (setq ne-beg (org-back-over-empty-lines))
5405 (setq beg (point)))
5406 (goto-char beg0)
5407 (setq ind (org-get-indentation))
5408 (org-end-of-item)
5409 (setq end0 (point))
5410 (setq ind1 (org-get-indentation))
5411 (setq ne-end (org-back-over-empty-lines))
5412 (setq end (point))
5413 (goto-char beg0)
5414 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5415 ;; include less whitespace
5416 (save-excursion
5417 (goto-char beg)
5418 (forward-line (- ne-beg ne-end))
5419 (setq beg (point))))
5420 (goto-char end0)
5421 (if (and (org-at-item-p) (= ind ind1))
5422 (progn
5423 (org-end-of-item)
5424 (org-back-over-empty-lines)
5425 (setq txt (buffer-substring beg end))
5426 (save-excursion
5427 (delete-region beg end))
5428 (setq pos (point))
5429 (insert txt)
5430 (goto-char pos) (org-skip-whitespace)
5431 (org-maybe-renumber-ordered-list))
5432 (goto-char pos)
5433 (error "Cannot move this item further down"))))
5435 (defun org-move-item-up (arg)
5436 "Move the plain list item at point up, i.e. swap with previous item.
5437 Subitems (items with larger indentation) are considered part of the item,
5438 so this really moves item trees."
5439 (interactive "p")
5440 (let (beg beg0 end ind ind1 (pos (point)) txt
5441 ne-beg ne-ins ins-end)
5442 (org-beginning-of-item)
5443 (setq beg0 (point))
5444 (setq ind (org-get-indentation))
5445 (save-excursion
5446 (setq ne-beg (org-back-over-empty-lines))
5447 (setq beg (point)))
5448 (goto-char beg0)
5449 (org-end-of-item)
5450 (setq end (point))
5451 (goto-char beg0)
5452 (catch 'exit
5453 (while t
5454 (beginning-of-line 0)
5455 (if (looking-at "[ \t]*$")
5456 (if org-empty-line-terminates-plain-lists
5457 (progn
5458 (goto-char pos)
5459 (error "Cannot move this item further up"))
5460 nil)
5461 (if (<= (setq ind1 (org-get-indentation)) ind)
5462 (throw 'exit t)))))
5463 (condition-case nil
5464 (org-beginning-of-item)
5465 (error (goto-char beg)
5466 (error "Cannot move this item further up")))
5467 (setq ind1 (org-get-indentation))
5468 (if (and (org-at-item-p) (= ind ind1))
5469 (progn
5470 (setq ne-ins (org-back-over-empty-lines))
5471 (setq txt (buffer-substring beg end))
5472 (save-excursion
5473 (delete-region beg end))
5474 (setq pos (point))
5475 (insert txt)
5476 (setq ins-end (point))
5477 (goto-char pos) (org-skip-whitespace)
5479 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5480 ;; Move whitespace back to beginning
5481 (save-excursion
5482 (goto-char ins-end)
5483 (let ((kill-whole-line t))
5484 (kill-line (- ne-ins ne-beg)) (point)))
5485 (insert (make-string (- ne-ins ne-beg) ?\n)))
5487 (org-maybe-renumber-ordered-list))
5488 (goto-char pos)
5489 (error "Cannot move this item further up"))))
5491 (defun org-maybe-renumber-ordered-list ()
5492 "Renumber the ordered list at point if setup allows it.
5493 This tests the user option `org-auto-renumber-ordered-lists' before
5494 doing the renumbering."
5495 (interactive)
5496 (when (and org-auto-renumber-ordered-lists
5497 (org-at-item-p))
5498 (if (match-beginning 3)
5499 (org-renumber-ordered-list 1)
5500 (org-fix-bullet-type))))
5502 (defun org-maybe-renumber-ordered-list-safe ()
5503 (condition-case nil
5504 (save-excursion
5505 (org-maybe-renumber-ordered-list))
5506 (error nil)))
5508 (defun org-cycle-list-bullet (&optional which)
5509 "Cycle through the different itemize/enumerate bullets.
5510 This cycle the entire list level through the sequence:
5512 `-' -> `+' -> `*' -> `1.' -> `1)'
5514 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5515 0 meand `-', 1 means `+' etc."
5516 (interactive "P")
5517 (org-preserve-lc
5518 (org-beginning-of-item-list)
5519 (org-at-item-p)
5520 (beginning-of-line 1)
5521 (let ((current (match-string 0))
5522 (prevp (eq which 'previous))
5523 new)
5524 (setq new (cond
5525 ((and (numberp which)
5526 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5527 ((string-match "-" current) (if prevp "1)" "+"))
5528 ((string-match "\\+" current)
5529 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5530 ((string-match "\\*" current) (if prevp "+" "1."))
5531 ((string-match "\\." current) (if prevp "*" "1)"))
5532 ((string-match ")" current) (if prevp "1." "-"))
5533 (t (error "This should not happen"))))
5534 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5535 (org-fix-bullet-type)
5536 (org-maybe-renumber-ordered-list))))
5538 (defun org-get-string-indentation (s)
5539 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5540 (let ((n -1) (i 0) (w tab-width) c)
5541 (catch 'exit
5542 (while (< (setq n (1+ n)) (length s))
5543 (setq c (aref s n))
5544 (cond ((= c ?\ ) (setq i (1+ i)))
5545 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5546 (t (throw 'exit t)))))
5549 (defun org-renumber-ordered-list (arg)
5550 "Renumber an ordered plain list.
5551 Cursor needs to be in the first line of an item, the line that starts
5552 with something like \"1.\" or \"2)\"."
5553 (interactive "p")
5554 (unless (and (org-at-item-p)
5555 (match-beginning 3))
5556 (error "This is not an ordered list"))
5557 (let ((line (org-current-line))
5558 (col (current-column))
5559 (ind (org-get-string-indentation
5560 (buffer-substring (point-at-bol) (match-beginning 3))))
5561 ;; (term (substring (match-string 3) -1))
5562 ind1 (n (1- arg))
5563 fmt)
5564 ;; find where this list begins
5565 (org-beginning-of-item-list)
5566 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5567 (setq fmt (concat "%d" (match-string 1)))
5568 (beginning-of-line 0)
5569 ;; walk forward and replace these numbers
5570 (catch 'exit
5571 (while t
5572 (catch 'next
5573 (beginning-of-line 2)
5574 (if (eobp) (throw 'exit nil))
5575 (if (looking-at "[ \t]*$") (throw 'next nil))
5576 (skip-chars-forward " \t") (setq ind1 (current-column))
5577 (if (> ind1 ind) (throw 'next t))
5578 (if (< ind1 ind) (throw 'exit t))
5579 (if (not (org-at-item-p)) (throw 'exit nil))
5580 (delete-region (match-beginning 2) (match-end 2))
5581 (goto-char (match-beginning 2))
5582 (insert (format fmt (setq n (1+ n)))))))
5583 (goto-line line)
5584 (move-to-column col)))
5586 (defun org-fix-bullet-type ()
5587 "Make sure all items in this list have the same bullet as the firsst item."
5588 (interactive)
5589 (unless (org-at-item-p) (error "This is not a list"))
5590 (let ((line (org-current-line))
5591 (col (current-column))
5592 (ind (current-indentation))
5593 ind1 bullet)
5594 ;; find where this list begins
5595 (org-beginning-of-item-list)
5596 (beginning-of-line 1)
5597 ;; find out what the bullet type is
5598 (looking-at "[ \t]*\\(\\S-+\\)")
5599 (setq bullet (match-string 1))
5600 ;; walk forward and replace these numbers
5601 (beginning-of-line 0)
5602 (catch 'exit
5603 (while t
5604 (catch 'next
5605 (beginning-of-line 2)
5606 (if (eobp) (throw 'exit nil))
5607 (if (looking-at "[ \t]*$") (throw 'next nil))
5608 (skip-chars-forward " \t") (setq ind1 (current-column))
5609 (if (> ind1 ind) (throw 'next t))
5610 (if (< ind1 ind) (throw 'exit t))
5611 (if (not (org-at-item-p)) (throw 'exit nil))
5612 (skip-chars-forward " \t")
5613 (looking-at "\\S-+")
5614 (replace-match bullet))))
5615 (goto-line line)
5616 (move-to-column col)
5617 (if (string-match "[0-9]" bullet)
5618 (org-renumber-ordered-list 1))))
5620 (defun org-beginning-of-item-list ()
5621 "Go to the beginning of the current item list.
5622 I.e. to the first item in this list."
5623 (interactive)
5624 (org-beginning-of-item)
5625 (let ((pos (point-at-bol))
5626 (ind (org-get-indentation))
5627 ind1)
5628 ;; find where this list begins
5629 (catch 'exit
5630 (while t
5631 (catch 'next
5632 (beginning-of-line 0)
5633 (if (looking-at "[ \t]*$")
5634 (throw (if (bobp) 'exit 'next) t))
5635 (skip-chars-forward " \t") (setq ind1 (current-column))
5636 (if (or (< ind1 ind)
5637 (and (= ind1 ind)
5638 (not (org-at-item-p)))
5639 (bobp))
5640 (throw 'exit t)
5641 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5642 (goto-char pos)))
5645 (defun org-end-of-item-list ()
5646 "Go to the end of the current item list.
5647 I.e. to the text after the last item."
5648 (interactive)
5649 (org-beginning-of-item)
5650 (let ((pos (point-at-bol))
5651 (ind (org-get-indentation))
5652 ind1)
5653 ;; find where this list begins
5654 (catch 'exit
5655 (while t
5656 (catch 'next
5657 (beginning-of-line 2)
5658 (if (looking-at "[ \t]*$")
5659 (throw (if (eobp) 'exit 'next) t))
5660 (skip-chars-forward " \t") (setq ind1 (current-column))
5661 (if (or (< ind1 ind)
5662 (and (= ind1 ind)
5663 (not (org-at-item-p)))
5664 (eobp))
5665 (progn
5666 (setq pos (point-at-bol))
5667 (throw 'exit t))))))
5668 (goto-char pos)))
5671 (defvar org-last-indent-begin-marker (make-marker))
5672 (defvar org-last-indent-end-marker (make-marker))
5674 (defun org-outdent-item (arg)
5675 "Outdent a local list item."
5676 (interactive "p")
5677 (org-indent-item (- arg)))
5679 (defun org-indent-item (arg)
5680 "Indent a local list item."
5681 (interactive "p")
5682 (unless (org-at-item-p)
5683 (error "Not on an item"))
5684 (save-excursion
5685 (let (beg end ind ind1 tmp delta ind-down ind-up)
5686 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5687 (setq beg org-last-indent-begin-marker
5688 end org-last-indent-end-marker)
5689 (org-beginning-of-item)
5690 (setq beg (move-marker org-last-indent-begin-marker (point)))
5691 (org-end-of-item)
5692 (setq end (move-marker org-last-indent-end-marker (point))))
5693 (goto-char beg)
5694 (setq tmp (org-item-indent-positions)
5695 ind (car tmp)
5696 ind-down (nth 2 tmp)
5697 ind-up (nth 1 tmp)
5698 delta (if (> arg 0)
5699 (if ind-down (- ind-down ind) 2)
5700 (if ind-up (- ind-up ind) -2)))
5701 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5702 (while (< (point) end)
5703 (beginning-of-line 1)
5704 (skip-chars-forward " \t") (setq ind1 (current-column))
5705 (delete-region (point-at-bol) (point))
5706 (or (eolp) (indent-to-column (+ ind1 delta)))
5707 (beginning-of-line 2))))
5708 (org-fix-bullet-type)
5709 (org-maybe-renumber-ordered-list-safe)
5710 (save-excursion
5711 (beginning-of-line 0)
5712 (condition-case nil (org-beginning-of-item) (error nil))
5713 (org-maybe-renumber-ordered-list-safe)))
5715 (defun org-item-indent-positions ()
5716 "Return indentation for plain list items.
5717 This returns a list with three values: The current indentation, the
5718 parent indentation and the indentation a child should habe.
5719 Assumes cursor in item line."
5720 (let* ((bolpos (point-at-bol))
5721 (ind (org-get-indentation))
5722 ind-down ind-up pos)
5723 (save-excursion
5724 (org-beginning-of-item-list)
5725 (skip-chars-backward "\n\r \t")
5726 (when (org-in-item-p)
5727 (org-beginning-of-item)
5728 (setq ind-up (org-get-indentation))))
5729 (setq pos (point))
5730 (save-excursion
5731 (cond
5732 ((and (condition-case nil (progn (org-previous-item) t)
5733 (error nil))
5734 (or (forward-char 1) t)
5735 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5736 (setq ind-down (org-get-indentation)))
5737 ((and (goto-char pos)
5738 (org-at-item-p))
5739 (goto-char (match-end 0))
5740 (skip-chars-forward " \t")
5741 (setq ind-down (current-column)))))
5742 (list ind ind-up ind-down)))
5744 ;;; The orgstruct minor mode
5746 ;; Define a minor mode which can be used in other modes in order to
5747 ;; integrate the org-mode structure editing commands.
5749 ;; This is really a hack, because the org-mode structure commands use
5750 ;; keys which normally belong to the major mode. Here is how it
5751 ;; works: The minor mode defines all the keys necessary to operate the
5752 ;; structure commands, but wraps the commands into a function which
5753 ;; tests if the cursor is currently at a headline or a plain list
5754 ;; item. If that is the case, the structure command is used,
5755 ;; temporarily setting many Org-mode variables like regular
5756 ;; expressions for filling etc. However, when any of those keys is
5757 ;; used at a different location, function uses `key-binding' to look
5758 ;; up if the key has an associated command in another currently active
5759 ;; keymap (minor modes, major mode, global), and executes that
5760 ;; command. There might be problems if any of the keys is otherwise
5761 ;; used as a prefix key.
5763 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5764 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5765 ;; addresses this by checking explicitly for both bindings.
5767 (defvar orgstruct-mode-map (make-sparse-keymap)
5768 "Keymap for the minor `orgstruct-mode'.")
5770 (defvar org-local-vars nil
5771 "List of local variables, for use by `orgstruct-mode'")
5773 ;;;###autoload
5774 (define-minor-mode orgstruct-mode
5775 "Toggle the minor more `orgstruct-mode'.
5776 This mode is for using Org-mode structure commands in other modes.
5777 The following key behave as if Org-mode was active, if the cursor
5778 is on a headline, or on a plain list item (both in the definition
5779 of Org-mode).
5781 M-up Move entry/item up
5782 M-down Move entry/item down
5783 M-left Promote
5784 M-right Demote
5785 M-S-up Move entry/item up
5786 M-S-down Move entry/item down
5787 M-S-left Promote subtree
5788 M-S-right Demote subtree
5789 M-q Fill paragraph and items like in Org-mode
5790 C-c ^ Sort entries
5791 C-c - Cycle list bullet
5792 TAB Cycle item visibility
5793 M-RET Insert new heading/item
5794 S-M-RET Insert new TODO heading / Chekbox item
5795 C-c C-c Set tags / toggle checkbox"
5796 nil " OrgStruct" nil
5797 (org-load-modules-maybe)
5798 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5800 ;;;###autoload
5801 (defun turn-on-orgstruct ()
5802 "Unconditionally turn on `orgstruct-mode'."
5803 (orgstruct-mode 1))
5805 ;;;###autoload
5806 (defun turn-on-orgstruct++ ()
5807 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5808 In addition to setting orgstruct-mode, this also exports all indentation and
5809 autofilling variables from org-mode into the buffer. Note that turning
5810 off orgstruct-mode will *not* remove these additional settings."
5811 (orgstruct-mode 1)
5812 (let (var val)
5813 (mapc
5814 (lambda (x)
5815 (when (string-match
5816 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5817 (symbol-name (car x)))
5818 (setq var (car x) val (nth 1 x))
5819 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5820 org-local-vars)))
5822 (defun orgstruct-error ()
5823 "Error when there is no default binding for a structure key."
5824 (interactive)
5825 (error "This key has no function outside structure elements"))
5827 (defun orgstruct-setup ()
5828 "Setup orgstruct keymaps."
5829 (let ((nfunc 0)
5830 (bindings
5831 (list
5832 '([(meta up)] org-metaup)
5833 '([(meta down)] org-metadown)
5834 '([(meta left)] org-metaleft)
5835 '([(meta right)] org-metaright)
5836 '([(meta shift up)] org-shiftmetaup)
5837 '([(meta shift down)] org-shiftmetadown)
5838 '([(meta shift left)] org-shiftmetaleft)
5839 '([(meta shift right)] org-shiftmetaright)
5840 '([(shift up)] org-shiftup)
5841 '([(shift down)] org-shiftdown)
5842 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5843 '("\M-q" fill-paragraph)
5844 '("\C-c^" org-sort)
5845 '("\C-c-" org-cycle-list-bullet)))
5846 elt key fun cmd)
5847 (while (setq elt (pop bindings))
5848 (setq nfunc (1+ nfunc))
5849 (setq key (org-key (car elt))
5850 fun (nth 1 elt)
5851 cmd (orgstruct-make-binding fun nfunc key))
5852 (org-defkey orgstruct-mode-map key cmd))
5854 ;; Special treatment needed for TAB and RET
5855 (org-defkey orgstruct-mode-map [(tab)]
5856 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5857 (org-defkey orgstruct-mode-map "\C-i"
5858 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5860 (org-defkey orgstruct-mode-map "\M-\C-m"
5861 (orgstruct-make-binding 'org-insert-heading 105
5862 "\M-\C-m" [(meta return)]))
5863 (org-defkey orgstruct-mode-map [(meta return)]
5864 (orgstruct-make-binding 'org-insert-heading 106
5865 [(meta return)] "\M-\C-m"))
5867 (org-defkey orgstruct-mode-map [(shift meta return)]
5868 (orgstruct-make-binding 'org-insert-todo-heading 107
5869 [(meta return)] "\M-\C-m"))
5871 (unless org-local-vars
5872 (setq org-local-vars (org-get-local-variables)))
5876 (defun orgstruct-make-binding (fun n &rest keys)
5877 "Create a function for binding in the structure minor mode.
5878 FUN is the command to call inside a table. N is used to create a unique
5879 command name. KEYS are keys that should be checked in for a command
5880 to execute outside of tables."
5881 (eval
5882 (list 'defun
5883 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5884 '(arg)
5885 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5886 "Outside of structure, run the binding of `"
5887 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5888 "'.")
5889 '(interactive "p")
5890 (list 'if
5891 '(org-context-p 'headline 'item)
5892 (list 'org-run-like-in-org-mode (list 'quote fun))
5893 (list 'let '(orgstruct-mode)
5894 (list 'call-interactively
5895 (append '(or)
5896 (mapcar (lambda (k)
5897 (list 'key-binding k))
5898 keys)
5899 '('orgstruct-error))))))))
5901 (defun org-context-p (&rest contexts)
5902 "Check if local context is and of CONTEXTS.
5903 Possible values in the list of contexts are `table', `headline', and `item'."
5904 (let ((pos (point)))
5905 (goto-char (point-at-bol))
5906 (prog1 (or (and (memq 'table contexts)
5907 (looking-at "[ \t]*|"))
5908 (and (memq 'headline contexts)
5909 (looking-at "\\*+"))
5910 (and (memq 'item contexts)
5911 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5912 (goto-char pos))))
5914 (defun org-get-local-variables ()
5915 "Return a list of all local variables in an org-mode buffer."
5916 (let (varlist)
5917 (with-current-buffer (get-buffer-create "*Org tmp*")
5918 (erase-buffer)
5919 (org-mode)
5920 (setq varlist (buffer-local-variables)))
5921 (kill-buffer "*Org tmp*")
5922 (delq nil
5923 (mapcar
5924 (lambda (x)
5925 (setq x
5926 (if (symbolp x)
5927 (list x)
5928 (list (car x) (list 'quote (cdr x)))))
5929 (if (string-match
5930 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5931 (symbol-name (car x)))
5932 x nil))
5933 varlist))))
5935 ;;;###autoload
5936 (defun org-run-like-in-org-mode (cmd)
5937 (org-load-modules-maybe)
5938 (unless org-local-vars
5939 (setq org-local-vars (org-get-local-variables)))
5940 (eval (list 'let org-local-vars
5941 (list 'call-interactively (list 'quote cmd)))))
5943 ;;;; Archiving
5945 (defun org-get-category (&optional pos)
5946 "Get the category applying to position POS."
5947 (get-text-property (or pos (point)) 'org-category))
5949 (defun org-refresh-category-properties ()
5950 "Refresh category text properties in the buffer."
5951 (let ((def-cat (cond
5952 ((null org-category)
5953 (if buffer-file-name
5954 (file-name-sans-extension
5955 (file-name-nondirectory buffer-file-name))
5956 "???"))
5957 ((symbolp org-category) (symbol-name org-category))
5958 (t org-category)))
5959 beg end cat pos optionp)
5960 (org-unmodified
5961 (save-excursion
5962 (save-restriction
5963 (widen)
5964 (goto-char (point-min))
5965 (put-text-property (point) (point-max) 'org-category def-cat)
5966 (while (re-search-forward
5967 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5968 (setq pos (match-end 0)
5969 optionp (equal (char-after (match-beginning 0)) ?#)
5970 cat (org-trim (match-string 2)))
5971 (if optionp
5972 (setq beg (point-at-bol) end (point-max))
5973 (org-back-to-heading t)
5974 (setq beg (point) end (org-end-of-subtree t t)))
5975 (put-text-property beg end 'org-category cat)
5976 (goto-char pos)))))))
5979 ;;;; Link Stuff
5981 ;;; Link abbreviations
5983 (defun org-link-expand-abbrev (link)
5984 "Apply replacements as defined in `org-link-abbrev-alist."
5985 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5986 (let* ((key (match-string 1 link))
5987 (as (or (assoc key org-link-abbrev-alist-local)
5988 (assoc key org-link-abbrev-alist)))
5989 (tag (and (match-end 2) (match-string 3 link)))
5990 rpl)
5991 (if (not as)
5992 link
5993 (setq rpl (cdr as))
5994 (cond
5995 ((symbolp rpl) (funcall rpl tag))
5996 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5997 (t (concat rpl tag)))))
5998 link))
6000 ;;; Storing and inserting links
6002 (defvar org-insert-link-history nil
6003 "Minibuffer history for links inserted with `org-insert-link'.")
6005 (defvar org-stored-links nil
6006 "Contains the links stored with `org-store-link'.")
6008 (defvar org-store-link-plist nil
6009 "Plist with info about the most recently link created with `org-store-link'.")
6011 (defvar org-link-protocols nil
6012 "Link protocols added to Org-mode using `org-add-link-type'.")
6014 (defvar org-store-link-functions nil
6015 "List of functions that are called to create and store a link.
6016 Each function will be called in turn until one returns a non-nil
6017 value. Each function should check if it is responsible for creating
6018 this link (for example by looking at the major mode).
6019 If not, it must exit and return nil.
6020 If yes, it should return a non-nil value after a calling
6021 `org-store-link-props' with a list of properties and values.
6022 Special properties are:
6024 :type The link prefix. like \"http\". This must be given.
6025 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6026 This is obligatory as well.
6027 :description Optional default description for the second pair
6028 of brackets in an Org-mode link. The user can still change
6029 this when inserting this link into an Org-mode buffer.
6031 In addition to these, any additional properties can be specified
6032 and then used in remember templates.")
6034 (defun org-add-link-type (type &optional follow export)
6035 "Add TYPE to the list of `org-link-types'.
6036 Re-compute all regular expressions depending on `org-link-types'
6038 FOLLOW and EXPORT are two functions.
6040 FOLLOW should take the link path as the single argument and do whatever
6041 is necessary to follow the link, for example find a file or display
6042 a mail message.
6044 EXPORT should format the link path for export to one of the export formats.
6045 It should be a function accepting three arguments:
6047 path the path of the link, the text after the prefix (like \"http:\")
6048 desc the description of the link, if any, nil if there was no descripton
6049 format the export format, a symbol like `html' or `latex'.
6051 The function may use the FORMAT information to return different values
6052 depending on the format. The return value will be put literally into
6053 the exported file.
6054 Org-mode has a built-in default for exporting links. If you are happy with
6055 this default, there is no need to define an export function for the link
6056 type. For a simple example of an export function, see `org-bbdb.el'."
6057 (add-to-list 'org-link-types type t)
6058 (org-make-link-regexps)
6059 (if (assoc type org-link-protocols)
6060 (setcdr (assoc type org-link-protocols) (list follow export))
6061 (push (list type follow export) org-link-protocols)))
6064 ;;;###autoload
6065 (defun org-store-link (arg)
6066 "\\<org-mode-map>Store an org-link to the current location.
6067 This link is added to `org-stored-links' and can later be inserted
6068 into an org-buffer with \\[org-insert-link].
6070 For some link types, a prefix arg is interpreted:
6071 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6072 For file links, arg negates `org-context-in-file-links'."
6073 (interactive "P")
6074 (org-load-modules-maybe)
6075 (setq org-store-link-plist nil) ; reset
6076 (let (link cpltxt desc description search txt)
6077 (cond
6079 ((run-hook-with-args-until-success 'org-store-link-functions)
6080 (setq link (plist-get org-store-link-plist :link)
6081 desc (or (plist-get org-store-link-plist :description) link)))
6083 ((eq major-mode 'calendar-mode)
6084 (let ((cd (calendar-cursor-to-date)))
6085 (setq link
6086 (format-time-string
6087 (car org-time-stamp-formats)
6088 (apply 'encode-time
6089 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6090 nil nil nil))))
6091 (org-store-link-props :type "calendar" :date cd)))
6093 ((eq major-mode 'w3-mode)
6094 (setq cpltxt (url-view-url t)
6095 link (org-make-link cpltxt))
6096 (org-store-link-props :type "w3" :url (url-view-url t)))
6098 ((eq major-mode 'w3m-mode)
6099 (setq cpltxt (or w3m-current-title w3m-current-url)
6100 link (org-make-link w3m-current-url))
6101 (org-store-link-props :type "w3m" :url (url-view-url t)))
6103 ((setq search (run-hook-with-args-until-success
6104 'org-create-file-search-functions))
6105 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6106 "::" search))
6107 (setq cpltxt (or description link)))
6109 ((eq major-mode 'image-mode)
6110 (setq cpltxt (concat "file:"
6111 (abbreviate-file-name buffer-file-name))
6112 link (org-make-link cpltxt))
6113 (org-store-link-props :type "image" :file buffer-file-name))
6115 ((eq major-mode 'dired-mode)
6116 ;; link to the file in the current line
6117 (setq cpltxt (concat "file:"
6118 (abbreviate-file-name
6119 (expand-file-name
6120 (dired-get-filename nil t))))
6121 link (org-make-link cpltxt)))
6123 ((and buffer-file-name (org-mode-p))
6124 ;; Just link to current headline
6125 (setq cpltxt (concat "file:"
6126 (abbreviate-file-name buffer-file-name)))
6127 ;; Add a context search string
6128 (when (org-xor org-context-in-file-links arg)
6129 ;; Check if we are on a target
6130 (if (org-in-regexp "<<\\(.*?\\)>>")
6131 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6132 (setq txt (cond
6133 ((org-on-heading-p) nil)
6134 ((org-region-active-p)
6135 (buffer-substring (region-beginning) (region-end)))
6136 (t nil)))
6137 (when (or (null txt) (string-match "\\S-" txt))
6138 (setq cpltxt
6139 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6140 desc "NONE"))))
6141 (if (string-match "::\\'" cpltxt)
6142 (setq cpltxt (substring cpltxt 0 -2)))
6143 (setq link (org-make-link cpltxt)))
6145 ((buffer-file-name (buffer-base-buffer))
6146 ;; Just link to this file here.
6147 (setq cpltxt (concat "file:"
6148 (abbreviate-file-name
6149 (buffer-file-name (buffer-base-buffer)))))
6150 ;; Add a context string
6151 (when (org-xor org-context-in-file-links arg)
6152 (setq txt (if (org-region-active-p)
6153 (buffer-substring (region-beginning) (region-end))
6154 (buffer-substring (point-at-bol) (point-at-eol))))
6155 ;; Only use search option if there is some text.
6156 (when (string-match "\\S-" txt)
6157 (setq cpltxt
6158 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6159 desc "NONE")))
6160 (setq link (org-make-link cpltxt)))
6162 ((interactive-p)
6163 (error "Cannot link to a buffer which is not visiting a file"))
6165 (t (setq link nil)))
6167 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6168 (setq link (or link cpltxt)
6169 desc (or desc cpltxt))
6170 (if (equal desc "NONE") (setq desc nil))
6172 (if (and (interactive-p) link)
6173 (progn
6174 (setq org-stored-links
6175 (cons (list link desc) org-stored-links))
6176 (message "Stored: %s" (or desc link)))
6177 (and link (org-make-link-string link desc)))))
6179 (defun org-store-link-props (&rest plist)
6180 "Store link properties, extract names and addresses."
6181 (let (x adr)
6182 (when (setq x (plist-get plist :from))
6183 (setq adr (mail-extract-address-components x))
6184 (plist-put plist :fromname (car adr))
6185 (plist-put plist :fromaddress (nth 1 adr)))
6186 (when (setq x (plist-get plist :to))
6187 (setq adr (mail-extract-address-components x))
6188 (plist-put plist :toname (car adr))
6189 (plist-put plist :toaddress (nth 1 adr))))
6190 (let ((from (plist-get plist :from))
6191 (to (plist-get plist :to)))
6192 (when (and from to org-from-is-user-regexp)
6193 (plist-put plist :fromto
6194 (if (string-match org-from-is-user-regexp from)
6195 (concat "to %t")
6196 (concat "from %f")))))
6197 (setq org-store-link-plist plist))
6199 (defun org-add-link-props (&rest plist)
6200 "Add these properties to the link property list."
6201 (let (key value)
6202 (while plist
6203 (setq key (pop plist) value (pop plist))
6204 (setq org-store-link-plist
6205 (plist-put org-store-link-plist key value)))))
6207 (defun org-email-link-description (&optional fmt)
6208 "Return the description part of an email link.
6209 This takes information from `org-store-link-plist' and formats it
6210 according to FMT (default from `org-email-link-description-format')."
6211 (setq fmt (or fmt org-email-link-description-format))
6212 (let* ((p org-store-link-plist)
6213 (to (plist-get p :toaddress))
6214 (from (plist-get p :fromaddress))
6215 (table
6216 (list
6217 (cons "%c" (plist-get p :fromto))
6218 (cons "%F" (plist-get p :from))
6219 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6220 (cons "%T" (plist-get p :to))
6221 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6222 (cons "%s" (plist-get p :subject))
6223 (cons "%m" (plist-get p :message-id)))))
6224 (when (string-match "%c" fmt)
6225 ;; Check if the user wrote this message
6226 (if (and org-from-is-user-regexp from to
6227 (save-match-data (string-match org-from-is-user-regexp from)))
6228 (setq fmt (replace-match "to %t" t t fmt))
6229 (setq fmt (replace-match "from %f" t t fmt))))
6230 (org-replace-escapes fmt table)))
6232 (defun org-make-org-heading-search-string (&optional string heading)
6233 "Make search string for STRING or current headline."
6234 (interactive)
6235 (let ((s (or string (org-get-heading))))
6236 (unless (and string (not heading))
6237 ;; We are using a headline, clean up garbage in there.
6238 (if (string-match org-todo-regexp s)
6239 (setq s (replace-match "" t t s)))
6240 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6241 (setq s (replace-match "" t t s)))
6242 (setq s (org-trim s))
6243 (if (string-match (concat "^\\(" org-quote-string "\\|"
6244 org-comment-string "\\)") s)
6245 (setq s (replace-match "" t t s)))
6246 (while (string-match org-ts-regexp s)
6247 (setq s (replace-match "" t t s))))
6248 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6249 (setq s (replace-match " " t t s)))
6250 (or string (setq s (concat "*" s))) ; Add * for headlines
6251 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6253 (defun org-make-link (&rest strings)
6254 "Concatenate STRINGS."
6255 (apply 'concat strings))
6257 (defun org-make-link-string (link &optional description)
6258 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6259 (unless (string-match "\\S-" link)
6260 (error "Empty link"))
6261 (when (stringp description)
6262 ;; Remove brackets from the description, they are fatal.
6263 (while (string-match "\\[" description)
6264 (setq description (replace-match "{" t t description)))
6265 (while (string-match "\\]" description)
6266 (setq description (replace-match "}" t t description))))
6267 (when (equal (org-link-escape link) description)
6268 ;; No description needed, it is identical
6269 (setq description nil))
6270 (when (and (not description)
6271 (not (equal link (org-link-escape link))))
6272 (setq description link))
6273 (concat "[[" (org-link-escape link) "]"
6274 (if description (concat "[" description "]") "")
6275 "]"))
6277 (defconst org-link-escape-chars
6278 '((?\ . "%20")
6279 (?\[ . "%5B")
6280 (?\] . "%5D")
6281 (?\340 . "%E0") ; `a
6282 (?\342 . "%E2") ; ^a
6283 (?\347 . "%E7") ; ,c
6284 (?\350 . "%E8") ; `e
6285 (?\351 . "%E9") ; 'e
6286 (?\352 . "%EA") ; ^e
6287 (?\356 . "%EE") ; ^i
6288 (?\364 . "%F4") ; ^o
6289 (?\371 . "%F9") ; `u
6290 (?\373 . "%FB") ; ^u
6291 (?\; . "%3B")
6292 (?? . "%3F")
6293 (?= . "%3D")
6294 (?+ . "%2B")
6296 "Association list of escapes for some characters problematic in links.
6297 This is the list that is used for internal purposes.")
6299 (defconst org-link-escape-chars-browser
6300 '((?\ . "%20")) ; 32 for the SPC char
6301 "Association list of escapes for some characters problematic in links.
6302 This is the list that is used before handing over to the browser.")
6304 (defun org-link-escape (text &optional table)
6305 "Escape charaters in TEXT that are problematic for links."
6306 (setq table (or table org-link-escape-chars))
6307 (when text
6308 (let ((re (mapconcat (lambda (x) (regexp-quote
6309 (char-to-string (car x))))
6310 table "\\|")))
6311 (while (string-match re text)
6312 (setq text
6313 (replace-match
6314 (cdr (assoc (string-to-char (match-string 0 text))
6315 table))
6316 t t text)))
6317 text)))
6319 (defun org-link-unescape (text &optional table)
6320 "Reverse the action of `org-link-escape'."
6321 (setq table (or table org-link-escape-chars))
6322 (when text
6323 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6324 table "\\|")))
6325 (while (string-match re text)
6326 (setq text
6327 (replace-match
6328 (char-to-string (car (rassoc (match-string 0 text) table)))
6329 t t text)))
6330 text)))
6332 (defun org-xor (a b)
6333 "Exclusive or."
6334 (if a (not b) b))
6336 (defun org-get-header (header)
6337 "Find a header field in the current buffer."
6338 (save-excursion
6339 (goto-char (point-min))
6340 (let ((case-fold-search t) s)
6341 (cond
6342 ((eq header 'from)
6343 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6344 (setq s (match-string 1)))
6345 (while (string-match "\"" s)
6346 (setq s (replace-match "" t t s)))
6347 (if (string-match "[<(].*" s)
6348 (setq s (replace-match "" t t s))))
6349 ((eq header 'message-id)
6350 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6351 (setq s (match-string 1))))
6352 ((eq header 'subject)
6353 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6354 (setq s (match-string 1)))))
6355 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6356 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6357 s)))
6360 (defun org-fixup-message-id-for-http (s)
6361 "Replace special characters in a message id, so it can be used in an http query."
6362 (while (string-match "<" s)
6363 (setq s (replace-match "%3C" t t s)))
6364 (while (string-match ">" s)
6365 (setq s (replace-match "%3E" t t s)))
6366 (while (string-match "@" s)
6367 (setq s (replace-match "%40" t t s)))
6370 ;;;###autoload
6371 (defun org-insert-link-global ()
6372 "Insert a link like Org-mode does.
6373 This command can be called in any mode to insert a link in Org-mode syntax."
6374 (interactive)
6375 (org-load-modules-maybe)
6376 (org-run-like-in-org-mode 'org-insert-link))
6378 (defun org-insert-link (&optional complete-file link-location)
6379 "Insert a link. At the prompt, enter the link.
6381 Completion can be used to select a link previously stored with
6382 `org-store-link'. When the empty string is entered (i.e. if you just
6383 press RET at the prompt), the link defaults to the most recently
6384 stored link. As SPC triggers completion in the minibuffer, you need to
6385 use M-SPC or C-q SPC to force the insertion of a space character.
6387 You will also be prompted for a description, and if one is given, it will
6388 be displayed in the buffer instead of the link.
6390 If there is already a link at point, this command will allow you to edit link
6391 and description parts.
6393 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6394 be selected using completion. The path to the file will be relative to the
6395 current directory if the file is in the current directory or a subdirectory.
6396 Otherwise, the link will be the absolute path as completed in the minibuffer
6397 \(i.e. normally ~/path/to/file).
6399 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6400 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6401 of `org-keep-stored-link-after-insertion'.
6403 If `org-make-link-description-function' is non-nil, this function will be
6404 called with the link target, and the result will be the default
6405 link description.
6407 If the LINK-LOCATION parameter is non-nil, this value will be
6408 used as the link location instead of reading one interactively."
6409 (interactive "P")
6410 (let* ((wcf (current-window-configuration))
6411 (region (if (org-region-active-p)
6412 (buffer-substring (region-beginning) (region-end))))
6413 (remove (and region (list (region-beginning) (region-end))))
6414 (desc region)
6415 tmphist ; byte-compile incorrectly complains about this
6416 (link link-location)
6417 entry file)
6418 (cond
6419 (link-location) ; specified by arg, just use it.
6420 ((org-in-regexp org-bracket-link-regexp 1)
6421 ;; We do have a link at point, and we are going to edit it.
6422 (setq remove (list (match-beginning 0) (match-end 0)))
6423 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6424 (setq link (read-string "Link: "
6425 (org-link-unescape
6426 (org-match-string-no-properties 1)))))
6427 ((or (org-in-regexp org-angle-link-re)
6428 (org-in-regexp org-plain-link-re))
6429 ;; Convert to bracket link
6430 (setq remove (list (match-beginning 0) (match-end 0))
6431 link (read-string "Link: "
6432 (org-remove-angle-brackets (match-string 0)))))
6433 ((equal complete-file '(4))
6434 ;; Completing read for file names.
6435 (setq file (read-file-name "File: "))
6436 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6437 (pwd1 (file-name-as-directory (abbreviate-file-name
6438 (expand-file-name ".")))))
6439 (cond
6440 ((equal complete-file '(16))
6441 (setq link (org-make-link
6442 "file:"
6443 (abbreviate-file-name (expand-file-name file)))))
6444 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6445 (setq link (org-make-link "file:" (match-string 1 file))))
6446 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6447 (expand-file-name file))
6448 (setq link (org-make-link
6449 "file:" (match-string 1 (expand-file-name file)))))
6450 (t (setq link (org-make-link "file:" file))))))
6452 ;; Read link, with completion for stored links.
6453 (with-output-to-temp-buffer "*Org Links*"
6454 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6455 (when org-stored-links
6456 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6457 (princ (mapconcat
6458 (lambda (x)
6459 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6460 (reverse org-stored-links) "\n"))))
6461 (let ((cw (selected-window)))
6462 (select-window (get-buffer-window "*Org Links*"))
6463 (shrink-window-if-larger-than-buffer)
6464 (setq truncate-lines t)
6465 (select-window cw))
6466 ;; Fake a link history, containing the stored links.
6467 (setq tmphist (append (mapcar 'car org-stored-links)
6468 org-insert-link-history))
6469 (unwind-protect
6470 (setq link (org-completing-read
6471 "Link: "
6472 (append
6473 (mapcar (lambda (x) (list (concat (car x) ":")))
6474 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6475 (mapcar (lambda (x) (list (concat x ":")))
6476 org-link-types))
6477 nil nil nil
6478 'tmphist
6479 (or (car (car org-stored-links)))))
6480 (set-window-configuration wcf)
6481 (kill-buffer "*Org Links*"))
6482 (setq entry (assoc link org-stored-links))
6483 (or entry (push link org-insert-link-history))
6484 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6485 (not org-keep-stored-link-after-insertion))
6486 (setq org-stored-links (delq (assoc link org-stored-links)
6487 org-stored-links)))
6488 (setq desc (or desc (nth 1 entry)))))
6490 (if (string-match org-plain-link-re link)
6491 ;; URL-like link, normalize the use of angular brackets.
6492 (setq link (org-make-link (org-remove-angle-brackets link))))
6494 ;; Check if we are linking to the current file with a search option
6495 ;; If yes, simplify the link by using only the search option.
6496 (when (and buffer-file-name
6497 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6498 (let* ((path (match-string 1 link))
6499 (case-fold-search nil)
6500 (search (match-string 2 link)))
6501 (save-match-data
6502 (if (equal (file-truename buffer-file-name) (file-truename path))
6503 ;; We are linking to this same file, with a search option
6504 (setq link search)))))
6506 ;; Check if we can/should use a relative path. If yes, simplify the link
6507 (when (string-match "\\<file:\\(.*\\)" link)
6508 (let* ((path (match-string 1 link))
6509 (origpath path)
6510 (case-fold-search nil))
6511 (cond
6512 ((eq org-link-file-path-type 'absolute)
6513 (setq path (abbreviate-file-name (expand-file-name path))))
6514 ((eq org-link-file-path-type 'noabbrev)
6515 (setq path (expand-file-name path)))
6516 ((eq org-link-file-path-type 'relative)
6517 (setq path (file-relative-name path)))
6519 (save-match-data
6520 (if (string-match (concat "^" (regexp-quote
6521 (file-name-as-directory
6522 (expand-file-name "."))))
6523 (expand-file-name path))
6524 ;; We are linking a file with relative path name.
6525 (setq path (substring (expand-file-name path)
6526 (match-end 0)))))))
6527 (setq link (concat "file:" path))
6528 (if (equal desc origpath)
6529 (setq desc path))))
6531 (if org-make-link-description-function
6532 (setq desc (funcall org-make-link-description-function link desc)))
6534 (setq desc (read-string "Description: " desc))
6535 (unless (string-match "\\S-" desc) (setq desc nil))
6536 (if remove (apply 'delete-region remove))
6537 (insert (org-make-link-string link desc))))
6539 (defun org-completing-read (&rest args)
6540 (let ((minibuffer-local-completion-map
6541 (copy-keymap minibuffer-local-completion-map)))
6542 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6543 (apply 'completing-read args)))
6545 ;;; Opening/following a link
6547 (defvar org-link-search-failed nil)
6549 (defun org-next-link ()
6550 "Move forward to the next link.
6551 If the link is in hidden text, expose it."
6552 (interactive)
6553 (when (and org-link-search-failed (eq this-command last-command))
6554 (goto-char (point-min))
6555 (message "Link search wrapped back to beginning of buffer"))
6556 (setq org-link-search-failed nil)
6557 (let* ((pos (point))
6558 (ct (org-context))
6559 (a (assoc :link ct)))
6560 (if a (goto-char (nth 2 a)))
6561 (if (re-search-forward org-any-link-re nil t)
6562 (progn
6563 (goto-char (match-beginning 0))
6564 (if (org-invisible-p) (org-show-context)))
6565 (goto-char pos)
6566 (setq org-link-search-failed t)
6567 (error "No further link found"))))
6569 (defun org-previous-link ()
6570 "Move backward to the previous link.
6571 If the link is in hidden text, expose it."
6572 (interactive)
6573 (when (and org-link-search-failed (eq this-command last-command))
6574 (goto-char (point-max))
6575 (message "Link search wrapped back to end of buffer"))
6576 (setq org-link-search-failed nil)
6577 (let* ((pos (point))
6578 (ct (org-context))
6579 (a (assoc :link ct)))
6580 (if a (goto-char (nth 1 a)))
6581 (if (re-search-backward org-any-link-re nil t)
6582 (progn
6583 (goto-char (match-beginning 0))
6584 (if (org-invisible-p) (org-show-context)))
6585 (goto-char pos)
6586 (setq org-link-search-failed t)
6587 (error "No further link found"))))
6589 (defun org-find-file-at-mouse (ev)
6590 "Open file link or URL at mouse."
6591 (interactive "e")
6592 (mouse-set-point ev)
6593 (org-open-at-point 'in-emacs))
6595 (defun org-open-at-mouse (ev)
6596 "Open file link or URL at mouse."
6597 (interactive "e")
6598 (mouse-set-point ev)
6599 (org-open-at-point))
6601 (defvar org-window-config-before-follow-link nil
6602 "The window configuration before following a link.
6603 This is saved in case the need arises to restore it.")
6605 (defvar org-open-link-marker (make-marker)
6606 "Marker pointing to the location where `org-open-at-point; was called.")
6608 ;;;###autoload
6609 (defun org-open-at-point-global ()
6610 "Follow a link like Org-mode does.
6611 This command can be called in any mode to follow a link that has
6612 Org-mode syntax."
6613 (interactive)
6614 (org-run-like-in-org-mode 'org-open-at-point))
6616 (defun org-open-at-point (&optional in-emacs)
6617 "Open link at or after point.
6618 If there is no link at point, this function will search forward up to
6619 the end of the current subtree.
6620 Normally, files will be opened by an appropriate application. If the
6621 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6622 (interactive "P")
6623 (org-load-modules-maybe)
6624 (move-marker org-open-link-marker (point))
6625 (setq org-window-config-before-follow-link (current-window-configuration))
6626 (org-remove-occur-highlights nil nil t)
6627 (if (org-at-timestamp-p t)
6628 (org-follow-timestamp-link)
6629 (let (type path link line search (pos (point)))
6630 (catch 'match
6631 (save-excursion
6632 (skip-chars-forward "^]\n\r")
6633 (when (org-in-regexp org-bracket-link-regexp)
6634 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6635 (while (string-match " *\n *" link)
6636 (setq link (replace-match " " t t link)))
6637 (setq link (org-link-expand-abbrev link))
6638 (if (string-match org-link-re-with-space2 link)
6639 (setq type (match-string 1 link) path (match-string 2 link))
6640 (setq type "thisfile" path link))
6641 (throw 'match t)))
6643 (when (get-text-property (point) 'org-linked-text)
6644 (setq type "thisfile"
6645 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6646 (1+ (point)) (point))
6647 path (buffer-substring
6648 (previous-single-property-change pos 'org-linked-text)
6649 (next-single-property-change pos 'org-linked-text)))
6650 (throw 'match t))
6652 (save-excursion
6653 (when (or (org-in-regexp org-angle-link-re)
6654 (org-in-regexp org-plain-link-re))
6655 (setq type (match-string 1) path (match-string 2))
6656 (throw 'match t)))
6657 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6658 (setq type "tree-match"
6659 path (match-string 1))
6660 (throw 'match t))
6661 (save-excursion
6662 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6663 (setq type "tags"
6664 path (match-string 1))
6665 (while (string-match ":" path)
6666 (setq path (replace-match "+" t t path)))
6667 (throw 'match t))))
6668 (unless path
6669 (error "No link found"))
6670 ;; Remove any trailing spaces in path
6671 (if (string-match " +\\'" path)
6672 (setq path (replace-match "" t t path)))
6674 (cond
6676 ((assoc type org-link-protocols)
6677 (funcall (nth 1 (assoc type org-link-protocols)) path))
6679 ((equal type "mailto")
6680 (let ((cmd (car org-link-mailto-program))
6681 (args (cdr org-link-mailto-program)) args1
6682 (address path) (subject "") a)
6683 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6684 (setq address (match-string 1 path)
6685 subject (org-link-escape (match-string 2 path))))
6686 (while args
6687 (cond
6688 ((not (stringp (car args))) (push (pop args) args1))
6689 (t (setq a (pop args))
6690 (if (string-match "%a" a)
6691 (setq a (replace-match address t t a)))
6692 (if (string-match "%s" a)
6693 (setq a (replace-match subject t t a)))
6694 (push a args1))))
6695 (apply cmd (nreverse args1))))
6697 ((member type '("http" "https" "ftp" "news"))
6698 (browse-url (concat type ":" (org-link-escape
6699 path org-link-escape-chars-browser))))
6701 ((member type '("message"))
6702 (browse-url (concat type ":" path)))
6704 ((string= type "tags")
6705 (org-tags-view in-emacs path))
6706 ((string= type "thisfile")
6707 (if in-emacs
6708 (switch-to-buffer-other-window
6709 (org-get-buffer-for-internal-link (current-buffer)))
6710 (org-mark-ring-push))
6711 (let ((cmd `(org-link-search
6712 ,path
6713 ,(cond ((equal in-emacs '(4)) 'occur)
6714 ((equal in-emacs '(16)) 'org-occur)
6715 (t nil))
6716 ,pos)))
6717 (condition-case nil (eval cmd)
6718 (error (progn (widen) (eval cmd))))))
6720 ((string= type "tree-match")
6721 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6723 ((string= type "file")
6724 (if (string-match "::\\([0-9]+\\)\\'" path)
6725 (setq line (string-to-number (match-string 1 path))
6726 path (substring path 0 (match-beginning 0)))
6727 (if (string-match "::\\(.+\\)\\'" path)
6728 (setq search (match-string 1 path)
6729 path (substring path 0 (match-beginning 0)))))
6730 (if (string-match "[*?{]" (file-name-nondirectory path))
6731 (dired path)
6732 (org-open-file path in-emacs line search)))
6734 ((string= type "news")
6735 (require 'org-gnus)
6736 (org-gnus-follow-link path))
6738 ((string= type "shell")
6739 (let ((cmd path))
6740 (if (or (not org-confirm-shell-link-function)
6741 (funcall org-confirm-shell-link-function
6742 (format "Execute \"%s\" in shell? "
6743 (org-add-props cmd nil
6744 'face 'org-warning))))
6745 (progn
6746 (message "Executing %s" cmd)
6747 (shell-command cmd))
6748 (error "Abort"))))
6750 ((string= type "elisp")
6751 (let ((cmd path))
6752 (if (or (not org-confirm-elisp-link-function)
6753 (funcall org-confirm-elisp-link-function
6754 (format "Execute \"%s\" as elisp? "
6755 (org-add-props cmd nil
6756 'face 'org-warning))))
6757 (message "%s => %s" cmd (eval (read cmd)))
6758 (error "Abort"))))
6761 (browse-url-at-point)))))
6762 (move-marker org-open-link-marker nil)
6763 (run-hook-with-args 'org-follow-link-hook))
6765 ;;; File search
6767 (defvar org-create-file-search-functions nil
6768 "List of functions to construct the right search string for a file link.
6769 These functions are called in turn with point at the location to
6770 which the link should point.
6772 A function in the hook should first test if it would like to
6773 handle this file type, for example by checking the major-mode or
6774 the file extension. If it decides not to handle this file, it
6775 should just return nil to give other functions a chance. If it
6776 does handle the file, it must return the search string to be used
6777 when following the link. The search string will be part of the
6778 file link, given after a double colon, and `org-open-at-point'
6779 will automatically search for it. If special measures must be
6780 taken to make the search successful, another function should be
6781 added to the companion hook `org-execute-file-search-functions',
6782 which see.
6784 A function in this hook may also use `setq' to set the variable
6785 `description' to provide a suggestion for the descriptive text to
6786 be used for this link when it gets inserted into an Org-mode
6787 buffer with \\[org-insert-link].")
6789 (defvar org-execute-file-search-functions nil
6790 "List of functions to execute a file search triggered by a link.
6792 Functions added to this hook must accept a single argument, the
6793 search string that was part of the file link, the part after the
6794 double colon. The function must first check if it would like to
6795 handle this search, for example by checking the major-mode or the
6796 file extension. If it decides not to handle this search, it
6797 should just return nil to give other functions a chance. If it
6798 does handle the search, it must return a non-nil value to keep
6799 other functions from trying.
6801 Each function can access the current prefix argument through the
6802 variable `current-prefix-argument'. Note that a single prefix is
6803 used to force opening a link in Emacs, so it may be good to only
6804 use a numeric or double prefix to guide the search function.
6806 In case this is needed, a function in this hook can also restore
6807 the window configuration before `org-open-at-point' was called using:
6809 (set-window-configuration org-window-config-before-follow-link)")
6811 (defun org-link-search (s &optional type avoid-pos)
6812 "Search for a link search option.
6813 If S is surrounded by forward slashes, it is interpreted as a
6814 regular expression. In org-mode files, this will create an `org-occur'
6815 sparse tree. In ordinary files, `occur' will be used to list matches.
6816 If the current buffer is in `dired-mode', grep will be used to search
6817 in all files. If AVOID-POS is given, ignore matches near that position."
6818 (let ((case-fold-search t)
6819 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6820 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6821 (append '(("") (" ") ("\t") ("\n"))
6822 org-emphasis-alist)
6823 "\\|") "\\)"))
6824 (pos (point))
6825 (pre nil) (post nil)
6826 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6827 (cond
6828 ;; First check if there are any special
6829 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6830 ;; Now try the builtin stuff
6831 ((save-excursion
6832 (goto-char (point-min))
6833 (and
6834 (re-search-forward
6835 (concat "<<" (regexp-quote s0) ">>") nil t)
6836 (setq type 'dedicated
6837 pos (match-beginning 0))))
6838 ;; There is an exact target for this
6839 (goto-char pos))
6840 ((string-match "^/\\(.*\\)/$" s)
6841 ;; A regular expression
6842 (cond
6843 ((org-mode-p)
6844 (org-occur (match-string 1 s)))
6845 ;;((eq major-mode 'dired-mode)
6846 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6847 (t (org-do-occur (match-string 1 s)))))
6849 ;; A normal search strings
6850 (when (equal (string-to-char s) ?*)
6851 ;; Anchor on headlines, post may include tags.
6852 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6853 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6854 s (substring s 1)))
6855 (remove-text-properties
6856 0 (length s)
6857 '(face nil mouse-face nil keymap nil fontified nil) s)
6858 ;; Make a series of regular expressions to find a match
6859 (setq words (org-split-string s "[ \n\r\t]+")
6861 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6862 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6863 "\\)" markers)
6864 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6865 re2a (concat "[ \t\r\n]" re2a_)
6866 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6867 re4 (concat "[^a-zA-Z_]" re4_)
6869 re1 (concat pre re2 post)
6870 re3 (concat pre (if pre re4_ re4) post)
6871 re5 (concat pre ".*" re4)
6872 re2 (concat pre re2)
6873 re2a (concat pre (if pre re2a_ re2a))
6874 re4 (concat pre (if pre re4_ re4))
6875 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6876 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6877 re5 "\\)"
6879 (cond
6880 ((eq type 'org-occur) (org-occur reall))
6881 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6882 (t (goto-char (point-min))
6883 (setq type 'fuzzy)
6884 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6885 (org-search-not-self 1 re1 nil t)
6886 (org-search-not-self 1 re2 nil t)
6887 (org-search-not-self 1 re2a nil t)
6888 (org-search-not-self 1 re3 nil t)
6889 (org-search-not-self 1 re4 nil t)
6890 (org-search-not-self 1 re5 nil t)
6892 (goto-char (match-beginning 1))
6893 (goto-char pos)
6894 (error "No match")))))
6896 ;; Normal string-search
6897 (goto-char (point-min))
6898 (if (search-forward s nil t)
6899 (goto-char (match-beginning 0))
6900 (error "No match"))))
6901 (and (org-mode-p) (org-show-context 'link-search))
6902 type))
6904 (defun org-search-not-self (group &rest args)
6905 "Execute `re-search-forward', but only accept matches that do not
6906 enclose the position of `org-open-link-marker'."
6907 (let ((m org-open-link-marker))
6908 (catch 'exit
6909 (while (apply 're-search-forward args)
6910 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6911 (goto-char (match-end group))
6912 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6913 (> (match-beginning 0) (marker-position m))
6914 (< (match-end 0) (marker-position m)))
6915 (save-match-data
6916 (or (not (org-in-regexp
6917 org-bracket-link-analytic-regexp 1))
6918 (not (match-end 4)) ; no description
6919 (and (<= (match-beginning 4) (point))
6920 (>= (match-end 4) (point))))))
6921 (throw 'exit (point))))))))
6923 (defun org-get-buffer-for-internal-link (buffer)
6924 "Return a buffer to be used for displaying the link target of internal links."
6925 (cond
6926 ((not org-display-internal-link-with-indirect-buffer)
6927 buffer)
6928 ((string-match "(Clone)$" (buffer-name buffer))
6929 (message "Buffer is already a clone, not making another one")
6930 ;; we also do not modify visibility in this case
6931 buffer)
6932 (t ; make a new indirect buffer for displaying the link
6933 (let* ((bn (buffer-name buffer))
6934 (ibn (concat bn "(Clone)"))
6935 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6936 (with-current-buffer ib (org-overview))
6937 ib))))
6939 (defun org-do-occur (regexp &optional cleanup)
6940 "Call the Emacs command `occur'.
6941 If CLEANUP is non-nil, remove the printout of the regular expression
6942 in the *Occur* buffer. This is useful if the regex is long and not useful
6943 to read."
6944 (occur regexp)
6945 (when cleanup
6946 (let ((cwin (selected-window)) win beg end)
6947 (when (setq win (get-buffer-window "*Occur*"))
6948 (select-window win))
6949 (goto-char (point-min))
6950 (when (re-search-forward "match[a-z]+" nil t)
6951 (setq beg (match-end 0))
6952 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6953 (setq end (1- (match-beginning 0)))))
6954 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6955 (goto-char (point-min))
6956 (select-window cwin))))
6958 ;;; The mark ring for links jumps
6960 (defvar org-mark-ring nil
6961 "Mark ring for positions before jumps in Org-mode.")
6962 (defvar org-mark-ring-last-goto nil
6963 "Last position in the mark ring used to go back.")
6964 ;; Fill and close the ring
6965 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6966 (loop for i from 1 to org-mark-ring-length do
6967 (push (make-marker) org-mark-ring))
6968 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6969 org-mark-ring)
6971 (defun org-mark-ring-push (&optional pos buffer)
6972 "Put the current position or POS into the mark ring and rotate it."
6973 (interactive)
6974 (setq pos (or pos (point)))
6975 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6976 (move-marker (car org-mark-ring)
6977 (or pos (point))
6978 (or buffer (current-buffer)))
6979 (message "%s"
6980 (substitute-command-keys
6981 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6983 (defun org-mark-ring-goto (&optional n)
6984 "Jump to the previous position in the mark ring.
6985 With prefix arg N, jump back that many stored positions. When
6986 called several times in succession, walk through the entire ring.
6987 Org-mode commands jumping to a different position in the current file,
6988 or to another Org-mode file, automatically push the old position
6989 onto the ring."
6990 (interactive "p")
6991 (let (p m)
6992 (if (eq last-command this-command)
6993 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6994 (setq p org-mark-ring))
6995 (setq org-mark-ring-last-goto p)
6996 (setq m (car p))
6997 (switch-to-buffer (marker-buffer m))
6998 (goto-char m)
6999 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7001 (defun org-remove-angle-brackets (s)
7002 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7003 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7005 (defun org-add-angle-brackets (s)
7006 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7007 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7010 ;;; Following specific links
7012 (defun org-follow-timestamp-link ()
7013 (cond
7014 ((org-at-date-range-p t)
7015 (let ((org-agenda-start-on-weekday)
7016 (t1 (match-string 1))
7017 (t2 (match-string 2)))
7018 (setq t1 (time-to-days (org-time-string-to-time t1))
7019 t2 (time-to-days (org-time-string-to-time t2)))
7020 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7021 ((org-at-timestamp-p t)
7022 (org-agenda-list nil (time-to-days (org-time-string-to-time
7023 (substring (match-string 1) 0 10)))
7025 (t (error "This should not happen"))))
7028 ;;; Following file links
7029 (defvar org-wait nil)
7030 (defun org-open-file (path &optional in-emacs line search)
7031 "Open the file at PATH.
7032 First, this expands any special file name abbreviations. Then the
7033 configuration variable `org-file-apps' is checked if it contains an
7034 entry for this file type, and if yes, the corresponding command is launched.
7035 If no application is found, Emacs simply visits the file.
7036 With optional argument IN-EMACS, Emacs will visit the file.
7037 Optional LINE specifies a line to go to, optional SEARCH a string to
7038 search for. If LINE or SEARCH is given, the file will always be
7039 opened in Emacs.
7040 If the file does not exist, an error is thrown."
7041 (setq in-emacs (or in-emacs line search))
7042 (let* ((file (if (equal path "")
7043 buffer-file-name
7044 (substitute-in-file-name (expand-file-name path))))
7045 (apps (append org-file-apps (org-default-apps)))
7046 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7047 (dirp (if remp nil (file-directory-p file)))
7048 (dfile (downcase file))
7049 (old-buffer (current-buffer))
7050 (old-pos (point))
7051 (old-mode major-mode)
7052 ext cmd)
7053 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7054 (setq ext (match-string 1 dfile))
7055 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7056 (setq ext (match-string 1 dfile))))
7057 (if in-emacs
7058 (setq cmd 'emacs)
7059 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7060 (and dirp (cdr (assoc 'directory apps)))
7061 (cdr (assoc ext apps))
7062 (cdr (assoc t apps)))))
7063 (when (eq cmd 'mailcap)
7064 (require 'mailcap)
7065 (mailcap-parse-mailcaps)
7066 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7067 (command (mailcap-mime-info mime-type)))
7068 (if (stringp command)
7069 (setq cmd command)
7070 (setq cmd 'emacs))))
7071 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7072 (not (file-exists-p file))
7073 (not org-open-non-existing-files))
7074 (error "No such file: %s" file))
7075 (cond
7076 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7077 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7078 (while (string-match "['\"]%s['\"]" cmd)
7079 (setq cmd (replace-match "%s" t t cmd)))
7080 (while (string-match "%s" cmd)
7081 (setq cmd (replace-match
7082 (save-match-data (shell-quote-argument file))
7083 t t cmd)))
7084 (save-window-excursion
7085 (start-process-shell-command cmd nil cmd)
7086 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7088 ((or (stringp cmd)
7089 (eq cmd 'emacs))
7090 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7091 (widen)
7092 (if line (goto-line line)
7093 (if search (org-link-search search))))
7094 ((consp cmd)
7095 (eval cmd))
7096 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7097 (and (org-mode-p) (eq old-mode 'org-mode)
7098 (or (not (equal old-buffer (current-buffer)))
7099 (not (equal old-pos (point))))
7100 (org-mark-ring-push old-pos old-buffer))))
7102 (defun org-default-apps ()
7103 "Return the default applications for this operating system."
7104 (cond
7105 ((eq system-type 'darwin)
7106 org-file-apps-defaults-macosx)
7107 ((eq system-type 'windows-nt)
7108 org-file-apps-defaults-windowsnt)
7109 (t org-file-apps-defaults-gnu)))
7111 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7112 (defun org-file-remote-p (file)
7113 "Test whether FILE specifies a location on a remote system.
7114 Return non-nil if the location is indeed remote.
7116 For example, the filename \"/user@host:/foo\" specifies a location
7117 on the system \"/user@host:\"."
7118 (cond ((fboundp 'file-remote-p)
7119 (file-remote-p file))
7120 ((fboundp 'tramp-handle-file-remote-p)
7121 (tramp-handle-file-remote-p file))
7122 ((and (boundp 'ange-ftp-name-format)
7123 (string-match (car ange-ftp-name-format) file))
7125 (t nil)))
7128 ;;;; Refiling
7130 (defun org-get-org-file ()
7131 "Read a filename, with default directory `org-directory'."
7132 (let ((default (or org-default-notes-file remember-data-file)))
7133 (read-file-name (format "File name [%s]: " default)
7134 (file-name-as-directory org-directory)
7135 default)))
7137 (defun org-notes-order-reversed-p ()
7138 "Check if the current file should receive notes in reversed order."
7139 (cond
7140 ((not org-reverse-note-order) nil)
7141 ((eq t org-reverse-note-order) t)
7142 ((not (listp org-reverse-note-order)) nil)
7143 (t (catch 'exit
7144 (let ((all org-reverse-note-order)
7145 entry)
7146 (while (setq entry (pop all))
7147 (if (string-match (car entry) buffer-file-name)
7148 (throw 'exit (cdr entry))))
7149 nil)))))
7151 (defvar org-refile-target-table nil
7152 "The list of refile targets, created by `org-refile'.")
7154 (defvar org-agenda-new-buffers nil
7155 "Buffers created to visit agenda files.")
7157 (defun org-get-refile-targets (&optional default-buffer)
7158 "Produce a table with refile targets."
7159 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7160 targets txt re files f desc descre)
7161 (with-current-buffer (or default-buffer (current-buffer))
7162 (while (setq entry (pop entries))
7163 (setq files (car entry) desc (cdr entry))
7164 (cond
7165 ((null files) (setq files (list (current-buffer))))
7166 ((eq files 'org-agenda-files)
7167 (setq files (org-agenda-files 'unrestricted)))
7168 ((and (symbolp files) (fboundp files))
7169 (setq files (funcall files)))
7170 ((and (symbolp files) (boundp files))
7171 (setq files (symbol-value files))))
7172 (if (stringp files) (setq files (list files)))
7173 (cond
7174 ((eq (car desc) :tag)
7175 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7176 ((eq (car desc) :todo)
7177 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7178 ((eq (car desc) :regexp)
7179 (setq descre (cdr desc)))
7180 ((eq (car desc) :level)
7181 (setq descre (concat "^\\*\\{" (number-to-string
7182 (if org-odd-levels-only
7183 (1- (* 2 (cdr desc)))
7184 (cdr desc)))
7185 "\\}[ \t]")))
7186 ((eq (car desc) :maxlevel)
7187 (setq descre (concat "^\\*\\{1," (number-to-string
7188 (if org-odd-levels-only
7189 (1- (* 2 (cdr desc)))
7190 (cdr desc)))
7191 "\\}[ \t]")))
7192 (t (error "Bad refiling target description %s" desc)))
7193 (while (setq f (pop files))
7194 (save-excursion
7195 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7196 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7197 (save-excursion
7198 (save-restriction
7199 (widen)
7200 (goto-char (point-min))
7201 (while (re-search-forward descre nil t)
7202 (goto-char (point-at-bol))
7203 (when (looking-at org-complex-heading-regexp)
7204 (setq txt (match-string 4)
7205 re (concat "^" (regexp-quote
7206 (buffer-substring (match-beginning 1)
7207 (match-end 4)))))
7208 (if (match-end 5) (setq re (concat re "[ \t]+"
7209 (regexp-quote
7210 (match-string 5)))))
7211 (setq re (concat re "[ \t]*$"))
7212 (when org-refile-use-outline-path
7213 (setq txt (mapconcat 'identity
7214 (append
7215 (if (eq org-refile-use-outline-path 'file)
7216 (list (file-name-nondirectory
7217 (buffer-file-name (buffer-base-buffer))))
7218 (if (eq org-refile-use-outline-path 'full-file-path)
7219 (list (buffer-file-name (buffer-base-buffer)))))
7220 (org-get-outline-path)
7221 (list txt))
7222 "/")))
7223 (push (list txt f re (point)) targets))
7224 (goto-char (point-at-eol))))))))
7225 (nreverse targets))))
7227 (defun org-get-outline-path ()
7228 "Return the outline path to the current entry, as a list."
7229 (let (rtn)
7230 (save-excursion
7231 (while (org-up-heading-safe)
7232 (when (looking-at org-complex-heading-regexp)
7233 (push (org-match-string-no-properties 4) rtn)))
7234 rtn)))
7236 (defvar org-refile-history nil
7237 "History for refiling operations.")
7239 (defun org-refile (&optional goto default-buffer)
7240 "Move the entry at point to another heading.
7241 The list of target headings is compiled using the information in
7242 `org-refile-targets', which see. This list is created before each use
7243 and will therefore always be up-to-date.
7245 At the target location, the entry is filed as a subitem of the target heading.
7246 Depending on `org-reverse-note-order', the new subitem will either be the
7247 first of the last subitem.
7249 With prefix arg GOTO, the command will only visit the target location,
7250 not actually move anything.
7251 With a double prefix `C-c C-c', go to the location where the last refiling
7252 operation has put the subtree."
7253 (interactive "P")
7254 (let* ((cbuf (current-buffer))
7255 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7256 pos it nbuf file re level reversed)
7257 (if (equal goto '(16))
7258 (org-refile-goto-last-stored)
7259 (when (setq it (org-refile-get-location
7260 (if goto "Goto: " "Refile to: ") default-buffer))
7261 (setq file (nth 1 it)
7262 re (nth 2 it)
7263 pos (nth 3 it))
7264 (setq nbuf (or (find-buffer-visiting file)
7265 (find-file-noselect file)))
7266 (if goto
7267 (progn
7268 (switch-to-buffer nbuf)
7269 (goto-char pos)
7270 (org-show-context 'org-goto))
7271 (org-copy-special)
7272 (save-excursion
7273 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7274 (find-file-noselect file))))
7275 (setq reversed (org-notes-order-reversed-p))
7276 (save-excursion
7277 (save-restriction
7278 (widen)
7279 (goto-char pos)
7280 (looking-at outline-regexp)
7281 (setq level (org-get-valid-level (funcall outline-level) 1))
7282 (goto-char
7283 (if reversed
7284 (outline-next-heading)
7285 (or (save-excursion (outline-get-next-sibling))
7286 (org-end-of-subtree t t)
7287 (point-max))))
7288 (bookmark-set "org-refile-last-stored")
7289 (org-paste-subtree level))))
7290 (org-cut-special)
7291 (message "Entry refiled to \"%s\"" (car it)))))))
7293 (defun org-refile-goto-last-stored ()
7294 "Go to the location where the last refile was stored."
7295 (interactive)
7296 (bookmark-jump "org-refile-last-stored")
7297 (message "This is the location of the last refile"))
7299 (defun org-refile-get-location (&optional prompt default-buffer)
7300 "Prompt the user for a refile location, using PROMPT."
7301 (let ((org-refile-targets org-refile-targets)
7302 (org-refile-use-outline-path org-refile-use-outline-path))
7303 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7304 (unless org-refile-target-table
7305 (error "No refile targets"))
7306 (let* ((cbuf (current-buffer))
7307 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7308 (fname (and filename (file-truename filename)))
7309 (tbl (mapcar
7310 (lambda (x)
7311 (if (not (equal fname (file-truename (nth 1 x))))
7312 (cons (concat (car x) " (" (file-name-nondirectory
7313 (nth 1 x)) ")")
7314 (cdr x))
7316 org-refile-target-table))
7317 (completion-ignore-case t))
7318 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7319 tbl)))
7321 ;;;; Dynamic blocks
7323 (defun org-find-dblock (name)
7324 "Find the first dynamic block with name NAME in the buffer.
7325 If not found, stay at current position and return nil."
7326 (let (pos)
7327 (save-excursion
7328 (goto-char (point-min))
7329 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7330 nil t)
7331 (match-beginning 0))))
7332 (if pos (goto-char pos))
7333 pos))
7335 (defconst org-dblock-start-re
7336 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7337 "Matches the startline of a dynamic block, with parameters.")
7339 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7340 "Matches the end of a dyhamic block.")
7342 (defun org-create-dblock (plist)
7343 "Create a dynamic block section, with parameters taken from PLIST.
7344 PLIST must containe a :name entry which is used as name of the block."
7345 (unless (bolp) (newline))
7346 (let ((name (plist-get plist :name)))
7347 (insert "#+BEGIN: " name)
7348 (while plist
7349 (if (eq (car plist) :name)
7350 (setq plist (cddr plist))
7351 (insert " " (prin1-to-string (pop plist)))))
7352 (insert "\n\n#+END:\n")
7353 (beginning-of-line -2)))
7355 (defun org-prepare-dblock ()
7356 "Prepare dynamic block for refresh.
7357 This empties the block, puts the cursor at the insert position and returns
7358 the property list including an extra property :name with the block name."
7359 (unless (looking-at org-dblock-start-re)
7360 (error "Not at a dynamic block"))
7361 (let* ((begdel (1+ (match-end 0)))
7362 (name (org-no-properties (match-string 1)))
7363 (params (append (list :name name)
7364 (read (concat "(" (match-string 3) ")")))))
7365 (unless (re-search-forward org-dblock-end-re nil t)
7366 (error "Dynamic block not terminated"))
7367 (setq params
7368 (append params
7369 (list :content (buffer-substring
7370 begdel (match-beginning 0)))))
7371 (delete-region begdel (match-beginning 0))
7372 (goto-char begdel)
7373 (open-line 1)
7374 params))
7376 (defun org-map-dblocks (&optional command)
7377 "Apply COMMAND to all dynamic blocks in the current buffer.
7378 If COMMAND is not given, use `org-update-dblock'."
7379 (let ((cmd (or command 'org-update-dblock))
7380 pos)
7381 (save-excursion
7382 (goto-char (point-min))
7383 (while (re-search-forward org-dblock-start-re nil t)
7384 (goto-char (setq pos (match-beginning 0)))
7385 (condition-case nil
7386 (funcall cmd)
7387 (error (message "Error during update of dynamic block")))
7388 (goto-char pos)
7389 (unless (re-search-forward org-dblock-end-re nil t)
7390 (error "Dynamic block not terminated"))))))
7392 (defun org-dblock-update (&optional arg)
7393 "User command for updating dynamic blocks.
7394 Update the dynamic block at point. With prefix ARG, update all dynamic
7395 blocks in the buffer."
7396 (interactive "P")
7397 (if arg
7398 (org-update-all-dblocks)
7399 (or (looking-at org-dblock-start-re)
7400 (org-beginning-of-dblock))
7401 (org-update-dblock)))
7403 (defun org-update-dblock ()
7404 "Update the dynamic block at point
7405 This means to empty the block, parse for parameters and then call
7406 the correct writing function."
7407 (save-window-excursion
7408 (let* ((pos (point))
7409 (line (org-current-line))
7410 (params (org-prepare-dblock))
7411 (name (plist-get params :name))
7412 (cmd (intern (concat "org-dblock-write:" name))))
7413 (message "Updating dynamic block `%s' at line %d..." name line)
7414 (funcall cmd params)
7415 (message "Updating dynamic block `%s' at line %d...done" name line)
7416 (goto-char pos))))
7418 (defun org-beginning-of-dblock ()
7419 "Find the beginning of the dynamic block at point.
7420 Error if there is no scuh block at point."
7421 (let ((pos (point))
7422 beg)
7423 (end-of-line 1)
7424 (if (and (re-search-backward org-dblock-start-re nil t)
7425 (setq beg (match-beginning 0))
7426 (re-search-forward org-dblock-end-re nil t)
7427 (> (match-end 0) pos))
7428 (goto-char beg)
7429 (goto-char pos)
7430 (error "Not in a dynamic block"))))
7432 (defun org-update-all-dblocks ()
7433 "Update all dynamic blocks in the buffer.
7434 This function can be used in a hook."
7435 (when (org-mode-p)
7436 (org-map-dblocks 'org-update-dblock)))
7439 ;;;; Completion
7441 (defconst org-additional-option-like-keywords
7442 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7443 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7444 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7446 (defun org-complete (&optional arg)
7447 "Perform completion on word at point.
7448 At the beginning of a headline, this completes TODO keywords as given in
7449 `org-todo-keywords'.
7450 If the current word is preceded by a backslash, completes the TeX symbols
7451 that are supported for HTML support.
7452 If the current word is preceded by \"#+\", completes special words for
7453 setting file options.
7454 In the line after \"#+STARTUP:, complete valid keywords.\"
7455 At all other locations, this simply calls the value of
7456 `org-completion-fallback-command'."
7457 (interactive "P")
7458 (org-without-partial-completion
7459 (catch 'exit
7460 (let* ((end (point))
7461 (beg1 (save-excursion
7462 (skip-chars-backward (org-re "[:alnum:]_@"))
7463 (point)))
7464 (beg (save-excursion
7465 (skip-chars-backward "a-zA-Z0-9_:$")
7466 (point)))
7467 (confirm (lambda (x) (stringp (car x))))
7468 (searchhead (equal (char-before beg) ?*))
7469 (tag (and (equal (char-before beg1) ?:)
7470 (equal (char-after (point-at-bol)) ?*)))
7471 (prop (and (equal (char-before beg1) ?:)
7472 (not (equal (char-after (point-at-bol)) ?*))))
7473 (texp (equal (char-before beg) ?\\))
7474 (link (equal (char-before beg) ?\[))
7475 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7476 beg)
7477 "#+"))
7478 (startup (string-match "^#\\+STARTUP:.*"
7479 (buffer-substring (point-at-bol) (point))))
7480 (completion-ignore-case opt)
7481 (type nil)
7482 (tbl nil)
7483 (table (cond
7484 (opt
7485 (setq type :opt)
7486 (require 'org-exp)
7487 (append
7488 (mapcar
7489 (lambda (x)
7490 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7491 (cons (match-string 2 x) (match-string 1 x)))
7492 (org-split-string (org-get-current-options) "\n"))
7493 (mapcar 'list org-additional-option-like-keywords)))
7494 (startup
7495 (setq type :startup)
7496 org-startup-options)
7497 (link (append org-link-abbrev-alist-local
7498 org-link-abbrev-alist))
7499 (texp
7500 (setq type :tex)
7501 org-html-entities)
7502 ((string-match "\\`\\*+[ \t]+\\'"
7503 (buffer-substring (point-at-bol) beg))
7504 (setq type :todo)
7505 (mapcar 'list org-todo-keywords-1))
7506 (searchhead
7507 (setq type :searchhead)
7508 (save-excursion
7509 (goto-char (point-min))
7510 (while (re-search-forward org-todo-line-regexp nil t)
7511 (push (list
7512 (org-make-org-heading-search-string
7513 (match-string 3) t))
7514 tbl)))
7515 tbl)
7516 (tag (setq type :tag beg beg1)
7517 (or org-tag-alist (org-get-buffer-tags)))
7518 (prop (setq type :prop beg beg1)
7519 (mapcar 'list (org-buffer-property-keys nil t t)))
7520 (t (progn
7521 (call-interactively org-completion-fallback-command)
7522 (throw 'exit nil)))))
7523 (pattern (buffer-substring-no-properties beg end))
7524 (completion (try-completion pattern table confirm)))
7525 (cond ((eq completion t)
7526 (if (not (assoc (upcase pattern) table))
7527 (message "Already complete")
7528 (if (and (equal type :opt)
7529 (not (member (car (assoc (upcase pattern) table))
7530 org-additional-option-like-keywords)))
7531 (insert (substring (cdr (assoc (upcase pattern) table))
7532 (length pattern)))
7533 (if (memq type '(:tag :prop)) (insert ":")))))
7534 ((null completion)
7535 (message "Can't find completion for \"%s\"" pattern)
7536 (ding))
7537 ((not (string= pattern completion))
7538 (delete-region beg end)
7539 (if (string-match " +$" completion)
7540 (setq completion (replace-match "" t t completion)))
7541 (insert completion)
7542 (if (get-buffer-window "*Completions*")
7543 (delete-window (get-buffer-window "*Completions*")))
7544 (if (assoc completion table)
7545 (if (eq type :todo) (insert " ")
7546 (if (memq type '(:tag :prop)) (insert ":"))))
7547 (if (and (equal type :opt) (assoc completion table))
7548 (message "%s" (substitute-command-keys
7549 "Press \\[org-complete] again to insert example settings"))))
7551 (message "Making completion list...")
7552 (let ((list (sort (all-completions pattern table confirm)
7553 'string<)))
7554 (with-output-to-temp-buffer "*Completions*"
7555 (condition-case nil
7556 ;; Protection needed for XEmacs and emacs 21
7557 (display-completion-list list pattern)
7558 (error (display-completion-list list)))))
7559 (message "Making completion list...%s" "done")))))))
7561 ;;;; TODO, DEADLINE, Comments
7563 (defun org-toggle-comment ()
7564 "Change the COMMENT state of an entry."
7565 (interactive)
7566 (save-excursion
7567 (org-back-to-heading)
7568 (let (case-fold-search)
7569 (if (looking-at (concat outline-regexp
7570 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7571 (replace-match "" t t nil 1)
7572 (if (looking-at outline-regexp)
7573 (progn
7574 (goto-char (match-end 0))
7575 (insert org-comment-string " ")))))))
7577 (defvar org-last-todo-state-is-todo nil
7578 "This is non-nil when the last TODO state change led to a TODO state.
7579 If the last change removed the TODO tag or switched to DONE, then
7580 this is nil.")
7582 (defvar org-setting-tags nil) ; dynamically skiped
7584 (defun org-parse-local-options (string var)
7585 "Parse STRING for startup setting relevant for variable VAR."
7586 (let ((rtn (symbol-value var))
7587 e opts)
7588 (save-match-data
7589 (if (or (not string) (not (string-match "\\S-" string)))
7591 (setq opts (delq nil (mapcar (lambda (x)
7592 (setq e (assoc x org-startup-options))
7593 (if (eq (nth 1 e) var) e nil))
7594 (org-split-string string "[ \t]+"))))
7595 (if (not opts)
7597 (setq rtn nil)
7598 (while (setq e (pop opts))
7599 (if (not (nth 3 e))
7600 (setq rtn (nth 2 e))
7601 (if (not (listp rtn)) (setq rtn nil))
7602 (push (nth 2 e) rtn)))
7603 rtn)))))
7605 (defvar org-blocker-hook nil
7606 "Hook for functions that are allowed to block a state change.
7608 Each function gets as its single argument a property list, see
7609 `org-trigger-hook' for more information about this list.
7611 If any of the functions in this hook returns nil, the state change
7612 is blocked.")
7614 (defvar org-trigger-hook nil
7615 "Hook for functions that are triggered by a state change.
7617 Each function gets as its single argument a property list with at least
7618 the following elements:
7620 (:type type-of-change :position pos-at-entry-start
7621 :from old-state :to new-state)
7623 Depending on the type, more properties may be present.
7625 This mechanism is currently implemented for:
7627 TODO state changes
7628 ------------------
7629 :type todo-state-change
7630 :from previous state (keyword as a string), or nil
7631 :to new state (keyword as a string), or nil")
7634 (defun org-todo (&optional arg)
7635 "Change the TODO state of an item.
7636 The state of an item is given by a keyword at the start of the heading,
7637 like
7638 *** TODO Write paper
7639 *** DONE Call mom
7641 The different keywords are specified in the variable `org-todo-keywords'.
7642 By default the available states are \"TODO\" and \"DONE\".
7643 So for this example: when the item starts with TODO, it is changed to DONE.
7644 When it starts with DONE, the DONE is removed. And when neither TODO nor
7645 DONE are present, add TODO at the beginning of the heading.
7647 With C-u prefix arg, use completion to determine the new state.
7648 With numeric prefix arg, switch to that state.
7650 For calling through lisp, arg is also interpreted in the following way:
7651 'none -> empty state
7652 \"\"(empty string) -> switch to empty state
7653 'done -> switch to DONE
7654 'nextset -> switch to the next set of keywords
7655 'previousset -> switch to the previous set of keywords
7656 \"WAITING\" -> switch to the specified keyword, but only if it
7657 really is a member of `org-todo-keywords'."
7658 (interactive "P")
7659 (save-excursion
7660 (catch 'exit
7661 (org-back-to-heading)
7662 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7663 (or (looking-at (concat " +" org-todo-regexp " *"))
7664 (looking-at " *"))
7665 (let* ((match-data (match-data))
7666 (startpos (point-at-bol))
7667 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7668 (org-log-done org-log-done)
7669 (org-log-repeat org-log-repeat)
7670 (org-todo-log-states org-todo-log-states)
7671 (this (match-string 1))
7672 (hl-pos (match-beginning 0))
7673 (head (org-get-todo-sequence-head this))
7674 (ass (assoc head org-todo-kwd-alist))
7675 (interpret (nth 1 ass))
7676 (done-word (nth 3 ass))
7677 (final-done-word (nth 4 ass))
7678 (last-state (or this ""))
7679 (completion-ignore-case t)
7680 (member (member this org-todo-keywords-1))
7681 (tail (cdr member))
7682 (state (cond
7683 ((and org-todo-key-trigger
7684 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7685 (and (not arg) org-use-fast-todo-selection
7686 (not (eq org-use-fast-todo-selection 'prefix)))))
7687 ;; Use fast selection
7688 (org-fast-todo-selection))
7689 ((and (equal arg '(4))
7690 (or (not org-use-fast-todo-selection)
7691 (not org-todo-key-trigger)))
7692 ;; Read a state with completion
7693 (completing-read "State: " (mapcar (lambda(x) (list x))
7694 org-todo-keywords-1)
7695 nil t))
7696 ((eq arg 'right)
7697 (if this
7698 (if tail (car tail) nil)
7699 (car org-todo-keywords-1)))
7700 ((eq arg 'left)
7701 (if (equal member org-todo-keywords-1)
7703 (if this
7704 (nth (- (length org-todo-keywords-1) (length tail) 2)
7705 org-todo-keywords-1)
7706 (org-last org-todo-keywords-1))))
7707 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7708 (setq arg nil))) ; hack to fall back to cycling
7709 (arg
7710 ;; user or caller requests a specific state
7711 (cond
7712 ((equal arg "") nil)
7713 ((eq arg 'none) nil)
7714 ((eq arg 'done) (or done-word (car org-done-keywords)))
7715 ((eq arg 'nextset)
7716 (or (car (cdr (member head org-todo-heads)))
7717 (car org-todo-heads)))
7718 ((eq arg 'previousset)
7719 (let ((org-todo-heads (reverse org-todo-heads)))
7720 (or (car (cdr (member head org-todo-heads)))
7721 (car org-todo-heads))))
7722 ((car (member arg org-todo-keywords-1)))
7723 ((nth (1- (prefix-numeric-value arg))
7724 org-todo-keywords-1))))
7725 ((null member) (or head (car org-todo-keywords-1)))
7726 ((equal this final-done-word) nil) ;; -> make empty
7727 ((null tail) nil) ;; -> first entry
7728 ((eq interpret 'sequence)
7729 (car tail))
7730 ((memq interpret '(type priority))
7731 (if (eq this-command last-command)
7732 (car tail)
7733 (if (> (length tail) 0)
7734 (or done-word (car org-done-keywords))
7735 nil)))
7736 (t nil)))
7737 (next (if state (concat " " state " ") " "))
7738 (change-plist (list :type 'todo-state-change :from this :to state
7739 :position startpos))
7740 dolog now-done-p)
7741 (when org-blocker-hook
7742 (unless (save-excursion
7743 (save-match-data
7744 (run-hook-with-args-until-failure
7745 'org-blocker-hook change-plist)))
7746 (if (interactive-p)
7747 (error "TODO state change from %s to %s blocked" this state)
7748 ;; fail silently
7749 (message "TODO state change from %s to %s blocked" this state)
7750 (throw 'exit nil))))
7751 (store-match-data match-data)
7752 (replace-match next t t)
7753 (unless (pos-visible-in-window-p hl-pos)
7754 (message "TODO state changed to %s" (org-trim next)))
7755 (unless head
7756 (setq head (org-get-todo-sequence-head state)
7757 ass (assoc head org-todo-kwd-alist)
7758 interpret (nth 1 ass)
7759 done-word (nth 3 ass)
7760 final-done-word (nth 4 ass)))
7761 (when (memq arg '(nextset previousset))
7762 (message "Keyword-Set %d/%d: %s"
7763 (- (length org-todo-sets) -1
7764 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7765 (length org-todo-sets)
7766 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7767 (setq org-last-todo-state-is-todo
7768 (not (member state org-done-keywords)))
7769 (setq now-done-p (and (member state org-done-keywords)
7770 (not (member this org-done-keywords))))
7771 (and logging (org-local-logging logging))
7772 (when (and (or org-todo-log-states org-log-done)
7773 (not (memq arg '(nextset previousset))))
7774 ;; we need to look at recording a time and note
7775 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7776 (nth 2 (assoc this org-todo-log-states))))
7777 (when (and state
7778 (member state org-not-done-keywords)
7779 (not (member this org-not-done-keywords)))
7780 ;; This is now a todo state and was not one before
7781 ;; If there was a CLOSED time stamp, get rid of it.
7782 (org-add-planning-info nil nil 'closed))
7783 (when (and now-done-p org-log-done)
7784 ;; It is now done, and it was not done before
7785 (org-add-planning-info 'closed (org-current-time))
7786 (if (and (not dolog) (eq 'note org-log-done))
7787 (org-add-log-setup 'done state 'findpos 'note)))
7788 (when (and state dolog)
7789 ;; This is a non-nil state, and we need to log it
7790 (org-add-log-setup 'state state 'findpos dolog)))
7791 ;; Fixup tag positioning
7792 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7793 (run-hooks 'org-after-todo-state-change-hook)
7794 (if (and arg (not (member state org-done-keywords)))
7795 (setq head (org-get-todo-sequence-head state)))
7796 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7797 ;; Do we need to trigger a repeat?
7798 (when now-done-p (org-auto-repeat-maybe state))
7799 ;; Fixup cursor location if close to the keyword
7800 (if (and (outline-on-heading-p)
7801 (not (bolp))
7802 (save-excursion (beginning-of-line 1)
7803 (looking-at org-todo-line-regexp))
7804 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7805 (progn
7806 (goto-char (or (match-end 2) (match-end 1)))
7807 (just-one-space)))
7808 (when org-trigger-hook
7809 (save-excursion
7810 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7812 (defun org-local-logging (value)
7813 "Get logging settings from a property VALUE."
7814 (let* (words w a)
7815 ;; directly set the variables, they are already local.
7816 (setq org-log-done nil
7817 org-log-repeat nil
7818 org-todo-log-states nil)
7819 (setq words (org-split-string value))
7820 (while (setq w (pop words))
7821 (cond
7822 ((setq a (assoc w org-startup-options))
7823 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7824 (set (nth 1 a) (nth 2 a))))
7825 ((setq a (org-extract-log-state-settings w))
7826 (and (member (car a) org-todo-keywords-1)
7827 (push a org-todo-log-states)))))))
7829 (defun org-get-todo-sequence-head (kwd)
7830 "Return the head of the TODO sequence to which KWD belongs.
7831 If KWD is not set, check if there is a text property remembering the
7832 right sequence."
7833 (let (p)
7834 (cond
7835 ((not kwd)
7836 (or (get-text-property (point-at-bol) 'org-todo-head)
7837 (progn
7838 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7839 nil (point-at-eol)))
7840 (get-text-property p 'org-todo-head))))
7841 ((not (member kwd org-todo-keywords-1))
7842 (car org-todo-keywords-1))
7843 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7845 (defun org-fast-todo-selection ()
7846 "Fast TODO keyword selection with single keys.
7847 Returns the new TODO keyword, or nil if no state change should occur."
7848 (let* ((fulltable org-todo-key-alist)
7849 (done-keywords org-done-keywords) ;; needed for the faces.
7850 (maxlen (apply 'max (mapcar
7851 (lambda (x)
7852 (if (stringp (car x)) (string-width (car x)) 0))
7853 fulltable)))
7854 (expert nil)
7855 (fwidth (+ maxlen 3 1 3))
7856 (ncol (/ (- (window-width) 4) fwidth))
7857 tg cnt e c tbl
7858 groups ingroup)
7859 (save-window-excursion
7860 (if expert
7861 (set-buffer (get-buffer-create " *Org todo*"))
7862 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7863 (erase-buffer)
7864 (org-set-local 'org-done-keywords done-keywords)
7865 (setq tbl fulltable cnt 0)
7866 (while (setq e (pop tbl))
7867 (cond
7868 ((equal e '(:startgroup))
7869 (push '() groups) (setq ingroup t)
7870 (when (not (= cnt 0))
7871 (setq cnt 0)
7872 (insert "\n"))
7873 (insert "{ "))
7874 ((equal e '(:endgroup))
7875 (setq ingroup nil cnt 0)
7876 (insert "}\n"))
7878 (setq tg (car e) c (cdr e))
7879 (if ingroup (push tg (car groups)))
7880 (setq tg (org-add-props tg nil 'face
7881 (org-get-todo-face tg)))
7882 (if (and (= cnt 0) (not ingroup)) (insert " "))
7883 (insert "[" c "] " tg (make-string
7884 (- fwidth 4 (length tg)) ?\ ))
7885 (when (= (setq cnt (1+ cnt)) ncol)
7886 (insert "\n")
7887 (if ingroup (insert " "))
7888 (setq cnt 0)))))
7889 (insert "\n")
7890 (goto-char (point-min))
7891 (if (and (not expert) (fboundp 'fit-window-to-buffer))
7892 (fit-window-to-buffer))
7893 (message "[a-z..]:Set [SPC]:clear")
7894 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
7895 (cond
7896 ((or (= c ?\C-g)
7897 (and (= c ?q) (not (rassoc c fulltable))))
7898 (setq quit-flag t))
7899 ((= c ?\ ) nil)
7900 ((setq e (rassoc c fulltable) tg (car e))
7902 (t (setq quit-flag t))))))
7904 (defun org-entry-is-todo-p ()
7905 (member (org-get-todo-state) org-not-done-keywords))
7907 (defun org-entry-is-done-p ()
7908 (member (org-get-todo-state) org-done-keywords))
7910 (defun org-get-todo-state ()
7911 (save-excursion
7912 (org-back-to-heading t)
7913 (and (looking-at org-todo-line-regexp)
7914 (match-end 2)
7915 (match-string 2))))
7917 (defun org-at-date-range-p (&optional inactive-ok)
7918 "Is the cursor inside a date range?"
7919 (interactive)
7920 (save-excursion
7921 (catch 'exit
7922 (let ((pos (point)))
7923 (skip-chars-backward "^[<\r\n")
7924 (skip-chars-backward "<[")
7925 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
7926 (>= (match-end 0) pos)
7927 (throw 'exit t))
7928 (skip-chars-backward "^<[\r\n")
7929 (skip-chars-backward "<[")
7930 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
7931 (>= (match-end 0) pos)
7932 (throw 'exit t)))
7933 nil)))
7935 (defun org-get-repeat ()
7936 "Check if tere is a deadline/schedule with repeater in this entry."
7937 (save-match-data
7938 (save-excursion
7939 (org-back-to-heading t)
7940 (if (re-search-forward
7941 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
7942 (match-string 1)))))
7944 (defvar org-last-changed-timestamp)
7945 (defvar org-log-post-message)
7946 (defvar org-log-note-purpose)
7947 (defvar org-log-note-how)
7948 (defun org-auto-repeat-maybe (done-word)
7949 "Check if the current headline contains a repeated deadline/schedule.
7950 If yes, set TODO state back to what it was and change the base date
7951 of repeating deadline/scheduled time stamps to new date.
7952 This function is run automatically after each state change to a DONE state."
7953 ;; last-state is dynamically scoped into this function
7954 (let* ((repeat (org-get-repeat))
7955 (aa (assoc last-state org-todo-kwd-alist))
7956 (interpret (nth 1 aa))
7957 (head (nth 2 aa))
7958 (whata '(("d" . day) ("m" . month) ("y" . year)))
7959 (msg "Entry repeats: ")
7960 (org-log-done nil)
7961 (org-todo-log-states nil)
7962 (nshiftmax 10) (nshift 0)
7963 re type n what ts mb0 time)
7964 (when repeat
7965 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
7966 (org-todo (if (eq interpret 'type) last-state head))
7967 (when org-log-repeat
7968 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
7969 (memq 'org-add-log-note post-command-hook))
7970 ;; OK, we are already setup for some record
7971 (if (eq org-log-repeat 'note)
7972 ;; make sure we take a note, not only a time stamp
7973 (setq org-log-note-how 'note))
7974 ;; Set up for taking a record
7975 (org-add-log-setup 'state (or done-word (car org-done-keywords))
7976 'findpos org-log-repeat)))
7977 (org-back-to-heading t)
7978 (org-add-planning-info nil nil 'closed)
7979 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
7980 org-deadline-time-regexp "\\)\\|\\("
7981 org-ts-regexp "\\)"))
7982 (while (re-search-forward
7983 re (save-excursion (outline-next-heading) (point)) t)
7984 (setq type (if (match-end 1) org-scheduled-string
7985 (if (match-end 3) org-deadline-string "Plain:"))
7986 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
7987 mb0 (match-beginning 0))
7988 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
7989 (setq n (string-to-number (match-string 2 ts))
7990 what (match-string 3 ts))
7991 (if (equal what "w") (setq n (* n 7) what "d"))
7992 ;; Preparation, see if we need to modify the start date for the change
7993 (when (match-end 1)
7994 (setq time (save-match-data (org-time-string-to-time ts)))
7995 (cond
7996 ((equal (match-string 1 ts) ".")
7997 ;; Shift starting date to today
7998 (org-timestamp-change
7999 (- (time-to-days (current-time)) (time-to-days time))
8000 'day))
8001 ((equal (match-string 1 ts) "+")
8002 (while (or (= nshift 0)
8003 (<= (time-to-days time) (time-to-days (current-time))))
8004 (when (= (incf nshift) nshiftmax)
8005 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8006 (error "Abort")))
8007 (org-timestamp-change n (cdr (assoc what whata)))
8008 (org-at-timestamp-p t)
8009 (setq ts (match-string 1))
8010 (setq time (save-match-data (org-time-string-to-time ts))))
8011 (org-timestamp-change (- n) (cdr (assoc what whata)))
8012 ;; rematch, so that we have everything in place for the real shift
8013 (org-at-timestamp-p t)
8014 (setq ts (match-string 1))
8015 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8016 (org-timestamp-change n (cdr (assoc what whata)))
8017 (setq msg (concat msg type org-last-changed-timestamp " "))))
8018 (setq org-log-post-message msg)
8019 (message "%s" msg))))
8021 (defun org-show-todo-tree (arg)
8022 "Make a compact tree which shows all headlines marked with TODO.
8023 The tree will show the lines where the regexp matches, and all higher
8024 headlines above the match.
8025 With a \\[universal-argument] prefix, also show the DONE entries.
8026 With a numeric prefix N, construct a sparse tree for the Nth element
8027 of `org-todo-keywords-1'."
8028 (interactive "P")
8029 (let ((case-fold-search nil)
8030 (kwd-re
8031 (cond ((null arg) org-not-done-regexp)
8032 ((equal arg '(4))
8033 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8034 (mapcar 'list org-todo-keywords-1))))
8035 (concat "\\("
8036 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8037 "\\)\\>")))
8038 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8039 (regexp-quote (nth (1- (prefix-numeric-value arg))
8040 org-todo-keywords-1)))
8041 (t (error "Invalid prefix argument: %s" arg)))))
8042 (message "%d TODO entries found"
8043 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8045 (defun org-deadline (&optional remove)
8046 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8047 With argument REMOVE, remove any deadline from the item."
8048 (interactive "P")
8049 (if remove
8050 (progn
8051 (org-remove-timestamp-with-keyword org-deadline-string)
8052 (message "Item no longer has a deadline."))
8053 (org-add-planning-info 'deadline nil 'closed)))
8055 (defun org-schedule (&optional remove)
8056 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8057 With argument REMOVE, remove any scheduling date from the item."
8058 (interactive "P")
8059 (if remove
8060 (progn
8061 (org-remove-timestamp-with-keyword org-scheduled-string)
8062 (message "Item is no longer scheduled."))
8063 (org-add-planning-info 'scheduled nil 'closed)))
8065 (defun org-remove-timestamp-with-keyword (keyword)
8066 "Remove all time stamps with KEYWORD in the current entry."
8067 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8068 beg)
8069 (save-excursion
8070 (org-back-to-heading t)
8071 (setq beg (point))
8072 (org-end-of-subtree t t)
8073 (while (re-search-backward re beg t)
8074 (replace-match "")
8075 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8076 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8078 (defun org-add-planning-info (what &optional time &rest remove)
8079 "Insert new timestamp with keyword in the line directly after the headline.
8080 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8081 If non is given, the user is prompted for a date.
8082 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8083 be removed."
8084 (interactive)
8085 (let (org-time-was-given org-end-time-was-given ts
8086 end default-time default-input)
8088 (when (and (not time) (memq what '(scheduled deadline)))
8089 ;; Try to get a default date/time from existing timestamp
8090 (save-excursion
8091 (org-back-to-heading t)
8092 (setq end (save-excursion (outline-next-heading) (point)))
8093 (when (re-search-forward (if (eq what 'scheduled)
8094 org-scheduled-time-regexp
8095 org-deadline-time-regexp)
8096 end t)
8097 (setq ts (match-string 1)
8098 default-time
8099 (apply 'encode-time (org-parse-time-string ts))
8100 default-input (and ts (org-get-compact-tod ts))))))
8101 (when what
8102 ;; If necessary, get the time from the user
8103 (setq time (or time (org-read-date nil 'to-time nil nil
8104 default-time default-input))))
8106 (when (and org-insert-labeled-timestamps-at-point
8107 (member what '(scheduled deadline)))
8108 (insert
8109 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8110 (org-insert-time-stamp time org-time-was-given
8111 nil nil nil (list org-end-time-was-given))
8112 (setq what nil))
8113 (save-excursion
8114 (save-restriction
8115 (let (col list elt ts buffer-invisibility-spec)
8116 (org-back-to-heading t)
8117 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8118 (goto-char (match-end 1))
8119 (setq col (current-column))
8120 (goto-char (match-end 0))
8121 (if (eobp) (insert "\n") (forward-char 1))
8122 (if (and (not (looking-at outline-regexp))
8123 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8124 "[^\r\n]*"))
8125 (not (equal (match-string 1) org-clock-string)))
8126 (narrow-to-region (match-beginning 0) (match-end 0))
8127 (insert-before-markers "\n")
8128 (backward-char 1)
8129 (narrow-to-region (point) (point))
8130 (indent-to-column col))
8131 ;; Check if we have to remove something.
8132 (setq list (cons what remove))
8133 (while list
8134 (setq elt (pop list))
8135 (goto-char (point-min))
8136 (when (or (and (eq elt 'scheduled)
8137 (re-search-forward org-scheduled-time-regexp nil t))
8138 (and (eq elt 'deadline)
8139 (re-search-forward org-deadline-time-regexp nil t))
8140 (and (eq elt 'closed)
8141 (re-search-forward org-closed-time-regexp nil t)))
8142 (replace-match "")
8143 (if (looking-at "--+<[^>]+>") (replace-match ""))
8144 (if (looking-at " +") (replace-match ""))))
8145 (goto-char (point-max))
8146 (when what
8147 (insert
8148 (if (not (equal (char-before) ?\ )) " " "")
8149 (cond ((eq what 'scheduled) org-scheduled-string)
8150 ((eq what 'deadline) org-deadline-string)
8151 ((eq what 'closed) org-closed-string))
8152 " ")
8153 (setq ts (org-insert-time-stamp
8154 time
8155 (or org-time-was-given
8156 (and (eq what 'closed) org-log-done-with-time))
8157 (eq what 'closed)
8158 nil nil (list org-end-time-was-given)))
8159 (end-of-line 1))
8160 (goto-char (point-min))
8161 (widen)
8162 (if (looking-at "[ \t]+\r?\n")
8163 (replace-match ""))
8164 ts)))))
8166 (defvar org-log-note-marker (make-marker))
8167 (defvar org-log-note-purpose nil)
8168 (defvar org-log-note-state nil)
8169 (defvar org-log-note-how nil)
8170 (defvar org-log-note-window-configuration nil)
8171 (defvar org-log-note-return-to (make-marker))
8172 (defvar org-log-post-message nil
8173 "Message to be displayed after a log note has been stored.
8174 The auto-repeater uses this.")
8176 (defun org-add-note ()
8177 "Add a note to the current entry.
8178 This is done in the same way as adding a state change note."
8179 (interactive)
8180 (org-add-log-setup 'note nil t nil))
8182 (defun org-add-log-setup (&optional purpose state findpos how)
8183 "Set up the post command hook to take a note.
8184 If this is about to TODO state change, the new state is expected in STATE.
8185 When FINDPOS is non-nil, find the correct position for the note in
8186 the current entry. If not, assume that it can be inserted at point."
8187 (save-excursion
8188 (when findpos
8189 (org-back-to-heading t)
8190 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8191 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8192 "[^\r\n]*\\)?"))
8193 (goto-char (match-end 0))
8194 (unless org-log-states-order-reversed
8195 (and (= (char-after) ?\n) (forward-char 1))
8196 (org-skip-over-state-notes)
8197 (skip-chars-backward " \t\n\r")))
8198 (move-marker org-log-note-marker (point))
8199 (setq org-log-note-purpose purpose
8200 org-log-note-state state
8201 org-log-note-how how)
8202 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8204 (defun org-skip-over-state-notes ()
8205 "Skip past the list of State notes in an entry."
8206 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8207 (while (looking-at "[ \t]*- State")
8208 (condition-case nil
8209 (org-next-item)
8210 (error (org-end-of-item)))))
8212 (defun org-add-log-note (&optional purpose)
8213 "Pop up a window for taking a note, and add this note later at point."
8214 (remove-hook 'post-command-hook 'org-add-log-note)
8215 (setq org-log-note-window-configuration (current-window-configuration))
8216 (delete-other-windows)
8217 (move-marker org-log-note-return-to (point))
8218 (switch-to-buffer (marker-buffer org-log-note-marker))
8219 (goto-char org-log-note-marker)
8220 (org-switch-to-buffer-other-window "*Org Note*")
8221 (erase-buffer)
8222 (if (memq org-log-note-how '(time state))
8223 (org-store-log-note)
8224 (let ((org-inhibit-startup t)) (org-mode))
8225 (insert (format "# Insert note for %s.
8226 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8227 (cond
8228 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8229 ((eq org-log-note-purpose 'done) "closed todo item")
8230 ((eq org-log-note-purpose 'state)
8231 (format "state change to \"%s\"" org-log-note-state))
8232 ((eq org-log-note-purpose 'note)
8233 "this entry")
8234 (t (error "This should not happen")))))
8235 (org-set-local 'org-finish-function 'org-store-log-note)))
8237 (defvar org-note-abort nil) ; dynamically scoped
8238 (defun org-store-log-note ()
8239 "Finish taking a log note, and insert it to where it belongs."
8240 (let ((txt (buffer-string))
8241 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8242 lines ind)
8243 (kill-buffer (current-buffer))
8244 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8245 (setq txt (replace-match "" t t txt)))
8246 (if (string-match "\\s-+\\'" txt)
8247 (setq txt (replace-match "" t t txt)))
8248 (setq lines (org-split-string txt "\n"))
8249 (when (and note (string-match "\\S-" note))
8250 (setq note
8251 (org-replace-escapes
8252 note
8253 (list (cons "%u" (user-login-name))
8254 (cons "%U" user-full-name)
8255 (cons "%t" (format-time-string
8256 (org-time-stamp-format 'long 'inactive)
8257 (current-time)))
8258 (cons "%s" (if org-log-note-state
8259 (concat "\"" org-log-note-state "\"")
8260 "")))))
8261 (if lines (setq note (concat note " \\\\")))
8262 (push note lines))
8263 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8264 (when lines
8265 (save-excursion
8266 (set-buffer (marker-buffer org-log-note-marker))
8267 (save-excursion
8268 (goto-char org-log-note-marker)
8269 (move-marker org-log-note-marker nil)
8270 (end-of-line 1)
8271 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8272 (indent-relative nil)
8273 (insert "- " (pop lines))
8274 (org-indent-line-function)
8275 (beginning-of-line 1)
8276 (looking-at "[ \t]*")
8277 (setq ind (concat (match-string 0) " "))
8278 (end-of-line 1)
8279 (while lines (insert "\n" ind (pop lines)))))))
8280 (set-window-configuration org-log-note-window-configuration)
8281 (with-current-buffer (marker-buffer org-log-note-return-to)
8282 (goto-char org-log-note-return-to))
8283 (move-marker org-log-note-return-to nil)
8284 (and org-log-post-message (message "%s" org-log-post-message)))
8286 (defun org-sparse-tree (&optional arg)
8287 "Create a sparse tree, prompt for the details.
8288 This command can create sparse trees. You first need to select the type
8289 of match used to create the tree:
8291 t Show entries with a specific TODO keyword.
8292 T Show entries selected by a tags match.
8293 p Enter a property name and its value (both with completion on existing
8294 names/values) and show entries with that property.
8295 r Show entries matching a regular expression
8296 d Show deadlines due within `org-deadline-warning-days'."
8297 (interactive "P")
8298 (let (ans kwd value)
8299 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8300 (setq ans (read-char-exclusive))
8301 (cond
8302 ((equal ans ?d)
8303 (call-interactively 'org-check-deadlines))
8304 ((equal ans ?b)
8305 (call-interactively 'org-check-before-date))
8306 ((equal ans ?t)
8307 (org-show-todo-tree '(4)))
8308 ((equal ans ?T)
8309 (call-interactively 'org-tags-sparse-tree))
8310 ((member ans '(?p ?P))
8311 (setq kwd (completing-read "Property: "
8312 (mapcar 'list (org-buffer-property-keys))))
8313 (setq value (completing-read "Value: "
8314 (mapcar 'list (org-property-values kwd))))
8315 (unless (string-match "\\`{.*}\\'" value)
8316 (setq value (concat "\"" value "\"")))
8317 (org-tags-sparse-tree arg (concat kwd "=" value)))
8318 ((member ans '(?r ?R ?/))
8319 (call-interactively 'org-occur))
8320 (t (error "No such sparse tree command \"%c\"" ans)))))
8322 (defvar org-occur-highlights nil
8323 "List of overlays used for occur matches.")
8324 (make-variable-buffer-local 'org-occur-highlights)
8325 (defvar org-occur-parameters nil
8326 "Parameters of the active org-occur calls.
8327 This is a list, each call to org-occur pushes as cons cell,
8328 containing the regular expression and the callback, onto the list.
8329 The list can contain several entries if `org-occur' has been called
8330 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8331 will only contain one set of parameters. When the highlights are
8332 removed (for example with `C-c C-c', or with the next edit (depending
8333 on `org-remove-highlights-with-change'), this variable is emptied
8334 as well.")
8335 (make-variable-buffer-local 'org-occur-parameters)
8337 (defun org-occur (regexp &optional keep-previous callback)
8338 "Make a compact tree which shows all matches of REGEXP.
8339 The tree will show the lines where the regexp matches, and all higher
8340 headlines above the match. It will also show the heading after the match,
8341 to make sure editing the matching entry is easy.
8342 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8343 call to `org-occur' will be kept, to allow stacking of calls to this
8344 command.
8345 If CALLBACK is non-nil, it is a function which is called to confirm
8346 that the match should indeed be shown."
8347 (interactive "sRegexp: \nP")
8348 (unless keep-previous
8349 (org-remove-occur-highlights nil nil t))
8350 (push (cons regexp callback) org-occur-parameters)
8351 (let ((cnt 0))
8352 (save-excursion
8353 (goto-char (point-min))
8354 (if (or (not keep-previous) ; do not want to keep
8355 (not org-occur-highlights)) ; no previous matches
8356 ;; hide everything
8357 (org-overview))
8358 (while (re-search-forward regexp nil t)
8359 (when (or (not callback)
8360 (save-match-data (funcall callback)))
8361 (setq cnt (1+ cnt))
8362 (when org-highlight-sparse-tree-matches
8363 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8364 (org-show-context 'occur-tree))))
8365 (when org-remove-highlights-with-change
8366 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8367 nil 'local))
8368 (unless org-sparse-tree-open-archived-trees
8369 (org-hide-archived-subtrees (point-min) (point-max)))
8370 (run-hooks 'org-occur-hook)
8371 (if (interactive-p)
8372 (message "%d match(es) for regexp %s" cnt regexp))
8373 cnt))
8375 (defun org-show-context (&optional key)
8376 "Make sure point and context and visible.
8377 How much context is shown depends upon the variables
8378 `org-show-hierarchy-above', `org-show-following-heading'. and
8379 `org-show-siblings'."
8380 (let ((heading-p (org-on-heading-p t))
8381 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8382 (following-p (org-get-alist-option org-show-following-heading key))
8383 (entry-p (org-get-alist-option org-show-entry-below key))
8384 (siblings-p (org-get-alist-option org-show-siblings key)))
8385 (catch 'exit
8386 ;; Show heading or entry text
8387 (if (and heading-p (not entry-p))
8388 (org-flag-heading nil) ; only show the heading
8389 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8390 (org-show-hidden-entry))) ; show entire entry
8391 (when following-p
8392 ;; Show next sibling, or heading below text
8393 (save-excursion
8394 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8395 (org-flag-heading nil))))
8396 (when siblings-p (org-show-siblings))
8397 (when hierarchy-p
8398 ;; show all higher headings, possibly with siblings
8399 (save-excursion
8400 (while (and (condition-case nil
8401 (progn (org-up-heading-all 1) t)
8402 (error nil))
8403 (not (bobp)))
8404 (org-flag-heading nil)
8405 (when siblings-p (org-show-siblings))))))))
8407 (defun org-reveal (&optional siblings)
8408 "Show current entry, hierarchy above it, and the following headline.
8409 This can be used to show a consistent set of context around locations
8410 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8411 not t for the search context.
8413 With optional argument SIBLINGS, on each level of the hierarchy all
8414 siblings are shown. This repairs the tree structure to what it would
8415 look like when opened with hierarchical calls to `org-cycle'."
8416 (interactive "P")
8417 (let ((org-show-hierarchy-above t)
8418 (org-show-following-heading t)
8419 (org-show-siblings (if siblings t org-show-siblings)))
8420 (org-show-context nil)))
8422 (defun org-highlight-new-match (beg end)
8423 "Highlight from BEG to END and mark the highlight is an occur headline."
8424 (let ((ov (org-make-overlay beg end)))
8425 (org-overlay-put ov 'face 'secondary-selection)
8426 (push ov org-occur-highlights)))
8428 (defun org-remove-occur-highlights (&optional beg end noremove)
8429 "Remove the occur highlights from the buffer.
8430 BEG and END are ignored. If NOREMOVE is nil, remove this function
8431 from the `before-change-functions' in the current buffer."
8432 (interactive)
8433 (unless org-inhibit-highlight-removal
8434 (mapc 'org-delete-overlay org-occur-highlights)
8435 (setq org-occur-highlights nil)
8436 (setq org-occur-parameters nil)
8437 (unless noremove
8438 (remove-hook 'before-change-functions
8439 'org-remove-occur-highlights 'local))))
8441 ;;;; Priorities
8443 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8444 "Regular expression matching the priority indicator.")
8446 (defvar org-remove-priority-next-time nil)
8448 (defun org-priority-up ()
8449 "Increase the priority of the current item."
8450 (interactive)
8451 (org-priority 'up))
8453 (defun org-priority-down ()
8454 "Decrease the priority of the current item."
8455 (interactive)
8456 (org-priority 'down))
8458 (defun org-priority (&optional action)
8459 "Change the priority of an item by ARG.
8460 ACTION can be `set', `up', `down', or a character."
8461 (interactive)
8462 (setq action (or action 'set))
8463 (let (current new news have remove)
8464 (save-excursion
8465 (org-back-to-heading)
8466 (if (looking-at org-priority-regexp)
8467 (setq current (string-to-char (match-string 2))
8468 have t)
8469 (setq current org-default-priority))
8470 (cond
8471 ((or (eq action 'set) (integerp action))
8472 (if (integerp action)
8473 (setq new action)
8474 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
8475 (setq new (read-char-exclusive)))
8476 (if (and (= (upcase org-highest-priority) org-highest-priority)
8477 (= (upcase org-lowest-priority) org-lowest-priority))
8478 (setq new (upcase new)))
8479 (cond ((equal new ?\ ) (setq remove t))
8480 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8481 (error "Priority must be between `%c' and `%c'"
8482 org-highest-priority org-lowest-priority))))
8483 ((eq action 'up)
8484 (if (and (not have) (eq last-command this-command))
8485 (setq new org-lowest-priority)
8486 (setq new (if (and org-priority-start-cycle-with-default (not have))
8487 org-default-priority (1- current)))))
8488 ((eq action 'down)
8489 (if (and (not have) (eq last-command this-command))
8490 (setq new org-highest-priority)
8491 (setq new (if (and org-priority-start-cycle-with-default (not have))
8492 org-default-priority (1+ current)))))
8493 (t (error "Invalid action")))
8494 (if (or (< (upcase new) org-highest-priority)
8495 (> (upcase new) org-lowest-priority))
8496 (setq remove t))
8497 (setq news (format "%c" new))
8498 (if have
8499 (if remove
8500 (replace-match "" t t nil 1)
8501 (replace-match news t t nil 2))
8502 (if remove
8503 (error "No priority cookie found in line")
8504 (looking-at org-todo-line-regexp)
8505 (if (match-end 2)
8506 (progn
8507 (goto-char (match-end 2))
8508 (insert " [#" news "]"))
8509 (goto-char (match-beginning 3))
8510 (insert "[#" news "] ")))))
8511 (org-preserve-lc (org-set-tags nil 'align))
8512 (if remove
8513 (message "Priority removed")
8514 (message "Priority of current item set to %s" news))))
8517 (defun org-get-priority (s)
8518 "Find priority cookie and return priority."
8519 (save-match-data
8520 (if (not (string-match org-priority-regexp s))
8521 (* 1000 (- org-lowest-priority org-default-priority))
8522 (* 1000 (- org-lowest-priority
8523 (string-to-char (match-string 2 s)))))))
8525 ;;;; Tags
8527 (defun org-scan-tags (action matcher &optional todo-only)
8528 "Scan headline tags with inheritance and produce output ACTION.
8529 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8530 evaluated, testing if a given set of tags qualifies a headline for
8531 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8532 are included in the output."
8533 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8534 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8535 (org-re
8536 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8537 (props (list 'face nil
8538 'done-face 'org-done
8539 'undone-face nil
8540 'mouse-face 'highlight
8541 'org-not-done-regexp org-not-done-regexp
8542 'org-todo-regexp org-todo-regexp
8543 'keymap org-agenda-keymap
8544 'help-echo
8545 (format "mouse-2 or RET jump to org file %s"
8546 (abbreviate-file-name
8547 (or (buffer-file-name (buffer-base-buffer))
8548 (buffer-name (buffer-base-buffer)))))))
8549 (case-fold-search nil)
8550 lspos
8551 tags tags-list tags-alist (llast 0) rtn level category i txt
8552 todo marker entry priority)
8553 (save-excursion
8554 (goto-char (point-min))
8555 (when (eq action 'sparse-tree)
8556 (org-overview)
8557 (org-remove-occur-highlights))
8558 (while (re-search-forward re nil t)
8559 (catch :skip
8560 (setq todo (if (match-end 1) (match-string 2))
8561 tags (if (match-end 4) (match-string 4)))
8562 (goto-char (setq lspos (1+ (match-beginning 0))))
8563 (setq level (org-reduced-level (funcall outline-level))
8564 category (org-get-category))
8565 (setq i llast llast level)
8566 ;; remove tag lists from same and sublevels
8567 (while (>= i level)
8568 (when (setq entry (assoc i tags-alist))
8569 (setq tags-alist (delete entry tags-alist)))
8570 (setq i (1- i)))
8571 ;; add the next tags
8572 (when tags
8573 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8574 tags-alist
8575 (cons (cons level tags) tags-alist)))
8576 ;; compile tags for current headline
8577 (setq tags-list
8578 (if org-use-tag-inheritance
8579 (apply 'append (mapcar 'cdr tags-alist))
8580 tags))
8581 (when (and tags org-use-tag-inheritance
8582 (not (eq t org-use-tag-inheritance)))
8583 ;; selective inheritance, remove uninherited ones
8584 (setcdr (car tags-alist)
8585 (org-remove-uniherited-tags (cdar tags-alist))))
8586 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8587 (eval matcher)
8588 (or (not org-agenda-skip-archived-trees)
8589 (not (member org-archive-tag tags-list))))
8590 (and (eq action 'agenda) (org-agenda-skip))
8591 ;; list this headline
8593 (if (eq action 'sparse-tree)
8594 (progn
8595 (and org-highlight-sparse-tree-matches
8596 (org-get-heading) (match-end 0)
8597 (org-highlight-new-match
8598 (match-beginning 0) (match-beginning 1)))
8599 (org-show-context 'tags-tree))
8600 (setq txt (org-format-agenda-item
8602 (concat
8603 (if org-tags-match-list-sublevels
8604 (make-string (1- level) ?.) "")
8605 (org-get-heading))
8606 category tags-list)
8607 priority (org-get-priority txt))
8608 (goto-char lspos)
8609 (setq marker (org-agenda-new-marker))
8610 (org-add-props txt props
8611 'org-marker marker 'org-hd-marker marker 'org-category category
8612 'priority priority 'type "tagsmatch")
8613 (push txt rtn))
8614 ;; if we are to skip sublevels, jump to end of subtree
8615 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8616 (when (and (eq action 'sparse-tree)
8617 (not org-sparse-tree-open-archived-trees))
8618 (org-hide-archived-subtrees (point-min) (point-max)))
8619 (nreverse rtn)))
8621 (defun org-remove-uniherited-tags (tags)
8622 "Remove all tags that are not inherited from the list TAGS."
8623 (cond
8624 ((eq org-use-tag-inheritance t) tags)
8625 ((not org-use-tag-inheritance) nil)
8626 ((stringp org-use-tag-inheritance)
8627 (delq nil (mapcar
8628 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8629 tags)))
8630 ((listp org-use-tag-inheritance)
8631 (org-delete-all org-use-tag-inheritance tags))))
8633 (defvar todo-only) ;; dynamically scoped
8635 (defun org-tags-sparse-tree (&optional todo-only match)
8636 "Create a sparse tree according to tags string MATCH.
8637 MATCH can contain positive and negative selection of tags, like
8638 \"+WORK+URGENT-WITHBOSS\".
8639 If optional argument TODO_ONLY is non-nil, only select lines that are
8640 also TODO lines."
8641 (interactive "P")
8642 (org-prepare-agenda-buffers (list (current-buffer)))
8643 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8645 (defvar org-cached-props nil)
8646 (defun org-cached-entry-get (pom property)
8647 (if (or (eq t org-use-property-inheritance)
8648 (and (stringp org-use-property-inheritance)
8649 (string-match org-use-property-inheritance property))
8650 (and (listp org-use-property-inheritance)
8651 (member property org-use-property-inheritance)))
8652 ;; Caching is not possible, check it directly
8653 (org-entry-get pom property 'inherit)
8654 ;; Get all properties, so that we can do complicated checks easily
8655 (cdr (assoc property (or org-cached-props
8656 (setq org-cached-props
8657 (org-entry-properties pom)))))))
8659 (defun org-global-tags-completion-table (&optional files)
8660 "Return the list of all tags in all agenda buffer/files."
8661 (save-excursion
8662 (org-uniquify
8663 (delq nil
8664 (apply 'append
8665 (mapcar
8666 (lambda (file)
8667 (set-buffer (find-file-noselect file))
8668 (append (org-get-buffer-tags)
8669 (mapcar (lambda (x) (if (stringp (car-safe x))
8670 (list (car-safe x)) nil))
8671 org-tag-alist)))
8672 (if (and files (car files))
8673 files
8674 (org-agenda-files))))))))
8676 (defun org-make-tags-matcher (match)
8677 "Create the TAGS//TODO matcher form for the selection string MATCH."
8678 ;; todo-only is scoped dynamically into this function, and the function
8679 ;; may change it it the matcher asksk for it.
8680 (unless match
8681 ;; Get a new match request, with completion
8682 (let ((org-last-tags-completion-table
8683 (org-global-tags-completion-table)))
8684 (setq match (completing-read
8685 "Match: " 'org-tags-completion-function nil nil nil
8686 'org-tags-history))))
8688 ;; Parse the string and create a lisp form
8689 (let ((match0 match)
8690 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
8691 minus tag mm
8692 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8693 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
8694 (if (string-match "/+" match)
8695 ;; match contains also a todo-matching request
8696 (progn
8697 (setq tagsmatch (substring match 0 (match-beginning 0))
8698 todomatch (substring match (match-end 0)))
8699 (if (string-match "^!" todomatch)
8700 (setq todo-only t todomatch (substring todomatch 1)))
8701 (if (string-match "^\\s-*$" todomatch)
8702 (setq todomatch nil)))
8703 ;; only matching tags
8704 (setq tagsmatch match todomatch nil))
8706 ;; Make the tags matcher
8707 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8708 (setq tagsmatcher t)
8709 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8710 (while (setq term (pop orterms))
8711 (while (and (equal (substring term -1) "\\") orterms)
8712 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8713 (while (string-match re term)
8714 (setq minus (and (match-end 1)
8715 (equal (match-string 1 term) "-"))
8716 tag (match-string 2 term)
8717 re-p (equal (string-to-char tag) ?{)
8718 level-p (match-end 3)
8719 prop-p (match-end 4)
8720 mm (cond
8721 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8722 (level-p `(= level ,(string-to-number
8723 (match-string 3 term))))
8724 (prop-p
8725 (setq pn (match-string 4 term)
8726 pv (match-string 5 term)
8727 cat-p (equal pn "CATEGORY")
8728 re-p (equal (string-to-char pv) ?{)
8729 pv (substring pv 1 -1))
8730 (if (equal pn "CATEGORY")
8731 (setq gv '(get-text-property (point) 'org-category))
8732 (setq gv `(org-cached-entry-get nil ,pn)))
8733 (if re-p
8734 `(string-match ,pv (or ,gv ""))
8735 `(equal ,pv (or ,gv ""))))
8736 (t `(member ,(downcase tag) tags-list)))
8737 mm (if minus (list 'not mm) mm)
8738 term (substring term (match-end 0)))
8739 (push mm tagsmatcher))
8740 (push (if (> (length tagsmatcher) 1)
8741 (cons 'and tagsmatcher)
8742 (car tagsmatcher))
8743 orlist)
8744 (setq tagsmatcher nil))
8745 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8746 (setq tagsmatcher
8747 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8749 ;; Make the todo matcher
8750 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8751 (setq todomatcher t)
8752 (setq orterms (org-split-string todomatch "|") orlist nil)
8753 (while (setq term (pop orterms))
8754 (while (string-match re term)
8755 (setq minus (and (match-end 1)
8756 (equal (match-string 1 term) "-"))
8757 kwd (match-string 2 term)
8758 re-p (equal (string-to-char kwd) ?{)
8759 term (substring term (match-end 0))
8760 mm (if re-p
8761 `(string-match ,(substring kwd 1 -1) todo)
8762 (list 'equal 'todo kwd))
8763 mm (if minus (list 'not mm) mm))
8764 (push mm todomatcher))
8765 (push (if (> (length todomatcher) 1)
8766 (cons 'and todomatcher)
8767 (car todomatcher))
8768 orlist)
8769 (setq todomatcher nil))
8770 (setq todomatcher (if (> (length orlist) 1)
8771 (cons 'or orlist) (car orlist))))
8773 ;; Return the string and lisp forms of the matcher
8774 (setq matcher (if todomatcher
8775 (list 'and tagsmatcher todomatcher)
8776 tagsmatcher))
8777 (cons match0 matcher)))
8779 (defun org-match-any-p (re list)
8780 "Does re match any element of list?"
8781 (setq list (mapcar (lambda (x) (string-match re x)) list))
8782 (delq nil list))
8784 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8785 (defvar org-tags-overlay (org-make-overlay 1 1))
8786 (org-detach-overlay org-tags-overlay)
8788 (defun org-get-tags-at (&optional pos)
8789 "Get a list of all headline tags applicable at POS.
8790 POS defaults to point. If tags are inherited, the list contains
8791 the targets in the same sequence as the headlines appear, i.e.
8792 sthe tags of the current headline come last."
8793 (interactive)
8794 (let (tags ltags lastpos parent)
8795 (save-excursion
8796 (save-restriction
8797 (widen)
8798 (goto-char (or pos (point)))
8799 (save-match-data
8800 (condition-case nil
8801 (progn
8802 (org-back-to-heading t)
8803 (while (not (equal lastpos (point)))
8804 (setq lastpos (point))
8805 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8806 (setq ltags (org-split-string
8807 (org-match-string-no-properties 1) ":"))
8808 (setq tags (append (org-remove-uniherited-tags ltags)
8809 tags)))
8810 (or org-use-tag-inheritance (error ""))
8811 (org-up-heading-all 1)
8812 (setq parent t)))
8813 (error nil))))
8814 tags)))
8816 (defun org-toggle-tag (tag &optional onoff)
8817 "Toggle the tag TAG for the current line.
8818 If ONOFF is `on' or `off', don't toggle but set to this state."
8819 (unless (org-on-heading-p t) (error "Not on headling"))
8820 (let (res current)
8821 (save-excursion
8822 (beginning-of-line)
8823 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8824 (point-at-eol) t)
8825 (progn
8826 (setq current (match-string 1))
8827 (replace-match ""))
8828 (setq current ""))
8829 (setq current (nreverse (org-split-string current ":")))
8830 (cond
8831 ((eq onoff 'on)
8832 (setq res t)
8833 (or (member tag current) (push tag current)))
8834 ((eq onoff 'off)
8835 (or (not (member tag current)) (setq current (delete tag current))))
8836 (t (if (member tag current)
8837 (setq current (delete tag current))
8838 (setq res t)
8839 (push tag current))))
8840 (end-of-line 1)
8841 (if current
8842 (progn
8843 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8844 (org-set-tags nil t))
8845 (delete-horizontal-space))
8846 (run-hooks 'org-after-tags-change-hook))
8847 res))
8849 (defun org-align-tags-here (to-col)
8850 ;; Assumes that this is a headline
8851 (let ((pos (point)) (col (current-column)) tags)
8852 (beginning-of-line 1)
8853 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
8854 (< pos (match-beginning 2)))
8855 (progn
8856 (setq tags (match-string 2))
8857 (goto-char (match-beginning 1))
8858 (insert " ")
8859 (delete-region (point) (1+ (match-end 0)))
8860 (backward-char 1)
8861 (move-to-column
8862 (max (1+ (current-column))
8863 (1+ col)
8864 (if (> to-col 0)
8865 to-col
8866 (- (abs to-col) (length tags))))
8868 (insert tags)
8869 (move-to-column (min (current-column) col) t))
8870 (goto-char pos))))
8872 (defun org-set-tags (&optional arg just-align)
8873 "Set the tags for the current headline.
8874 With prefix ARG, realign all tags in headings in the current buffer."
8875 (interactive "P")
8876 (let* ((re (concat "^" outline-regexp))
8877 (current (org-get-tags-string))
8878 (col (current-column))
8879 (org-setting-tags t)
8880 table current-tags inherited-tags ; computed below when needed
8881 tags p0 c0 c1 rpl)
8882 (if arg
8883 (save-excursion
8884 (goto-char (point-min))
8885 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
8886 (while (re-search-forward re nil t)
8887 (org-set-tags nil t)
8888 (end-of-line 1)))
8889 (message "All tags realigned to column %d" org-tags-column))
8890 (if just-align
8891 (setq tags current)
8892 ;; Get a new set of tags from the user
8893 (save-excursion
8894 (setq table (or org-tag-alist (org-get-buffer-tags))
8895 org-last-tags-completion-table table
8896 current-tags (org-split-string current ":")
8897 inherited-tags (nreverse
8898 (nthcdr (length current-tags)
8899 (nreverse (org-get-tags-at))))
8900 tags
8901 (if (or (eq t org-use-fast-tag-selection)
8902 (and org-use-fast-tag-selection
8903 (delq nil (mapcar 'cdr table))))
8904 (org-fast-tag-selection
8905 current-tags inherited-tags table
8906 (if org-fast-tag-selection-include-todo org-todo-key-alist))
8907 (let ((org-add-colon-after-tag-completion t))
8908 (org-trim
8909 (org-without-partial-completion
8910 (completing-read "Tags: " 'org-tags-completion-function
8911 nil nil current 'org-tags-history)))))))
8912 (while (string-match "[-+&]+" tags)
8913 ;; No boolean logic, just a list
8914 (setq tags (replace-match ":" t t tags))))
8916 (if (string-match "\\`[\t ]*\\'" tags)
8917 (setq tags "")
8918 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8919 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8921 ;; Insert new tags at the correct column
8922 (beginning-of-line 1)
8923 (cond
8924 ((and (equal current "") (equal tags "")))
8925 ((re-search-forward
8926 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
8927 (point-at-eol) t)
8928 (if (equal tags "")
8929 (setq rpl "")
8930 (goto-char (match-beginning 0))
8931 (setq c0 (current-column) p0 (point)
8932 c1 (max (1+ c0) (if (> org-tags-column 0)
8933 org-tags-column
8934 (- (- org-tags-column) (length tags))))
8935 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
8936 (replace-match rpl t t)
8937 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
8938 tags)
8939 (t (error "Tags alignment failed")))
8940 (move-to-column col)
8941 (unless just-align
8942 (run-hooks 'org-after-tags-change-hook)))))
8944 (defun org-change-tag-in-region (beg end tag off)
8945 "Add or remove TAG for each entry in the region.
8946 This works in the agenda, and also in an org-mode buffer."
8947 (interactive
8948 (list (region-beginning) (region-end)
8949 (let ((org-last-tags-completion-table
8950 (if (org-mode-p)
8951 (org-get-buffer-tags)
8952 (org-global-tags-completion-table))))
8953 (completing-read
8954 "Tag: " 'org-tags-completion-function nil nil nil
8955 'org-tags-history))
8956 (progn
8957 (message "[s]et or [r]emove? ")
8958 (equal (read-char-exclusive) ?r))))
8959 (if (fboundp 'deactivate-mark) (deactivate-mark))
8960 (let ((agendap (equal major-mode 'org-agenda-mode))
8961 l1 l2 m buf pos newhead (cnt 0))
8962 (goto-char end)
8963 (setq l2 (1- (org-current-line)))
8964 (goto-char beg)
8965 (setq l1 (org-current-line))
8966 (loop for l from l1 to l2 do
8967 (goto-line l)
8968 (setq m (get-text-property (point) 'org-hd-marker))
8969 (when (or (and (org-mode-p) (org-on-heading-p))
8970 (and agendap m))
8971 (setq buf (if agendap (marker-buffer m) (current-buffer))
8972 pos (if agendap m (point)))
8973 (with-current-buffer buf
8974 (save-excursion
8975 (save-restriction
8976 (goto-char pos)
8977 (setq cnt (1+ cnt))
8978 (org-toggle-tag tag (if off 'off 'on))
8979 (setq newhead (org-get-heading)))))
8980 (and agendap (org-agenda-change-all-lines newhead m))))
8981 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
8983 (defun org-tags-completion-function (string predicate &optional flag)
8984 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8985 (confirm (lambda (x) (stringp (car x)))))
8986 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8987 (setq s1 (match-string 1 string)
8988 s2 (match-string 2 string))
8989 (setq s1 "" s2 string))
8990 (cond
8991 ((eq flag nil)
8992 ;; try completion
8993 (setq rtn (try-completion s2 ctable confirm))
8994 (if (stringp rtn)
8995 (setq rtn
8996 (concat s1 s2 (substring rtn (length s2))
8997 (if (and org-add-colon-after-tag-completion
8998 (assoc rtn ctable))
8999 ":" ""))))
9000 rtn)
9001 ((eq flag t)
9002 ;; all-completions
9003 (all-completions s2 ctable confirm)
9005 ((eq flag 'lambda)
9006 ;; exact match?
9007 (assoc s2 ctable)))
9010 (defun org-fast-tag-insert (kwd tags face &optional end)
9011 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9012 (insert (format "%-12s" (concat kwd ":"))
9013 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9014 (or end "")))
9016 (defun org-fast-tag-show-exit (flag)
9017 (save-excursion
9018 (goto-line 3)
9019 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9020 (replace-match ""))
9021 (when flag
9022 (end-of-line 1)
9023 (move-to-column (- (window-width) 19) t)
9024 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9026 (defun org-set-current-tags-overlay (current prefix)
9027 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9028 (if (featurep 'xemacs)
9029 (org-overlay-display org-tags-overlay (concat prefix s)
9030 'secondary-selection)
9031 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9032 (org-overlay-display org-tags-overlay (concat prefix s)))))
9034 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9035 "Fast tag selection with single keys.
9036 CURRENT is the current list of tags in the headline, INHERITED is the
9037 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9038 possibly with grouping information. TODO-TABLE is a similar table with
9039 TODO keywords, should these have keys assigned to them.
9040 If the keys are nil, a-z are automatically assigned.
9041 Returns the new tags string, or nil to not change the current settings."
9042 (let* ((fulltable (append table todo-table))
9043 (maxlen (apply 'max (mapcar
9044 (lambda (x)
9045 (if (stringp (car x)) (string-width (car x)) 0))
9046 fulltable)))
9047 (buf (current-buffer))
9048 (expert (eq org-fast-tag-selection-single-key 'expert))
9049 (buffer-tags nil)
9050 (fwidth (+ maxlen 3 1 3))
9051 (ncol (/ (- (window-width) 4) fwidth))
9052 (i-face 'org-done)
9053 (c-face 'org-todo)
9054 tg cnt e c char c1 c2 ntable tbl rtn
9055 ov-start ov-end ov-prefix
9056 (exit-after-next org-fast-tag-selection-single-key)
9057 (done-keywords org-done-keywords)
9058 groups ingroup)
9059 (save-excursion
9060 (beginning-of-line 1)
9061 (if (looking-at
9062 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9063 (setq ov-start (match-beginning 1)
9064 ov-end (match-end 1)
9065 ov-prefix "")
9066 (setq ov-start (1- (point-at-eol))
9067 ov-end (1+ ov-start))
9068 (skip-chars-forward "^\n\r")
9069 (setq ov-prefix
9070 (concat
9071 (buffer-substring (1- (point)) (point))
9072 (if (> (current-column) org-tags-column)
9074 (make-string (- org-tags-column (current-column)) ?\ ))))))
9075 (org-move-overlay org-tags-overlay ov-start ov-end)
9076 (save-window-excursion
9077 (if expert
9078 (set-buffer (get-buffer-create " *Org tags*"))
9079 (delete-other-windows)
9080 (split-window-vertically)
9081 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9082 (erase-buffer)
9083 (org-set-local 'org-done-keywords done-keywords)
9084 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9085 (org-fast-tag-insert "Current" current c-face "\n\n")
9086 (org-fast-tag-show-exit exit-after-next)
9087 (org-set-current-tags-overlay current ov-prefix)
9088 (setq tbl fulltable char ?a cnt 0)
9089 (while (setq e (pop tbl))
9090 (cond
9091 ((equal e '(:startgroup))
9092 (push '() groups) (setq ingroup t)
9093 (when (not (= cnt 0))
9094 (setq cnt 0)
9095 (insert "\n"))
9096 (insert "{ "))
9097 ((equal e '(:endgroup))
9098 (setq ingroup nil cnt 0)
9099 (insert "}\n"))
9101 (setq tg (car e) c2 nil)
9102 (if (cdr e)
9103 (setq c (cdr e))
9104 ;; automatically assign a character.
9105 (setq c1 (string-to-char
9106 (downcase (substring
9107 tg (if (= (string-to-char tg) ?@) 1 0)))))
9108 (if (or (rassoc c1 ntable) (rassoc c1 table))
9109 (while (or (rassoc char ntable) (rassoc char table))
9110 (setq char (1+ char)))
9111 (setq c2 c1))
9112 (setq c (or c2 char)))
9113 (if ingroup (push tg (car groups)))
9114 (setq tg (org-add-props tg nil 'face
9115 (cond
9116 ((not (assoc tg table))
9117 (org-get-todo-face tg))
9118 ((member tg current) c-face)
9119 ((member tg inherited) i-face)
9120 (t nil))))
9121 (if (and (= cnt 0) (not ingroup)) (insert " "))
9122 (insert "[" c "] " tg (make-string
9123 (- fwidth 4 (length tg)) ?\ ))
9124 (push (cons tg c) ntable)
9125 (when (= (setq cnt (1+ cnt)) ncol)
9126 (insert "\n")
9127 (if ingroup (insert " "))
9128 (setq cnt 0)))))
9129 (setq ntable (nreverse ntable))
9130 (insert "\n")
9131 (goto-char (point-min))
9132 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9133 (fit-window-to-buffer))
9134 (setq rtn
9135 (catch 'exit
9136 (while t
9137 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9138 (if groups " [!] no groups" " [!]groups")
9139 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9140 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9141 (cond
9142 ((= c ?\r) (throw 'exit t))
9143 ((= c ?!)
9144 (setq groups (not groups))
9145 (goto-char (point-min))
9146 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9147 ((= c ?\C-c)
9148 (if (not expert)
9149 (org-fast-tag-show-exit
9150 (setq exit-after-next (not exit-after-next)))
9151 (setq expert nil)
9152 (delete-other-windows)
9153 (split-window-vertically)
9154 (org-switch-to-buffer-other-window " *Org tags*")
9155 (and (fboundp 'fit-window-to-buffer)
9156 (fit-window-to-buffer))))
9157 ((or (= c ?\C-g)
9158 (and (= c ?q) (not (rassoc c ntable))))
9159 (org-detach-overlay org-tags-overlay)
9160 (setq quit-flag t))
9161 ((= c ?\ )
9162 (setq current nil)
9163 (if exit-after-next (setq exit-after-next 'now)))
9164 ((= c ?\t)
9165 (condition-case nil
9166 (setq tg (completing-read
9167 "Tag: "
9168 (or buffer-tags
9169 (with-current-buffer buf
9170 (org-get-buffer-tags)))))
9171 (quit (setq tg "")))
9172 (when (string-match "\\S-" tg)
9173 (add-to-list 'buffer-tags (list tg))
9174 (if (member tg current)
9175 (setq current (delete tg current))
9176 (push tg current)))
9177 (if exit-after-next (setq exit-after-next 'now)))
9178 ((setq e (rassoc c todo-table) tg (car e))
9179 (with-current-buffer buf
9180 (save-excursion (org-todo tg)))
9181 (if exit-after-next (setq exit-after-next 'now)))
9182 ((setq e (rassoc c ntable) tg (car e))
9183 (if (member tg current)
9184 (setq current (delete tg current))
9185 (loop for g in groups do
9186 (if (member tg g)
9187 (mapc (lambda (x)
9188 (setq current (delete x current)))
9189 g)))
9190 (push tg current))
9191 (if exit-after-next (setq exit-after-next 'now))))
9193 ;; Create a sorted list
9194 (setq current
9195 (sort current
9196 (lambda (a b)
9197 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9198 (if (eq exit-after-next 'now) (throw 'exit t))
9199 (goto-char (point-min))
9200 (beginning-of-line 2)
9201 (delete-region (point) (point-at-eol))
9202 (org-fast-tag-insert "Current" current c-face)
9203 (org-set-current-tags-overlay current ov-prefix)
9204 (while (re-search-forward
9205 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9206 (setq tg (match-string 1))
9207 (add-text-properties
9208 (match-beginning 1) (match-end 1)
9209 (list 'face
9210 (cond
9211 ((member tg current) c-face)
9212 ((member tg inherited) i-face)
9213 (t (get-text-property (match-beginning 1) 'face))))))
9214 (goto-char (point-min)))))
9215 (org-detach-overlay org-tags-overlay)
9216 (if rtn
9217 (mapconcat 'identity current ":")
9218 nil))))
9220 (defun org-get-tags-string ()
9221 "Get the TAGS string in the current headline."
9222 (unless (org-on-heading-p t)
9223 (error "Not on a heading"))
9224 (save-excursion
9225 (beginning-of-line 1)
9226 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9227 (org-match-string-no-properties 1)
9228 "")))
9230 (defun org-get-tags ()
9231 "Get the list of tags specified in the current headline."
9232 (org-split-string (org-get-tags-string) ":"))
9234 (defun org-get-buffer-tags ()
9235 "Get a table of all tags used in the buffer, for completion."
9236 (let (tags)
9237 (save-excursion
9238 (goto-char (point-min))
9239 (while (re-search-forward
9240 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9241 (when (equal (char-after (point-at-bol 0)) ?*)
9242 (mapc (lambda (x) (add-to-list 'tags x))
9243 (org-split-string (org-match-string-no-properties 1) ":")))))
9244 (mapcar 'list tags)))
9247 ;;;; Properties
9249 ;;; Setting and retrieving properties
9251 (defconst org-special-properties
9252 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9253 "TIMESTAMP" "TIMESTAMP_IA")
9254 "The special properties valid in Org-mode.
9256 These are properties that are not defined in the property drawer,
9257 but in some other way.")
9259 (defconst org-default-properties
9260 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9261 "LOCATION" "LOGGING" "COLUMNS")
9262 "Some properties that are used by Org-mode for various purposes.
9263 Being in this list makes sure that they are offered for completion.")
9265 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9266 "Regular expression matching the first line of a property drawer.")
9268 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9269 "Regular expression matching the first line of a property drawer.")
9271 (defun org-property-action ()
9272 "Do an action on properties."
9273 (interactive)
9274 (let (c)
9275 (org-at-property-p)
9276 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9277 (setq c (read-char-exclusive))
9278 (cond
9279 ((equal c ?s)
9280 (call-interactively 'org-set-property))
9281 ((equal c ?d)
9282 (call-interactively 'org-delete-property))
9283 ((equal c ?D)
9284 (call-interactively 'org-delete-property-globally))
9285 ((equal c ?c)
9286 (call-interactively 'org-compute-property-at-point))
9287 (t (error "No such property action %c" c)))))
9289 (defun org-at-property-p ()
9290 "Is the cursor in a property line?"
9291 ;; FIXME: Does not check if we are actually in the drawer.
9292 ;; FIXME: also returns true on any drawers.....
9293 ;; This is used by C-c C-c for property action.
9294 (save-excursion
9295 (beginning-of-line 1)
9296 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9298 (defun org-get-property-block (&optional beg end force)
9299 "Return the (beg . end) range of the body of the property drawer.
9300 BEG and END can be beginning and end of subtree, if not given
9301 they will be found.
9302 If the drawer does not exist and FORCE is non-nil, create the drawer."
9303 (catch 'exit
9304 (save-excursion
9305 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9306 (end (or end (progn (outline-next-heading) (point)))))
9307 (goto-char beg)
9308 (if (re-search-forward org-property-start-re end t)
9309 (setq beg (1+ (match-end 0)))
9310 (if force
9311 (save-excursion
9312 (org-insert-property-drawer)
9313 (setq end (progn (outline-next-heading) (point))))
9314 (throw 'exit nil))
9315 (goto-char beg)
9316 (if (re-search-forward org-property-start-re end t)
9317 (setq beg (1+ (match-end 0)))))
9318 (if (re-search-forward org-property-end-re end t)
9319 (setq end (match-beginning 0))
9320 (or force (throw 'exit nil))
9321 (goto-char beg)
9322 (setq end beg)
9323 (org-indent-line-function)
9324 (insert ":END:\n"))
9325 (cons beg end)))))
9327 (defun org-entry-properties (&optional pom which)
9328 "Get all properties of the entry at point-or-marker POM.
9329 This includes the TODO keyword, the tags, time strings for deadline,
9330 scheduled, and clocking, and any additional properties defined in the
9331 entry. The return value is an alist, keys may occur multiple times
9332 if the property key was used several times.
9333 POM may also be nil, in which case the current entry is used.
9334 If WHICH is nil or `all', get all properties. If WHICH is
9335 `special' or `standard', only get that subclass."
9336 (setq which (or which 'all))
9337 (org-with-point-at pom
9338 (let ((clockstr (substring org-clock-string 0 -1))
9339 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9340 beg end range props sum-props key value string clocksum)
9341 (save-excursion
9342 (when (condition-case nil (org-back-to-heading t) (error nil))
9343 (setq beg (point))
9344 (setq sum-props (get-text-property (point) 'org-summaries))
9345 (setq clocksum (get-text-property (point) :org-clock-minutes))
9346 (outline-next-heading)
9347 (setq end (point))
9348 (when (memq which '(all special))
9349 ;; Get the special properties, like TODO and tags
9350 (goto-char beg)
9351 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9352 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9353 (when (looking-at org-priority-regexp)
9354 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9355 (when (and (setq value (org-get-tags-string))
9356 (string-match "\\S-" value))
9357 (push (cons "TAGS" value) props))
9358 (when (setq value (org-get-tags-at))
9359 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9360 props))
9361 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9362 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9363 string (if (equal key clockstr)
9364 (org-no-properties
9365 (org-trim
9366 (buffer-substring
9367 (match-beginning 3) (goto-char (point-at-eol)))))
9368 (substring (org-match-string-no-properties 3) 1 -1)))
9369 (unless key
9370 (if (= (char-after (match-beginning 3)) ?\[)
9371 (setq key "TIMESTAMP_IA")
9372 (setq key "TIMESTAMP")))
9373 (when (or (equal key clockstr) (not (assoc key props)))
9374 (push (cons key string) props)))
9378 (when (memq which '(all standard))
9379 ;; Get the standard properties, like :PORP: ...
9380 (setq range (org-get-property-block beg end))
9381 (when range
9382 (goto-char (car range))
9383 (while (re-search-forward
9384 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9385 (cdr range) t)
9386 (setq key (org-match-string-no-properties 1)
9387 value (org-trim (or (org-match-string-no-properties 2) "")))
9388 (unless (member key excluded)
9389 (push (cons key (or value "")) props)))))
9390 (if clocksum
9391 (push (cons "CLOCKSUM"
9392 (org-columns-number-to-string (/ (float clocksum) 60.)
9393 'add_times))
9394 props))
9395 (append sum-props (nreverse props)))))))
9397 (defun org-entry-get (pom property &optional inherit)
9398 "Get value of PROPERTY for entry at point-or-marker POM.
9399 If INHERIT is non-nil and the entry does not have the property,
9400 then also check higher levels of the hierarchy.
9401 If INHERIT is the symbol `selective', use inheritance only if the setting
9402 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9403 If the property is present but empty, the return value is the empty string.
9404 If the property is not present at all, nil is returned."
9405 (org-with-point-at pom
9406 (if (and inherit (if (eq inherit 'selective)
9407 (org-property-inherit-p property)
9409 (org-entry-get-with-inheritance property)
9410 (if (member property org-special-properties)
9411 ;; We need a special property. Use brute force, get all properties.
9412 (cdr (assoc property (org-entry-properties nil 'special)))
9413 (let ((range (org-get-property-block)))
9414 (if (and range
9415 (goto-char (car range))
9416 (re-search-forward
9417 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9418 (cdr range) t))
9419 ;; Found the property, return it.
9420 (if (match-end 1)
9421 (org-match-string-no-properties 1)
9422 "")))))))
9424 (defun org-property-or-variable-value (var &optional inherit)
9425 "Check if there is a property fixing the value of VAR.
9426 If yes, return this value. If not, return the current value of the variable."
9427 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9428 (if (and prop (stringp prop) (string-match "\\S-" prop))
9429 (read prop)
9430 (symbol-value var))))
9432 (defun org-entry-delete (pom property)
9433 "Delete the property PROPERTY from entry at point-or-marker POM."
9434 (org-with-point-at pom
9435 (if (member property org-special-properties)
9436 nil ; cannot delete these properties.
9437 (let ((range (org-get-property-block)))
9438 (if (and range
9439 (goto-char (car range))
9440 (re-search-forward
9441 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9442 (cdr range) t))
9443 (progn
9444 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9446 nil)))))
9448 ;; Multi-values properties are properties that contain multiple values
9449 ;; These values are assumed to be single words, separated by whitespace.
9450 (defun org-entry-add-to-multivalued-property (pom property value)
9451 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9452 (let* ((old (org-entry-get pom property))
9453 (values (and old (org-split-string old "[ \t]"))))
9454 (unless (member value values)
9455 (setq values (cons value values))
9456 (org-entry-put pom property
9457 (mapconcat 'identity values " ")))))
9459 (defun org-entry-remove-from-multivalued-property (pom property value)
9460 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9461 (let* ((old (org-entry-get pom property))
9462 (values (and old (org-split-string old "[ \t]"))))
9463 (when (member value values)
9464 (setq values (delete value values))
9465 (org-entry-put pom property
9466 (mapconcat 'identity values " ")))))
9468 (defun org-entry-member-in-multivalued-property (pom property value)
9469 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9470 (let* ((old (org-entry-get pom property))
9471 (values (and old (org-split-string old "[ \t]"))))
9472 (member value values)))
9474 (defvar org-entry-property-inherited-from (make-marker))
9476 (defun org-entry-get-with-inheritance (property)
9477 "Get entry property, and search higher levels if not present."
9478 (let (tmp)
9479 (save-excursion
9480 (save-restriction
9481 (widen)
9482 (catch 'ex
9483 (while t
9484 (when (setq tmp (org-entry-get nil property))
9485 (org-back-to-heading t)
9486 (move-marker org-entry-property-inherited-from (point))
9487 (throw 'ex tmp))
9488 (or (org-up-heading-safe) (throw 'ex nil)))))
9489 (or tmp (cdr (assoc property org-local-properties))
9490 (cdr (assoc property org-global-properties))))))
9492 (defun org-entry-put (pom property value)
9493 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9494 (org-with-point-at pom
9495 (org-back-to-heading t)
9496 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9497 range)
9498 (cond
9499 ((equal property "TODO")
9500 (when (and (stringp value) (string-match "\\S-" value)
9501 (not (member value org-todo-keywords-1)))
9502 (error "\"%s\" is not a valid TODO state" value))
9503 (if (or (not value)
9504 (not (string-match "\\S-" value)))
9505 (setq value 'none))
9506 (org-todo value)
9507 (org-set-tags nil 'align))
9508 ((equal property "PRIORITY")
9509 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9510 (string-to-char value) ?\ ))
9511 (org-set-tags nil 'align))
9512 ((equal property "SCHEDULED")
9513 (if (re-search-forward org-scheduled-time-regexp end t)
9514 (cond
9515 ((eq value 'earlier) (org-timestamp-change -1 'day))
9516 ((eq value 'later) (org-timestamp-change 1 'day))
9517 (t (call-interactively 'org-schedule)))
9518 (call-interactively 'org-schedule)))
9519 ((equal property "DEADLINE")
9520 (if (re-search-forward org-deadline-time-regexp end t)
9521 (cond
9522 ((eq value 'earlier) (org-timestamp-change -1 'day))
9523 ((eq value 'later) (org-timestamp-change 1 'day))
9524 (t (call-interactively 'org-deadline)))
9525 (call-interactively 'org-deadline)))
9526 ((member property org-special-properties)
9527 (error "The %s property can not yet be set with `org-entry-put'"
9528 property))
9529 (t ; a non-special property
9530 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9531 (setq range (org-get-property-block beg end 'force))
9532 (goto-char (car range))
9533 (if (re-search-forward
9534 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9535 (progn
9536 (delete-region (match-beginning 1) (match-end 1))
9537 (goto-char (match-beginning 1)))
9538 (goto-char (cdr range))
9539 (insert "\n")
9540 (backward-char 1)
9541 (org-indent-line-function)
9542 (insert ":" property ":"))
9543 (and value (insert " " value))
9544 (org-indent-line-function)))))))
9546 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9547 "Get all property keys in the current buffer.
9548 With INCLUDE-SPECIALS, also list the special properties that relect things
9549 like tags and TODO state.
9550 With INCLUDE-DEFAULTS, also include properties that has special meaning
9551 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9552 With INCLUDE-COLUMNS, also include property names given in COLUMN
9553 formats in the current buffer."
9554 (let (rtn range cfmt cols s p)
9555 (save-excursion
9556 (save-restriction
9557 (widen)
9558 (goto-char (point-min))
9559 (while (re-search-forward org-property-start-re nil t)
9560 (setq range (org-get-property-block))
9561 (goto-char (car range))
9562 (while (re-search-forward
9563 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9564 (cdr range) t)
9565 (add-to-list 'rtn (org-match-string-no-properties 1)))
9566 (outline-next-heading))))
9568 (when include-specials
9569 (setq rtn (append org-special-properties rtn)))
9571 (when include-defaults
9572 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9574 (when include-columns
9575 (save-excursion
9576 (save-restriction
9577 (widen)
9578 (goto-char (point-min))
9579 (while (re-search-forward
9580 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9581 nil t)
9582 (setq cfmt (match-string 2) s 0)
9583 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9584 cfmt s)
9585 (setq s (match-end 0)
9586 p (match-string 1 cfmt))
9587 (unless (or (equal p "ITEM")
9588 (member p org-special-properties))
9589 (add-to-list 'rtn (match-string 1 cfmt))))))))
9591 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9593 (defun org-property-values (key)
9594 "Return a list of all values of property KEY."
9595 (save-excursion
9596 (save-restriction
9597 (widen)
9598 (goto-char (point-min))
9599 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9600 values)
9601 (while (re-search-forward re nil t)
9602 (add-to-list 'values (org-trim (match-string 1))))
9603 (delete "" values)))))
9605 (defun org-insert-property-drawer ()
9606 "Insert a property drawer into the current entry."
9607 (interactive)
9608 (org-back-to-heading t)
9609 (looking-at outline-regexp)
9610 (let ((indent (- (match-end 0)(match-beginning 0)))
9611 (beg (point))
9612 (re (concat "^[ \t]*" org-keyword-time-regexp))
9613 end hiddenp)
9614 (outline-next-heading)
9615 (setq end (point))
9616 (goto-char beg)
9617 (while (re-search-forward re end t))
9618 (setq hiddenp (org-invisible-p))
9619 (end-of-line 1)
9620 (and (equal (char-after) ?\n) (forward-char 1))
9621 (org-skip-over-state-notes)
9622 (skip-chars-backward " \t\n\r")
9623 (if (eq (char-before) ?*) (forward-char 1))
9624 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9625 (beginning-of-line 0)
9626 (indent-to-column indent)
9627 (beginning-of-line 2)
9628 (indent-to-column indent)
9629 (beginning-of-line 0)
9630 (if hiddenp
9631 (save-excursion
9632 (org-back-to-heading t)
9633 (hide-entry))
9634 (org-flag-drawer t))))
9636 (defun org-set-property (property value)
9637 "In the current entry, set PROPERTY to VALUE.
9638 When called interactively, this will prompt for a property name, offering
9639 completion on existing and default properties. And then it will prompt
9640 for a value, offering competion either on allowed values (via an inherited
9641 xxx_ALL property) or on existing values in other instances of this property
9642 in the current file."
9643 (interactive
9644 (let* ((prop (completing-read
9645 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9646 (cur (org-entry-get nil prop))
9647 (allowed (org-property-get-allowed-values nil prop 'table))
9648 (existing (mapcar 'list (org-property-values prop)))
9649 (val (if allowed
9650 (completing-read "Value: " allowed nil 'req-match)
9651 (completing-read
9652 (concat "Value" (if (and cur (string-match "\\S-" cur))
9653 (concat "[" cur "]") "")
9654 ": ")
9655 existing nil nil "" nil cur))))
9656 (list prop (if (equal val "") cur val))))
9657 (unless (equal (org-entry-get nil property) value)
9658 (org-entry-put nil property value)))
9660 (defun org-delete-property (property)
9661 "In the current entry, delete PROPERTY."
9662 (interactive
9663 (let* ((prop (completing-read
9664 "Property: " (org-entry-properties nil 'standard))))
9665 (list prop)))
9666 (message "Property %s %s" property
9667 (if (org-entry-delete nil property)
9668 "deleted"
9669 "was not present in the entry")))
9671 (defun org-delete-property-globally (property)
9672 "Remove PROPERTY globally, from all entries."
9673 (interactive
9674 (let* ((prop (completing-read
9675 "Globally remove property: "
9676 (mapcar 'list (org-buffer-property-keys)))))
9677 (list prop)))
9678 (save-excursion
9679 (save-restriction
9680 (widen)
9681 (goto-char (point-min))
9682 (let ((cnt 0))
9683 (while (re-search-forward
9684 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9685 nil t)
9686 (setq cnt (1+ cnt))
9687 (replace-match ""))
9688 (message "Property \"%s\" removed from %d entries" property cnt)))))
9690 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9692 (defun org-compute-property-at-point ()
9693 "Compute the property at point.
9694 This looks for an enclosing column format, extracts the operator and
9695 then applies it to the proerty in the column format's scope."
9696 (interactive)
9697 (unless (org-at-property-p)
9698 (error "Not at a property"))
9699 (let ((prop (org-match-string-no-properties 2)))
9700 (org-columns-get-format-and-top-level)
9701 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9702 (error "No operator defined for property %s" prop))
9703 (org-columns-compute prop)))
9705 (defun org-property-get-allowed-values (pom property &optional table)
9706 "Get allowed values for the property PROPERTY.
9707 When TABLE is non-nil, return an alist that can directly be used for
9708 completion."
9709 (let (vals)
9710 (cond
9711 ((equal property "TODO")
9712 (setq vals (org-with-point-at pom
9713 (append org-todo-keywords-1 '("")))))
9714 ((equal property "PRIORITY")
9715 (let ((n org-lowest-priority))
9716 (while (>= n org-highest-priority)
9717 (push (char-to-string n) vals)
9718 (setq n (1- n)))))
9719 ((member property org-special-properties))
9721 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9723 (when (and vals (string-match "\\S-" vals))
9724 (setq vals (car (read-from-string (concat "(" vals ")"))))
9725 (setq vals (mapcar (lambda (x)
9726 (cond ((stringp x) x)
9727 ((numberp x) (number-to-string x))
9728 ((symbolp x) (symbol-name x))
9729 (t "???")))
9730 vals)))))
9731 (if table (mapcar 'list vals) vals)))
9733 (defun org-property-previous-allowed-value (&optional previous)
9734 "Switch to the next allowed value for this property."
9735 (interactive)
9736 (org-property-next-allowed-value t))
9738 (defun org-property-next-allowed-value (&optional previous)
9739 "Switch to the next allowed value for this property."
9740 (interactive)
9741 (unless (org-at-property-p)
9742 (error "Not at a property"))
9743 (let* ((key (match-string 2))
9744 (value (match-string 3))
9745 (allowed (or (org-property-get-allowed-values (point) key)
9746 (and (member value '("[ ]" "[-]" "[X]"))
9747 '("[ ]" "[X]"))))
9748 nval)
9749 (unless allowed
9750 (error "Allowed values for this property have not been defined"))
9751 (if previous (setq allowed (reverse allowed)))
9752 (if (member value allowed)
9753 (setq nval (car (cdr (member value allowed)))))
9754 (setq nval (or nval (car allowed)))
9755 (if (equal nval value)
9756 (error "Only one allowed value for this property"))
9757 (org-at-property-p)
9758 (replace-match (concat " :" key ": " nval) t t)
9759 (org-indent-line-function)
9760 (beginning-of-line 1)
9761 (skip-chars-forward " \t")))
9763 (defun org-find-entry-with-id (ident)
9764 "Locate the entry that contains the ID property with exact value IDENT.
9765 IDENT can be a string, a symbol or a number, this function will search for
9766 the string representation of it.
9767 Return the position where this entry starts, or nil if there is no such entry."
9768 (let ((id (cond
9769 ((stringp ident) ident)
9770 ((symbol-name ident) (symbol-name ident))
9771 ((numberp ident) (number-to-string ident))
9772 (t (error "IDENT %s must be a string, symbol or number" ident))))
9773 (case-fold-search nil))
9774 (save-excursion
9775 (save-restriction
9776 (widen)
9777 (goto-char (point-min))
9778 (when (re-search-forward
9779 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9780 nil t)
9781 (org-back-to-heading)
9782 (point))))))
9784 ;;;; Timestamps
9786 (defvar org-last-changed-timestamp nil)
9787 (defvar org-time-was-given) ; dynamically scoped parameter
9788 (defvar org-end-time-was-given) ; dynamically scoped parameter
9789 (defvar org-ts-what) ; dynamically scoped parameter
9791 (defun org-time-stamp (arg)
9792 "Prompt for a date/time and insert a time stamp.
9793 If the user specifies a time like HH:MM, or if this command is called
9794 with a prefix argument, the time stamp will contain date and time.
9795 Otherwise, only the date will be included. All parts of a date not
9796 specified by the user will be filled in from the current date/time.
9797 So if you press just return without typing anything, the time stamp
9798 will represent the current date/time. If there is already a timestamp
9799 at the cursor, it will be modified."
9800 (interactive "P")
9801 (let* ((ts nil)
9802 (default-time
9803 ;; Default time is either today, or, when entering a range,
9804 ;; the range start.
9805 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9806 (save-excursion
9807 (re-search-backward
9808 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9809 (- (point) 20) t)))
9810 (apply 'encode-time (org-parse-time-string (match-string 1)))
9811 (current-time)))
9812 (default-input (and ts (org-get-compact-tod ts)))
9813 org-time-was-given org-end-time-was-given time)
9814 (cond
9815 ((and (org-at-timestamp-p)
9816 (eq last-command 'org-time-stamp)
9817 (eq this-command 'org-time-stamp))
9818 (insert "--")
9819 (setq time (let ((this-command this-command))
9820 (org-read-date arg 'totime nil nil default-time default-input)))
9821 (org-insert-time-stamp time (or org-time-was-given arg)))
9822 ((org-at-timestamp-p)
9823 (setq time (let ((this-command this-command))
9824 (org-read-date arg 'totime nil nil default-time default-input)))
9825 (when (org-at-timestamp-p) ; just to get the match data
9826 (replace-match "")
9827 (setq org-last-changed-timestamp
9828 (org-insert-time-stamp
9829 time (or org-time-was-given arg)
9830 nil nil nil (list org-end-time-was-given))))
9831 (message "Timestamp updated"))
9833 (setq time (let ((this-command this-command))
9834 (org-read-date arg 'totime nil nil default-time default-input)))
9835 (org-insert-time-stamp time (or org-time-was-given arg)
9836 nil nil nil (list org-end-time-was-given))))))
9838 ;; FIXME: can we use this for something else, like computing time differences?
9839 (defun org-get-compact-tod (s)
9840 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
9841 (let* ((t1 (match-string 1 s))
9842 (h1 (string-to-number (match-string 2 s)))
9843 (m1 (string-to-number (match-string 3 s)))
9844 (t2 (and (match-end 4) (match-string 5 s)))
9845 (h2 (and t2 (string-to-number (match-string 6 s))))
9846 (m2 (and t2 (string-to-number (match-string 7 s))))
9847 dh dm)
9848 (if (not t2)
9850 (setq dh (- h2 h1) dm (- m2 m1))
9851 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
9852 (concat t1 "+" (number-to-string dh)
9853 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
9855 (defun org-time-stamp-inactive (&optional arg)
9856 "Insert an inactive time stamp.
9857 An inactive time stamp is enclosed in square brackets instead of angle
9858 brackets. It is inactive in the sense that it does not trigger agenda entries,
9859 does not link to the calendar and cannot be changed with the S-cursor keys.
9860 So these are more for recording a certain time/date."
9861 (interactive "P")
9862 (let (org-time-was-given org-end-time-was-given time)
9863 (setq time (org-read-date arg 'totime))
9864 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
9865 nil nil (list org-end-time-was-given))))
9867 (defvar org-date-ovl (org-make-overlay 1 1))
9868 (org-overlay-put org-date-ovl 'face 'org-warning)
9869 (org-detach-overlay org-date-ovl)
9871 (defvar org-ans1) ; dynamically scoped parameter
9872 (defvar org-ans2) ; dynamically scoped parameter
9874 (defvar org-plain-time-of-day-regexp) ; defined below
9876 (defvar org-read-date-overlay nil)
9877 (defvar org-dcst nil) ; dynamically scoped
9879 (defun org-read-date (&optional with-time to-time from-string prompt
9880 default-time default-input)
9881 "Read a date, possibly a time, and make things smooth for the user.
9882 The prompt will suggest to enter an ISO date, but you can also enter anything
9883 which will at least partially be understood by `parse-time-string'.
9884 Unrecognized parts of the date will default to the current day, month, year,
9885 hour and minute. If this command is called to replace a timestamp at point,
9886 of to enter the second timestamp of a range, the default time is taken from the
9887 existing stamp. For example,
9888 3-2-5 --> 2003-02-05
9889 feb 15 --> currentyear-02-15
9890 sep 12 9 --> 2009-09-12
9891 12:45 --> today 12:45
9892 22 sept 0:34 --> currentyear-09-22 0:34
9893 12 --> currentyear-currentmonth-12
9894 Fri --> nearest Friday (today or later)
9895 etc.
9897 Furthermore you can specify a relative date by giving, as the *first* thing
9898 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
9899 change in days weeks, months, years.
9900 With a single plus or minus, the date is relative to today. With a double
9901 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
9902 +4d --> four days from today
9903 +4 --> same as above
9904 +2w --> two weeks from today
9905 ++5 --> five days from default date
9907 The function understands only English month and weekday abbreviations,
9908 but this can be configured with the variables `parse-time-months' and
9909 `parse-time-weekdays'.
9911 While prompting, a calendar is popped up - you can also select the
9912 date with the mouse (button 1). The calendar shows a period of three
9913 months. To scroll it to other months, use the keys `>' and `<'.
9914 If you don't like the calendar, turn it off with
9915 \(setq org-read-date-popup-calendar nil)
9917 With optional argument TO-TIME, the date will immediately be converted
9918 to an internal time.
9919 With an optional argument WITH-TIME, the prompt will suggest to also
9920 insert a time. Note that when WITH-TIME is not set, you can still
9921 enter a time, and this function will inform the calling routine about
9922 this change. The calling routine may then choose to change the format
9923 used to insert the time stamp into the buffer to include the time.
9924 With optional argument FROM-STRING, read from this string instead from
9925 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
9926 the time/date that is used for everything that is not specified by the
9927 user."
9928 (require 'parse-time)
9929 (let* ((org-time-stamp-rounding-minutes
9930 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
9931 (org-dcst org-display-custom-times)
9932 (ct (org-current-time))
9933 (def (or default-time ct))
9934 (defdecode (decode-time def))
9935 (dummy (progn
9936 (when (< (nth 2 defdecode) org-extend-today-until)
9937 (setcar (nthcdr 2 defdecode) -1)
9938 (setcar (nthcdr 1 defdecode) 59)
9939 (setq def (apply 'encode-time defdecode)
9940 defdecode (decode-time def)))))
9941 (calendar-move-hook nil)
9942 (calendar-view-diary-initially-flag nil)
9943 (view-diary-entries-initially nil)
9944 (calendar-view-holidays-initially-flag nil)
9945 (view-calendar-holidays-initially nil)
9946 (timestr (format-time-string
9947 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
9948 (prompt (concat (if prompt (concat prompt " ") "")
9949 (format "Date+time [%s]: " timestr)))
9950 ans (org-ans0 "") org-ans1 org-ans2 final)
9952 (cond
9953 (from-string (setq ans from-string))
9954 (org-read-date-popup-calendar
9955 (save-excursion
9956 (save-window-excursion
9957 (calendar)
9958 (calendar-forward-day (- (time-to-days def)
9959 (calendar-absolute-from-gregorian
9960 (calendar-current-date))))
9961 (org-eval-in-calendar nil t)
9962 (let* ((old-map (current-local-map))
9963 (map (copy-keymap calendar-mode-map))
9964 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
9965 (org-defkey map (kbd "RET") 'org-calendar-select)
9966 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
9967 'org-calendar-select-mouse)
9968 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
9969 'org-calendar-select-mouse)
9970 (org-defkey minibuffer-local-map [(meta shift left)]
9971 (lambda () (interactive)
9972 (org-eval-in-calendar '(calendar-backward-month 1))))
9973 (org-defkey minibuffer-local-map [(meta shift right)]
9974 (lambda () (interactive)
9975 (org-eval-in-calendar '(calendar-forward-month 1))))
9976 (org-defkey minibuffer-local-map [(meta shift up)]
9977 (lambda () (interactive)
9978 (org-eval-in-calendar '(calendar-backward-year 1))))
9979 (org-defkey minibuffer-local-map [(meta shift down)]
9980 (lambda () (interactive)
9981 (org-eval-in-calendar '(calendar-forward-year 1))))
9982 (org-defkey minibuffer-local-map [(shift up)]
9983 (lambda () (interactive)
9984 (org-eval-in-calendar '(calendar-backward-week 1))))
9985 (org-defkey minibuffer-local-map [(shift down)]
9986 (lambda () (interactive)
9987 (org-eval-in-calendar '(calendar-forward-week 1))))
9988 (org-defkey minibuffer-local-map [(shift left)]
9989 (lambda () (interactive)
9990 (org-eval-in-calendar '(calendar-backward-day 1))))
9991 (org-defkey minibuffer-local-map [(shift right)]
9992 (lambda () (interactive)
9993 (org-eval-in-calendar '(calendar-forward-day 1))))
9994 (org-defkey minibuffer-local-map ">"
9995 (lambda () (interactive)
9996 (org-eval-in-calendar '(scroll-calendar-left 1))))
9997 (org-defkey minibuffer-local-map "<"
9998 (lambda () (interactive)
9999 (org-eval-in-calendar '(scroll-calendar-right 1))))
10000 (unwind-protect
10001 (progn
10002 (use-local-map map)
10003 (add-hook 'post-command-hook 'org-read-date-display)
10004 (setq org-ans0 (read-string prompt default-input nil nil))
10005 ;; org-ans0: from prompt
10006 ;; org-ans1: from mouse click
10007 ;; org-ans2: from calendar motion
10008 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10009 (remove-hook 'post-command-hook 'org-read-date-display)
10010 (use-local-map old-map)
10011 (when org-read-date-overlay
10012 (org-delete-overlay org-read-date-overlay)
10013 (setq org-read-date-overlay nil)))))))
10015 (t ; Naked prompt only
10016 (unwind-protect
10017 (setq ans (read-string prompt default-input nil timestr))
10018 (when org-read-date-overlay
10019 (org-delete-overlay org-read-date-overlay)
10020 (setq org-read-date-overlay nil)))))
10022 (setq final (org-read-date-analyze ans def defdecode))
10024 (if to-time
10025 (apply 'encode-time final)
10026 (if (and (boundp 'org-time-was-given) org-time-was-given)
10027 (format "%04d-%02d-%02d %02d:%02d"
10028 (nth 5 final) (nth 4 final) (nth 3 final)
10029 (nth 2 final) (nth 1 final))
10030 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10031 (defvar def)
10032 (defvar defdecode)
10033 (defvar with-time)
10034 (defun org-read-date-display ()
10035 "Display the currrent date prompt interpretation in the minibuffer."
10036 (when org-read-date-display-live
10037 (when org-read-date-overlay
10038 (org-delete-overlay org-read-date-overlay))
10039 (let ((p (point)))
10040 (end-of-line 1)
10041 (while (not (equal (buffer-substring
10042 (max (point-min) (- (point) 4)) (point))
10043 " "))
10044 (insert " "))
10045 (goto-char p))
10046 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10047 " " (or org-ans1 org-ans2)))
10048 (org-end-time-was-given nil)
10049 (f (org-read-date-analyze ans def defdecode))
10050 (fmts (if org-dcst
10051 org-time-stamp-custom-formats
10052 org-time-stamp-formats))
10053 (fmt (if (or with-time
10054 (and (boundp 'org-time-was-given) org-time-was-given))
10055 (cdr fmts)
10056 (car fmts)))
10057 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10058 (when (and org-end-time-was-given
10059 (string-match org-plain-time-of-day-regexp txt))
10060 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10061 org-end-time-was-given
10062 (substring txt (match-end 0)))))
10063 (setq org-read-date-overlay
10064 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10065 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10067 (defun org-read-date-analyze (ans def defdecode)
10068 "Analyze the combined answer of the date prompt."
10069 ;; FIXME: cleanup and comment
10070 (let (delta deltan deltaw deltadef year month day
10071 hour minute second wday pm h2 m2 tl wday1
10072 iso-year iso-weekday iso-week iso-year iso-date)
10074 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10075 (setq ans (replace-match "" t t ans)
10076 deltan (car delta)
10077 deltaw (nth 1 delta)
10078 deltadef (nth 2 delta)))
10080 ;; Check if there is an iso week date in there
10081 ;; If yes, sore the info and ostpone interpreting it until the rest
10082 ;; of the parsing is done
10083 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10084 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10085 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10086 iso-week (string-to-number (match-string 2 ans)))
10087 (setq ans (replace-match "" t t ans)))
10089 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10090 (when (string-match
10091 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10092 (setq year (if (match-end 2)
10093 (string-to-number (match-string 2 ans))
10094 (string-to-number (format-time-string "%Y")))
10095 month (string-to-number (match-string 3 ans))
10096 day (string-to-number (match-string 4 ans)))
10097 (if (< year 100) (setq year (+ 2000 year)))
10098 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10099 t nil ans)))
10100 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10101 ;; If there is a time with am/pm, and *no* time without it, we convert
10102 ;; so that matching will be successful.
10103 (loop for i from 1 to 2 do ; twice, for end time as well
10104 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10105 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10106 (setq hour (string-to-number (match-string 1 ans))
10107 minute (if (match-end 3)
10108 (string-to-number (match-string 3 ans))
10110 pm (equal ?p
10111 (string-to-char (downcase (match-string 4 ans)))))
10112 (if (and (= hour 12) (not pm))
10113 (setq hour 0)
10114 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10115 (setq ans (replace-match (format "%02d:%02d" hour minute)
10116 t t ans))))
10118 ;; Check if a time range is given as a duration
10119 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10120 (setq hour (string-to-number (match-string 1 ans))
10121 h2 (+ hour (string-to-number (match-string 3 ans)))
10122 minute (string-to-number (match-string 2 ans))
10123 m2 (+ minute (if (match-end 5) (string-to-number
10124 (match-string 5 ans))0)))
10125 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10126 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10127 t t ans)))
10129 ;; Check if there is a time range
10130 (when (boundp 'org-end-time-was-given)
10131 (setq org-time-was-given nil)
10132 (when (and (string-match org-plain-time-of-day-regexp ans)
10133 (match-end 8))
10134 (setq org-end-time-was-given (match-string 8 ans))
10135 (setq ans (concat (substring ans 0 (match-beginning 7))
10136 (substring ans (match-end 7))))))
10138 (setq tl (parse-time-string ans)
10139 day (or (nth 3 tl) (nth 3 defdecode))
10140 month (or (nth 4 tl)
10141 (if (and org-read-date-prefer-future
10142 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10143 (1+ (nth 4 defdecode))
10144 (nth 4 defdecode)))
10145 year (or (nth 5 tl)
10146 (if (and org-read-date-prefer-future
10147 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10148 (1+ (nth 5 defdecode))
10149 (nth 5 defdecode)))
10150 hour (or (nth 2 tl) (nth 2 defdecode))
10151 minute (or (nth 1 tl) (nth 1 defdecode))
10152 second (or (nth 0 tl) 0)
10153 wday (nth 6 tl))
10155 ;; Special date definitions below
10156 (cond
10157 (iso-week
10158 ;; There was an iso week
10159 (setq year (or iso-year year)
10160 day (or iso-weekday wday 1)
10161 wday nil ; to make sure that the trigger below does not match
10162 iso-date (calendar-gregorian-from-absolute
10163 (calendar-absolute-from-iso
10164 (list iso-week day year))))
10165 ; FIXME: Should we also push ISO weeks into the future?
10166 ; (when (and org-read-date-prefer-future
10167 ; (not iso-year)
10168 ; (< (calendar-absolute-from-gregorian iso-date)
10169 ; (time-to-days (current-time))))
10170 ; (setq year (1+ year)
10171 ; iso-date (calendar-gregorian-from-absolute
10172 ; (calendar-absolute-from-iso
10173 ; (list iso-week day year)))))
10174 (setq month (car iso-date)
10175 year (nth 2 iso-date)
10176 day (nth 1 iso-date)))
10177 (deltan
10178 (unless deltadef
10179 (let ((now (decode-time (current-time))))
10180 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10181 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10182 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10183 ((equal deltaw "m") (setq month (+ month deltan)))
10184 ((equal deltaw "y") (setq year (+ year deltan)))))
10185 ((and wday (not (nth 3 tl)))
10186 ;; Weekday was given, but no day, so pick that day in the week
10187 ;; on or after the derived date.
10188 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10189 (unless (equal wday wday1)
10190 (setq day (+ day (% (- wday wday1 -7) 7))))))
10191 (if (and (boundp 'org-time-was-given)
10192 (nth 2 tl))
10193 (setq org-time-was-given t))
10194 (if (< year 100) (setq year (+ 2000 year)))
10195 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10196 (list second minute hour day month year)))
10198 (defvar parse-time-weekdays)
10200 (defun org-read-date-get-relative (s today default)
10201 "Check string S for special relative date string.
10202 TODAY and DEFAULT are internal times, for today and for a default.
10203 Return shift list (N what def-flag)
10204 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10205 N is the number of WHATs to shift.
10206 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10207 the DEFAULT date rather than TODAY."
10208 (when (string-match
10209 (concat
10210 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10211 "\\([0-9]+\\)?"
10212 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10213 "\\([ \t]\\|$\\)") s)
10214 (let* ((dir (if (match-end 1)
10215 (string-to-char (substring (match-string 1 s) -1))
10216 ?+))
10217 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10218 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10219 (what (if (match-end 3) (match-string 3 s) "d"))
10220 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10221 (date (if rel default today))
10222 (wday (nth 6 (decode-time date)))
10223 delta)
10224 (if wday1
10225 (progn
10226 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10227 (if (= dir ?-) (setq delta (- delta 7)))
10228 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10229 (list delta "d" rel))
10230 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10232 (defun org-eval-in-calendar (form &optional keepdate)
10233 "Eval FORM in the calendar window and return to current window.
10234 Also, store the cursor date in variable org-ans2."
10235 (let ((sw (selected-window)))
10236 (select-window (get-buffer-window "*Calendar*"))
10237 (eval form)
10238 (when (and (not keepdate) (calendar-cursor-to-date))
10239 (let* ((date (calendar-cursor-to-date))
10240 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10241 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10242 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10243 (select-window sw)))
10245 ; ;; Update the prompt to show new default date
10246 ; (save-excursion
10247 ; (goto-char (point-min))
10248 ; (when (and org-ans2
10249 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10250 ; (get-text-property (match-end 0) 'field))
10251 ; (let ((inhibit-read-only t))
10252 ; (replace-match (concat "[" org-ans2 "]") t t)
10253 ; (add-text-properties (point-min) (1+ (match-end 0))
10254 ; (text-properties-at (1+ (point-min)))))))))
10256 (defun org-calendar-select ()
10257 "Return to `org-read-date' with the date currently selected.
10258 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10259 (interactive)
10260 (when (calendar-cursor-to-date)
10261 (let* ((date (calendar-cursor-to-date))
10262 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10263 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10264 (if (active-minibuffer-window) (exit-minibuffer))))
10266 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10267 "Insert a date stamp for the date given by the internal TIME.
10268 WITH-HM means, use the stamp format that includes the time of the day.
10269 INACTIVE means use square brackets instead of angular ones, so that the
10270 stamp will not contribute to the agenda.
10271 PRE and POST are optional strings to be inserted before and after the
10272 stamp.
10273 The command returns the inserted time stamp."
10274 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10275 stamp)
10276 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10277 (insert-before-markers (or pre ""))
10278 (insert-before-markers (setq stamp (format-time-string fmt time)))
10279 (when (listp extra)
10280 (setq extra (car extra))
10281 (if (and (stringp extra)
10282 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10283 (setq extra (format "-%02d:%02d"
10284 (string-to-number (match-string 1 extra))
10285 (string-to-number (match-string 2 extra))))
10286 (setq extra nil)))
10287 (when extra
10288 (backward-char 1)
10289 (insert-before-markers extra)
10290 (forward-char 1))
10291 (insert-before-markers (or post ""))
10292 stamp))
10294 (defun org-toggle-time-stamp-overlays ()
10295 "Toggle the use of custom time stamp formats."
10296 (interactive)
10297 (setq org-display-custom-times (not org-display-custom-times))
10298 (unless org-display-custom-times
10299 (let ((p (point-min)) (bmp (buffer-modified-p)))
10300 (while (setq p (next-single-property-change p 'display))
10301 (if (and (get-text-property p 'display)
10302 (eq (get-text-property p 'face) 'org-date))
10303 (remove-text-properties
10304 p (setq p (next-single-property-change p 'display))
10305 '(display t))))
10306 (set-buffer-modified-p bmp)))
10307 (if (featurep 'xemacs)
10308 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10309 (org-restart-font-lock)
10310 (setq org-table-may-need-update t)
10311 (if org-display-custom-times
10312 (message "Time stamps are overlayed with custom format")
10313 (message "Time stamp overlays removed")))
10315 (defun org-display-custom-time (beg end)
10316 "Overlay modified time stamp format over timestamp between BED and END."
10317 (let* ((ts (buffer-substring beg end))
10318 t1 w1 with-hm tf time str w2 (off 0))
10319 (save-match-data
10320 (setq t1 (org-parse-time-string ts t))
10321 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10322 (setq off (- (match-end 0) (match-beginning 0)))))
10323 (setq end (- end off))
10324 (setq w1 (- end beg)
10325 with-hm (and (nth 1 t1) (nth 2 t1))
10326 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10327 time (org-fix-decoded-time t1)
10328 str (org-add-props
10329 (format-time-string
10330 (substring tf 1 -1) (apply 'encode-time time))
10331 nil 'mouse-face 'highlight)
10332 w2 (length str))
10333 (if (not (= w2 w1))
10334 (add-text-properties (1+ beg) (+ 2 beg)
10335 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10336 (if (featurep 'xemacs)
10337 (progn
10338 (put-text-property beg end 'invisible t)
10339 (put-text-property beg end 'end-glyph (make-glyph str)))
10340 (put-text-property beg end 'display str))))
10342 (defun org-translate-time (string)
10343 "Translate all timestamps in STRING to custom format.
10344 But do this only if the variable `org-display-custom-times' is set."
10345 (when org-display-custom-times
10346 (save-match-data
10347 (let* ((start 0)
10348 (re org-ts-regexp-both)
10349 t1 with-hm inactive tf time str beg end)
10350 (while (setq start (string-match re string start))
10351 (setq beg (match-beginning 0)
10352 end (match-end 0)
10353 t1 (save-match-data
10354 (org-parse-time-string (substring string beg end) t))
10355 with-hm (and (nth 1 t1) (nth 2 t1))
10356 inactive (equal (substring string beg (1+ beg)) "[")
10357 tf (funcall (if with-hm 'cdr 'car)
10358 org-time-stamp-custom-formats)
10359 time (org-fix-decoded-time t1)
10360 str (format-time-string
10361 (concat
10362 (if inactive "[" "<") (substring tf 1 -1)
10363 (if inactive "]" ">"))
10364 (apply 'encode-time time))
10365 string (replace-match str t t string)
10366 start (+ start (length str)))))))
10367 string)
10369 (defun org-fix-decoded-time (time)
10370 "Set 0 instead of nil for the first 6 elements of time.
10371 Don't touch the rest."
10372 (let ((n 0))
10373 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10375 (defun org-days-to-time (timestamp-string)
10376 "Difference between TIMESTAMP-STRING and now in days."
10377 (- (time-to-days (org-time-string-to-time timestamp-string))
10378 (time-to-days (current-time))))
10380 (defun org-deadline-close (timestamp-string &optional ndays)
10381 "Is the time in TIMESTAMP-STRING close to the current date?"
10382 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10383 (and (< (org-days-to-time timestamp-string) ndays)
10384 (not (org-entry-is-done-p))))
10386 (defun org-get-wdays (ts)
10387 "Get the deadline lead time appropriate for timestring TS."
10388 (cond
10389 ((<= org-deadline-warning-days 0)
10390 ;; 0 or negative, enforce this value no matter what
10391 (- org-deadline-warning-days))
10392 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10393 ;; lead time is specified.
10394 (floor (* (string-to-number (match-string 1 ts))
10395 (cdr (assoc (match-string 2 ts)
10396 '(("d" . 1) ("w" . 7)
10397 ("m" . 30.4) ("y" . 365.25)))))))
10398 ;; go for the default.
10399 (t org-deadline-warning-days)))
10401 (defun org-calendar-select-mouse (ev)
10402 "Return to `org-read-date' with the date currently selected.
10403 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10404 (interactive "e")
10405 (mouse-set-point ev)
10406 (when (calendar-cursor-to-date)
10407 (let* ((date (calendar-cursor-to-date))
10408 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10409 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10410 (if (active-minibuffer-window) (exit-minibuffer))))
10412 (defun org-check-deadlines (ndays)
10413 "Check if there are any deadlines due or past due.
10414 A deadline is considered due if it happens within `org-deadline-warning-days'
10415 days from today's date. If the deadline appears in an entry marked DONE,
10416 it is not shown. The prefix arg NDAYS can be used to test that many
10417 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10418 (interactive "P")
10419 (let* ((org-warn-days
10420 (cond
10421 ((equal ndays '(4)) 100000)
10422 (ndays (prefix-numeric-value ndays))
10423 (t (abs org-deadline-warning-days))))
10424 (case-fold-search nil)
10425 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10426 (callback
10427 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10429 (message "%d deadlines past-due or due within %d days"
10430 (org-occur regexp nil callback)
10431 org-warn-days)))
10433 (defun org-check-before-date (date)
10434 "Check if there are deadlines or scheduled entries before DATE."
10435 (interactive (list (org-read-date)))
10436 (let ((case-fold-search nil)
10437 (regexp (concat "\\<\\(" org-deadline-string
10438 "\\|" org-scheduled-string
10439 "\\) *<\\([^>]+\\)>"))
10440 (callback
10441 (lambda () (time-less-p
10442 (org-time-string-to-time (match-string 2))
10443 (org-time-string-to-time date)))))
10444 (message "%d entries before %s"
10445 (org-occur regexp nil callback) date)))
10447 (defun org-evaluate-time-range (&optional to-buffer)
10448 "Evaluate a time range by computing the difference between start and end.
10449 Normally the result is just printed in the echo area, but with prefix arg
10450 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10451 If the time range is actually in a table, the result is inserted into the
10452 next column.
10453 For time difference computation, a year is assumed to be exactly 365
10454 days in order to avoid rounding problems."
10455 (interactive "P")
10457 (org-clock-update-time-maybe)
10458 (save-excursion
10459 (unless (org-at-date-range-p t)
10460 (goto-char (point-at-bol))
10461 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10462 (if (not (org-at-date-range-p t))
10463 (error "Not at a time-stamp range, and none found in current line")))
10464 (let* ((ts1 (match-string 1))
10465 (ts2 (match-string 2))
10466 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10467 (match-end (match-end 0))
10468 (time1 (org-time-string-to-time ts1))
10469 (time2 (org-time-string-to-time ts2))
10470 (t1 (time-to-seconds time1))
10471 (t2 (time-to-seconds time2))
10472 (diff (abs (- t2 t1)))
10473 (negative (< (- t2 t1) 0))
10474 ;; (ys (floor (* 365 24 60 60)))
10475 (ds (* 24 60 60))
10476 (hs (* 60 60))
10477 (fy "%dy %dd %02d:%02d")
10478 (fy1 "%dy %dd")
10479 (fd "%dd %02d:%02d")
10480 (fd1 "%dd")
10481 (fh "%02d:%02d")
10482 y d h m align)
10483 (if havetime
10484 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10486 d (floor (/ diff ds)) diff (mod diff ds)
10487 h (floor (/ diff hs)) diff (mod diff hs)
10488 m (floor (/ diff 60)))
10489 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10491 d (floor (+ (/ diff ds) 0.5))
10492 h 0 m 0))
10493 (if (not to-buffer)
10494 (message "%s" (org-make-tdiff-string y d h m))
10495 (if (org-at-table-p)
10496 (progn
10497 (goto-char match-end)
10498 (setq align t)
10499 (and (looking-at " *|") (goto-char (match-end 0))))
10500 (goto-char match-end))
10501 (if (looking-at
10502 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10503 (replace-match ""))
10504 (if negative (insert " -"))
10505 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10506 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10507 (insert " " (format fh h m))))
10508 (if align (org-table-align))
10509 (message "Time difference inserted")))))
10511 (defun org-make-tdiff-string (y d h m)
10512 (let ((fmt "")
10513 (l nil))
10514 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10515 l (push y l)))
10516 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10517 l (push d l)))
10518 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10519 l (push h l)))
10520 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10521 l (push m l)))
10522 (apply 'format fmt (nreverse l))))
10524 (defun org-time-string-to-time (s)
10525 (apply 'encode-time (org-parse-time-string s)))
10527 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10528 "Convert a time stamp to an absolute day number.
10529 If there is a specifyer for a cyclic time stamp, get the closest date to
10530 DAYNR.
10531 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10532 (cond
10533 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10534 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10535 daynr
10536 (+ daynr 1000)))
10537 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10538 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10539 (time-to-days (current-time))) (match-string 0 s)
10540 prefer show-all))
10541 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10543 (defun org-days-to-iso-week (days)
10544 "Return the iso week number."
10545 (require 'cal-iso)
10546 (car (calendar-iso-from-absolute days)))
10548 (defun org-small-year-to-year (year)
10549 "Convert 2-digit years into 4-digit years.
10550 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10551 The year 2000 cannot be abbreviated. Any year lager than 99
10552 is retrned unchanged."
10553 (if (< year 38)
10554 (setq year (+ 2000 year))
10555 (if (< year 100)
10556 (setq year (+ 1900 year))))
10557 year)
10559 (defun org-time-from-absolute (d)
10560 "Return the time corresponding to date D.
10561 D may be an absolute day number, or a calendar-type list (month day year)."
10562 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10563 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10565 (defun org-calendar-holiday ()
10566 "List of holidays, for Diary display in Org-mode."
10567 (require 'holidays)
10568 (let ((hl (funcall
10569 (if (fboundp 'calendar-check-holidays)
10570 'calendar-check-holidays 'check-calendar-holidays) date)))
10571 (if hl (mapconcat 'identity hl "; "))))
10573 (defun org-diary-sexp-entry (sexp entry date)
10574 "Process a SEXP diary ENTRY for DATE."
10575 (require 'diary-lib)
10576 (let ((result (if calendar-debug-sexp
10577 (let ((stack-trace-on-error t))
10578 (eval (car (read-from-string sexp))))
10579 (condition-case nil
10580 (eval (car (read-from-string sexp)))
10581 (error
10582 (beep)
10583 (message "Bad sexp at line %d in %s: %s"
10584 (org-current-line)
10585 (buffer-file-name) sexp)
10586 (sleep-for 2))))))
10587 (cond ((stringp result) result)
10588 ((and (consp result)
10589 (stringp (cdr result))) (cdr result))
10590 (result entry)
10591 (t nil))))
10593 (defun org-diary-to-ical-string (frombuf)
10594 "Get iCalendar entries from diary entries in buffer FROMBUF.
10595 This uses the icalendar.el library."
10596 (let* ((tmpdir (if (featurep 'xemacs)
10597 (temp-directory)
10598 temporary-file-directory))
10599 (tmpfile (make-temp-name
10600 (expand-file-name "orgics" tmpdir)))
10601 buf rtn b e)
10602 (save-excursion
10603 (set-buffer frombuf)
10604 (icalendar-export-region (point-min) (point-max) tmpfile)
10605 (setq buf (find-buffer-visiting tmpfile))
10606 (set-buffer buf)
10607 (goto-char (point-min))
10608 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10609 (setq b (match-beginning 0)))
10610 (goto-char (point-max))
10611 (if (re-search-backward "^END:VEVENT" nil t)
10612 (setq e (match-end 0)))
10613 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10614 (kill-buffer buf)
10615 (kill-buffer frombuf)
10616 (delete-file tmpfile)
10617 rtn))
10619 (defun org-closest-date (start current change prefer show-all)
10620 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10621 When PREFER is `past' return a date that is either CURRENT or past.
10622 When PREFER is `future', return a date that is either CURRENT or future.
10623 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10624 ;; Make the proper lists from the dates
10625 (catch 'exit
10626 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10627 dn dw sday cday n1 n2
10628 d m y y1 y2 date1 date2 nmonths nm ny m2)
10630 (setq start (org-date-to-gregorian start)
10631 current (org-date-to-gregorian
10632 (if show-all
10633 current
10634 (time-to-days (current-time))))
10635 sday (calendar-absolute-from-gregorian start)
10636 cday (calendar-absolute-from-gregorian current))
10638 (if (<= cday sday) (throw 'exit sday))
10640 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10641 (setq dn (string-to-number (match-string 1 change))
10642 dw (cdr (assoc (match-string 2 change) a1)))
10643 (error "Invalid change specifyer: %s" change))
10644 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10645 (cond
10646 ((eq dw 'day)
10647 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10648 n2 (+ n1 dn)))
10649 ((eq dw 'year)
10650 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10651 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10652 (setq date1 (list m d y1)
10653 n1 (calendar-absolute-from-gregorian date1)
10654 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10655 n2 (calendar-absolute-from-gregorian date2)))
10656 ((eq dw 'month)
10657 ;; approx number of month between the tow dates
10658 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10659 ;; How often does dn fit in there?
10660 (setq d (nth 1 start) m (car start) y (nth 2 start)
10661 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10662 m (+ m nm)
10663 ny (floor (/ m 12))
10664 y (+ y ny)
10665 m (- m (* ny 12)))
10666 (while (> m 12) (setq m (- m 12) y (1+ y)))
10667 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10668 (setq m2 (+ m dn) y2 y)
10669 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10670 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10671 (while (< n2 cday)
10672 (setq n1 n2 m m2 y y2)
10673 (setq m2 (+ m dn) y2 y)
10674 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10675 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10677 (if show-all
10678 (cond
10679 ((eq prefer 'past) n1)
10680 ((eq prefer 'future) (if (= cday n1) n1 n2))
10681 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10682 (cond
10683 ((eq prefer 'past) n1)
10684 ((eq prefer 'future) (if (= cday n1) n1 n2))
10685 (t (if (= cday n1) n1 n2)))))))
10687 (defun org-date-to-gregorian (date)
10688 "Turn any specification of DATE into a gregorian date for the calendar."
10689 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10690 ((and (listp date) (= (length date) 3)) date)
10691 ((stringp date)
10692 (setq date (org-parse-time-string date))
10693 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10694 ((listp date)
10695 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10697 (defun org-parse-time-string (s &optional nodefault)
10698 "Parse the standard Org-mode time string.
10699 This should be a lot faster than the normal `parse-time-string'.
10700 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10701 hour and minute fields will be nil if not given."
10702 (if (string-match org-ts-regexp0 s)
10703 (list 0
10704 (if (or (match-beginning 8) (not nodefault))
10705 (string-to-number (or (match-string 8 s) "0")))
10706 (if (or (match-beginning 7) (not nodefault))
10707 (string-to-number (or (match-string 7 s) "0")))
10708 (string-to-number (match-string 4 s))
10709 (string-to-number (match-string 3 s))
10710 (string-to-number (match-string 2 s))
10711 nil nil nil)
10712 (make-list 9 0)))
10714 (defun org-timestamp-up (&optional arg)
10715 "Increase the date item at the cursor by one.
10716 If the cursor is on the year, change the year. If it is on the month or
10717 the day, change that.
10718 With prefix ARG, change by that many units."
10719 (interactive "p")
10720 (org-timestamp-change (prefix-numeric-value arg)))
10722 (defun org-timestamp-down (&optional arg)
10723 "Decrease the date item at the cursor by one.
10724 If the cursor is on the year, change the year. If it is on the month or
10725 the day, change that.
10726 With prefix ARG, change by that many units."
10727 (interactive "p")
10728 (org-timestamp-change (- (prefix-numeric-value arg))))
10730 (defun org-timestamp-up-day (&optional arg)
10731 "Increase the date in the time stamp by one day.
10732 With prefix ARG, change that many days."
10733 (interactive "p")
10734 (if (and (not (org-at-timestamp-p t))
10735 (org-on-heading-p))
10736 (org-todo 'up)
10737 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10739 (defun org-timestamp-down-day (&optional arg)
10740 "Decrease the date in the time stamp by one day.
10741 With prefix ARG, change that many days."
10742 (interactive "p")
10743 (if (and (not (org-at-timestamp-p t))
10744 (org-on-heading-p))
10745 (org-todo 'down)
10746 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10748 (defun org-at-timestamp-p (&optional inactive-ok)
10749 "Determine if the cursor is in or at a timestamp."
10750 (interactive)
10751 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10752 (pos (point))
10753 (ans (or (looking-at tsr)
10754 (save-excursion
10755 (skip-chars-backward "^[<\n\r\t")
10756 (if (> (point) (point-min)) (backward-char 1))
10757 (and (looking-at tsr)
10758 (> (- (match-end 0) pos) -1))))))
10759 (and ans
10760 (boundp 'org-ts-what)
10761 (setq org-ts-what
10762 (cond
10763 ((= pos (match-beginning 0)) 'bracket)
10764 ((= pos (1- (match-end 0))) 'bracket)
10765 ((org-pos-in-match-range pos 2) 'year)
10766 ((org-pos-in-match-range pos 3) 'month)
10767 ((org-pos-in-match-range pos 7) 'hour)
10768 ((org-pos-in-match-range pos 8) 'minute)
10769 ((or (org-pos-in-match-range pos 4)
10770 (org-pos-in-match-range pos 5)) 'day)
10771 ((and (> pos (or (match-end 8) (match-end 5)))
10772 (< pos (match-end 0)))
10773 (- pos (or (match-end 8) (match-end 5))))
10774 (t 'day))))
10775 ans))
10777 (defun org-toggle-timestamp-type ()
10778 "Toggle the type (<active> or [inactive]) of a time stamp."
10779 (interactive)
10780 (when (org-at-timestamp-p t)
10781 (save-excursion
10782 (goto-char (match-beginning 0))
10783 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10784 (goto-char (1- (match-end 0)))
10785 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10786 (message "Timestamp is now %sactive"
10787 (if (equal (char-before) ?>) "in" ""))))
10789 (defun org-timestamp-change (n &optional what)
10790 "Change the date in the time stamp at point.
10791 The date will be changed by N times WHAT. WHAT can be `day', `month',
10792 `year', `minute', `second'. If WHAT is not given, the cursor position
10793 in the timestamp determines what will be changed."
10794 (let ((pos (point))
10795 with-hm inactive
10796 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10797 org-ts-what
10798 extra rem
10799 ts time time0)
10800 (if (not (org-at-timestamp-p t))
10801 (error "Not at a timestamp"))
10802 (if (and (not what) (eq org-ts-what 'bracket))
10803 (org-toggle-timestamp-type)
10804 (if (and (not what) (not (eq org-ts-what 'day))
10805 org-display-custom-times
10806 (get-text-property (point) 'display)
10807 (not (get-text-property (1- (point)) 'display)))
10808 (setq org-ts-what 'day))
10809 (setq org-ts-what (or what org-ts-what)
10810 inactive (= (char-after (match-beginning 0)) ?\[)
10811 ts (match-string 0))
10812 (replace-match "")
10813 (if (string-match
10814 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10816 (setq extra (match-string 1 ts)))
10817 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10818 (setq with-hm t))
10819 (setq time0 (org-parse-time-string ts))
10820 (when (and (eq org-ts-what 'minute)
10821 (eq current-prefix-arg nil))
10822 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10823 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10824 (setcar (cdr time0) (+ (nth 1 time0)
10825 (if (> n 0) (- rem) (- dm rem))))))
10826 (setq time
10827 (encode-time (or (car time0) 0)
10828 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
10829 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
10830 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
10831 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
10832 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
10833 (nthcdr 6 time0)))
10834 (when (integerp org-ts-what)
10835 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
10836 (if (eq what 'calendar)
10837 (let ((cal-date (org-get-date-from-calendar)))
10838 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
10839 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
10840 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
10841 (setcar time0 (or (car time0) 0))
10842 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
10843 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
10844 (setq time (apply 'encode-time time0))))
10845 (setq org-last-changed-timestamp
10846 (org-insert-time-stamp time with-hm inactive nil nil extra))
10847 (org-clock-update-time-maybe)
10848 (goto-char pos)
10849 ;; Try to recenter the calendar window, if any
10850 (if (and org-calendar-follow-timestamp-change
10851 (get-buffer-window "*Calendar*" t)
10852 (memq org-ts-what '(day month year)))
10853 (org-recenter-calendar (time-to-days time))))))
10855 (defun org-modify-ts-extra (s pos n dm)
10856 "Change the different parts of the lead-time and repeat fields in timestamp."
10857 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
10858 ng h m new rem)
10859 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
10860 (cond
10861 ((or (org-pos-in-match-range pos 2)
10862 (org-pos-in-match-range pos 3))
10863 (setq m (string-to-number (match-string 3 s))
10864 h (string-to-number (match-string 2 s)))
10865 (if (org-pos-in-match-range pos 2)
10866 (setq h (+ h n))
10867 (setq n (* dm (org-no-warnings (signum n))))
10868 (when (not (= 0 (setq rem (% m dm))))
10869 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
10870 (setq m (+ m n)))
10871 (if (< m 0) (setq m (+ m 60) h (1- h)))
10872 (if (> m 59) (setq m (- m 60) h (1+ h)))
10873 (setq h (min 24 (max 0 h)))
10874 (setq ng 1 new (format "-%02d:%02d" h m)))
10875 ((org-pos-in-match-range pos 6)
10876 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
10877 ((org-pos-in-match-range pos 5)
10878 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
10880 ((org-pos-in-match-range pos 9)
10881 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
10882 ((org-pos-in-match-range pos 8)
10883 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
10885 (when ng
10886 (setq s (concat
10887 (substring s 0 (match-beginning ng))
10889 (substring s (match-end ng))))))
10892 (defun org-recenter-calendar (date)
10893 "If the calendar is visible, recenter it to DATE."
10894 (let* ((win (selected-window))
10895 (cwin (get-buffer-window "*Calendar*" t))
10896 (calendar-move-hook nil))
10897 (when cwin
10898 (select-window cwin)
10899 (calendar-goto-date (if (listp date) date
10900 (calendar-gregorian-from-absolute date)))
10901 (select-window win))))
10903 (defun org-goto-calendar (&optional arg)
10904 "Go to the Emacs calendar at the current date.
10905 If there is a time stamp in the current line, go to that date.
10906 A prefix ARG can be used to force the current date."
10907 (interactive "P")
10908 (let ((tsr org-ts-regexp) diff
10909 (calendar-move-hook nil)
10910 (calendar-view-holidays-initially-flag nil)
10911 (view-calendar-holidays-initially nil)
10912 (calendar-view-diary-initially-flag nil)
10913 (view-diary-entries-initially nil))
10914 (if (or (org-at-timestamp-p)
10915 (save-excursion
10916 (beginning-of-line 1)
10917 (looking-at (concat ".*" tsr))))
10918 (let ((d1 (time-to-days (current-time)))
10919 (d2 (time-to-days
10920 (org-time-string-to-time (match-string 1)))))
10921 (setq diff (- d2 d1))))
10922 (calendar)
10923 (calendar-goto-today)
10924 (if (and diff (not arg)) (calendar-forward-day diff))))
10926 (defun org-get-date-from-calendar ()
10927 "Return a list (month day year) of date at point in calendar."
10928 (with-current-buffer "*Calendar*"
10929 (save-match-data
10930 (calendar-cursor-to-date))))
10932 (defun org-date-from-calendar ()
10933 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
10934 If there is already a time stamp at the cursor position, update it."
10935 (interactive)
10936 (if (org-at-timestamp-p t)
10937 (org-timestamp-change 0 'calendar)
10938 (let ((cal-date (org-get-date-from-calendar)))
10939 (org-insert-time-stamp
10940 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
10942 (defun org-minutes-to-hours (m)
10943 "Compute H:MM from a number of minutes."
10944 (let ((h (/ m 60)))
10945 (setq m (- m (* 60 h)))
10946 (format "%d:%02d" h m)))
10949 ;;;; Agenda files
10951 ;;;###autoload
10952 (defun org-iswitchb (&optional arg)
10953 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
10954 With a prefix argument, restrict available to files.
10955 With two prefix arguments, restrict available buffers to agenda files.
10957 Due to some yet unresolved reason, global function
10958 `iswitchb-mode' needs to be active for this function to work."
10959 (interactive "P")
10960 (require 'iswitchb)
10961 (let ((enabled iswitchb-mode) blist)
10962 (or enabled (iswitchb-mode 1))
10963 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
10964 ((equal arg '(16)) (org-buffer-list 'agenda))
10965 (t (org-buffer-list))))
10966 (unwind-protect
10967 (let ((iswitchb-make-buflist-hook
10968 (lambda ()
10969 (setq iswitchb-temp-buflist
10970 (mapcar 'buffer-name blist)))))
10971 (switch-to-buffer
10972 (iswitchb-read-buffer
10973 "Switch-to: " nil t))
10974 (or enabled (iswitchb-mode -1))))))
10976 (defun org-buffer-list (&optional predicate tmp)
10977 "Return a list of Org buffers.
10978 PREDICATE can be either 'export, 'files or 'agenda.
10980 'export restrict the list to Export buffers.
10981 'files restrict the list to buffers visiting Org files.
10982 'agenda restrict the list to buffers visiting agenda files.
10984 If TMP is non-nil, don't include temporary buffers."
10985 (let (filter blist)
10986 (setq filter
10987 (cond ((eq predicate 'files) "\.org$")
10988 ((eq predicate 'export) "\*Org .*Export")
10989 (t "\*Org \\|\.org$")))
10990 (setq blist
10991 (mapcar
10992 (lambda(b)
10993 (let ((bname (buffer-name b))
10994 (bfile (buffer-file-name b)))
10995 (if (and (string-match filter bname)
10996 (if (eq predicate 'agenda)
10997 (member bfile
10998 (mapcar (lambda(f) (file-truename f))
10999 org-agenda-files)) t)
11000 (if tmp (not (string-match "tmp" bname)) t)) b)))
11001 (buffer-list)))
11002 (delete nil blist)))
11004 (defun org-agenda-files (&optional unrestricted)
11005 "Get the list of agenda files.
11006 Optional UNRESTRICTED means return the full list even if a restriction
11007 is currently in place."
11008 (let ((files
11009 (cond
11010 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11011 ((stringp org-agenda-files) (org-read-agenda-file-list))
11012 ((listp org-agenda-files) org-agenda-files)
11013 (t (error "Invalid value of `org-agenda-files'")))))
11014 (setq files (apply 'append
11015 (mapcar (lambda (f)
11016 (if (file-directory-p f)
11017 (directory-files f t
11018 org-agenda-file-regexp)
11019 (list f)))
11020 files)))
11021 (if org-agenda-skip-unavailable-files
11022 (delq nil
11023 (mapcar (function
11024 (lambda (file)
11025 (and (file-readable-p file) file)))
11026 files))
11027 files))) ; `org-check-agenda-file' will remove them from the list
11029 (defun org-edit-agenda-file-list ()
11030 "Edit the list of agenda files.
11031 Depending on setup, this either uses customize to edit the variable
11032 `org-agenda-files', or it visits the file that is holding the list. In the
11033 latter case, the buffer is set up in a way that saving it automatically kills
11034 the buffer and restores the previous window configuration."
11035 (interactive)
11036 (if (stringp org-agenda-files)
11037 (let ((cw (current-window-configuration)))
11038 (find-file org-agenda-files)
11039 (org-set-local 'org-window-configuration cw)
11040 (org-add-hook 'after-save-hook
11041 (lambda ()
11042 (set-window-configuration
11043 (prog1 org-window-configuration
11044 (kill-buffer (current-buffer))))
11045 (org-install-agenda-files-menu)
11046 (message "New agenda file list installed"))
11047 nil 'local)
11048 (message "%s" (substitute-command-keys
11049 "Edit list and finish with \\[save-buffer]")))
11050 (customize-variable 'org-agenda-files)))
11052 (defun org-store-new-agenda-file-list (list)
11053 "Set new value for the agenda file list and save it correcly."
11054 (if (stringp org-agenda-files)
11055 (let ((f org-agenda-files) b)
11056 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11057 (with-temp-file f
11058 (insert (mapconcat 'identity list "\n") "\n")))
11059 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11060 (setq org-agenda-files list)
11061 (customize-save-variable 'org-agenda-files org-agenda-files))))
11063 (defun org-read-agenda-file-list ()
11064 "Read the list of agenda files from a file."
11065 (when (stringp org-agenda-files)
11066 (with-temp-buffer
11067 (insert-file-contents org-agenda-files)
11068 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11071 ;;;###autoload
11072 (defun org-cycle-agenda-files ()
11073 "Cycle through the files in `org-agenda-files'.
11074 If the current buffer visits an agenda file, find the next one in the list.
11075 If the current buffer does not, find the first agenda file."
11076 (interactive)
11077 (let* ((fs (org-agenda-files t))
11078 (files (append fs (list (car fs))))
11079 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11080 file)
11081 (unless files (error "No agenda files"))
11082 (catch 'exit
11083 (while (setq file (pop files))
11084 (if (equal (file-truename file) tcf)
11085 (when (car files)
11086 (find-file (car files))
11087 (throw 'exit t))))
11088 (find-file (car fs)))
11089 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11091 (defun org-agenda-file-to-front (&optional to-end)
11092 "Move/add the current file to the top of the agenda file list.
11093 If the file is not present in the list, it is added to the front. If it is
11094 present, it is moved there. With optional argument TO-END, add/move to the
11095 end of the list."
11096 (interactive "P")
11097 (let ((org-agenda-skip-unavailable-files nil)
11098 (file-alist (mapcar (lambda (x)
11099 (cons (file-truename x) x))
11100 (org-agenda-files t)))
11101 (ctf (file-truename buffer-file-name))
11102 x had)
11103 (setq x (assoc ctf file-alist) had x)
11105 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11106 (if to-end
11107 (setq file-alist (append (delq x file-alist) (list x)))
11108 (setq file-alist (cons x (delq x file-alist))))
11109 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11110 (org-install-agenda-files-menu)
11111 (message "File %s to %s of agenda file list"
11112 (if had "moved" "added") (if to-end "end" "front"))))
11114 (defun org-remove-file (&optional file)
11115 "Remove current file from the list of files in variable `org-agenda-files'.
11116 These are the files which are being checked for agenda entries.
11117 Optional argument FILE means, use this file instead of the current."
11118 (interactive)
11119 (let* ((org-agenda-skip-unavailable-files nil)
11120 (file (or file buffer-file-name))
11121 (true-file (file-truename file))
11122 (afile (abbreviate-file-name file))
11123 (files (delq nil (mapcar
11124 (lambda (x)
11125 (if (equal true-file
11126 (file-truename x))
11127 nil x))
11128 (org-agenda-files t)))))
11129 (if (not (= (length files) (length (org-agenda-files t))))
11130 (progn
11131 (org-store-new-agenda-file-list files)
11132 (org-install-agenda-files-menu)
11133 (message "Removed file: %s" afile))
11134 (message "File was not in list: %s (not removed)" afile))))
11136 (defun org-file-menu-entry (file)
11137 (vector file (list 'find-file file) t))
11139 (defun org-check-agenda-file (file)
11140 "Make sure FILE exists. If not, ask user what to do."
11141 (when (not (file-exists-p file))
11142 (message "non-existent file %s. [R]emove from list or [A]bort?"
11143 (abbreviate-file-name file))
11144 (let ((r (downcase (read-char-exclusive))))
11145 (cond
11146 ((equal r ?r)
11147 (org-remove-file file)
11148 (throw 'nextfile t))
11149 (t (error "Abort"))))))
11151 (defun org-get-agenda-file-buffer (file)
11152 "Get a buffer visiting FILE. If the buffer needs to be created, add
11153 it to the list of buffers which might be released later."
11154 (let ((buf (org-find-base-buffer-visiting file)))
11155 (if buf
11156 buf ; just return it
11157 ;; Make a new buffer and remember it
11158 (setq buf (find-file-noselect file))
11159 (if buf (push buf org-agenda-new-buffers))
11160 buf)))
11162 (defun org-release-buffers (blist)
11163 "Release all buffers in list, asking the user for confirmation when needed.
11164 When a buffer is unmodified, it is just killed. When modified, it is saved
11165 \(if the user agrees) and then killed."
11166 (let (buf file)
11167 (while (setq buf (pop blist))
11168 (setq file (buffer-file-name buf))
11169 (when (and (buffer-modified-p buf)
11170 file
11171 (y-or-n-p (format "Save file %s? " file)))
11172 (with-current-buffer buf (save-buffer)))
11173 (kill-buffer buf))))
11175 (defun org-prepare-agenda-buffers (files)
11176 "Create buffers for all agenda files, protect archived trees and comments."
11177 (interactive)
11178 (let ((pa '(:org-archived t))
11179 (pc '(:org-comment t))
11180 (pall '(:org-archived t :org-comment t))
11181 (inhibit-read-only t)
11182 (rea (concat ":" org-archive-tag ":"))
11183 bmp file re)
11184 (save-excursion
11185 (save-restriction
11186 (while (setq file (pop files))
11187 (if (bufferp file)
11188 (set-buffer file)
11189 (org-check-agenda-file file)
11190 (set-buffer (org-get-agenda-file-buffer file)))
11191 (widen)
11192 (setq bmp (buffer-modified-p))
11193 (org-refresh-category-properties)
11194 (setq org-todo-keywords-for-agenda
11195 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11196 (setq org-done-keywords-for-agenda
11197 (append org-done-keywords-for-agenda org-done-keywords))
11198 (save-excursion
11199 (remove-text-properties (point-min) (point-max) pall)
11200 (when org-agenda-skip-archived-trees
11201 (goto-char (point-min))
11202 (while (re-search-forward rea nil t)
11203 (if (org-on-heading-p t)
11204 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11205 (goto-char (point-min))
11206 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11207 (while (re-search-forward re nil t)
11208 (add-text-properties
11209 (match-beginning 0) (org-end-of-subtree t) pc)))
11210 (set-buffer-modified-p bmp))))))
11212 ;;;; Embedded LaTeX
11214 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11215 "Keymap for the minor `org-cdlatex-mode'.")
11217 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11218 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11219 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11220 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11221 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11223 (defvar org-cdlatex-texmathp-advice-is-done nil
11224 "Flag remembering if we have applied the advice to texmathp already.")
11226 (define-minor-mode org-cdlatex-mode
11227 "Toggle the minor `org-cdlatex-mode'.
11228 This mode supports entering LaTeX environment and math in LaTeX fragments
11229 in Org-mode.
11230 \\{org-cdlatex-mode-map}"
11231 nil " OCDL" nil
11232 (when org-cdlatex-mode (require 'cdlatex))
11233 (unless org-cdlatex-texmathp-advice-is-done
11234 (setq org-cdlatex-texmathp-advice-is-done t)
11235 (defadvice texmathp (around org-math-always-on activate)
11236 "Always return t in org-mode buffers.
11237 This is because we want to insert math symbols without dollars even outside
11238 the LaTeX math segments. If Orgmode thinks that point is actually inside
11239 en embedded LaTeX fragement, let texmathp do its job.
11240 \\[org-cdlatex-mode-map]"
11241 (interactive)
11242 (let (p)
11243 (cond
11244 ((not (org-mode-p)) ad-do-it)
11245 ((eq this-command 'cdlatex-math-symbol)
11246 (setq ad-return-value t
11247 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11249 (let ((p (org-inside-LaTeX-fragment-p)))
11250 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11251 (setq ad-return-value t
11252 texmathp-why '("Org-mode embedded math" . 0))
11253 (if p ad-do-it)))))))))
11255 (defun turn-on-org-cdlatex ()
11256 "Unconditionally turn on `org-cdlatex-mode'."
11257 (org-cdlatex-mode 1))
11259 (defun org-inside-LaTeX-fragment-p ()
11260 "Test if point is inside a LaTeX fragment.
11261 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11262 sequence appearing also before point.
11263 Even though the matchers for math are configurable, this function assumes
11264 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11265 delimiters are skipped when they have been removed by customization.
11266 The return value is nil, or a cons cell with the delimiter and
11267 and the position of this delimiter.
11269 This function does a reasonably good job, but can locally be fooled by
11270 for example currency specifications. For example it will assume being in
11271 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11272 fragments that are properly closed, but during editing, we have to live
11273 with the uncertainty caused by missing closing delimiters. This function
11274 looks only before point, not after."
11275 (catch 'exit
11276 (let ((pos (point))
11277 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11278 (lim (progn
11279 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11280 (point)))
11281 dd-on str (start 0) m re)
11282 (goto-char pos)
11283 (when dodollar
11284 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11285 re (nth 1 (assoc "$" org-latex-regexps)))
11286 (while (string-match re str start)
11287 (cond
11288 ((= (match-end 0) (length str))
11289 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11290 ((= (match-end 0) (- (length str) 5))
11291 (throw 'exit nil))
11292 (t (setq start (match-end 0))))))
11293 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11294 (goto-char pos)
11295 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11296 (and (match-beginning 2) (throw 'exit nil))
11297 ;; count $$
11298 (while (re-search-backward "\\$\\$" lim t)
11299 (setq dd-on (not dd-on)))
11300 (goto-char pos)
11301 (if dd-on (cons "$$" m))))))
11304 (defun org-try-cdlatex-tab ()
11305 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11306 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11307 - inside a LaTeX fragment, or
11308 - after the first word in a line, where an abbreviation expansion could
11309 insert a LaTeX environment."
11310 (when org-cdlatex-mode
11311 (cond
11312 ((save-excursion
11313 (skip-chars-backward "a-zA-Z0-9*")
11314 (skip-chars-backward " \t")
11315 (bolp))
11316 (cdlatex-tab) t)
11317 ((org-inside-LaTeX-fragment-p)
11318 (cdlatex-tab) t)
11319 (t nil))))
11321 (defun org-cdlatex-underscore-caret (&optional arg)
11322 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11323 Revert to the normal definition outside of these fragments."
11324 (interactive "P")
11325 (if (org-inside-LaTeX-fragment-p)
11326 (call-interactively 'cdlatex-sub-superscript)
11327 (let (org-cdlatex-mode)
11328 (call-interactively (key-binding (vector last-input-event))))))
11330 (defun org-cdlatex-math-modify (&optional arg)
11331 "Execute `cdlatex-math-modify' in LaTeX fragments.
11332 Revert to the normal definition outside of these fragments."
11333 (interactive "P")
11334 (if (org-inside-LaTeX-fragment-p)
11335 (call-interactively 'cdlatex-math-modify)
11336 (let (org-cdlatex-mode)
11337 (call-interactively (key-binding (vector last-input-event))))))
11339 (defvar org-latex-fragment-image-overlays nil
11340 "List of overlays carrying the images of latex fragments.")
11341 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11343 (defun org-remove-latex-fragment-image-overlays ()
11344 "Remove all overlays with LaTeX fragment images in current buffer."
11345 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11346 (setq org-latex-fragment-image-overlays nil))
11348 (defun org-preview-latex-fragment (&optional subtree)
11349 "Preview the LaTeX fragment at point, or all locally or globally.
11350 If the cursor is in a LaTeX fragment, create the image and overlay
11351 it over the source code. If there is no fragment at point, display
11352 all fragments in the current text, from one headline to the next. With
11353 prefix SUBTREE, display all fragments in the current subtree. With a
11354 double prefix `C-u C-u', or when the cursor is before the first headline,
11355 display all fragments in the buffer.
11356 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11357 (interactive "P")
11358 (org-remove-latex-fragment-image-overlays)
11359 (save-excursion
11360 (save-restriction
11361 (let (beg end at msg)
11362 (cond
11363 ((or (equal subtree '(16))
11364 (not (save-excursion
11365 (re-search-backward (concat "^" outline-regexp) nil t))))
11366 (setq beg (point-min) end (point-max)
11367 msg "Creating images for buffer...%s"))
11368 ((equal subtree '(4))
11369 (org-back-to-heading)
11370 (setq beg (point) end (org-end-of-subtree t)
11371 msg "Creating images for subtree...%s"))
11373 (if (setq at (org-inside-LaTeX-fragment-p))
11374 (goto-char (max (point-min) (- (cdr at) 2)))
11375 (org-back-to-heading))
11376 (setq beg (point) end (progn (outline-next-heading) (point))
11377 msg (if at "Creating image...%s"
11378 "Creating images for entry...%s"))))
11379 (message msg "")
11380 (narrow-to-region beg end)
11381 (goto-char beg)
11382 (org-format-latex
11383 (concat "ltxpng/" (file-name-sans-extension
11384 (file-name-nondirectory
11385 buffer-file-name)))
11386 default-directory 'overlays msg at 'forbuffer)
11387 (message msg "done. Use `C-c C-c' to remove images.")))))
11389 (defvar org-latex-regexps
11390 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11391 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11392 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11393 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11394 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11395 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11396 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11397 "Regular expressions for matching embedded LaTeX.")
11399 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11400 "Replace LaTeX fragments with links to an image, and produce images."
11401 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11402 (let* ((prefixnodir (file-name-nondirectory prefix))
11403 (absprefix (expand-file-name prefix dir))
11404 (todir (file-name-directory absprefix))
11405 (opt org-format-latex-options)
11406 (matchers (plist-get opt :matchers))
11407 (re-list org-latex-regexps)
11408 (cnt 0) txt link beg end re e checkdir
11409 m n block linkfile movefile ov)
11410 ;; Check if there are old images files with this prefix, and remove them
11411 (when (file-directory-p todir)
11412 (mapc 'delete-file
11413 (directory-files
11414 todir 'full
11415 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11416 ;; Check the different regular expressions
11417 (while (setq e (pop re-list))
11418 (setq m (car e) re (nth 1 e) n (nth 2 e)
11419 block (if (nth 3 e) "\n\n" ""))
11420 (when (member m matchers)
11421 (goto-char (point-min))
11422 (while (re-search-forward re nil t)
11423 (when (or (not at) (equal (cdr at) (match-beginning n)))
11424 (setq txt (match-string n)
11425 beg (match-beginning n) end (match-end n)
11426 cnt (1+ cnt)
11427 linkfile (format "%s_%04d.png" prefix cnt)
11428 movefile (format "%s_%04d.png" absprefix cnt)
11429 link (concat block "[[file:" linkfile "]]" block))
11430 (if msg (message msg cnt))
11431 (goto-char beg)
11432 (unless checkdir ; make sure the directory exists
11433 (setq checkdir t)
11434 (or (file-directory-p todir) (make-directory todir)))
11435 (org-create-formula-image
11436 txt movefile opt forbuffer)
11437 (if overlays
11438 (progn
11439 (setq ov (org-make-overlay beg end))
11440 (if (featurep 'xemacs)
11441 (progn
11442 (org-overlay-put ov 'invisible t)
11443 (org-overlay-put
11444 ov 'end-glyph
11445 (make-glyph (vector 'png :file movefile))))
11446 (org-overlay-put
11447 ov 'display
11448 (list 'image :type 'png :file movefile :ascent 'center)))
11449 (push ov org-latex-fragment-image-overlays)
11450 (goto-char end))
11451 (delete-region beg end)
11452 (insert link))))))))
11454 ;; This function borrows from Ganesh Swami's latex2png.el
11455 (defun org-create-formula-image (string tofile options buffer)
11456 (let* ((tmpdir (if (featurep 'xemacs)
11457 (temp-directory)
11458 temporary-file-directory))
11459 (texfilebase (make-temp-name
11460 (expand-file-name "orgtex" tmpdir)))
11461 (texfile (concat texfilebase ".tex"))
11462 (dvifile (concat texfilebase ".dvi"))
11463 (pngfile (concat texfilebase ".png"))
11464 (fnh (face-attribute 'default :height nil))
11465 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11466 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11467 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11468 "Black"))
11469 (bg (or (plist-get options (if buffer :background :html-background))
11470 "Transparent")))
11471 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11472 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11473 (with-temp-file texfile
11474 (insert org-format-latex-header
11475 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11476 (let ((dir default-directory))
11477 (condition-case nil
11478 (progn
11479 (cd tmpdir)
11480 (call-process "latex" nil nil nil texfile))
11481 (error nil))
11482 (cd dir))
11483 (if (not (file-exists-p dvifile))
11484 (progn (message "Failed to create dvi file from %s" texfile) nil)
11485 (call-process "dvipng" nil nil nil
11486 "-E" "-fg" fg "-bg" bg
11487 "-D" dpi
11488 ;;"-x" scale "-y" scale
11489 "-T" "tight"
11490 "-o" pngfile
11491 dvifile)
11492 (if (not (file-exists-p pngfile))
11493 (progn (message "Failed to create png file from %s" texfile) nil)
11494 ;; Use the requested file name and clean up
11495 (copy-file pngfile tofile 'replace)
11496 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11497 (delete-file (concat texfilebase e)))
11498 pngfile))))
11500 (defun org-dvipng-color (attr)
11501 "Return an rgb color specification for dvipng."
11502 (apply 'format "rgb %s %s %s"
11503 (mapcar 'org-normalize-color
11504 (color-values (face-attribute 'default attr nil)))))
11506 (defun org-normalize-color (value)
11507 "Return string to be used as color value for an RGB component."
11508 (format "%g" (/ value 65535.0)))
11511 ;;;; Key bindings
11513 ;; Make `C-c C-x' a prefix key
11514 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11516 ;; TAB key with modifiers
11517 (org-defkey org-mode-map "\C-i" 'org-cycle)
11518 (org-defkey org-mode-map [(tab)] 'org-cycle)
11519 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11520 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11521 (org-defkey org-mode-map "\M-\t" 'org-complete)
11522 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11523 ;; The following line is necessary under Suse GNU/Linux
11524 (unless (featurep 'xemacs)
11525 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11526 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11527 (define-key org-mode-map [backtab] 'org-shifttab)
11529 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11530 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11531 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11533 ;; Cursor keys with modifiers
11534 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11535 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11536 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11537 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11539 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11540 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11541 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11542 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11544 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11545 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11546 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11547 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11549 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11550 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11552 ;;; Extra keys for tty access.
11553 ;; We only set them when really needed because otherwise the
11554 ;; menus don't show the simple keys
11556 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11557 (not window-system))
11558 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11559 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11560 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11561 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11562 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11563 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11564 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11565 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11566 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11567 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11568 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11569 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11570 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11571 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11572 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11573 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11574 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11575 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11576 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11577 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11578 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11579 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11581 ;; All the other keys
11583 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11584 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11585 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11586 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11587 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11588 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11589 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11590 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11591 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11592 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11593 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11594 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11595 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11596 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11597 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11598 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11599 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11600 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11601 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11602 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11603 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11604 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11605 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11606 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11607 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11608 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11609 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11610 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11611 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11612 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11613 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11614 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11615 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11616 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11617 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11618 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11619 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11620 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11621 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11622 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11623 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11624 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11625 (org-defkey org-mode-map "\C-c^" 'org-sort)
11626 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11627 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11628 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11629 (org-defkey org-mode-map "\C-m" 'org-return)
11630 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11631 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11632 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11633 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11634 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11635 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11636 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11637 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11638 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11639 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11640 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11641 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11642 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11643 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11644 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11645 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11647 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11648 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11649 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11650 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11652 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11653 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11654 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11655 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11656 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11657 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11658 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11659 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11660 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11661 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11662 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11663 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11665 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11667 (when (featurep 'xemacs)
11668 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11670 (defvar org-table-auto-blank-field) ; defined in org-table.el
11671 (defun org-self-insert-command (N)
11672 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11673 If the cursor is in a table looking at whitespace, the whitespace is
11674 overwritten, and the table is not marked as requiring realignment."
11675 (interactive "p")
11676 (if (and (org-table-p)
11677 (progn
11678 ;; check if we blank the field, and if that triggers align
11679 (and (featurep 'org-table) org-table-auto-blank-field
11680 (member last-command
11681 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11682 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11683 ;; got extra space, this field does not determine column width
11684 (let (org-table-may-need-update) (org-table-blank-field))
11685 ;; no extra space, this field may determine column width
11686 (org-table-blank-field)))
11688 (eq N 1)
11689 (looking-at "[^|\n]* |"))
11690 (let (org-table-may-need-update)
11691 (goto-char (1- (match-end 0)))
11692 (delete-backward-char 1)
11693 (goto-char (match-beginning 0))
11694 (self-insert-command N))
11695 (setq org-table-may-need-update t)
11696 (self-insert-command N)
11697 (org-fix-tags-on-the-fly)))
11699 (defun org-fix-tags-on-the-fly ()
11700 (when (and (equal (char-after (point-at-bol)) ?*)
11701 (org-on-heading-p))
11702 (org-align-tags-here org-tags-column)))
11704 (defun org-delete-backward-char (N)
11705 "Like `delete-backward-char', insert whitespace at field end in tables.
11706 When deleting backwards, in tables this function will insert whitespace in
11707 front of the next \"|\" separator, to keep the table aligned. The table will
11708 still be marked for re-alignment if the field did fill the entire column,
11709 because, in this case the deletion might narrow the column."
11710 (interactive "p")
11711 (if (and (org-table-p)
11712 (eq N 1)
11713 (string-match "|" (buffer-substring (point-at-bol) (point)))
11714 (looking-at ".*?|"))
11715 (let ((pos (point))
11716 (noalign (looking-at "[^|\n\r]* |"))
11717 (c org-table-may-need-update))
11718 (backward-delete-char N)
11719 (skip-chars-forward "^|")
11720 (insert " ")
11721 (goto-char (1- pos))
11722 ;; noalign: if there were two spaces at the end, this field
11723 ;; does not determine the width of the column.
11724 (if noalign (setq org-table-may-need-update c)))
11725 (backward-delete-char N)
11726 (org-fix-tags-on-the-fly)))
11728 (defun org-delete-char (N)
11729 "Like `delete-char', but insert whitespace at field end in tables.
11730 When deleting characters, in tables this function will insert whitespace in
11731 front of the next \"|\" separator, to keep the table aligned. The table will
11732 still be marked for re-alignment if the field did fill the entire column,
11733 because, in this case the deletion might narrow the column."
11734 (interactive "p")
11735 (if (and (org-table-p)
11736 (not (bolp))
11737 (not (= (char-after) ?|))
11738 (eq N 1))
11739 (if (looking-at ".*?|")
11740 (let ((pos (point))
11741 (noalign (looking-at "[^|\n\r]* |"))
11742 (c org-table-may-need-update))
11743 (replace-match (concat
11744 (substring (match-string 0) 1 -1)
11745 " |"))
11746 (goto-char pos)
11747 ;; noalign: if there were two spaces at the end, this field
11748 ;; does not determine the width of the column.
11749 (if noalign (setq org-table-may-need-update c)))
11750 (delete-char N))
11751 (delete-char N)
11752 (org-fix-tags-on-the-fly)))
11754 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11755 (put 'org-self-insert-command 'delete-selection t)
11756 (put 'orgtbl-self-insert-command 'delete-selection t)
11757 (put 'org-delete-char 'delete-selection 'supersede)
11758 (put 'org-delete-backward-char 'delete-selection 'supersede)
11760 ;; Make `flyspell-mode' delay after some commands
11761 (put 'org-self-insert-command 'flyspell-delayed t)
11762 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11763 (put 'org-delete-char 'flyspell-delayed t)
11764 (put 'org-delete-backward-char 'flyspell-delayed t)
11766 ;; Make pabbrev-mode expand after org-mode commands
11767 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11768 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11770 ;; How to do this: Measure non-white length of current string
11771 ;; If equal to column width, we should realign.
11773 (defun org-remap (map &rest commands)
11774 "In MAP, remap the functions given in COMMANDS.
11775 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11776 (let (new old)
11777 (while commands
11778 (setq old (pop commands) new (pop commands))
11779 (if (fboundp 'command-remapping)
11780 (org-defkey map (vector 'remap old) new)
11781 (substitute-key-definition old new map global-map)))))
11783 (when (eq org-enable-table-editor 'optimized)
11784 ;; If the user wants maximum table support, we need to hijack
11785 ;; some standard editing functions
11786 (org-remap org-mode-map
11787 'self-insert-command 'org-self-insert-command
11788 'delete-char 'org-delete-char
11789 'delete-backward-char 'org-delete-backward-char)
11790 (org-defkey org-mode-map "|" 'org-force-self-insert))
11792 (defun org-shiftcursor-error ()
11793 "Throw an error because Shift-Cursor command was applied in wrong context."
11794 (error "This command is active in special context like tables, headlines or timestamps"))
11796 (defun org-shifttab (&optional arg)
11797 "Global visibility cycling or move to previous table field.
11798 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11799 on context.
11800 See the individual commands for more information."
11801 (interactive "P")
11802 (cond
11803 ((org-at-table-p) (call-interactively 'org-table-previous-field))
11804 (arg (message "Content view to level: ")
11805 (org-content (prefix-numeric-value arg))
11806 (setq org-cycle-global-status 'overview))
11807 (t (call-interactively 'org-global-cycle))))
11809 (defun org-shiftmetaleft ()
11810 "Promote subtree or delete table column.
11811 Calls `org-promote-subtree', `org-outdent-item',
11812 or `org-table-delete-column', depending on context.
11813 See the individual commands for more information."
11814 (interactive)
11815 (cond
11816 ((org-at-table-p) (call-interactively 'org-table-delete-column))
11817 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
11818 ((org-at-item-p) (call-interactively 'org-outdent-item))
11819 (t (org-shiftcursor-error))))
11821 (defun org-shiftmetaright ()
11822 "Demote subtree or insert table column.
11823 Calls `org-demote-subtree', `org-indent-item',
11824 or `org-table-insert-column', depending on context.
11825 See the individual commands for more information."
11826 (interactive)
11827 (cond
11828 ((org-at-table-p) (call-interactively 'org-table-insert-column))
11829 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
11830 ((org-at-item-p) (call-interactively 'org-indent-item))
11831 (t (org-shiftcursor-error))))
11833 (defun org-shiftmetaup (&optional arg)
11834 "Move subtree up or kill table row.
11835 Calls `org-move-subtree-up' or `org-table-kill-row' or
11836 `org-move-item-up' depending on context. See the individual commands
11837 for more information."
11838 (interactive "P")
11839 (cond
11840 ((org-at-table-p) (call-interactively 'org-table-kill-row))
11841 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11842 ((org-at-item-p) (call-interactively 'org-move-item-up))
11843 (t (org-shiftcursor-error))))
11844 (defun org-shiftmetadown (&optional arg)
11845 "Move subtree down or insert table row.
11846 Calls `org-move-subtree-down' or `org-table-insert-row' or
11847 `org-move-item-down', depending on context. See the individual
11848 commands for more information."
11849 (interactive "P")
11850 (cond
11851 ((org-at-table-p) (call-interactively 'org-table-insert-row))
11852 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11853 ((org-at-item-p) (call-interactively 'org-move-item-down))
11854 (t (org-shiftcursor-error))))
11856 (defun org-metaleft (&optional arg)
11857 "Promote heading or move table column to left.
11858 Calls `org-do-promote' or `org-table-move-column', depending on context.
11859 With no specific context, calls the Emacs default `backward-word'.
11860 See the individual commands for more information."
11861 (interactive "P")
11862 (cond
11863 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
11864 ((or (org-on-heading-p) (org-region-active-p))
11865 (call-interactively 'org-do-promote))
11866 ((org-at-item-p) (call-interactively 'org-outdent-item))
11867 (t (call-interactively 'backward-word))))
11869 (defun org-metaright (&optional arg)
11870 "Demote subtree or move table column to right.
11871 Calls `org-do-demote' or `org-table-move-column', depending on context.
11872 With no specific context, calls the Emacs default `forward-word'.
11873 See the individual commands for more information."
11874 (interactive "P")
11875 (cond
11876 ((org-at-table-p) (call-interactively 'org-table-move-column))
11877 ((or (org-on-heading-p) (org-region-active-p))
11878 (call-interactively 'org-do-demote))
11879 ((org-at-item-p) (call-interactively 'org-indent-item))
11880 (t (call-interactively 'forward-word))))
11882 (defun org-metaup (&optional arg)
11883 "Move subtree up or move table row up.
11884 Calls `org-move-subtree-up' or `org-table-move-row' or
11885 `org-move-item-up', depending on context. See the individual commands
11886 for more information."
11887 (interactive "P")
11888 (cond
11889 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
11890 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11891 ((org-at-item-p) (call-interactively 'org-move-item-up))
11892 (t (transpose-lines 1) (beginning-of-line -1))))
11894 (defun org-metadown (&optional arg)
11895 "Move subtree down or move table row down.
11896 Calls `org-move-subtree-down' or `org-table-move-row' or
11897 `org-move-item-down', depending on context. See the individual
11898 commands for more information."
11899 (interactive "P")
11900 (cond
11901 ((org-at-table-p) (call-interactively 'org-table-move-row))
11902 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11903 ((org-at-item-p) (call-interactively 'org-move-item-down))
11904 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
11906 (defun org-shiftup (&optional arg)
11907 "Increase item in timestamp or increase priority of current headline.
11908 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
11909 depending on context. See the individual commands for more information."
11910 (interactive "P")
11911 (cond
11912 ((org-at-timestamp-p t)
11913 (call-interactively (if org-edit-timestamp-down-means-later
11914 'org-timestamp-down 'org-timestamp-up)))
11915 ((org-on-heading-p) (call-interactively 'org-priority-up))
11916 ((org-at-item-p) (call-interactively 'org-previous-item))
11917 ((org-clocktable-try-shift 'up arg))
11918 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
11920 (defun org-shiftdown (&optional arg)
11921 "Decrease item in timestamp or decrease priority of current headline.
11922 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
11923 depending on context. See the individual commands for more information."
11924 (interactive "P")
11925 (cond
11926 ((org-at-timestamp-p t)
11927 (call-interactively (if org-edit-timestamp-down-means-later
11928 'org-timestamp-up 'org-timestamp-down)))
11929 ((org-on-heading-p) (call-interactively 'org-priority-down))
11930 ((org-clocktable-try-shift 'down arg))
11931 (t (call-interactively 'org-next-item))))
11933 (defun org-shiftright (&optional arg)
11934 "Next TODO keyword or timestamp one day later, depending on context."
11935 (interactive "P")
11936 (cond
11937 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
11938 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
11939 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
11940 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
11941 ((org-clocktable-try-shift 'right arg))
11942 (t (org-shiftcursor-error))))
11944 (defun org-shiftleft (&optional arg)
11945 "Previous TODO keyword or timestamp one day earlier, depending on context."
11946 (interactive "P")
11947 (cond
11948 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
11949 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
11950 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
11951 ((org-at-property-p)
11952 (call-interactively 'org-property-previous-allowed-value))
11953 ((org-clocktable-try-shift 'left arg))
11954 (t (org-shiftcursor-error))))
11956 (defun org-shiftcontrolright ()
11957 "Switch to next TODO set."
11958 (interactive)
11959 (cond
11960 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
11961 (t (org-shiftcursor-error))))
11963 (defun org-shiftcontrolleft ()
11964 "Switch to previous TODO set."
11965 (interactive)
11966 (cond
11967 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
11968 (t (org-shiftcursor-error))))
11970 (defun org-ctrl-c-ret ()
11971 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
11972 (interactive)
11973 (cond
11974 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
11975 (t (call-interactively 'org-insert-heading))))
11977 (defun org-copy-special ()
11978 "Copy region in table or copy current subtree.
11979 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11980 See the individual commands for more information."
11981 (interactive)
11982 (call-interactively
11983 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11985 (defun org-cut-special ()
11986 "Cut region in table or cut current subtree.
11987 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11988 See the individual commands for more information."
11989 (interactive)
11990 (call-interactively
11991 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11993 (defun org-paste-special (arg)
11994 "Paste rectangular region into table, or past subtree relative to level.
11995 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11996 See the individual commands for more information."
11997 (interactive "P")
11998 (if (org-at-table-p)
11999 (org-table-paste-rectangle)
12000 (org-paste-subtree arg)))
12002 (defun org-ctrl-c-ctrl-c (&optional arg)
12003 "Set tags in headline, or update according to changed information at point.
12005 This command does many different things, depending on context:
12007 - If the cursor is in a headline, prompt for tags and insert them
12008 into the current line, aligned to `org-tags-column'. When called
12009 with prefix arg, realign all tags in the current buffer.
12011 - If the cursor is in one of the special #+KEYWORD lines, this
12012 triggers scanning the buffer for these lines and updating the
12013 information.
12015 - If the cursor is inside a table, realign the table. This command
12016 works even if the automatic table editor has been turned off.
12018 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12019 the entire table.
12021 - If the cursor is a the beginning of a dynamic block, update it.
12023 - If the cursor is inside a table created by the table.el package,
12024 activate that table.
12026 - If the current buffer is a remember buffer, close note and file it.
12027 with a prefix argument, file it without further interaction to the default
12028 location.
12030 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12031 links in this buffer.
12033 - If the cursor is on a numbered item in a plain list, renumber the
12034 ordered list.
12036 - If the cursor is on a checkbox, toggle it."
12037 (interactive "P")
12038 (let ((org-enable-table-editor t))
12039 (cond
12040 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12041 org-occur-highlights
12042 org-latex-fragment-image-overlays)
12043 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12044 (org-remove-occur-highlights)
12045 (org-remove-latex-fragment-image-overlays)
12046 (message "Temporary highlights/overlays removed from current buffer"))
12047 ((and (local-variable-p 'org-finish-function (current-buffer))
12048 (fboundp org-finish-function))
12049 (funcall org-finish-function))
12050 ((org-at-property-p)
12051 (call-interactively 'org-property-action))
12052 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12053 ((org-on-heading-p) (call-interactively 'org-set-tags))
12054 ((org-at-table.el-p)
12055 (require 'table)
12056 (beginning-of-line 1)
12057 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12058 (call-interactively 'table-recognize-table))
12059 ((org-at-table-p)
12060 (org-table-maybe-eval-formula)
12061 (if arg
12062 (call-interactively 'org-table-recalculate)
12063 (org-table-maybe-recalculate-line))
12064 (call-interactively 'org-table-align))
12065 ((org-at-item-checkbox-p)
12066 (call-interactively 'org-toggle-checkbox))
12067 ((org-at-item-p)
12068 (call-interactively 'org-maybe-renumber-ordered-list))
12069 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12070 ;; Dynamic block
12071 (beginning-of-line 1)
12072 (org-update-dblock))
12073 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12074 (cond
12075 ((equal (match-string 1) "TBLFM")
12076 ;; Recalculate the table before this line
12077 (save-excursion
12078 (beginning-of-line 1)
12079 (skip-chars-backward " \r\n\t")
12080 (if (org-at-table-p)
12081 (org-call-with-arg 'org-table-recalculate t))))
12083 (call-interactively 'org-mode-restart))))
12084 (t (error "C-c C-c can do nothing useful at this location.")))))
12086 (defun org-mode-restart ()
12087 "Restart Org-mode, to scan again for special lines.
12088 Also updates the keyword regular expressions."
12089 (interactive)
12090 (let ((org-inhibit-startup t)) (org-mode))
12091 (message "Org-mode restarted to refresh keyword and special line setup"))
12093 (defun org-kill-note-or-show-branches ()
12094 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12095 (interactive)
12096 (if (not org-finish-function)
12097 (call-interactively 'show-branches)
12098 (let ((org-note-abort t))
12099 (funcall org-finish-function))))
12101 (defun org-return (&optional indent)
12102 "Goto next table row or insert a newline.
12103 Calls `org-table-next-row' or `newline', depending on context.
12104 See the individual commands for more information."
12105 (interactive)
12106 (cond
12107 ((bobp) (if indent (newline-and-indent) (newline)))
12108 ((and (org-at-heading-p)
12109 (looking-at
12110 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12111 (org-show-entry)
12112 (end-of-line 1)
12113 (newline))
12114 ((org-at-table-p)
12115 (org-table-justify-field-maybe)
12116 (call-interactively 'org-table-next-row))
12117 (t (if indent (newline-and-indent) (newline)))))
12119 (defun org-return-indent ()
12120 "Goto next table row or insert a newline and indent.
12121 Calls `org-table-next-row' or `newline-and-indent', depending on
12122 context. See the individual commands for more information."
12123 (interactive)
12124 (org-return t))
12126 (defun org-ctrl-c-star ()
12127 "Compute table, or change heading status of lines.
12128 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12129 depending on context. This will also turn a plain list item or a normal
12130 line into a subheading."
12131 (interactive)
12132 (cond
12133 ((org-at-table-p)
12134 (call-interactively 'org-table-recalculate))
12135 ((org-region-active-p)
12136 ;; Convert all lines in region to list items
12137 (call-interactively 'org-toggle-region-headings))
12138 ((org-on-heading-p)
12139 (org-toggle-region-headings (point-at-bol)
12140 (min (1+ (point-at-eol)) (point-max))))
12141 ((org-at-item-p)
12142 ;; Convert to heading
12143 (let ((level (save-match-data
12144 (save-excursion
12145 (condition-case nil
12146 (progn
12147 (org-back-to-heading t)
12148 (funcall outline-level))
12149 (error 0))))))
12150 (replace-match
12151 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12152 (t (org-toggle-region-headings (point-at-bol)
12153 (min (1+ (point-at-eol)) (point-max))))))
12155 (defun org-ctrl-c-minus ()
12156 "Insert separator line in table or modify bullet status of line.
12157 Also turns a plain line or a region of lines into list items.
12158 Calls `org-table-insert-hline', `org-toggle-region-items', or
12159 `org-cycle-list-bullet', depending on context."
12160 (interactive)
12161 (cond
12162 ((org-at-table-p)
12163 (call-interactively 'org-table-insert-hline))
12164 ((org-on-heading-p)
12165 ;; Convert to item
12166 (save-excursion
12167 (beginning-of-line 1)
12168 (if (looking-at "\\*+ ")
12169 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12170 ((org-region-active-p)
12171 ;; Convert all lines in region to list items
12172 (call-interactively 'org-toggle-region-items))
12173 ((org-in-item-p)
12174 (call-interactively 'org-cycle-list-bullet))
12175 (t (org-toggle-region-items (point-at-bol)
12176 (min (1+ (point-at-eol)) (point-max))))))
12178 (defun org-toggle-region-items (beg end)
12179 "Convert all lines in region to list items.
12180 If the first line is already an item, convert all list items in the region
12181 to normal lines."
12182 (interactive "r")
12183 (let (l2 l)
12184 (save-excursion
12185 (goto-char end)
12186 (setq l2 (org-current-line))
12187 (goto-char beg)
12188 (beginning-of-line 1)
12189 (setq l (1- (org-current-line)))
12190 (if (org-at-item-p)
12191 ;; We already have items, de-itemize
12192 (while (< (setq l (1+ l)) l2)
12193 (when (org-at-item-p)
12194 (goto-char (match-beginning 2))
12195 (delete-region (match-beginning 2) (match-end 2))
12196 (and (looking-at "[ \t]+") (replace-match "")))
12197 (beginning-of-line 2))
12198 (while (< (setq l (1+ l)) l2)
12199 (unless (org-at-item-p)
12200 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12201 (replace-match "\\1- \\2")))
12202 (beginning-of-line 2))))))
12204 (defun org-toggle-region-headings (beg end)
12205 "Convert all lines in region to list items.
12206 If the first line is already an item, convert all list items in the region
12207 to normal lines."
12208 (interactive "r")
12209 (let (l2 l)
12210 (save-excursion
12211 (goto-char end)
12212 (setq l2 (org-current-line))
12213 (goto-char beg)
12214 (beginning-of-line 1)
12215 (setq l (1- (org-current-line)))
12216 (if (org-on-heading-p)
12217 ;; We already have headlines, de-star them
12218 (while (< (setq l (1+ l)) l2)
12219 (when (org-on-heading-p t)
12220 (and (looking-at outline-regexp) (replace-match "")))
12221 (beginning-of-line 2))
12222 (let* ((stars (save-excursion
12223 (re-search-backward org-complex-heading-regexp nil t)
12224 (or (match-string 1) "*")))
12225 (add-stars (if org-odd-levels-only "**" "*"))
12226 (rpl (concat stars add-stars " \\2")))
12227 (while (< (setq l (1+ l)) l2)
12228 (unless (org-on-heading-p)
12229 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12230 (replace-match rpl)))
12231 (beginning-of-line 2)))))))
12233 (defun org-meta-return (&optional arg)
12234 "Insert a new heading or wrap a region in a table.
12235 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12236 See the individual commands for more information."
12237 (interactive "P")
12238 (cond
12239 ((org-at-table-p)
12240 (call-interactively 'org-table-wrap-region))
12241 (t (call-interactively 'org-insert-heading))))
12243 ;;; Menu entries
12245 ;; Define the Org-mode menus
12246 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12247 '("Tbl"
12248 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12249 ["Next Field" org-cycle (org-at-table-p)]
12250 ["Previous Field" org-shifttab (org-at-table-p)]
12251 ["Next Row" org-return (org-at-table-p)]
12252 "--"
12253 ["Blank Field" org-table-blank-field (org-at-table-p)]
12254 ["Edit Field" org-table-edit-field (org-at-table-p)]
12255 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12256 "--"
12257 ("Column"
12258 ["Move Column Left" org-metaleft (org-at-table-p)]
12259 ["Move Column Right" org-metaright (org-at-table-p)]
12260 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12261 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12262 ("Row"
12263 ["Move Row Up" org-metaup (org-at-table-p)]
12264 ["Move Row Down" org-metadown (org-at-table-p)]
12265 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12266 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12267 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12268 "--"
12269 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12270 ("Rectangle"
12271 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12272 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12273 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12274 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12275 "--"
12276 ("Calculate"
12277 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12278 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12279 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12280 "--"
12281 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12282 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12283 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12284 "--"
12285 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12286 "--"
12287 ["Sum Column/Rectangle" org-table-sum
12288 (or (org-at-table-p) (org-region-active-p))]
12289 ["Which Column?" org-table-current-column (org-at-table-p)])
12290 ["Debug Formulas"
12291 org-table-toggle-formula-debugger
12292 :style toggle :selected org-table-formula-debug]
12293 ["Show Col/Row Numbers"
12294 org-table-toggle-coordinate-overlays
12295 :style toggle :selected org-table-overlay-coordinates]
12296 "--"
12297 ["Create" org-table-create (and (not (org-at-table-p))
12298 org-enable-table-editor)]
12299 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12300 ["Import from File" org-table-import (not (org-at-table-p))]
12301 ["Export to File" org-table-export (org-at-table-p)]
12302 "--"
12303 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12305 (easy-menu-define org-org-menu org-mode-map "Org menu"
12306 '("Org"
12307 ("Show/Hide"
12308 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12309 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12310 ["Sparse Tree..." org-sparse-tree t]
12311 ["Reveal Context" org-reveal t]
12312 ["Show All" show-all t]
12313 "--"
12314 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12315 "--"
12316 ["New Heading" org-insert-heading t]
12317 ("Navigate Headings"
12318 ["Up" outline-up-heading t]
12319 ["Next" outline-next-visible-heading t]
12320 ["Previous" outline-previous-visible-heading t]
12321 ["Next Same Level" outline-forward-same-level t]
12322 ["Previous Same Level" outline-backward-same-level t]
12323 "--"
12324 ["Jump" org-goto t])
12325 ("Edit Structure"
12326 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12327 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12328 "--"
12329 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12330 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12331 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12332 "--"
12333 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12334 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12335 ["Demote Heading" org-metaright (not (org-at-table-p))]
12336 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12337 "--"
12338 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12339 "--"
12340 ["Convert to odd levels" org-convert-to-odd-levels t]
12341 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12342 ("Editing"
12343 ["Emphasis..." org-emphasize t])
12344 ("Archive"
12345 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12346 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12347 ; :active t :keys "C-u C-c C-x C-a"]
12348 ["Sparse trees open ARCHIVE trees"
12349 (setq org-sparse-tree-open-archived-trees
12350 (not org-sparse-tree-open-archived-trees))
12351 :style toggle :selected org-sparse-tree-open-archived-trees]
12352 ["Cycling opens ARCHIVE trees"
12353 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12354 :style toggle :selected org-cycle-open-archived-trees]
12355 ["Agenda includes ARCHIVE trees"
12356 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12357 :style toggle :selected (not org-agenda-skip-archived-trees)]
12358 "--"
12359 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12360 ; ["Check and Move Children" (org-archive-subtree '(4))
12361 ; :active t :keys "C-u C-c C-x C-s"]
12363 "--"
12364 ("TODO Lists"
12365 ["TODO/DONE/-" org-todo t]
12366 ("Select keyword"
12367 ["Next keyword" org-shiftright (org-on-heading-p)]
12368 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12369 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12370 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12371 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12372 ["Show TODO Tree" org-show-todo-tree t]
12373 ["Global TODO list" org-todo-list t]
12374 "--"
12375 ["Set Priority" org-priority t]
12376 ["Priority Up" org-shiftup t]
12377 ["Priority Down" org-shiftdown t])
12378 ("TAGS and Properties"
12379 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12380 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12381 "--"
12382 ["Set property" 'org-set-property t]
12383 ["Column view of properties" org-columns t]
12384 ["Insert Column View DBlock" org-insert-columns-dblock t])
12385 ("Dates and Scheduling"
12386 ["Timestamp" org-time-stamp t]
12387 ["Timestamp (inactive)" org-time-stamp-inactive t]
12388 ("Change Date"
12389 ["1 Day Later" org-shiftright t]
12390 ["1 Day Earlier" org-shiftleft t]
12391 ["1 ... Later" org-shiftup t]
12392 ["1 ... Earlier" org-shiftdown t])
12393 ["Compute Time Range" org-evaluate-time-range t]
12394 ["Schedule Item" org-schedule t]
12395 ["Deadline" org-deadline t]
12396 "--"
12397 ["Custom time format" org-toggle-time-stamp-overlays
12398 :style radio :selected org-display-custom-times]
12399 "--"
12400 ["Goto Calendar" org-goto-calendar t]
12401 ["Date from Calendar" org-date-from-calendar t])
12402 ("Logging work"
12403 ["Clock in" org-clock-in t]
12404 ["Clock out" org-clock-out t]
12405 ["Clock cancel" org-clock-cancel t]
12406 ["Goto running clock" org-clock-goto t]
12407 ["Display times" org-clock-display t]
12408 ["Create clock table" org-clock-report t]
12409 "--"
12410 ["Record DONE time"
12411 (progn (setq org-log-done (not org-log-done))
12412 (message "Switching to %s will %s record a timestamp"
12413 (car org-done-keywords)
12414 (if org-log-done "automatically" "not")))
12415 :style toggle :selected org-log-done])
12416 "--"
12417 ["Agenda Command..." org-agenda t]
12418 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12419 ("File List for Agenda")
12420 ("Special views current file"
12421 ["TODO Tree" org-show-todo-tree t]
12422 ["Check Deadlines" org-check-deadlines t]
12423 ["Timeline" org-timeline t]
12424 ["Tags Tree" org-tags-sparse-tree t])
12425 "--"
12426 ("Hyperlinks"
12427 ["Store Link (Global)" org-store-link t]
12428 ["Insert Link" org-insert-link t]
12429 ["Follow Link" org-open-at-point t]
12430 "--"
12431 ["Next link" org-next-link t]
12432 ["Previous link" org-previous-link t]
12433 "--"
12434 ["Descriptive Links"
12435 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12436 :style radio
12437 :selected (member '(org-link) buffer-invisibility-spec)]
12438 ["Literal Links"
12439 (progn
12440 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12441 :style radio
12442 :selected (not (member '(org-link) buffer-invisibility-spec))])
12443 "--"
12444 ["Export/Publish..." org-export t]
12445 ("LaTeX"
12446 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12447 :selected org-cdlatex-mode]
12448 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12449 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12450 ["Modify math symbol" org-cdlatex-math-modify
12451 (org-inside-LaTeX-fragment-p)]
12452 ["Export LaTeX fragments as images"
12453 (if (featurep 'org-exp)
12454 (setq org-export-with-LaTeX-fragments
12455 (not org-export-with-LaTeX-fragments))
12456 (require 'org-exp))
12457 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12458 org-export-with-LaTeX-fragments)])
12459 "--"
12460 ("Documentation"
12461 ["Show Version" org-version t]
12462 ["Info Documentation" org-info t])
12463 ("Customize"
12464 ["Browse Org Group" org-customize t]
12465 "--"
12466 ["Expand This Menu" org-create-customize-menu
12467 (fboundp 'customize-menu-create)])
12468 "--"
12469 ["Refresh setup" org-mode-restart t]
12472 (defun org-info (&optional node)
12473 "Read documentation for Org-mode in the info system.
12474 With optional NODE, go directly to that node."
12475 (interactive)
12476 (info (format "(org)%s" (or node ""))))
12478 (defun org-install-agenda-files-menu ()
12479 (let ((bl (buffer-list)))
12480 (save-excursion
12481 (while bl
12482 (set-buffer (pop bl))
12483 (if (org-mode-p) (setq bl nil)))
12484 (when (org-mode-p)
12485 (easy-menu-change
12486 '("Org") "File List for Agenda"
12487 (append
12488 (list
12489 ["Edit File List" (org-edit-agenda-file-list) t]
12490 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12491 ["Remove Current File from List" org-remove-file t]
12492 ["Cycle through agenda files" org-cycle-agenda-files t]
12493 ["Occur in all agenda files" org-occur-in-agenda-files t]
12494 "--")
12495 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12497 ;;;; Documentation
12499 (defun org-require-autoloaded-modules ()
12500 (interactive)
12501 (mapc 'require
12502 '(org-agenda org-archive org-clock org-colview
12503 org-exp org-export-latex org-publish
12504 org-remember org-table)))
12506 (defun org-customize ()
12507 "Call the customize function with org as argument."
12508 (interactive)
12509 (org-load-modules-maybe)
12510 (org-require-autoloaded-modules)
12511 (customize-browse 'org))
12513 (defun org-create-customize-menu ()
12514 "Create a full customization menu for Org-mode, insert it into the menu."
12515 (interactive)
12516 (org-load-modules-maybe)
12517 (org-require-autoloaded-modules)
12518 (if (fboundp 'customize-menu-create)
12519 (progn
12520 (easy-menu-change
12521 '("Org") "Customize"
12522 `(["Browse Org group" org-customize t]
12523 "--"
12524 ,(customize-menu-create 'org)
12525 ["Set" Custom-set t]
12526 ["Save" Custom-save t]
12527 ["Reset to Current" Custom-reset-current t]
12528 ["Reset to Saved" Custom-reset-saved t]
12529 ["Reset to Standard Settings" Custom-reset-standard t]))
12530 (message "\"Org\"-menu now contains full customization menu"))
12531 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12533 ;;;; Miscellaneous stuff
12535 ;;; Generally useful functions
12537 (defun org-plist-delete (plist property)
12538 "Delete PROPERTY from PLIST.
12539 This is in contrast to merely setting it to 0."
12540 (let (p)
12541 (while plist
12542 (if (not (eq property (car plist)))
12543 (setq p (plist-put p (car plist) (nth 1 plist))))
12544 (setq plist (cddr plist)))
12547 (defun org-force-self-insert (N)
12548 "Needed to enforce self-insert under remapping."
12549 (interactive "p")
12550 (self-insert-command N))
12552 (defun org-string-width (s)
12553 "Compute width of string, ignoring invisible characters.
12554 This ignores character with invisibility property `org-link', and also
12555 characters with property `org-cwidth', because these will become invisible
12556 upon the next fontification round."
12557 (let (b l)
12558 (when (or (eq t buffer-invisibility-spec)
12559 (assq 'org-link buffer-invisibility-spec))
12560 (while (setq b (text-property-any 0 (length s)
12561 'invisible 'org-link s))
12562 (setq s (concat (substring s 0 b)
12563 (substring s (or (next-single-property-change
12564 b 'invisible s) (length s)))))))
12565 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12566 (setq s (concat (substring s 0 b)
12567 (substring s (or (next-single-property-change
12568 b 'org-cwidth s) (length s))))))
12569 (setq l (string-width s) b -1)
12570 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12571 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12575 (defun org-trim (s)
12576 "Remove whitespace at beginning and end of string."
12577 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12578 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12581 (defun org-wrap (string &optional width lines)
12582 "Wrap string to either a number of lines, or a width in characters.
12583 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12584 that costs. If there is a word longer than WIDTH, the text is actually
12585 wrapped to the length of that word.
12586 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12587 many lines, whatever width that takes.
12588 The return value is a list of lines, without newlines at the end."
12589 (let* ((words (org-split-string string "[ \t\n]+"))
12590 (maxword (apply 'max (mapcar 'org-string-width words)))
12591 w ll)
12592 (cond (width
12593 (org-do-wrap words (max maxword width)))
12594 (lines
12595 (setq w maxword)
12596 (setq ll (org-do-wrap words maxword))
12597 (if (<= (length ll) lines)
12599 (setq ll words)
12600 (while (> (length ll) lines)
12601 (setq w (1+ w))
12602 (setq ll (org-do-wrap words w)))
12603 ll))
12604 (t (error "Cannot wrap this")))))
12606 (defun org-do-wrap (words width)
12607 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12608 (let (lines line)
12609 (while words
12610 (setq line (pop words))
12611 (while (and words (< (+ (length line) (length (car words))) width))
12612 (setq line (concat line " " (pop words))))
12613 (setq lines (push line lines)))
12614 (nreverse lines)))
12616 (defun org-split-string (string &optional separators)
12617 "Splits STRING into substrings at SEPARATORS.
12618 No empty strings are returned if there are matches at the beginning
12619 and end of string."
12620 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12621 (start 0)
12622 notfirst
12623 (list nil))
12624 (while (and (string-match rexp string
12625 (if (and notfirst
12626 (= start (match-beginning 0))
12627 (< start (length string)))
12628 (1+ start) start))
12629 (< (match-beginning 0) (length string)))
12630 (setq notfirst t)
12631 (or (eq (match-beginning 0) 0)
12632 (and (eq (match-beginning 0) (match-end 0))
12633 (eq (match-beginning 0) start))
12634 (setq list
12635 (cons (substring string start (match-beginning 0))
12636 list)))
12637 (setq start (match-end 0)))
12638 (or (eq start (length string))
12639 (setq list
12640 (cons (substring string start)
12641 list)))
12642 (nreverse list)))
12644 (defun org-context ()
12645 "Return a list of contexts of the current cursor position.
12646 If several contexts apply, all are returned.
12647 Each context entry is a list with a symbol naming the context, and
12648 two positions indicating start and end of the context. Possible
12649 contexts are:
12651 :headline anywhere in a headline
12652 :headline-stars on the leading stars in a headline
12653 :todo-keyword on a TODO keyword (including DONE) in a headline
12654 :tags on the TAGS in a headline
12655 :priority on the priority cookie in a headline
12656 :item on the first line of a plain list item
12657 :item-bullet on the bullet/number of a plain list item
12658 :checkbox on the checkbox in a plain list item
12659 :table in an org-mode table
12660 :table-special on a special filed in a table
12661 :table-table in a table.el table
12662 :link on a hyperlink
12663 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12664 :target on a <<target>>
12665 :radio-target on a <<<radio-target>>>
12666 :latex-fragment on a LaTeX fragment
12667 :latex-preview on a LaTeX fragment with overlayed preview image
12669 This function expects the position to be visible because it uses font-lock
12670 faces as a help to recognize the following contexts: :table-special, :link,
12671 and :keyword."
12672 (let* ((f (get-text-property (point) 'face))
12673 (faces (if (listp f) f (list f)))
12674 (p (point)) clist o)
12675 ;; First the large context
12676 (cond
12677 ((org-on-heading-p t)
12678 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12679 (when (progn
12680 (beginning-of-line 1)
12681 (looking-at org-todo-line-tags-regexp))
12682 (push (org-point-in-group p 1 :headline-stars) clist)
12683 (push (org-point-in-group p 2 :todo-keyword) clist)
12684 (push (org-point-in-group p 4 :tags) clist))
12685 (goto-char p)
12686 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12687 (if (looking-at "\\[#[A-Z0-9]\\]")
12688 (push (org-point-in-group p 0 :priority) clist)))
12690 ((org-at-item-p)
12691 (push (org-point-in-group p 2 :item-bullet) clist)
12692 (push (list :item (point-at-bol)
12693 (save-excursion (org-end-of-item) (point)))
12694 clist)
12695 (and (org-at-item-checkbox-p)
12696 (push (org-point-in-group p 0 :checkbox) clist)))
12698 ((org-at-table-p)
12699 (push (list :table (org-table-begin) (org-table-end)) clist)
12700 (if (memq 'org-formula faces)
12701 (push (list :table-special
12702 (previous-single-property-change p 'face)
12703 (next-single-property-change p 'face)) clist)))
12704 ((org-at-table-p 'any)
12705 (push (list :table-table) clist)))
12706 (goto-char p)
12708 ;; Now the small context
12709 (cond
12710 ((org-at-timestamp-p)
12711 (push (org-point-in-group p 0 :timestamp) clist))
12712 ((memq 'org-link faces)
12713 (push (list :link
12714 (previous-single-property-change p 'face)
12715 (next-single-property-change p 'face)) clist))
12716 ((memq 'org-special-keyword faces)
12717 (push (list :keyword
12718 (previous-single-property-change p 'face)
12719 (next-single-property-change p 'face)) clist))
12720 ((org-on-target-p)
12721 (push (org-point-in-group p 0 :target) clist)
12722 (goto-char (1- (match-beginning 0)))
12723 (if (looking-at org-radio-target-regexp)
12724 (push (org-point-in-group p 0 :radio-target) clist))
12725 (goto-char p))
12726 ((setq o (car (delq nil
12727 (mapcar
12728 (lambda (x)
12729 (if (memq x org-latex-fragment-image-overlays) x))
12730 (org-overlays-at (point))))))
12731 (push (list :latex-fragment
12732 (org-overlay-start o) (org-overlay-end o)) clist)
12733 (push (list :latex-preview
12734 (org-overlay-start o) (org-overlay-end o)) clist))
12735 ((org-inside-LaTeX-fragment-p)
12736 ;; FIXME: positions wrong.
12737 (push (list :latex-fragment (point) (point)) clist)))
12739 (setq clist (nreverse (delq nil clist)))
12740 clist))
12742 ;; FIXME: Compare with at-regexp-p Do we need both?
12743 (defun org-in-regexp (re &optional nlines visually)
12744 "Check if point is inside a match of regexp.
12745 Normally only the current line is checked, but you can include NLINES extra
12746 lines both before and after point into the search.
12747 If VISUALLY is set, require that the cursor is not after the match but
12748 really on, so that the block visually is on the match."
12749 (catch 'exit
12750 (let ((pos (point))
12751 (eol (point-at-eol (+ 1 (or nlines 0))))
12752 (inc (if visually 1 0)))
12753 (save-excursion
12754 (beginning-of-line (- 1 (or nlines 0)))
12755 (while (re-search-forward re eol t)
12756 (if (and (<= (match-beginning 0) pos)
12757 (>= (+ inc (match-end 0)) pos))
12758 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12760 (defun org-at-regexp-p (regexp)
12761 "Is point inside a match of REGEXP in the current line?"
12762 (catch 'exit
12763 (save-excursion
12764 (let ((pos (point)) (end (point-at-eol)))
12765 (beginning-of-line 1)
12766 (while (re-search-forward regexp end t)
12767 (if (and (<= (match-beginning 0) pos)
12768 (>= (match-end 0) pos))
12769 (throw 'exit t)))
12770 nil))))
12772 (defun org-occur-in-agenda-files (regexp &optional nlines)
12773 "Call `multi-occur' with buffers for all agenda files."
12774 (interactive "sOrg-files matching: \np")
12775 (let* ((files (org-agenda-files))
12776 (tnames (mapcar 'file-truename files))
12777 (extra org-agenda-text-search-extra-files)
12779 (while (setq f (pop extra))
12780 (unless (member (file-truename f) tnames)
12781 (add-to-list 'files f 'append)
12782 (add-to-list 'tnames (file-truename f) 'append)))
12783 (multi-occur
12784 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
12785 regexp)))
12787 (if (boundp 'occur-mode-find-occurrence-hook)
12788 ;; Emacs 23
12789 (add-hook 'occur-mode-find-occurrence-hook
12790 (lambda ()
12791 (when (org-mode-p)
12792 (org-reveal))))
12793 ;; Emacs 22
12794 (defadvice occur-mode-goto-occurrence
12795 (after org-occur-reveal activate)
12796 (and (org-mode-p) (org-reveal)))
12797 (defadvice occur-mode-goto-occurrence-other-window
12798 (after org-occur-reveal activate)
12799 (and (org-mode-p) (org-reveal)))
12800 (defadvice occur-mode-display-occurrence
12801 (after org-occur-reveal activate)
12802 (when (org-mode-p)
12803 (let ((pos (occur-mode-find-occurrence)))
12804 (with-current-buffer (marker-buffer pos)
12805 (save-excursion
12806 (goto-char pos)
12807 (org-reveal)))))))
12809 (defun org-uniquify (list)
12810 "Remove duplicate elements from LIST."
12811 (let (res)
12812 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
12813 res))
12815 (defun org-delete-all (elts list)
12816 "Remove all elements in ELTS from LIST."
12817 (while elts
12818 (setq list (delete (pop elts) list)))
12819 list)
12821 (defun org-back-over-empty-lines ()
12822 "Move backwards over witespace, to the beginning of the first empty line.
12823 Returns the number of empty lines passed."
12824 (let ((pos (point)))
12825 (skip-chars-backward " \t\n\r")
12826 (beginning-of-line 2)
12827 (goto-char (min (point) pos))
12828 (count-lines (point) pos)))
12830 (defun org-skip-whitespace ()
12831 (skip-chars-forward " \t\n\r"))
12833 (defun org-point-in-group (point group &optional context)
12834 "Check if POINT is in match-group GROUP.
12835 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
12836 match. If the match group does ot exist or point is not inside it,
12837 return nil."
12838 (and (match-beginning group)
12839 (>= point (match-beginning group))
12840 (<= point (match-end group))
12841 (if context
12842 (list context (match-beginning group) (match-end group))
12843 t)))
12845 (defun org-switch-to-buffer-other-window (&rest args)
12846 "Switch to buffer in a second window on the current frame.
12847 In particular, do not allow pop-up frames."
12848 (let (pop-up-frames special-display-buffer-names special-display-regexps
12849 special-display-function)
12850 (apply 'switch-to-buffer-other-window args)))
12852 (defun org-combine-plists (&rest plists)
12853 "Create a single property list from all plists in PLISTS.
12854 The process starts by copying the first list, and then setting properties
12855 from the other lists. Settings in the last list are the most significant
12856 ones and overrule settings in the other lists."
12857 (let ((rtn (copy-sequence (pop plists)))
12858 p v ls)
12859 (while plists
12860 (setq ls (pop plists))
12861 (while ls
12862 (setq p (pop ls) v (pop ls))
12863 (setq rtn (plist-put rtn p v))))
12864 rtn))
12866 (defun org-move-line-down (arg)
12867 "Move the current line down. With prefix argument, move it past ARG lines."
12868 (interactive "p")
12869 (let ((col (current-column))
12870 beg end pos)
12871 (beginning-of-line 1) (setq beg (point))
12872 (beginning-of-line 2) (setq end (point))
12873 (beginning-of-line (+ 1 arg))
12874 (setq pos (move-marker (make-marker) (point)))
12875 (insert (delete-and-extract-region beg end))
12876 (goto-char pos)
12877 (move-to-column col)))
12879 (defun org-move-line-up (arg)
12880 "Move the current line up. With prefix argument, move it past ARG lines."
12881 (interactive "p")
12882 (let ((col (current-column))
12883 beg end pos)
12884 (beginning-of-line 1) (setq beg (point))
12885 (beginning-of-line 2) (setq end (point))
12886 (beginning-of-line (- arg))
12887 (setq pos (move-marker (make-marker) (point)))
12888 (insert (delete-and-extract-region beg end))
12889 (goto-char pos)
12890 (move-to-column col)))
12892 (defun org-replace-escapes (string table)
12893 "Replace %-escapes in STRING with values in TABLE.
12894 TABLE is an association list with keys like \"%a\" and string values.
12895 The sequences in STRING may contain normal field width and padding information,
12896 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
12897 so values can contain further %-escapes if they are define later in TABLE."
12898 (let ((case-fold-search nil)
12899 e re rpl)
12900 (while (setq e (pop table))
12901 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
12902 (while (string-match re string)
12903 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
12904 (cdr e)))
12905 (setq string (replace-match rpl t t string))))
12906 string))
12909 (defun org-sublist (list start end)
12910 "Return a section of LIST, from START to END.
12911 Counting starts at 1."
12912 (let (rtn (c start))
12913 (setq list (nthcdr (1- start) list))
12914 (while (and list (<= c end))
12915 (push (pop list) rtn)
12916 (setq c (1+ c)))
12917 (nreverse rtn)))
12919 (defun org-find-base-buffer-visiting (file)
12920 "Like `find-buffer-visiting' but alway return the base buffer and
12921 not an indirect buffer."
12922 (let ((buf (find-buffer-visiting file)))
12923 (if buf
12924 (or (buffer-base-buffer buf) buf)
12925 nil)))
12927 (defun org-image-file-name-regexp ()
12928 "Return regexp matching the file names of images."
12929 (if (fboundp 'image-file-name-regexp)
12930 (image-file-name-regexp)
12931 (let ((image-file-name-extensions
12932 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12933 "xbm" "xpm" "pbm" "pgm" "ppm")))
12934 (concat "\\."
12935 (regexp-opt (nconc (mapcar 'upcase
12936 image-file-name-extensions)
12937 image-file-name-extensions)
12939 "\\'"))))
12941 (defun org-file-image-p (file)
12942 "Return non-nil if FILE is an image."
12943 (save-match-data
12944 (string-match (org-image-file-name-regexp) file)))
12946 ;;; Paragraph filling stuff.
12947 ;; We want this to be just right, so use the full arsenal.
12949 (defun org-indent-line-function ()
12950 "Indent line like previous, but further if previous was headline or item."
12951 (interactive)
12952 (let* ((pos (point))
12953 (itemp (org-at-item-p))
12954 column bpos bcol tpos tcol bullet btype bullet-type)
12955 ;; Find the previous relevant line
12956 (beginning-of-line 1)
12957 (cond
12958 ((looking-at "#") (setq column 0))
12959 ((looking-at "\\*+ ") (setq column 0))
12961 (beginning-of-line 0)
12962 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
12963 (beginning-of-line 0))
12964 (cond
12965 ((looking-at "\\*+[ \t]+")
12966 (goto-char (match-end 0))
12967 (setq column (current-column)))
12968 ((org-in-item-p)
12969 (org-beginning-of-item)
12970 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
12971 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
12972 (setq bpos (match-beginning 1) tpos (match-end 0)
12973 bcol (progn (goto-char bpos) (current-column))
12974 tcol (progn (goto-char tpos) (current-column))
12975 bullet (match-string 1)
12976 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
12977 (if (not itemp)
12978 (setq column tcol)
12979 (goto-char pos)
12980 (beginning-of-line 1)
12981 (if (looking-at "\\S-")
12982 (progn
12983 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
12984 (setq bullet (match-string 1)
12985 btype (if (string-match "[0-9]" bullet) "n" bullet))
12986 (setq column (if (equal btype bullet-type) bcol tcol)))
12987 (setq column (org-get-indentation)))))
12988 (t (setq column (org-get-indentation))))))
12989 (goto-char pos)
12990 (if (<= (current-column) (current-indentation))
12991 (indent-line-to column)
12992 (save-excursion (indent-line-to column)))
12993 (setq column (current-column))
12994 (beginning-of-line 1)
12995 (if (looking-at
12996 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
12997 (replace-match (concat "\\1" (format org-property-format
12998 (match-string 2) (match-string 3)))
12999 t nil))
13000 (move-to-column column)))
13002 (defun org-set-autofill-regexps ()
13003 (interactive)
13004 ;; In the paragraph separator we include headlines, because filling
13005 ;; text in a line directly attached to a headline would otherwise
13006 ;; fill the headline as well.
13007 (org-set-local 'comment-start-skip "^#+[ \t]*")
13008 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13009 ;; The paragraph starter includes hand-formatted lists.
13010 (org-set-local 'paragraph-start
13011 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13012 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13013 ;; But only if the user has not turned off tables or fixed-width regions
13014 (org-set-local
13015 'auto-fill-inhibit-regexp
13016 (concat "\\*+ \\|#\\+"
13017 "\\|[ \t]*" org-keyword-time-regexp
13018 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13019 (concat
13020 "\\|[ \t]*["
13021 (if org-enable-table-editor "|" "")
13022 (if org-enable-fixed-width-editor ":" "")
13023 "]"))))
13024 ;; We use our own fill-paragraph function, to make sure that tables
13025 ;; and fixed-width regions are not wrapped. That function will pass
13026 ;; through to `fill-paragraph' when appropriate.
13027 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13028 ; Adaptive filling: To get full control, first make sure that
13029 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13030 (org-set-local 'adaptive-fill-regexp "\000")
13031 (org-set-local 'adaptive-fill-function
13032 'org-adaptive-fill-function)
13033 (org-set-local
13034 'align-mode-rules-list
13035 '((org-in-buffer-settings
13036 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13037 (modes . '(org-mode))))))
13039 (defun org-fill-paragraph (&optional justify)
13040 "Re-align a table, pass through to fill-paragraph if no table."
13041 (let ((table-p (org-at-table-p))
13042 (table.el-p (org-at-table.el-p)))
13043 (cond ((and (equal (char-after (point-at-bol)) ?*)
13044 (save-excursion (goto-char (point-at-bol))
13045 (looking-at outline-regexp)))
13046 t) ; skip headlines
13047 (table.el-p t) ; skip table.el tables
13048 (table-p (org-table-align) t) ; align org-mode tables
13049 (t nil)))) ; call paragraph-fill
13051 ;; For reference, this is the default value of adaptive-fill-regexp
13052 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13054 (defun org-adaptive-fill-function ()
13055 "Return a fill prefix for org-mode files.
13056 In particular, this makes sure hanging paragraphs for hand-formatted lists
13057 work correctly."
13058 (cond ((looking-at "#[ \t]+")
13059 (match-string 0))
13060 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13061 (save-excursion
13062 (goto-char (match-end 0))
13063 (make-string (current-column) ?\ )))
13064 (t nil)))
13066 ;;; Other stuff.
13068 (defun org-toggle-fixed-width-section (arg)
13069 "Toggle the fixed-width export.
13070 If there is no active region, the QUOTE keyword at the current headline is
13071 inserted or removed. When present, it causes the text between this headline
13072 and the next to be exported as fixed-width text, and unmodified.
13073 If there is an active region, this command adds or removes a colon as the
13074 first character of this line. If the first character of a line is a colon,
13075 this line is also exported in fixed-width font."
13076 (interactive "P")
13077 (let* ((cc 0)
13078 (regionp (org-region-active-p))
13079 (beg (if regionp (region-beginning) (point)))
13080 (end (if regionp (region-end)))
13081 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13082 (case-fold-search nil)
13083 (re "[ \t]*\\(:\\)")
13084 off)
13085 (if regionp
13086 (save-excursion
13087 (goto-char beg)
13088 (setq cc (current-column))
13089 (beginning-of-line 1)
13090 (setq off (looking-at re))
13091 (while (> nlines 0)
13092 (setq nlines (1- nlines))
13093 (beginning-of-line 1)
13094 (cond
13095 (arg
13096 (move-to-column cc t)
13097 (insert ":\n")
13098 (forward-line -1))
13099 ((and off (looking-at re))
13100 (replace-match "" t t nil 1))
13101 ((not off) (move-to-column cc t) (insert ":")))
13102 (forward-line 1)))
13103 (save-excursion
13104 (org-back-to-heading)
13105 (if (looking-at (concat outline-regexp
13106 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13107 (replace-match "" t t nil 1)
13108 (if (looking-at outline-regexp)
13109 (progn
13110 (goto-char (match-end 0))
13111 (insert org-quote-string " "))))))))
13113 ;;;; Functions extending outline functionality
13115 (defun org-beginning-of-line (&optional arg)
13116 "Go to the beginning of the current line. If that is invisible, continue
13117 to a visible line beginning. This makes the function of C-a more intuitive.
13118 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13119 first attempt, and only move to after the tags when the cursor is already
13120 beyond the end of the headline."
13121 (interactive "P")
13122 (let ((pos (point)))
13123 (beginning-of-line 1)
13124 (if (bobp)
13126 (backward-char 1)
13127 (if (org-invisible-p)
13128 (while (and (not (bobp)) (org-invisible-p))
13129 (backward-char 1)
13130 (beginning-of-line 1))
13131 (forward-char 1)))
13132 (when org-special-ctrl-a/e
13133 (cond
13134 ((and (looking-at org-todo-line-regexp)
13135 (= (char-after (match-end 1)) ?\ ))
13136 (goto-char
13137 (if (eq org-special-ctrl-a/e t)
13138 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13139 ((= pos (point)) (match-beginning 3))
13140 (t (point)))
13141 (cond ((> pos (point)) (point))
13142 ((not (eq last-command this-command)) (point))
13143 (t (match-beginning 3))))))
13144 ((org-at-item-p)
13145 (goto-char
13146 (if (eq org-special-ctrl-a/e t)
13147 (cond ((> pos (match-end 4)) (match-end 4))
13148 ((= pos (point)) (match-end 4))
13149 (t (point)))
13150 (cond ((> pos (point)) (point))
13151 ((not (eq last-command this-command)) (point))
13152 (t (match-end 4))))))))))
13154 (defun org-end-of-line (&optional arg)
13155 "Go to the end of the line.
13156 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13157 first attempt, and only move to after the tags when the cursor is already
13158 beyond the end of the headline."
13159 (interactive "P")
13160 (if (or (not org-special-ctrl-a/e)
13161 (not (org-on-heading-p)))
13162 (end-of-line arg)
13163 (let ((pos (point)))
13164 (beginning-of-line 1)
13165 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13166 (if (eq org-special-ctrl-a/e t)
13167 (if (or (< pos (match-beginning 1))
13168 (= pos (match-end 0)))
13169 (goto-char (match-beginning 1))
13170 (goto-char (match-end 0)))
13171 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13172 (goto-char (match-end 0))
13173 (goto-char (match-beginning 1))))
13174 (end-of-line arg)))))
13176 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13177 (define-key org-mode-map "\C-e" 'org-end-of-line)
13179 (defun org-kill-line (&optional arg)
13180 "Kill line, to tags or end of line."
13181 (interactive "P")
13182 (cond
13183 ((or (not org-special-ctrl-k)
13184 (bolp)
13185 (not (org-on-heading-p)))
13186 (call-interactively 'kill-line))
13187 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13188 (kill-region (point) (match-beginning 1))
13189 (org-set-tags nil t))
13190 (t (kill-region (point) (point-at-eol)))))
13192 (define-key org-mode-map "\C-k" 'org-kill-line)
13194 (defun org-invisible-p ()
13195 "Check if point is at a character currently not visible."
13196 ;; Early versions of noutline don't have `outline-invisible-p'.
13197 (if (fboundp 'outline-invisible-p)
13198 (outline-invisible-p)
13199 (get-char-property (point) 'invisible)))
13201 (defun org-invisible-p2 ()
13202 "Check if point is at a character currently not visible."
13203 (save-excursion
13204 (if (and (eolp) (not (bobp))) (backward-char 1))
13205 ;; Early versions of noutline don't have `outline-invisible-p'.
13206 (if (fboundp 'outline-invisible-p)
13207 (outline-invisible-p)
13208 (get-char-property (point) 'invisible))))
13210 (defalias 'org-back-to-heading 'outline-back-to-heading)
13211 (defalias 'org-on-heading-p 'outline-on-heading-p)
13212 (defalias 'org-at-heading-p 'outline-on-heading-p)
13213 (defun org-at-heading-or-item-p ()
13214 (or (org-on-heading-p) (org-at-item-p)))
13216 (defun org-on-target-p ()
13217 (or (org-in-regexp org-radio-target-regexp)
13218 (org-in-regexp org-target-regexp)))
13220 (defun org-up-heading-all (arg)
13221 "Move to the heading line of which the present line is a subheading.
13222 This function considers both visible and invisible heading lines.
13223 With argument, move up ARG levels."
13224 (if (fboundp 'outline-up-heading-all)
13225 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13226 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13228 (defun org-up-heading-safe ()
13229 "Move to the heading line of which the present line is a subheading.
13230 This version will not throw an error. It will return the level of the
13231 headline found, or nil if no higher level is found."
13232 (let ((pos (point)) start-level level
13233 (re (concat "^" outline-regexp)))
13234 (catch 'exit
13235 (outline-back-to-heading t)
13236 (setq start-level (funcall outline-level))
13237 (if (equal start-level 1) (throw 'exit nil))
13238 (while (re-search-backward re nil t)
13239 (setq level (funcall outline-level))
13240 (if (< level start-level) (throw 'exit level)))
13241 nil)))
13243 (defun org-first-sibling-p ()
13244 "Is this heading the first child of its parents?"
13245 (interactive)
13246 (let ((re (concat "^" outline-regexp))
13247 level l)
13248 (unless (org-at-heading-p t)
13249 (error "Not at a heading"))
13250 (setq level (funcall outline-level))
13251 (save-excursion
13252 (if (not (re-search-backward re nil t))
13254 (setq l (funcall outline-level))
13255 (< l level)))))
13257 (defun org-goto-sibling (&optional previous)
13258 "Goto the next sibling, even if it is invisible.
13259 When PREVIOUS is set, go to the previous sibling instead. Returns t
13260 when a sibling was found. When none is found, return nil and don't
13261 move point."
13262 (let ((fun (if previous 're-search-backward 're-search-forward))
13263 (pos (point))
13264 (re (concat "^" outline-regexp))
13265 level l)
13266 (when (condition-case nil (org-back-to-heading t) (error nil))
13267 (setq level (funcall outline-level))
13268 (catch 'exit
13269 (or previous (forward-char 1))
13270 (while (funcall fun re nil t)
13271 (setq l (funcall outline-level))
13272 (when (< l level) (goto-char pos) (throw 'exit nil))
13273 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13274 (goto-char pos)
13275 nil))))
13277 (defun org-show-siblings ()
13278 "Show all siblings of the current headline."
13279 (save-excursion
13280 (while (org-goto-sibling) (org-flag-heading nil)))
13281 (save-excursion
13282 (while (org-goto-sibling 'previous)
13283 (org-flag-heading nil))))
13285 (defun org-show-hidden-entry ()
13286 "Show an entry where even the heading is hidden."
13287 (save-excursion
13288 (org-show-entry)))
13290 (defun org-flag-heading (flag &optional entry)
13291 "Flag the current heading. FLAG non-nil means make invisible.
13292 When ENTRY is non-nil, show the entire entry."
13293 (save-excursion
13294 (org-back-to-heading t)
13295 ;; Check if we should show the entire entry
13296 (if entry
13297 (progn
13298 (org-show-entry)
13299 (save-excursion
13300 (and (outline-next-heading)
13301 (org-flag-heading nil))))
13302 (outline-flag-region (max (point-min) (1- (point)))
13303 (save-excursion (outline-end-of-heading) (point))
13304 flag))))
13306 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13307 ;; This is an exact copy of the original function, but it uses
13308 ;; `org-back-to-heading', to make it work also in invisible
13309 ;; trees. And is uses an invisible-OK argument.
13310 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13311 (org-back-to-heading invisible-OK)
13312 (let ((first t)
13313 (level (funcall outline-level)))
13314 (while (and (not (eobp))
13315 (or first (> (funcall outline-level) level)))
13316 (setq first nil)
13317 (outline-next-heading))
13318 (unless to-heading
13319 (if (memq (preceding-char) '(?\n ?\^M))
13320 (progn
13321 ;; Go to end of line before heading
13322 (forward-char -1)
13323 (if (memq (preceding-char) '(?\n ?\^M))
13324 ;; leave blank line before heading
13325 (forward-char -1))))))
13326 (point))
13328 (defun org-show-subtree ()
13329 "Show everything after this heading at deeper levels."
13330 (outline-flag-region
13331 (point)
13332 (save-excursion
13333 (outline-end-of-subtree) (outline-next-heading) (point))
13334 nil))
13336 (defun org-show-entry ()
13337 "Show the body directly following this heading.
13338 Show the heading too, if it is currently invisible."
13339 (interactive)
13340 (save-excursion
13341 (condition-case nil
13342 (progn
13343 (org-back-to-heading t)
13344 (outline-flag-region
13345 (max (point-min) (1- (point)))
13346 (save-excursion
13347 (re-search-forward
13348 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13349 (or (match-beginning 1) (point-max)))
13350 nil))
13351 (error nil))))
13353 (defun org-make-options-regexp (kwds)
13354 "Make a regular expression for keyword lines."
13355 (concat
13357 "#?[ \t]*\\+\\("
13358 (mapconcat 'regexp-quote kwds "\\|")
13359 "\\):[ \t]*"
13360 "\\(.+\\)"))
13362 ;; Make isearch reveal the necessary context
13363 (defun org-isearch-end ()
13364 "Reveal context after isearch exits."
13365 (when isearch-success ; only if search was successful
13366 (if (featurep 'xemacs)
13367 ;; Under XEmacs, the hook is run in the correct place,
13368 ;; we directly show the context.
13369 (org-show-context 'isearch)
13370 ;; In Emacs the hook runs *before* restoring the overlays.
13371 ;; So we have to use a one-time post-command-hook to do this.
13372 ;; (Emacs 22 has a special variable, see function `org-mode')
13373 (unless (and (boundp 'isearch-mode-end-hook-quit)
13374 isearch-mode-end-hook-quit)
13375 ;; Only when the isearch was not quitted.
13376 (org-add-hook 'post-command-hook 'org-isearch-post-command
13377 'append 'local)))))
13379 (defun org-isearch-post-command ()
13380 "Remove self from hook, and show context."
13381 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13382 (org-show-context 'isearch))
13385 ;;;; Integration with and fixes for other packages
13387 ;;; Imenu support
13389 (defvar org-imenu-markers nil
13390 "All markers currently used by Imenu.")
13391 (make-variable-buffer-local 'org-imenu-markers)
13393 (defun org-imenu-new-marker (&optional pos)
13394 "Return a new marker for use by Imenu, and remember the marker."
13395 (let ((m (make-marker)))
13396 (move-marker m (or pos (point)))
13397 (push m org-imenu-markers)
13400 (defun org-imenu-get-tree ()
13401 "Produce the index for Imenu."
13402 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13403 (setq org-imenu-markers nil)
13404 (let* ((n org-imenu-depth)
13405 (re (concat "^" outline-regexp))
13406 (subs (make-vector (1+ n) nil))
13407 (last-level 0)
13408 m tree level head)
13409 (save-excursion
13410 (save-restriction
13411 (widen)
13412 (goto-char (point-max))
13413 (while (re-search-backward re nil t)
13414 (setq level (org-reduced-level (funcall outline-level)))
13415 (when (<= level n)
13416 (looking-at org-complex-heading-regexp)
13417 (setq head (org-match-string-no-properties 4)
13418 m (org-imenu-new-marker))
13419 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13420 (if (>= level last-level)
13421 (push (cons head m) (aref subs level))
13422 (push (cons head (aref subs (1+ level))) (aref subs level))
13423 (loop for i from (1+ level) to n do (aset subs i nil)))
13424 (setq last-level level)))))
13425 (aref subs 1)))
13427 (eval-after-load "imenu"
13428 '(progn
13429 (add-hook 'imenu-after-jump-hook
13430 (lambda () (org-show-context 'org-goto)))))
13432 ;; Speedbar support
13434 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13435 "Overlay marking the agenda restriction line in speedbar.")
13436 (org-overlay-put org-speedbar-restriction-lock-overlay
13437 'face 'org-agenda-restriction-lock)
13438 (org-overlay-put org-speedbar-restriction-lock-overlay
13439 'help-echo "Agendas are currently limited to this item.")
13440 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13442 (defun org-speedbar-set-agenda-restriction ()
13443 "Restrict future agenda commands to the location at point in speedbar.
13444 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13445 (interactive)
13446 (require 'org-agenda)
13447 (let (p m tp np dir txt w)
13448 (cond
13449 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13450 'org-imenu t))
13451 (setq m (get-text-property p 'org-imenu-marker))
13452 (save-excursion
13453 (save-restriction
13454 (set-buffer (marker-buffer m))
13455 (goto-char m)
13456 (org-agenda-set-restriction-lock 'subtree))))
13457 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13458 'speedbar-function 'speedbar-find-file))
13459 (setq tp (previous-single-property-change
13460 (1+ p) 'speedbar-function)
13461 np (next-single-property-change
13462 tp 'speedbar-function)
13463 dir (speedbar-line-directory)
13464 txt (buffer-substring-no-properties (or tp (point-min))
13465 (or np (point-max))))
13466 (save-excursion
13467 (save-restriction
13468 (set-buffer (find-file-noselect
13469 (let ((default-directory dir))
13470 (expand-file-name txt))))
13471 (unless (org-mode-p)
13472 (error "Cannot restrict to non-Org-mode file"))
13473 (org-agenda-set-restriction-lock 'file))))
13474 (t (error "Don't know how to restrict Org-mode's agenda")))
13475 (org-move-overlay org-speedbar-restriction-lock-overlay
13476 (point-at-bol) (point-at-eol))
13477 (setq current-prefix-arg nil)
13478 (org-agenda-maybe-redo)))
13480 (eval-after-load "speedbar"
13481 '(progn
13482 (speedbar-add-supported-extension ".org")
13483 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13484 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13485 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13486 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13487 (add-hook 'speedbar-visiting-tag-hook
13488 (lambda () (org-show-context 'org-goto)))))
13491 ;;; Fixes and Hacks for problems with other packages
13493 ;; Make flyspell not check words in links, to not mess up our keymap
13494 (defun org-mode-flyspell-verify ()
13495 "Don't let flyspell put overlays at active buttons."
13496 (not (get-text-property (point) 'keymap)))
13498 ;; Make `bookmark-jump' show the jump location if it was hidden.
13499 (eval-after-load "bookmark"
13500 '(if (boundp 'bookmark-after-jump-hook)
13501 ;; We can use the hook
13502 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13503 ;; Hook not available, use advice
13504 (defadvice bookmark-jump (after org-make-visible activate)
13505 "Make the position visible."
13506 (org-bookmark-jump-unhide))))
13508 (defun org-bookmark-jump-unhide ()
13509 "Unhide the current position, to show the bookmark location."
13510 (and (org-mode-p)
13511 (or (org-invisible-p)
13512 (save-excursion (goto-char (max (point-min) (1- (point))))
13513 (org-invisible-p)))
13514 (org-show-context 'bookmark-jump)))
13516 ;; Make session.el ignore our circular variable
13517 (eval-after-load "session"
13518 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13520 ;;;; Experimental code
13522 (defun org-closed-in-range ()
13523 "Sparse tree of items closed in a certain time range.
13524 Still experimental, may disappear in the future."
13525 (interactive)
13526 ;; Get the time interval from the user.
13527 (let* ((time1 (time-to-seconds
13528 (org-read-date nil 'to-time nil "Starting date: ")))
13529 (time2 (time-to-seconds
13530 (org-read-date nil 'to-time nil "End date:")))
13531 ;; callback function
13532 (callback (lambda ()
13533 (let ((time
13534 (time-to-seconds
13535 (apply 'encode-time
13536 (org-parse-time-string
13537 (match-string 1))))))
13538 ;; check if time in interval
13539 (and (>= time time1) (<= time time2))))))
13540 ;; make tree, check each match with the callback
13541 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13544 ;;;; Finish up
13546 (provide 'org)
13548 (run-hooks 'org-load-hook)
13550 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13551 ;;; org.el ends here
13553 (defun org-open-link-from-string (s &optional arg)
13554 "Open a link in the string S, as if it was in Org-mode."
13555 (interactive)
13556 (with-temp-buffer
13557 (let ((org-inhibit-startup t))
13558 (org-mode)
13559 (insert s)
13560 (goto-char (point-min))
13561 (org-open-at-point arg))))