Release 6.17b
[org-mode.git] / lisp / org.el
blob9753c8c9ac30b3ac1daac915a335ed6e80913e48
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.17b
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
89 (require 'org-list)
90 (require 'org-footnote)
92 ;;;; Customization variables
94 ;;; Version
96 (defconst org-version "6.17b"
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-modules'."
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 (when (org-bound-and-true-p org-modules)
144 (let ((a (member 'org-infojs org-modules)))
145 (and a (setcar a 'org-jsinfo))))
147 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
148 "Modules that should always be loaded together with org.el.
149 If a description starts with <C>, the file is not part of Emacs
150 and loading it will require that you have downloaded and properly installed
151 the org-mode distribution.
153 You can also use this system to load external packages (i.e. neither Org
154 core modules, not modules from the CONTRIB directory). Just add symbols
155 to the end of the list. If the package is called org-xyz.el, then you need
156 to add the symbol `xyz', and the package must have a call to
158 (provide 'org-xyz)"
159 :group 'org
160 :set 'org-set-modules
161 :type
162 '(set :greedy t
163 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
164 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
165 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
166 (const :tag " id: Global IDs for identifying entries" org-id)
167 (const :tag " info: Links to Info nodes" org-info)
168 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
169 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
170 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
171 (const :tag " mew Links to Mew folders/messages" org-mew)
172 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
173 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
174 (const :tag " vm: Links to VM folders/messages" org-vm)
175 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
176 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
177 (const :tag " mouse: Additional mouse support" org-mouse)
179 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
180 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
181 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
182 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
183 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
184 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
185 (const :tag "C eval: Include command output as text" org-eval)
186 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
187 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
188 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
189 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
190 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
191 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
192 (const :tag "C mtags: Support for muse-like tags" org-mtags)
193 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
194 (const :tag "C registry: A registry for Org links" org-registry)
195 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
196 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
197 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
198 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
199 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
202 (defgroup org-startup nil
203 "Options concerning startup of Org-mode."
204 :tag "Org Startup"
205 :group 'org)
207 (defcustom org-startup-folded t
208 "Non-nil means, entering Org-mode will switch to OVERVIEW.
209 This can also be configured on a per-file basis by adding one of
210 the following lines anywhere in the buffer:
212 #+STARTUP: fold
213 #+STARTUP: nofold
214 #+STARTUP: content"
215 :group 'org-startup
216 :type '(choice
217 (const :tag "nofold: show all" nil)
218 (const :tag "fold: overview" t)
219 (const :tag "content: all headlines" content)))
221 (defcustom org-startup-truncated t
222 "Non-nil means, entering Org-mode will set `truncate-lines'.
223 This is useful since some lines containing links can be very long and
224 uninteresting. Also tables look terrible when wrapped."
225 :group 'org-startup
226 :type 'boolean)
228 (defcustom org-startup-align-all-tables nil
229 "Non-nil means, align all tables when visiting a file.
230 This is useful when the column width in tables is forced with <N> cookies
231 in table fields. Such tables will look correct only after the first re-align.
232 This can also be configured on a per-file basis by adding one of
233 the following lines anywhere in the buffer:
234 #+STARTUP: align
235 #+STARTUP: noalign"
236 :group 'org-startup
237 :type 'boolean)
239 (defcustom org-insert-mode-line-in-empty-file nil
240 "Non-nil means insert the first line setting Org-mode in empty files.
241 When the function `org-mode' is called interactively in an empty file, this
242 normally means that the file name does not automatically trigger Org-mode.
243 To ensure that the file will always be in Org-mode in the future, a
244 line enforcing Org-mode will be inserted into the buffer, if this option
245 has been set."
246 :group 'org-startup
247 :type 'boolean)
249 (defcustom org-replace-disputed-keys nil
250 "Non-nil means use alternative key bindings for some keys.
251 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
252 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
253 If you want to use Org-mode together with one of these other modes,
254 or more generally if you would like to move some Org-mode commands to
255 other keys, set this variable and configure the keys with the variable
256 `org-disputed-keys'.
258 This option is only relevant at load-time of Org-mode, and must be set
259 *before* org.el is loaded. Changing it requires a restart of Emacs to
260 become effective."
261 :group 'org-startup
262 :type 'boolean)
264 (defcustom org-use-extra-keys nil
265 "Non-nil means use extra key sequence definitions for certain
266 commands. This happens automatically if you run XEmacs or if
267 window-system is nil. This variable lets you do the same
268 manually. You must set it before loading org.
270 Example: on Carbon Emacs 22 running graphically, with an external
271 keyboard on a Powerbook, the default way of setting M-left might
272 not work for either Alt or ESC. Setting this variable will make
273 it work for ESC."
274 :group 'org-startup
275 :type 'boolean)
277 (if (fboundp 'defvaralias)
278 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
280 (defcustom org-disputed-keys
281 '(([(shift up)] . [(meta p)])
282 ([(shift down)] . [(meta n)])
283 ([(shift left)] . [(meta -)])
284 ([(shift right)] . [(meta +)])
285 ([(control shift right)] . [(meta shift +)])
286 ([(control shift left)] . [(meta shift -)]))
287 "Keys for which Org-mode and other modes compete.
288 This is an alist, cars are the default keys, second element specifies
289 the alternative to use when `org-replace-disputed-keys' is t.
291 Keys can be specified in any syntax supported by `define-key'.
292 The value of this option takes effect only at Org-mode's startup,
293 therefore you'll have to restart Emacs to apply it after changing."
294 :group 'org-startup
295 :type 'alist)
297 (defun org-key (key)
298 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
299 Or return the original if not disputed."
300 (if org-replace-disputed-keys
301 (let* ((nkey (key-description key))
302 (x (org-find-if (lambda (x)
303 (equal (key-description (car x)) nkey))
304 org-disputed-keys)))
305 (if x (cdr x) key))
306 key))
308 (defun org-find-if (predicate seq)
309 (catch 'exit
310 (while seq
311 (if (funcall predicate (car seq))
312 (throw 'exit (car seq))
313 (pop seq)))))
315 (defun org-defkey (keymap key def)
316 "Define a key, possibly translated, as returned by `org-key'."
317 (define-key keymap (org-key key) def))
319 (defcustom org-ellipsis nil
320 "The ellipsis to use in the Org-mode outline.
321 When nil, just use the standard three dots. When a string, use that instead,
322 When a face, use the standard 3 dots, but with the specified face.
323 The change affects only Org-mode (which will then use its own display table).
324 Changing this requires executing `M-x org-mode' in a buffer to become
325 effective."
326 :group 'org-startup
327 :type '(choice (const :tag "Default" nil)
328 (face :tag "Face" :value org-warning)
329 (string :tag "String" :value "...#")))
331 (defvar org-display-table nil
332 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
334 (defgroup org-keywords nil
335 "Keywords in Org-mode."
336 :tag "Org Keywords"
337 :group 'org)
339 (defcustom org-deadline-string "DEADLINE:"
340 "String to mark deadline entries.
341 A deadline is this string, followed by a time stamp. Should be a word,
342 terminated by a colon. You can insert a schedule keyword and
343 a timestamp with \\[org-deadline].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
348 (defcustom org-scheduled-string "SCHEDULED:"
349 "String to mark scheduled TODO entries.
350 A schedule is this string, followed by a time stamp. Should be a word,
351 terminated by a colon. You can insert a schedule keyword and
352 a timestamp with \\[org-schedule].
353 Changes become only effective after restarting Emacs."
354 :group 'org-keywords
355 :type 'string)
357 (defcustom org-closed-string "CLOSED:"
358 "String used as the prefix for timestamps logging closing a TODO entry."
359 :group 'org-keywords
360 :type 'string)
362 (defcustom org-clock-string "CLOCK:"
363 "String used as prefix for timestamps clocking work hours on an item."
364 :group 'org-keywords
365 :type 'string)
367 (defcustom org-comment-string "COMMENT"
368 "Entries starting with this keyword will never be exported.
369 An entry can be toggled between COMMENT and normal with
370 \\[org-toggle-comment].
371 Changes become only effective after restarting Emacs."
372 :group 'org-keywords
373 :type 'string)
375 (defcustom org-quote-string "QUOTE"
376 "Entries starting with this keyword will be exported in fixed-width font.
377 Quoting applies only to the text in the entry following the headline, and does
378 not extend beyond the next headline, even if that is lower level.
379 An entry can be toggled between QUOTE and normal with
380 \\[org-toggle-fixed-width-section]."
381 :group 'org-keywords
382 :type 'string)
384 (defconst org-repeat-re
385 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
386 "Regular expression for specifying repeated events.
387 After a match, group 1 contains the repeat expression.")
389 (defgroup org-structure nil
390 "Options concerning the general structure of Org-mode files."
391 :tag "Org Structure"
392 :group 'org)
394 (defgroup org-reveal-location nil
395 "Options about how to make context of a location visible."
396 :tag "Org Reveal Location"
397 :group 'org-structure)
399 (defconst org-context-choice
400 '(choice
401 (const :tag "Always" t)
402 (const :tag "Never" nil)
403 (repeat :greedy t :tag "Individual contexts"
404 (cons
405 (choice :tag "Context"
406 (const agenda)
407 (const org-goto)
408 (const occur-tree)
409 (const tags-tree)
410 (const link-search)
411 (const mark-goto)
412 (const bookmark-jump)
413 (const isearch)
414 (const default))
415 (boolean))))
416 "Contexts for the reveal options.")
418 (defcustom org-show-hierarchy-above '((default . t))
419 "Non-nil means, show full hierarchy when revealing a location.
420 Org-mode often shows locations in an org-mode file which might have
421 been invisible before. When this is set, the hierarchy of headings
422 above the exposed location is shown.
423 Turning this off for example for sparse trees makes them very compact.
424 Instead of t, this can also be an alist specifying this option for different
425 contexts. Valid contexts are
426 agenda when exposing an entry from the agenda
427 org-goto when using the command `org-goto' on key C-c C-j
428 occur-tree when using the command `org-occur' on key C-c /
429 tags-tree when constructing a sparse tree based on tags matches
430 link-search when exposing search matches associated with a link
431 mark-goto when exposing the jump goal of a mark
432 bookmark-jump when exposing a bookmark location
433 isearch when exiting from an incremental search
434 default default for all contexts not set explicitly"
435 :group 'org-reveal-location
436 :type org-context-choice)
438 (defcustom org-show-following-heading '((default . nil))
439 "Non-nil means, show following heading when revealing a location.
440 Org-mode often shows locations in an org-mode file which might have
441 been invisible before. When this is set, the heading following the
442 match is shown.
443 Turning this off for example for sparse trees makes them very compact,
444 but makes it harder to edit the location of the match. In such a case,
445 use the command \\[org-reveal] to show more context.
446 Instead of t, this can also be an alist specifying this option for different
447 contexts. See `org-show-hierarchy-above' for valid contexts."
448 :group 'org-reveal-location
449 :type org-context-choice)
451 (defcustom org-show-siblings '((default . nil) (isearch t))
452 "Non-nil means, show all sibling heading when revealing a location.
453 Org-mode often shows locations in an org-mode file which might have
454 been invisible before. When this is set, the sibling of the current entry
455 heading are all made visible. If `org-show-hierarchy-above' is t,
456 the same happens on each level of the hierarchy above the current entry.
458 By default this is on for the isearch context, off for all other contexts.
459 Turning this off for example for sparse trees makes them very compact,
460 but makes it harder to edit the location of the match. In such a case,
461 use the command \\[org-reveal] to show more context.
462 Instead of t, this can also be an alist specifying this option for different
463 contexts. See `org-show-hierarchy-above' for valid contexts."
464 :group 'org-reveal-location
465 :type org-context-choice)
467 (defcustom org-show-entry-below '((default . nil))
468 "Non-nil means, show the entry below a headline when revealing a location.
469 Org-mode often shows locations in an org-mode file which might have
470 been invisible before. When this is set, the text below the headline that is
471 exposed is also shown.
473 By default this is off for all contexts.
474 Instead of t, this can also be an alist specifying this option for different
475 contexts. See `org-show-hierarchy-above' for valid contexts."
476 :group 'org-reveal-location
477 :type org-context-choice)
479 (defcustom org-indirect-buffer-display 'other-window
480 "How should indirect tree buffers be displayed?
481 This applies to indirect buffers created with the commands
482 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
483 Valid values are:
484 current-window Display in the current window
485 other-window Just display in another window.
486 dedicated-frame Create one new frame, and re-use it each time.
487 new-frame Make a new frame each time. Note that in this case
488 previously-made indirect buffers are kept, and you need to
489 kill these buffers yourself."
490 :group 'org-structure
491 :group 'org-agenda-windows
492 :type '(choice
493 (const :tag "In current window" current-window)
494 (const :tag "In current frame, other window" other-window)
495 (const :tag "Each time a new frame" new-frame)
496 (const :tag "One dedicated frame" dedicated-frame)))
498 (defgroup org-cycle nil
499 "Options concerning visibility cycling in Org-mode."
500 :tag "Org Cycle"
501 :group 'org-structure)
503 (defcustom org-drawers '("PROPERTIES" "CLOCK")
504 "Names of drawers. Drawers are not opened by cycling on the headline above.
505 Drawers only open with a TAB on the drawer line itself. A drawer looks like
506 this:
507 :DRAWERNAME:
508 .....
509 :END:
510 The drawer \"PROPERTIES\" is special for capturing properties through
511 the property API.
513 Drawers can be defined on the per-file basis with a line like:
515 #+DRAWERS: HIDDEN STATE PROPERTIES"
516 :group 'org-structure
517 :type '(repeat (string :tag "Drawer Name")))
519 (defcustom org-cycle-global-at-bob nil
520 "Cycle globally if cursor is at beginning of buffer and not at a headline.
521 This makes it possible to do global cycling without having to use S-TAB or
522 C-u TAB. For this special case to work, the first line of the buffer
523 must not be a headline - it may be empty ot some other text. When used in
524 this way, `org-cycle-hook' is disables temporarily, to make sure the
525 cursor stays at the beginning of the buffer.
526 When this option is nil, don't do anything special at the beginning
527 of the buffer."
528 :group 'org-cycle
529 :type 'boolean)
531 (defcustom org-cycle-emulate-tab t
532 "Where should `org-cycle' emulate TAB.
533 nil Never
534 white Only in completely white lines
535 whitestart Only at the beginning of lines, before the first non-white char
536 t Everywhere except in headlines
537 exc-hl-bol Everywhere except at the start of a headline
538 If TAB is used in a place where it does not emulate TAB, the current subtree
539 visibility is cycled."
540 :group 'org-cycle
541 :type '(choice (const :tag "Never" nil)
542 (const :tag "Only in completely white lines" white)
543 (const :tag "Before first char in a line" whitestart)
544 (const :tag "Everywhere except in headlines" t)
545 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
548 (defcustom org-cycle-separator-lines 2
549 "Number of empty lines needed to keep an empty line between collapsed trees.
550 If you leave an empty line between the end of a subtree and the following
551 headline, this empty line is hidden when the subtree is folded.
552 Org-mode will leave (exactly) one empty line visible if the number of
553 empty lines is equal or larger to the number given in this variable.
554 So the default 2 means, at least 2 empty lines after the end of a subtree
555 are needed to produce free space between a collapsed subtree and the
556 following headline.
558 Special case: when 0, never leave empty lines in collapsed view."
559 :group 'org-cycle
560 :type 'integer)
561 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
563 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
564 org-cycle-hide-drawers
565 org-cycle-show-empty-lines
566 org-optimize-window-after-visibility-change)
567 "Hook that is run after `org-cycle' has changed the buffer visibility.
568 The function(s) in this hook must accept a single argument which indicates
569 the new state that was set by the most recent `org-cycle' command. The
570 argument is a symbol. After a global state change, it can have the values
571 `overview', `content', or `all'. After a local state change, it can have
572 the values `folded', `children', or `subtree'."
573 :group 'org-cycle
574 :type 'hook)
576 (defgroup org-edit-structure nil
577 "Options concerning structure editing in Org-mode."
578 :tag "Org Edit Structure"
579 :group 'org-structure)
581 (defcustom org-odd-levels-only nil
582 "Non-nil means, skip even levels and only use odd levels for the outline.
583 This has the effect that two stars are being added/taken away in
584 promotion/demotion commands. It also influences how levels are
585 handled by the exporters.
586 Changing it requires restart of `font-lock-mode' to become effective
587 for fontification also in regions already fontified.
588 You may also set this on a per-file basis by adding one of the following
589 lines to the buffer:
591 #+STARTUP: odd
592 #+STARTUP: oddeven"
593 :group 'org-edit-structure
594 :group 'org-font-lock
595 :type 'boolean)
597 (defcustom org-adapt-indentation t
598 "Non-nil means, adapt indentation when promoting and demoting.
599 When this is set and the *entire* text in an entry is indented, the
600 indentation is increased by one space in a demotion command, and
601 decreased by one in a promotion command. If any line in the entry
602 body starts at column 0, indentation is not changed at all."
603 :group 'org-edit-structure
604 :type 'boolean)
606 (defcustom org-special-ctrl-a/e nil
607 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
608 When t, `C-a' will bring back the cursor to the beginning of the
609 headline text, i.e. after the stars and after a possible TODO keyword.
610 In an item, this will be the position after the bullet.
611 When the cursor is already at that position, another `C-a' will bring
612 it to the beginning of the line.
613 `C-e' will jump to the end of the headline, ignoring the presence of tags
614 in the headline. A second `C-e' will then jump to the true end of the
615 line, after any tags.
616 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
617 and only a directly following, identical keypress will bring the cursor
618 to the special positions."
619 :group 'org-edit-structure
620 :type '(choice
621 (const :tag "off" nil)
622 (const :tag "after bullet first" t)
623 (const :tag "border first" reversed)))
625 (if (fboundp 'defvaralias)
626 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
628 (defcustom org-special-ctrl-k nil
629 "Non-nil means `C-k' will behave specially in headlines.
630 When nil, `C-k' will call the default `kill-line' command.
631 When t, the following will happen while the cursor is in the headline:
633 - When the cursor is at the beginning of a headline, kill the entire
634 line and possible the folded subtree below the line.
635 - When in the middle of the headline text, kill the headline up to the tags.
636 - When after the headline text, kill the tags."
637 :group 'org-edit-structure
638 :type 'boolean)
640 (defcustom org-yank-folded-subtrees t
641 "Non-nil means, when yanking subtrees, fold them.
642 If the kill is a single subtree, or a sequence of subtrees, i.e. if
643 it starts with a heading and all other headings in it are either children
644 or siblings, then fold all the subtrees. However, do this only if no
645 text after the yank would be swallowed into a folded tree by this action."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defcustom org-yank-adjusted-subtrees t
650 "Non-nil means, when yanking subtrees, adjust the level.
651 With this setting, `org-paste-subtree' is used to insert the subtree, see
652 this function for details."
653 :group 'org-edit-structure
654 :type 'boolean)
656 (defcustom org-M-RET-may-split-line '((default . t))
657 "Non-nil means, M-RET will split the line at the cursor position.
658 When nil, it will go to the end of the line before making a
659 new line.
660 You may also set this option in a different way for different
661 contexts. Valid contexts are:
663 headline when creating a new headline
664 item when creating a new item
665 table in a table field
666 default the value to be used for all contexts not explicitly
667 customized"
668 :group 'org-structure
669 :group 'org-table
670 :type '(choice
671 (const :tag "Always" t)
672 (const :tag "Never" nil)
673 (repeat :greedy t :tag "Individual contexts"
674 (cons
675 (choice :tag "Context"
676 (const headline)
677 (const item)
678 (const table)
679 (const default))
680 (boolean)))))
683 (defcustom org-insert-heading-respect-content nil
684 "Non-nil means, insert new headings after the current subtree.
685 When nil, the new heading is created directly after the current line.
686 The commands \\[org-insert-heading-respect-content] and
687 \\[org-insert-todo-heading-respect-content] turn this variable on
688 for the duration of the command."
689 :group 'org-structure
690 :type 'boolean)
692 (defcustom org-blank-before-new-entry '((heading . nil)
693 (plain-list-item . nil))
694 "Should `org-insert-heading' leave a blank line before new heading/item?
695 The value is an alist, with `heading' and `plain-list-item' as car,
696 and a boolean flag as cdr."
697 :group 'org-edit-structure
698 :type '(list
699 (cons (const heading) (boolean))
700 (cons (const plain-list-item) (boolean))))
702 (defcustom org-insert-heading-hook nil
703 "Hook being run after inserting a new heading."
704 :group 'org-edit-structure
705 :type 'hook)
707 (defcustom org-enable-fixed-width-editor t
708 "Non-nil means, lines starting with \":\" are treated as fixed-width.
709 This currently only means, they are never auto-wrapped.
710 When nil, such lines will be treated like ordinary lines.
711 See also the QUOTE keyword."
712 :group 'org-edit-structure
713 :type 'boolean)
715 (defcustom org-edit-src-region-extra nil
716 "Additional regexps to identify regions for editing with `org-edit-src-code'.
717 For examples see the function `org-edit-src-find-region-and-lang'.
718 The regular expression identifying the begin marker should end with a newline,
719 and the regexp marking the end line should start with a newline, to make sure
720 there are kept outside the narrowed region."
721 :group 'org-edit-structure
722 :type '(repeat
723 (list
724 (regexp :tag "begin regexp")
725 (regexp :tag "end regexp")
726 (choice :tag "language"
727 (string :tag "specify")
728 (integer :tag "from match group")
729 (const :tag "from `lang' element")
730 (const :tag "from `style' element")))))
732 (defcustom org-coderef-label-format "(ref:%s)"
733 "The default coderef format.
734 This format string will be used to search for coderef labels in literal
735 examples (EXAMPLE and SRC blocks). The format can be overwritten
736 an individual literal example with the -f option, like
738 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
740 #+END_SRC
742 If you want to use this for HTML export, make sure that the format does
743 not introduce special font-locking, and avoid the HTML special
744 characters `<', `>', and `&'. The reason for this restriction is that
745 the labels are searched for only after htmlize has done its job."
746 :group 'org-edit-structure ; FIXME this is not in the right group
747 :type 'string)
749 (defcustom org-edit-fixed-width-region-mode 'artist-mode
750 "The mode that should be used to edit fixed-width regions.
751 These are the regions where each line starts with a colon."
752 :group 'org-edit-structure
753 :type '(choice
754 (const artist-mode)
755 (const picture-mode)
756 (const fundamental-mode)
757 (function :tag "Other (specify)")))
759 (defcustom org-goto-auto-isearch t
760 "Non-nil means, typing characters in org-goto starts incremental search."
761 :group 'org-edit-structure
762 :type 'boolean)
764 (defgroup org-sparse-trees nil
765 "Options concerning sparse trees in Org-mode."
766 :tag "Org Sparse Trees"
767 :group 'org-structure)
769 (defcustom org-highlight-sparse-tree-matches t
770 "Non-nil means, highlight all matches that define a sparse tree.
771 The highlights will automatically disappear the next time the buffer is
772 changed by an edit command."
773 :group 'org-sparse-trees
774 :type 'boolean)
776 (defcustom org-remove-highlights-with-change t
777 "Non-nil means, any change to the buffer will remove temporary highlights.
778 Such highlights are created by `org-occur' and `org-clock-display'.
779 When nil, `C-c C-c needs to be used to get rid of the highlights.
780 The highlights created by `org-preview-latex-fragment' always need
781 `C-c C-c' to be removed."
782 :group 'org-sparse-trees
783 :group 'org-time
784 :type 'boolean)
787 (defcustom org-occur-hook '(org-first-headline-recenter)
788 "Hook that is run after `org-occur' has constructed a sparse tree.
789 This can be used to recenter the window to show as much of the structure
790 as possible."
791 :group 'org-sparse-trees
792 :type 'hook)
794 (defgroup org-imenu-and-speedbar nil
795 "Options concerning imenu and speedbar in Org-mode."
796 :tag "Org Imenu and Speedbar"
797 :group 'org-structure)
799 (defcustom org-imenu-depth 2
800 "The maximum level for Imenu access to Org-mode headlines.
801 This also applied for speedbar access."
802 :group 'org-imenu-and-speedbar
803 :type 'number)
805 (defgroup org-table nil
806 "Options concerning tables in Org-mode."
807 :tag "Org Table"
808 :group 'org)
810 (defcustom org-enable-table-editor 'optimized
811 "Non-nil means, lines starting with \"|\" are handled by the table editor.
812 When nil, such lines will be treated like ordinary lines.
814 When equal to the symbol `optimized', the table editor will be optimized to
815 do the following:
816 - Automatic overwrite mode in front of whitespace in table fields.
817 This makes the structure of the table stay in tact as long as the edited
818 field does not exceed the column width.
819 - Minimize the number of realigns. Normally, the table is aligned each time
820 TAB or RET are pressed to move to another field. With optimization this
821 happens only if changes to a field might have changed the column width.
822 Optimization requires replacing the functions `self-insert-command',
823 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
824 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
825 very good at guessing when a re-align will be necessary, but you can always
826 force one with \\[org-ctrl-c-ctrl-c].
828 If you would like to use the optimized version in Org-mode, but the
829 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
831 This variable can be used to turn on and off the table editor during a session,
832 but in order to toggle optimization, a restart is required.
834 See also the variable `org-table-auto-blank-field'."
835 :group 'org-table
836 :type '(choice
837 (const :tag "off" nil)
838 (const :tag "on" t)
839 (const :tag "on, optimized" optimized)))
841 (defcustom org-table-tab-recognizes-table.el t
842 "Non-nil means, TAB will automatically notice a table.el table.
843 When it sees such a table, it moves point into it and - if necessary -
844 calls `table-recognize-table'."
845 :group 'org-table-editing
846 :type 'boolean)
848 (defgroup org-link nil
849 "Options concerning links in Org-mode."
850 :tag "Org Link"
851 :group 'org)
853 (defvar org-link-abbrev-alist-local nil
854 "Buffer-local version of `org-link-abbrev-alist', which see.
855 The value of this is taken from the #+LINK lines.")
856 (make-variable-buffer-local 'org-link-abbrev-alist-local)
858 (defcustom org-link-abbrev-alist nil
859 "Alist of link abbreviations.
860 The car of each element is a string, to be replaced at the start of a link.
861 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
862 links in Org-mode buffers can have an optional tag after a double colon, e.g.
864 [[linkkey:tag][description]]
866 If REPLACE is a string, the tag will simply be appended to create the link.
867 If the string contains \"%s\", the tag will be inserted there. Alternatively,
868 the placeholder \"%h\" will cause a url-encoded version of the tag to
869 be inserted at that point (see the function `url-hexify-string').
871 REPLACE may also be a function that will be called with the tag as the
872 only argument to create the link, which should be returned as a string.
874 See the manual for examples."
875 :group 'org-link
876 :type '(repeat
877 (cons
878 (string :tag "Protocol")
879 (choice
880 (string :tag "Format")
881 (function)))))
883 (defcustom org-descriptive-links t
884 "Non-nil means, hide link part and only show description of bracket links.
885 Bracket links are like [[link][description]]. This variable sets the initial
886 state in new org-mode buffers. The setting can then be toggled on a
887 per-buffer basis from the Org->Hyperlinks menu."
888 :group 'org-link
889 :type 'boolean)
891 (defcustom org-link-file-path-type 'adaptive
892 "How the path name in file links should be stored.
893 Valid values are:
895 relative Relative to the current directory, i.e. the directory of the file
896 into which the link is being inserted.
897 absolute Absolute path, if possible with ~ for home directory.
898 noabbrev Absolute path, no abbreviation of home directory.
899 adaptive Use relative path for files in the current directory and sub-
900 directories of it. For other files, use an absolute path."
901 :group 'org-link
902 :type '(choice
903 (const relative)
904 (const absolute)
905 (const noabbrev)
906 (const adaptive)))
908 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
909 "Types of links that should be activated in Org-mode files.
910 This is a list of symbols, each leading to the activation of a certain link
911 type. In principle, it does not hurt to turn on most link types - there may
912 be a small gain when turning off unused link types. The types are:
914 bracket The recommended [[link][description]] or [[link]] links with hiding.
915 angular Links in angular brackets that may contain whitespace like
916 <bbdb:Carsten Dominik>.
917 plain Plain links in normal text, no whitespace, like http://google.com.
918 radio Text that is matched by a radio target, see manual for details.
919 tag Tag settings in a headline (link to tag search).
920 date Time stamps (link to calendar).
921 footnote Footnote labels.
923 Changing this variable requires a restart of Emacs to become effective."
924 :group 'org-link
925 :type '(set :greedy t
926 (const :tag "Double bracket links (new style)" bracket)
927 (const :tag "Angular bracket links (old style)" angular)
928 (const :tag "Plain text links" plain)
929 (const :tag "Radio target matches" radio)
930 (const :tag "Tags" tag)
931 (const :tag "Timestamps" date)
932 (const :tag "Footnotes" footnote)))
934 (defcustom org-make-link-description-function nil
935 "Function to use to generate link descriptions from links. If
936 nil the link location will be used. This function must take two
937 parameters; the first is the link and the second the description
938 org-insert-link has generated, and should return the description
939 to use."
940 :group 'org-link
941 :type 'function)
943 (defgroup org-link-store nil
944 "Options concerning storing links in Org-mode."
945 :tag "Org Store Link"
946 :group 'org-link)
948 (defcustom org-email-link-description-format "Email %c: %.30s"
949 "Format of the description part of a link to an email or usenet message.
950 The following %-escapes will be replaced by corresponding information:
952 %F full \"From\" field
953 %f name, taken from \"From\" field, address if no name
954 %T full \"To\" field
955 %t first name in \"To\" field, address if no name
956 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
957 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
958 %s subject
959 %m message-id.
961 You may use normal field width specification between the % and the letter.
962 This is for example useful to limit the length of the subject.
964 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
965 :group 'org-link-store
966 :type 'string)
968 (defcustom org-from-is-user-regexp
969 (let (r1 r2)
970 (when (and user-mail-address (not (string= user-mail-address "")))
971 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
972 (when (and user-full-name (not (string= user-full-name "")))
973 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
974 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
975 "Regexp matched against the \"From:\" header of an email or usenet message.
976 It should match if the message is from the user him/herself."
977 :group 'org-link-store
978 :type 'regexp)
980 (defcustom org-link-to-org-use-id 'create-if-interactive
981 "Non-nil means, storing a link to an Org file will use entry IDs.
983 Note that before this variable is even considered, org-id must be loaded,
984 to please customize `org-modules' and turn it on.
986 The variable can have the following values:
988 t Create an ID if needed to make a link to the current entry.
990 create-if-interactive
991 If `org-store-link' is called directly (interactively, as a user
992 command), do create an ID to support the link. But when doing the
993 job for remember, only use the ID if it already exists. The
994 purpose of this setting is to avoid proliferation of unwanted
995 IDs, just because you happen to be in an Org file when you
996 call `org-remember' that automatically and preemptively
997 creates a link. If you do want to get an ID link in a remember
998 template to an entry not having an ID, create it first by
999 explicitly creating a link to it, using `C-c C-l' first.
1001 use-existing
1002 Use existing ID, do not create one.
1004 nil Never use an ID to make a link, instead link using a text search for
1005 the headline text."
1006 :group 'org-link-store
1007 :type '(choice
1008 (const :tag "Create ID to make link" t)
1009 (const :tag "Create if string link interactively"
1010 'create-if-interactive)
1011 (const :tag "Only use existing" 'use-existing)
1012 (const :tag "Do not use ID to create link" nil)))
1014 (defcustom org-context-in-file-links t
1015 "Non-nil means, file links from `org-store-link' contain context.
1016 A search string will be added to the file name with :: as separator and
1017 used to find the context when the link is activated by the command
1018 `org-open-at-point'.
1019 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1020 negates this setting for the duration of the command."
1021 :group 'org-link-store
1022 :type 'boolean)
1024 (defcustom org-keep-stored-link-after-insertion nil
1025 "Non-nil means, keep link in list for entire session.
1027 The command `org-store-link' adds a link pointing to the current
1028 location to an internal list. These links accumulate during a session.
1029 The command `org-insert-link' can be used to insert links into any
1030 Org-mode file (offering completion for all stored links). When this
1031 option is nil, every link which has been inserted once using \\[org-insert-link]
1032 will be removed from the list, to make completing the unused links
1033 more efficient."
1034 :group 'org-link-store
1035 :type 'boolean)
1037 (defgroup org-link-follow nil
1038 "Options concerning following links in Org-mode."
1039 :tag "Org Follow Link"
1040 :group 'org-link)
1042 (defcustom org-link-translation-function nil
1043 "Function to translate links with different syntax to Org syntax.
1044 This can be used to translate links created for example by the Planner
1045 or emacs-wiki packages to Org syntax.
1046 The function must accept two parameters, a TYPE containing the link
1047 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1048 which is everything after the link protocol. It should return a cons
1049 with possibly modified values of type and path.
1050 Org contains a function for this, so if you set this variable to
1051 `org-translate-link-from-planner', you should be able follow many
1052 links created by planner."
1053 :group 'org-link-follow
1054 :type 'function)
1056 (defcustom org-follow-link-hook nil
1057 "Hook that is run after a link has been followed."
1058 :group 'org-link-follow
1059 :type 'hook)
1061 (defcustom org-tab-follows-link nil
1062 "Non-nil means, on links TAB will follow the link.
1063 Needs to be set before org.el is loaded."
1064 :group 'org-link-follow
1065 :type 'boolean)
1067 (defcustom org-return-follows-link nil
1068 "Non-nil means, on links RET will follow the link.
1069 Needs to be set before org.el is loaded."
1070 :group 'org-link-follow
1071 :type 'boolean)
1073 (defcustom org-mouse-1-follows-link
1074 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1075 "Non-nil means, mouse-1 on a link will follow the link.
1076 A longer mouse click will still set point. Does not work on XEmacs.
1077 Needs to be set before org.el is loaded."
1078 :group 'org-link-follow
1079 :type 'boolean)
1081 (defcustom org-mark-ring-length 4
1082 "Number of different positions to be recorded in the ring
1083 Changing this requires a restart of Emacs to work correctly."
1084 :group 'org-link-follow
1085 :type 'integer)
1087 (defcustom org-link-frame-setup
1088 '((vm . vm-visit-folder-other-frame)
1089 (gnus . gnus-other-frame)
1090 (file . find-file-other-window))
1091 "Setup the frame configuration for following links.
1092 When following a link with Emacs, it may often be useful to display
1093 this link in another window or frame. This variable can be used to
1094 set this up for the different types of links.
1095 For VM, use any of
1096 `vm-visit-folder'
1097 `vm-visit-folder-other-frame'
1098 For Gnus, use any of
1099 `gnus'
1100 `gnus-other-frame'
1101 `org-gnus-no-new-news'
1102 For FILE, use any of
1103 `find-file'
1104 `find-file-other-window'
1105 `find-file-other-frame'
1106 For the calendar, use the variable `calendar-setup'.
1107 For BBDB, it is currently only possible to display the matches in
1108 another window."
1109 :group 'org-link-follow
1110 :type '(list
1111 (cons (const vm)
1112 (choice
1113 (const vm-visit-folder)
1114 (const vm-visit-folder-other-window)
1115 (const vm-visit-folder-other-frame)))
1116 (cons (const gnus)
1117 (choice
1118 (const gnus)
1119 (const gnus-other-frame)
1120 (const org-gnus-no-new-news)))
1121 (cons (const file)
1122 (choice
1123 (const find-file)
1124 (const find-file-other-window)
1125 (const find-file-other-frame)))))
1127 (defcustom org-display-internal-link-with-indirect-buffer nil
1128 "Non-nil means, use indirect buffer to display infile links.
1129 Activating internal links (from one location in a file to another location
1130 in the same file) normally just jumps to the location. When the link is
1131 activated with a C-u prefix (or with mouse-3), the link is displayed in
1132 another window. When this option is set, the other window actually displays
1133 an indirect buffer clone of the current buffer, to avoid any visibility
1134 changes to the current buffer."
1135 :group 'org-link-follow
1136 :type 'boolean)
1138 (defcustom org-open-non-existing-files nil
1139 "Non-nil means, `org-open-file' will open non-existing files.
1140 When nil, an error will be generated."
1141 :group 'org-link-follow
1142 :type 'boolean)
1144 (defcustom org-open-directory-means-index-dot-org nil
1145 "Non-nil means, a link to a directory really means to index.org.
1146 When nil, following a directory link will run dired or open a finder/explorer
1147 window on that directory."
1148 :group 'org-link-follow
1149 :type 'boolean)
1151 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1152 "Function and arguments to call for following mailto links.
1153 This is a list with the first element being a lisp function, and the
1154 remaining elements being arguments to the function. In string arguments,
1155 %a will be replaced by the address, and %s will be replaced by the subject
1156 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1157 :group 'org-link-follow
1158 :type '(choice
1159 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1160 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1161 (const :tag "message-mail" (message-mail "%a" "%s"))
1162 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1164 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1165 "Non-nil means, ask for confirmation before executing shell links.
1166 Shell links can be dangerous: just think about a link
1168 [[shell:rm -rf ~/*][Google Search]]
1170 This link would show up in your Org-mode document as \"Google Search\",
1171 but really it would remove your entire home directory.
1172 Therefore we advise against setting this variable to nil.
1173 Just change it to `y-or-n-p' of you want to confirm with a
1174 single keystroke rather than having to type \"yes\"."
1175 :group 'org-link-follow
1176 :type '(choice
1177 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1178 (const :tag "with y-or-n (faster)" y-or-n-p)
1179 (const :tag "no confirmation (dangerous)" nil)))
1181 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1182 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1183 Elisp links can be dangerous: just think about a link
1185 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1187 This link would show up in your Org-mode document as \"Google Search\",
1188 but really it would remove your entire home directory.
1189 Therefore we advise against setting this variable to nil.
1190 Just change it to `y-or-n-p' of you want to confirm with a
1191 single keystroke rather than having to type \"yes\"."
1192 :group 'org-link-follow
1193 :type '(choice
1194 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1195 (const :tag "with y-or-n (faster)" y-or-n-p)
1196 (const :tag "no confirmation (dangerous)" nil)))
1198 (defconst org-file-apps-defaults-gnu
1199 '((remote . emacs)
1200 (system . mailcap)
1201 (t . mailcap))
1202 "Default file applications on a UNIX or GNU/Linux system.
1203 See `org-file-apps'.")
1205 (defconst org-file-apps-defaults-macosx
1206 '((remote . emacs)
1207 (t . "open %s")
1208 (system . "open %s")
1209 ("ps.gz" . "gv %s")
1210 ("eps.gz" . "gv %s")
1211 ("dvi" . "xdvi %s")
1212 ("fig" . "xfig %s"))
1213 "Default file applications on a MacOS X system.
1214 The system \"open\" is known as a default, but we use X11 applications
1215 for some files for which the OS does not have a good default.
1216 See `org-file-apps'.")
1218 (defconst org-file-apps-defaults-windowsnt
1219 (list
1220 '(remote . emacs)
1221 (cons t
1222 (list (if (featurep 'xemacs)
1223 'mswindows-shell-execute
1224 'w32-shell-execute)
1225 "open" 'file))
1226 (cons 'system
1227 (list (if (featurep 'xemacs)
1228 'mswindows-shell-execute
1229 'w32-shell-execute)
1230 "open" 'file)))
1231 "Default file applications on a Windows NT system.
1232 The system \"open\" is used for most files.
1233 See `org-file-apps'.")
1235 (defcustom org-file-apps
1237 (auto-mode . emacs)
1238 ("\\.x?html?\\'" . default)
1239 ("\\.pdf\\'" . default)
1241 "External applications for opening `file:path' items in a document.
1242 Org-mode uses system defaults for different file types, but
1243 you can use this variable to set the application for a given file
1244 extension. The entries in this list are cons cells where the car identifies
1245 files and the cdr the corresponding command. Possible values for the
1246 file identifier are
1247 \"regex\" Regular expression matched against the file name. For backward
1248 compatibility, this can also be a string with only alphanumeric
1249 characters, which is then interpreted as an extension.
1250 `directory' Matches a directory
1251 `remote' Matches a remote file, accessible through tramp or efs.
1252 Remote files most likely should be visited through Emacs
1253 because external applications cannot handle such paths.
1254 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1255 so all files Emacs knows how to handle. Using this with
1256 command `emacs' will open most files in Emacs. Beware that this
1257 will also open html files inside Emacs, unless you add
1258 (\"html\" . default) to the list as well.
1259 t Default for files not matched by any of the other options.
1260 `system' The system command to open files, like `open' on Windows
1261 and Mac OS X, and mailcap under GNU/Linux. This is the command
1262 that will be selected if you call `C-c C-o' with a double
1263 `C-u C-u' prefix.
1265 Possible values for the command are:
1266 `emacs' The file will be visited by the current Emacs process.
1267 `default' Use the default application for this file type, which is the
1268 association for t in the list, most likely in the system-specific
1269 part.
1270 This can be used to overrule an unwanted setting in the
1271 system-specific variable.
1272 `system' Use the system command for opening files, like \"open\".
1273 This command is specified by the entry whose car is `system'.
1274 Most likely, the system-specific version of this variable
1275 does define this command, but you can overrule/replace it
1276 here.
1277 string A command to be executed by a shell; %s will be replaced
1278 by the path to the file.
1279 sexp A Lisp form which will be evaluated. The file path will
1280 be available in the Lisp variable `file'.
1281 For more examples, see the system specific constants
1282 `org-file-apps-defaults-macosx'
1283 `org-file-apps-defaults-windowsnt'
1284 `org-file-apps-defaults-gnu'."
1285 :group 'org-link-follow
1286 :type '(repeat
1287 (cons (choice :value ""
1288 (string :tag "Extension")
1289 (const :tag "System command to open files" system)
1290 (const :tag "Default for unrecognized files" t)
1291 (const :tag "Remote file" remote)
1292 (const :tag "Links to a directory" directory)
1293 (const :tag "Any files that have Emacs modes"
1294 auto-mode))
1295 (choice :value ""
1296 (const :tag "Visit with Emacs" emacs)
1297 (const :tag "Use default" default)
1298 (const :tag "Use the system command" system)
1299 (string :tag "Command")
1300 (sexp :tag "Lisp form")))))
1302 (defgroup org-refile nil
1303 "Options concerning refiling entries in Org-mode."
1304 :tag "Org Refile"
1305 :group 'org)
1307 (defcustom org-directory "~/org"
1308 "Directory with org files.
1309 This directory will be used as default to prompt for org files.
1310 Used by the hooks for remember.el."
1311 :group 'org-refile
1312 :group 'org-remember
1313 :type 'directory)
1315 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1316 "Default target for storing notes.
1317 Used by the hooks for remember.el. This can be a string, or nil to mean
1318 the value of `remember-data-file'.
1319 You can set this on a per-template basis with the variable
1320 `org-remember-templates'."
1321 :group 'org-refile
1322 :group 'org-remember
1323 :type '(choice
1324 (const :tag "Default from remember-data-file" nil)
1325 file))
1327 (defcustom org-goto-interface 'outline
1328 "The default interface to be used for `org-goto'.
1329 Allowed values are:
1330 outline The interface shows an outline of the relevant file
1331 and the correct heading is found by moving through
1332 the outline or by searching with incremental search.
1333 outline-path-completion Headlines in the current buffer are offered via
1334 completion. This is the interface also used by
1335 the refile command."
1336 :group 'org-refile
1337 :type '(choice
1338 (const :tag "Outline" outline)
1339 (const :tag "Outline-path-completion" outline-path-completion)))
1341 (defcustom org-goto-max-level 5
1342 "Maximum level to be considered when running org-goto with refile interface."
1343 :group 'org-refile
1344 :type 'number)
1346 (defcustom org-reverse-note-order nil
1347 "Non-nil means, store new notes at the beginning of a file or entry.
1348 When nil, new notes will be filed to the end of a file or entry.
1349 This can also be a list with cons cells of regular expressions that
1350 are matched against file names, and values."
1351 :group 'org-remember
1352 :group 'org-refile
1353 :type '(choice
1354 (const :tag "Reverse always" t)
1355 (const :tag "Reverse never" nil)
1356 (repeat :tag "By file name regexp"
1357 (cons regexp boolean))))
1359 (defcustom org-refile-targets nil
1360 "Targets for refiling entries with \\[org-refile].
1361 This is list of cons cells. Each cell contains:
1362 - a specification of the files to be considered, either a list of files,
1363 or a symbol whose function or variable value will be used to retrieve
1364 a file name or a list of file names. If you use `org-agenda-files' for
1365 that, all agenda files will be scanned for targets. Nil means, consider
1366 headings in the current buffer.
1367 - A specification of how to select find candidate refile targets. This
1368 may be any of
1369 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1370 This tag has to be present in all target headlines, inheritance will
1371 not be considered.
1372 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1373 todo keyword.
1374 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1375 headlines that are refiling targets.
1376 - a cons cell (:level . N). Any headline of level N is considered a target.
1377 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1379 When this variable is nil, all top-level headlines in the current buffer
1380 are used, equivalent to the value `((nil . (:level . 1))'."
1381 :group 'org-refile
1382 :type '(repeat
1383 (cons
1384 (choice :value org-agenda-files
1385 (const :tag "All agenda files" org-agenda-files)
1386 (const :tag "Current buffer" nil)
1387 (function) (variable) (file))
1388 (choice :tag "Identify target headline by"
1389 (cons :tag "Specific tag" (const :value :tag) (string))
1390 (cons :tag "TODO keyword" (const :value :todo) (string))
1391 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1392 (cons :tag "Level number" (const :value :level) (integer))
1393 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1395 (defcustom org-refile-use-outline-path nil
1396 "Non-nil means, provide refile targets as paths.
1397 So a level 3 headline will be available as level1/level2/level3.
1398 When the value is `file', also include the file name (without directory)
1399 into the path. When `full-file-path', include the full file path."
1400 :group 'org-refile
1401 :type '(choice
1402 (const :tag "Not" nil)
1403 (const :tag "Yes" t)
1404 (const :tag "Start with file name" file)
1405 (const :tag "Start with full file path" full-file-path)))
1407 (defcustom org-outline-path-complete-in-steps t
1408 "Non-nil means, complete the outline path in hierarchical steps.
1409 When Org-mode uses the refile interface to select an outline path
1410 \(see variable `org-refile-use-outline-path'), the completion of
1411 the path can be done is a single go, or if can be done in steps down
1412 the headline hierarchy. Going in steps is probably the best if you
1413 do not use a special completion package like `ido' or `icicles'.
1414 However, when using these packages, going in one step can be very
1415 fast, while still showing the whole path to the entry."
1416 :group 'org-refile
1417 :type 'boolean)
1419 (defgroup org-todo nil
1420 "Options concerning TODO items in Org-mode."
1421 :tag "Org TODO"
1422 :group 'org)
1424 (defgroup org-progress nil
1425 "Options concerning Progress logging in Org-mode."
1426 :tag "Org Progress"
1427 :group 'org-time)
1429 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1430 "List of TODO entry keyword sequences and their interpretation.
1431 \\<org-mode-map>This is a list of sequences.
1433 Each sequence starts with a symbol, either `sequence' or `type',
1434 indicating if the keywords should be interpreted as a sequence of
1435 action steps, or as different types of TODO items. The first
1436 keywords are states requiring action - these states will select a headline
1437 for inclusion into the global TODO list Org-mode produces. If one of
1438 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1439 signify that no further action is necessary. If \"|\" is not found,
1440 the last keyword is treated as the only DONE state of the sequence.
1442 The command \\[org-todo] cycles an entry through these states, and one
1443 additional state where no keyword is present. For details about this
1444 cycling, see the manual.
1446 TODO keywords and interpretation can also be set on a per-file basis with
1447 the special #+SEQ_TODO and #+TYP_TODO lines.
1449 Each keyword can optionally specify a character for fast state selection
1450 \(in combination with the variable `org-use-fast-todo-selection')
1451 and specifiers for state change logging, using the same syntax
1452 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1453 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1454 indicates to record a time stamp each time this state is selected.
1456 Each keyword may also specify if a timestamp or a note should be
1457 recorded when entering or leaving the state, by adding additional
1458 characters in the parenthesis after the keyword. This looks like this:
1459 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1460 record only the time of the state change. With X and Y being either
1461 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1462 Y when leaving the state if and only if the *target* state does not
1463 define X. You may omit any of the fast-selection key or X or /Y,
1464 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1466 For backward compatibility, this variable may also be just a list
1467 of keywords - in this case the interpretation (sequence or type) will be
1468 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1469 :group 'org-todo
1470 :group 'org-keywords
1471 :type '(choice
1472 (repeat :tag "Old syntax, just keywords"
1473 (string :tag "Keyword"))
1474 (repeat :tag "New syntax"
1475 (cons
1476 (choice
1477 :tag "Interpretation"
1478 (const :tag "Sequence (cycling hits every state)" sequence)
1479 (const :tag "Type (cycling directly to DONE)" type))
1480 (repeat
1481 (string :tag "Keyword"))))))
1483 (defvar org-todo-keywords-1 nil
1484 "All TODO and DONE keywords active in a buffer.")
1485 (make-variable-buffer-local 'org-todo-keywords-1)
1486 (defvar org-todo-keywords-for-agenda nil)
1487 (defvar org-done-keywords-for-agenda nil)
1488 (defvar org-todo-keyword-alist-for-agenda nil)
1489 (defvar org-tag-alist-for-agenda nil)
1490 (defvar org-agenda-contributing-files nil)
1491 (defvar org-not-done-keywords nil)
1492 (make-variable-buffer-local 'org-not-done-keywords)
1493 (defvar org-done-keywords nil)
1494 (make-variable-buffer-local 'org-done-keywords)
1495 (defvar org-todo-heads nil)
1496 (make-variable-buffer-local 'org-todo-heads)
1497 (defvar org-todo-sets nil)
1498 (make-variable-buffer-local 'org-todo-sets)
1499 (defvar org-todo-log-states nil)
1500 (make-variable-buffer-local 'org-todo-log-states)
1501 (defvar org-todo-kwd-alist nil)
1502 (make-variable-buffer-local 'org-todo-kwd-alist)
1503 (defvar org-todo-key-alist nil)
1504 (make-variable-buffer-local 'org-todo-key-alist)
1505 (defvar org-todo-key-trigger nil)
1506 (make-variable-buffer-local 'org-todo-key-trigger)
1508 (defcustom org-todo-interpretation 'sequence
1509 "Controls how TODO keywords are interpreted.
1510 This variable is in principle obsolete and is only used for
1511 backward compatibility, if the interpretation of todo keywords is
1512 not given already in `org-todo-keywords'. See that variable for
1513 more information."
1514 :group 'org-todo
1515 :group 'org-keywords
1516 :type '(choice (const sequence)
1517 (const type)))
1519 (defcustom org-use-fast-todo-selection 'prefix
1520 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1521 This variable describes if and under what circumstances the cycling
1522 mechanism for TODO keywords will be replaced by a single-key, direct
1523 selection scheme.
1525 When nil, fast selection is never used.
1527 When the symbol `prefix', it will be used when `org-todo' is called with
1528 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1529 in an agenda buffer.
1531 When t, fast selection is used by default. In this case, the prefix
1532 argument forces cycling instead.
1534 In all cases, the special interface is only used if access keys have actually
1535 been assigned by the user, i.e. if keywords in the configuration are followed
1536 by a letter in parenthesis, like TODO(t)."
1537 :group 'org-todo
1538 :type '(choice
1539 (const :tag "Never" nil)
1540 (const :tag "By default" t)
1541 (const :tag "Only with C-u C-c C-t" prefix)))
1543 (defcustom org-provide-todo-statistics t
1544 "Non-nil means, update todo statistics after insert and toggle.
1545 When this is set, todo statistics is updated in the parent of the current
1546 entry each time a todo state is changed."
1547 :group 'org-todo
1548 :type 'boolean)
1550 (defcustom org-after-todo-state-change-hook nil
1551 "Hook which is run after the state of a TODO item was changed.
1552 The new state (a string with a TODO keyword, or nil) is available in the
1553 Lisp variable `state'."
1554 :group 'org-todo
1555 :type 'hook)
1557 (defcustom org-todo-state-tags-triggers nil
1558 "Tag changes that should be triggered by TODO state changes.
1559 This is a list. Each entry is
1561 (state-change (tag . flag) .......)
1563 State-change can be a string with a state, and empty string to indicate the
1564 state that has no TODO keyword, or it can be one of the symbols `todo'
1565 or `done', meaning any not-done or done state, respectively."
1566 :group 'org-todo
1567 :group 'org-tags
1568 :type '(repeat
1569 (cons (choice :tag "When changing to"
1570 (const :tag "Not-done state" todo)
1571 (const :tag "Done state" done)
1572 (string :tag "State"))
1573 (repeat
1574 (cons :tag "Tag action"
1575 (string :tag "Tag")
1576 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1578 (defcustom org-log-done nil
1579 "Information to record when a task moves to the DONE state.
1581 Possible values are:
1583 nil Don't add anything, just change the keyword
1584 time Add a time stamp to the task
1585 note Prompt a closing note and add it with template `org-log-note-headings'
1587 This option can also be set with on a per-file-basis with
1589 #+STARTUP: nologdone
1590 #+STARTUP: logdone
1591 #+STARTUP: lognotedone
1593 You can have local logging settings for a subtree by setting the LOGGING
1594 property to one or more of these keywords."
1595 :group 'org-todo
1596 :group 'org-progress
1597 :type '(choice
1598 (const :tag "No logging" nil)
1599 (const :tag "Record CLOSED timestamp" time)
1600 (const :tag "Record CLOSED timestamp with closing note." note)))
1602 ;; Normalize old uses of org-log-done.
1603 (cond
1604 ((eq org-log-done t) (setq org-log-done 'time))
1605 ((and (listp org-log-done) (memq 'done org-log-done))
1606 (setq org-log-done 'note)))
1608 (defcustom org-log-note-clock-out nil
1609 "Non-nil means, record a note when clocking out of an item.
1610 This can also be configured on a per-file basis by adding one of
1611 the following lines anywhere in the buffer:
1613 #+STARTUP: lognoteclock-out
1614 #+STARTUP: nolognoteclock-out"
1615 :group 'org-todo
1616 :group 'org-progress
1617 :type 'boolean)
1619 (defcustom org-log-done-with-time t
1620 "Non-nil means, the CLOSED time stamp will contain date and time.
1621 When nil, only the date will be recorded."
1622 :group 'org-progress
1623 :type 'boolean)
1625 (defcustom org-log-note-headings
1626 '((done . "CLOSING NOTE %t")
1627 (state . "State %-12s %t")
1628 (note . "Note taken on %t")
1629 (clock-out . ""))
1630 "Headings for notes added to entries.
1631 The value is an alist, with the car being a symbol indicating the note
1632 context, and the cdr is the heading to be used. The heading may also be the
1633 empty string.
1634 %t in the heading will be replaced by a time stamp.
1635 %s will be replaced by the new TODO state, in double quotes.
1636 %u will be replaced by the user name.
1637 %U will be replaced by the full user name."
1638 :group 'org-todo
1639 :group 'org-progress
1640 :type '(list :greedy t
1641 (cons (const :tag "Heading when closing an item" done) string)
1642 (cons (const :tag
1643 "Heading when changing todo state (todo sequence only)"
1644 state) string)
1645 (cons (const :tag "Heading when just taking a note" note) string)
1646 (cons (const :tag "Heading when clocking out" clock-out) string)))
1648 (unless (assq 'note org-log-note-headings)
1649 (push '(note . "%t") org-log-note-headings))
1651 (defcustom org-log-state-notes-insert-after-drawers nil
1652 "Non-nil means, insert state change notes after any drawers in entry.
1653 Only the drawers that *immediately* follow the headline and the
1654 deadline/scheduled line are skipped.
1655 When nil, insert notes right after the heading and perhaps the line
1656 with deadline/scheduling if present."
1657 :group 'org-todo
1658 :group 'org-progress
1659 :type 'boolean)
1661 (defcustom org-log-states-order-reversed t
1662 "Non-nil means, the latest state change note will be directly after heading.
1663 When nil, the notes will be orderer according to time."
1664 :group 'org-todo
1665 :group 'org-progress
1666 :type 'boolean)
1668 (defcustom org-log-repeat 'time
1669 "Non-nil means, record moving through the DONE state when triggering repeat.
1670 An auto-repeating tasks is immediately switched back to TODO when marked
1671 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1672 the TODO keyword definition, or recording a closing note by setting
1673 `org-log-done', there will be no record of the task moving through DONE.
1674 This variable forces taking a note anyway. Possible values are:
1676 nil Don't force a record
1677 time Record a time stamp
1678 note Record a note
1680 This option can also be set with on a per-file-basis with
1682 #+STARTUP: logrepeat
1683 #+STARTUP: lognoterepeat
1684 #+STARTUP: nologrepeat
1686 You can have local logging settings for a subtree by setting the LOGGING
1687 property to one or more of these keywords."
1688 :group 'org-todo
1689 :group 'org-progress
1690 :type '(choice
1691 (const :tag "Don't force a record" nil)
1692 (const :tag "Force recording the DONE state" time)
1693 (const :tag "Force recording a note with the DONE state" note)))
1696 (defgroup org-priorities nil
1697 "Priorities in Org-mode."
1698 :tag "Org Priorities"
1699 :group 'org-todo)
1701 (defcustom org-highest-priority ?A
1702 "The highest priority of TODO items. A character like ?A, ?B etc.
1703 Must have a smaller ASCII number than `org-lowest-priority'."
1704 :group 'org-priorities
1705 :type 'character)
1707 (defcustom org-lowest-priority ?C
1708 "The lowest priority of TODO items. A character like ?A, ?B etc.
1709 Must have a larger ASCII number than `org-highest-priority'."
1710 :group 'org-priorities
1711 :type 'character)
1713 (defcustom org-default-priority ?B
1714 "The default priority of TODO items.
1715 This is the priority an item get if no explicit priority is given."
1716 :group 'org-priorities
1717 :type 'character)
1719 (defcustom org-priority-start-cycle-with-default t
1720 "Non-nil means, start with default priority when starting to cycle.
1721 When this is nil, the first step in the cycle will be (depending on the
1722 command used) one higher or lower that the default priority."
1723 :group 'org-priorities
1724 :type 'boolean)
1726 (defgroup org-time nil
1727 "Options concerning time stamps and deadlines in Org-mode."
1728 :tag "Org Time"
1729 :group 'org)
1731 (defcustom org-insert-labeled-timestamps-at-point nil
1732 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1733 When nil, these labeled time stamps are forces into the second line of an
1734 entry, just after the headline. When scheduling from the global TODO list,
1735 the time stamp will always be forced into the second line."
1736 :group 'org-time
1737 :type 'boolean)
1739 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1740 "Formats for `format-time-string' which are used for time stamps.
1741 It is not recommended to change this constant.")
1743 (defcustom org-time-stamp-rounding-minutes '(0 5)
1744 "Number of minutes to round time stamps to.
1745 These are two values, the first applies when first creating a time stamp.
1746 The second applies when changing it with the commands `S-up' and `S-down'.
1747 When changing the time stamp, this means that it will change in steps
1748 of N minutes, as given by the second value.
1750 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1751 numbers should be factors of 60, so for example 5, 10, 15.
1753 When this is larger than 1, you can still force an exact time-stamp by using
1754 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1755 and by using a prefix arg to `S-up/down' to specify the exact number
1756 of minutes to shift."
1757 :group 'org-time
1758 :get '(lambda (var) ; Make sure all entries have 5 elements
1759 (if (integerp (default-value var))
1760 (list (default-value var) 5)
1761 (default-value var)))
1762 :type '(list
1763 (integer :tag "when inserting times")
1764 (integer :tag "when modifying times")))
1766 ;; Normalize old customizations of this variable.
1767 (when (integerp org-time-stamp-rounding-minutes)
1768 (setq org-time-stamp-rounding-minutes
1769 (list org-time-stamp-rounding-minutes
1770 org-time-stamp-rounding-minutes)))
1772 (defcustom org-display-custom-times nil
1773 "Non-nil means, overlay custom formats over all time stamps.
1774 The formats are defined through the variable `org-time-stamp-custom-formats'.
1775 To turn this on on a per-file basis, insert anywhere in the file:
1776 #+STARTUP: customtime"
1777 :group 'org-time
1778 :set 'set-default
1779 :type 'sexp)
1780 (make-variable-buffer-local 'org-display-custom-times)
1782 (defcustom org-time-stamp-custom-formats
1783 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1784 "Custom formats for time stamps. See `format-time-string' for the syntax.
1785 These are overlayed over the default ISO format if the variable
1786 `org-display-custom-times' is set. Time like %H:%M should be at the
1787 end of the second format."
1788 :group 'org-time
1789 :type 'sexp)
1791 (defun org-time-stamp-format (&optional long inactive)
1792 "Get the right format for a time string."
1793 (let ((f (if long (cdr org-time-stamp-formats)
1794 (car org-time-stamp-formats))))
1795 (if inactive
1796 (concat "[" (substring f 1 -1) "]")
1797 f)))
1799 (defcustom org-time-clocksum-format "%d:%02d"
1800 "The format string used when creating CLOCKSUM lines, or when
1801 org-mode generates a time duration."
1802 :group 'org-time
1803 :type 'string)
1805 (defcustom org-deadline-warning-days 14
1806 "No. of days before expiration during which a deadline becomes active.
1807 This variable governs the display in sparse trees and in the agenda.
1808 When 0 or negative, it means use this number (the absolute value of it)
1809 even if a deadline has a different individual lead time specified."
1810 :group 'org-time
1811 :group 'org-agenda-daily/weekly
1812 :type 'number)
1814 (defcustom org-read-date-prefer-future t
1815 "Non-nil means, assume future for incomplete date input from user.
1816 This affects the following situations:
1817 1. The user gives a day, but no month.
1818 For example, if today is the 15th, and you enter \"3\", Org-mode will
1819 read this as the third of *next* month. However, if you enter \"17\",
1820 it will be considered as *this* month.
1821 2. The user gives a month but not a year.
1822 For example, if it is april and you enter \"feb 2\", this will be read
1823 as feb 2, *next* year. \"May 5\", however, will be this year.
1825 Currently this does not work for ISO week specifications.
1827 When this option is nil, the current month and year will always be used
1828 as defaults."
1829 :group 'org-time
1830 :type 'boolean)
1832 (defcustom org-read-date-display-live t
1833 "Non-nil means, display current interpretation of date prompt live.
1834 This display will be in an overlay, in the minibuffer."
1835 :group 'org-time
1836 :type 'boolean)
1838 (defcustom org-read-date-popup-calendar t
1839 "Non-nil means, pop up a calendar when prompting for a date.
1840 In the calendar, the date can be selected with mouse-1. However, the
1841 minibuffer will also be active, and you can simply enter the date as well.
1842 When nil, only the minibuffer will be available."
1843 :group 'org-time
1844 :type 'boolean)
1845 (if (fboundp 'defvaralias)
1846 (defvaralias 'org-popup-calendar-for-date-prompt
1847 'org-read-date-popup-calendar))
1849 (defcustom org-extend-today-until 0
1850 "The hour when your day really ends. Must be an integer.
1851 This has influence for the following applications:
1852 - When switching the agenda to \"today\". It it is still earlier than
1853 the time given here, the day recognized as TODAY is actually yesterday.
1854 - When a date is read from the user and it is still before the time given
1855 here, the current date and time will be assumed to be yesterday, 23:59.
1856 Also, timestamps inserted in remember templates follow this rule.
1858 IMPORTANT: This is a feature whose implementation is and likely will
1859 remain incomplete. Really, it is only here because past midnight seems to
1860 be the favorite working time of John Wiegley :-)"
1861 :group 'org-time
1862 :type 'number)
1864 (defcustom org-edit-timestamp-down-means-later nil
1865 "Non-nil means, S-down will increase the time in a time stamp.
1866 When nil, S-up will increase."
1867 :group 'org-time
1868 :type 'boolean)
1870 (defcustom org-calendar-follow-timestamp-change t
1871 "Non-nil means, make the calendar window follow timestamp changes.
1872 When a timestamp is modified and the calendar window is visible, it will be
1873 moved to the new date."
1874 :group 'org-time
1875 :type 'boolean)
1877 (defgroup org-tags nil
1878 "Options concerning tags in Org-mode."
1879 :tag "Org Tags"
1880 :group 'org)
1882 (defcustom org-tag-alist nil
1883 "List of tags allowed in Org-mode files.
1884 When this list is nil, Org-mode will base TAG input on what is already in the
1885 buffer.
1886 The value of this variable is an alist, the car of each entry must be a
1887 keyword as a string, the cdr may be a character that is used to select
1888 that tag through the fast-tag-selection interface.
1889 See the manual for details."
1890 :group 'org-tags
1891 :type '(repeat
1892 (choice
1893 (cons (string :tag "Tag name")
1894 (character :tag "Access char"))
1895 (const :tag "Start radio group" (:startgroup))
1896 (const :tag "End radio group" (:endgroup)))))
1898 (defvar org-file-tags nil
1899 "List of tags that can be inherited by all entries in the file.
1900 The tags will be inherited if the variable `org-use-tag-inheritance'
1901 says they should be.
1902 This variable is populated from #+TAG lines.")
1904 (defcustom org-use-fast-tag-selection 'auto
1905 "Non-nil means, use fast tag selection scheme.
1906 This is a special interface to select and deselect tags with single keys.
1907 When nil, fast selection is never used.
1908 When the symbol `auto', fast selection is used if and only if selection
1909 characters for tags have been configured, either through the variable
1910 `org-tag-alist' or through a #+TAGS line in the buffer.
1911 When t, fast selection is always used and selection keys are assigned
1912 automatically if necessary."
1913 :group 'org-tags
1914 :type '(choice
1915 (const :tag "Always" t)
1916 (const :tag "Never" nil)
1917 (const :tag "When selection characters are configured" 'auto)))
1919 (defcustom org-fast-tag-selection-single-key nil
1920 "Non-nil means, fast tag selection exits after first change.
1921 When nil, you have to press RET to exit it.
1922 During fast tag selection, you can toggle this flag with `C-c'.
1923 This variable can also have the value `expert'. In this case, the window
1924 displaying the tags menu is not even shown, until you press C-c again."
1925 :group 'org-tags
1926 :type '(choice
1927 (const :tag "No" nil)
1928 (const :tag "Yes" t)
1929 (const :tag "Expert" expert)))
1931 (defvar org-fast-tag-selection-include-todo nil
1932 "Non-nil means, fast tags selection interface will also offer TODO states.
1933 This is an undocumented feature, you should not rely on it.")
1935 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1936 "The column to which tags should be indented in a headline.
1937 If this number is positive, it specifies the column. If it is negative,
1938 it means that the tags should be flushright to that column. For example,
1939 -80 works well for a normal 80 character screen."
1940 :group 'org-tags
1941 :type 'integer)
1943 (defcustom org-auto-align-tags t
1944 "Non-nil means, realign tags after pro/demotion of TODO state change.
1945 These operations change the length of a headline and therefore shift
1946 the tags around. With this options turned on, after each such operation
1947 the tags are again aligned to `org-tags-column'."
1948 :group 'org-tags
1949 :type 'boolean)
1951 (defcustom org-use-tag-inheritance t
1952 "Non-nil means, tags in levels apply also for sublevels.
1953 When nil, only the tags directly given in a specific line apply there.
1954 This may also be a list of tags that should be inherited, or a regexp that
1955 matches tags that should be inherited. Additional control is possible
1956 with the variable `org-tags-exclude-from-inheritance' which gives an
1957 explicit list of tags to be excluded from inheritance., even if the value of
1958 `org-use-tag-inheritance' would select it for inheritance.
1960 If this option is t, a match early-on in a tree can lead to a large
1961 number of matches in the subtree when constructing the agenda or creating
1962 a sparse tree. If you only want to see the first match in a tree during
1963 a search, check out the variable `org-tags-match-list-sublevels'."
1964 :group 'org-tags
1965 :type '(choice
1966 (const :tag "Not" nil)
1967 (const :tag "Always" t)
1968 (repeat :tag "Specific tags" (string :tag "Tag"))
1969 (regexp :tag "Tags matched by regexp")))
1971 (defcustom org-tags-exclude-from-inheritance nil
1972 "List of tags that should never be inherited.
1973 This is a way to exclude a few tags from inheritance. For way to do
1974 the opposite, to actively allow inheritance for selected tags,
1975 see the variable `org-use-tag-inheritance'."
1976 :group 'org-tags
1977 :type '(repeat (string :tag "Tag")))
1979 (defun org-tag-inherit-p (tag)
1980 "Check if TAG is one that should be inherited."
1981 (cond
1982 ((member tag org-tags-exclude-from-inheritance) nil)
1983 ((eq org-use-tag-inheritance t) t)
1984 ((not org-use-tag-inheritance) nil)
1985 ((stringp org-use-tag-inheritance)
1986 (string-match org-use-tag-inheritance tag))
1987 ((listp org-use-tag-inheritance)
1988 (member tag org-use-tag-inheritance))
1989 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1991 (defcustom org-tags-match-list-sublevels t
1992 "Non-nil means list also sublevels of headlines matching tag search.
1993 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1994 the sublevels of a headline matching a tag search often also match
1995 the same search. Listing all of them can create very long lists.
1996 Setting this variable to nil causes subtrees of a match to be skipped.
1997 This option is off by default, because inheritance in on. If you turn
1998 inheritance off, you very likely want to turn this option on.
2000 As a special case, if the tag search is restricted to TODO items, the
2001 value of this variable is ignored and sublevels are always checked, to
2002 make sure all corresponding TODO items find their way into the list.
2004 This variable is semi-obsolete and probably should always be true. It
2005 is better to limit inheritance to certain tags using the variables
2006 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2007 :group 'org-tags
2008 :type 'boolean)
2010 (defvar org-tags-history nil
2011 "History of minibuffer reads for tags.")
2012 (defvar org-last-tags-completion-table nil
2013 "The last used completion table for tags.")
2014 (defvar org-after-tags-change-hook nil
2015 "Hook that is run after the tags in a line have changed.")
2017 (defgroup org-properties nil
2018 "Options concerning properties in Org-mode."
2019 :tag "Org Properties"
2020 :group 'org)
2022 (defcustom org-property-format "%-10s %s"
2023 "How property key/value pairs should be formatted by `indent-line'.
2024 When `indent-line' hits a property definition, it will format the line
2025 according to this format, mainly to make sure that the values are
2026 lined-up with respect to each other."
2027 :group 'org-properties
2028 :type 'string)
2030 (defcustom org-use-property-inheritance nil
2031 "Non-nil means, properties apply also for sublevels.
2033 This setting is chiefly used during property searches. Turning it on can
2034 cause significant overhead when doing a search, which is why it is not
2035 on by default.
2037 When nil, only the properties directly given in the current entry count.
2038 When t, every property is inherited. The value may also be a list of
2039 properties that should have inheritance, or a regular expression matching
2040 properties that should be inherited.
2042 However, note that some special properties use inheritance under special
2043 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2044 and the properties ending in \"_ALL\" when they are used as descriptor
2045 for valid values of a property.
2047 Note for programmers:
2048 When querying an entry with `org-entry-get', you can control if inheritance
2049 should be used. By default, `org-entry-get' looks only at the local
2050 properties. You can request inheritance by setting the inherit argument
2051 to t (to force inheritance) or to `selective' (to respect the setting
2052 in this variable)."
2053 :group 'org-properties
2054 :type '(choice
2055 (const :tag "Not" nil)
2056 (const :tag "Always" t)
2057 (repeat :tag "Specific properties" (string :tag "Property"))
2058 (regexp :tag "Properties matched by regexp")))
2060 (defun org-property-inherit-p (property)
2061 "Check if PROPERTY is one that should be inherited."
2062 (cond
2063 ((eq org-use-property-inheritance t) t)
2064 ((not org-use-property-inheritance) nil)
2065 ((stringp org-use-property-inheritance)
2066 (string-match org-use-property-inheritance property))
2067 ((listp org-use-property-inheritance)
2068 (member property org-use-property-inheritance))
2069 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2071 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2072 "The default column format, if no other format has been defined.
2073 This variable can be set on the per-file basis by inserting a line
2075 #+COLUMNS: %25ITEM ....."
2076 :group 'org-properties
2077 :type 'string)
2079 (defcustom org-columns-ellipses ".."
2080 "The ellipses to be used when a field in column view is truncated.
2081 When this is the empty string, as many characters as possible are shown,
2082 but then there will be no visual indication that the field has been truncated.
2083 When this is a string of length N, the last N characters of a truncated
2084 field are replaced by this string. If the column is narrower than the
2085 ellipses string, only part of the ellipses string will be shown."
2086 :group 'org-properties
2087 :type 'string)
2089 (defcustom org-columns-modify-value-for-display-function nil
2090 "Function that modifies values for display in column view.
2091 For example, it can be used to cut out a certain part from a time stamp.
2092 The function must take 2 arguments:
2094 column-title The title of the column (*not* the property name)
2095 value The value that should be modified.
2097 The function should return the value that should be displayed,
2098 or nil if the normal value should be used."
2099 :group 'org-properties
2100 :type 'function)
2102 (defcustom org-effort-property "Effort"
2103 "The property that is being used to keep track of effort estimates.
2104 Effort estimates given in this property need to have the format H:MM."
2105 :group 'org-properties
2106 :group 'org-progress
2107 :type '(string :tag "Property"))
2109 (defconst org-global-properties-fixed
2110 '(("VISIBILITY_ALL" . "folded children content all"))
2111 "List of property/value pairs that can be inherited by any entry.
2112 These are fixed values, for the preset properties.")
2115 (defcustom org-global-properties nil
2116 "List of property/value pairs that can be inherited by any entry.
2117 You can set buffer-local values for the same purpose in the variable
2118 `org-file-properties' this by adding lines like
2120 #+PROPERTY: NAME VALUE"
2121 :group 'org-properties
2122 :type '(repeat
2123 (cons (string :tag "Property")
2124 (string :tag "Value"))))
2126 (defvar org-file-properties nil
2127 "List of property/value pairs that can be inherited by any entry.
2128 Valid for the current buffer.
2129 This variable is populated from #+PROPERTY lines.")
2130 (make-variable-buffer-local 'org-file-properties)
2132 (defgroup org-agenda nil
2133 "Options concerning agenda views in Org-mode."
2134 :tag "Org Agenda"
2135 :group 'org)
2137 (defvar org-category nil
2138 "Variable used by org files to set a category for agenda display.
2139 Such files should use a file variable to set it, for example
2141 # -*- mode: org; org-category: \"ELisp\"
2143 or contain a special line
2145 #+CATEGORY: ELisp
2147 If the file does not specify a category, then file's base name
2148 is used instead.")
2149 (make-variable-buffer-local 'org-category)
2150 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2152 (defcustom org-agenda-files nil
2153 "The files to be used for agenda display.
2154 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2155 \\[org-remove-file]. You can also use customize to edit the list.
2157 If an entry is a directory, all files in that directory that are matched by
2158 `org-agenda-file-regexp' will be part of the file list.
2160 If the value of the variable is not a list but a single file name, then
2161 the list of agenda files is actually stored and maintained in that file, one
2162 agenda file per line."
2163 :group 'org-agenda
2164 :type '(choice
2165 (repeat :tag "List of files and directories" file)
2166 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2168 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2169 "Regular expression to match files for `org-agenda-files'.
2170 If any element in the list in that variable contains a directory instead
2171 of a normal file, all files in that directory that are matched by this
2172 regular expression will be included."
2173 :group 'org-agenda
2174 :type 'regexp)
2176 (defcustom org-agenda-text-search-extra-files nil
2177 "List of extra files to be searched by text search commands.
2178 These files will be search in addition to the agenda files by the
2179 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2180 Note that these files will only be searched for text search commands,
2181 not for the other agenda views like todo lists, tag searches or the weekly
2182 agenda. This variable is intended to list notes and possibly archive files
2183 that should also be searched by these two commands.
2184 In fact, if the first element in the list is the symbol `agenda-archives',
2185 than all archive files of all agenda files will be added to the search
2186 scope."
2187 :group 'org-agenda
2188 :type '(set :greedy t
2189 (const :tag "Agenda Archives" agenda-archives)
2190 (repeat :inline t (file))))
2192 (if (fboundp 'defvaralias)
2193 (defvaralias 'org-agenda-multi-occur-extra-files
2194 'org-agenda-text-search-extra-files))
2196 (defcustom org-agenda-skip-unavailable-files nil
2197 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2198 A nil value means to remove them, after a query, from the list."
2199 :group 'org-agenda
2200 :type 'boolean)
2202 (defcustom org-calendar-to-agenda-key [?c]
2203 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2204 The command `org-calendar-goto-agenda' will be bound to this key. The
2205 default is the character `c' because then `c' can be used to switch back and
2206 forth between agenda and calendar."
2207 :group 'org-agenda
2208 :type 'sexp)
2210 (defcustom org-calendar-agenda-action-key [?k]
2211 "The key to be installed in `calendar-mode-map' for agenda-action.
2212 The command `org-agenda-action' will be bound to this key. The
2213 default is the character `k' because we use the same key in the agenda."
2214 :group 'org-agenda
2215 :type 'sexp)
2217 (eval-after-load "calendar"
2218 '(progn
2219 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2220 'org-calendar-goto-agenda)
2221 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2222 'org-agenda-action)))
2224 (defgroup org-latex nil
2225 "Options for embedding LaTeX code into Org-mode."
2226 :tag "Org LaTeX"
2227 :group 'org)
2229 (defcustom org-format-latex-options
2230 '(:foreground default :background default :scale 1.0
2231 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2232 :matchers ("begin" "$" "$$" "\\(" "\\["))
2233 "Options for creating images from LaTeX fragments.
2234 This is a property list with the following properties:
2235 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2236 `default' means use the foreground of the default face.
2237 :background the background color, or \"Transparent\".
2238 `default' means use the background of the default face.
2239 :scale a scaling factor for the size of the images.
2240 :html-foreground, :html-background, :html-scale
2241 the same numbers for HTML export.
2242 :matchers a list indicating which matchers should be used to
2243 find LaTeX fragments. Valid members of this list are:
2244 \"begin\" find environments
2245 \"$\" find math expressions surrounded by $...$
2246 \"$$\" find math expressions surrounded by $$....$$
2247 \"\\(\" find math expressions surrounded by \\(...\\)
2248 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2249 :group 'org-latex
2250 :type 'plist)
2252 (defcustom org-format-latex-header "\\documentclass{article}
2253 \\usepackage{fullpage} % do not remove
2254 \\usepackage{amssymb}
2255 \\usepackage[usenames]{color}
2256 \\usepackage{amsmath}
2257 \\usepackage{latexsym}
2258 \\usepackage[mathscr]{eucal}
2259 \\pagestyle{empty} % do not remove"
2260 "The document header used for processing LaTeX fragments."
2261 :group 'org-latex
2262 :type 'string)
2265 (defgroup org-font-lock nil
2266 "Font-lock settings for highlighting in Org-mode."
2267 :tag "Org Font Lock"
2268 :group 'org)
2270 (defcustom org-level-color-stars-only nil
2271 "Non-nil means fontify only the stars in each headline.
2272 When nil, the entire headline is fontified.
2273 Changing it requires restart of `font-lock-mode' to become effective
2274 also in regions already fontified."
2275 :group 'org-font-lock
2276 :type 'boolean)
2278 (defcustom org-hide-leading-stars nil
2279 "Non-nil means, hide the first N-1 stars in a headline.
2280 This works by using the face `org-hide' for these stars. This
2281 face is white for a light background, and black for a dark
2282 background. You may have to customize the face `org-hide' to
2283 make this work.
2284 Changing it requires restart of `font-lock-mode' to become effective
2285 also in regions already fontified.
2286 You may also set this on a per-file basis by adding one of the following
2287 lines to the buffer:
2289 #+STARTUP: hidestars
2290 #+STARTUP: showstars"
2291 :group 'org-font-lock
2292 :type 'boolean)
2294 (defcustom org-fontify-done-headline nil
2295 "Non-nil means, change the face of a headline if it is marked DONE.
2296 Normally, only the TODO/DONE keyword indicates the state of a headline.
2297 When this is non-nil, the headline after the keyword is set to the
2298 `org-headline-done' as an additional indication."
2299 :group 'org-font-lock
2300 :type 'boolean)
2302 (defcustom org-fontify-emphasized-text t
2303 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2304 Changing this variable requires a restart of Emacs to take effect."
2305 :group 'org-font-lock
2306 :type 'boolean)
2308 (defcustom org-highlight-latex-fragments-and-specials nil
2309 "Non-nil means, fontify what is treated specially by the exporters."
2310 :group 'org-font-lock
2311 :type 'boolean)
2313 (defcustom org-hide-emphasis-markers nil
2314 "Non-nil mean font-lock should hide the emphasis marker characters."
2315 :group 'org-font-lock
2316 :type 'boolean)
2318 (defvar org-emph-re nil
2319 "Regular expression for matching emphasis.")
2320 (defvar org-verbatim-re nil
2321 "Regular expression for matching verbatim text.")
2322 (defvar org-emphasis-regexp-components) ; defined just below
2323 (defvar org-emphasis-alist) ; defined just below
2324 (defun org-set-emph-re (var val)
2325 "Set variable and compute the emphasis regular expression."
2326 (set var val)
2327 (when (and (boundp 'org-emphasis-alist)
2328 (boundp 'org-emphasis-regexp-components)
2329 org-emphasis-alist org-emphasis-regexp-components)
2330 (let* ((e org-emphasis-regexp-components)
2331 (pre (car e))
2332 (post (nth 1 e))
2333 (border (nth 2 e))
2334 (body (nth 3 e))
2335 (nl (nth 4 e))
2336 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2337 (body1 (concat body "*?"))
2338 (markers (mapconcat 'car org-emphasis-alist ""))
2339 (vmarkers (mapconcat
2340 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2341 org-emphasis-alist "")))
2342 ;; make sure special characters appear at the right position in the class
2343 (if (string-match "\\^" markers)
2344 (setq markers (concat (replace-match "" t t markers) "^")))
2345 (if (string-match "-" markers)
2346 (setq markers (concat (replace-match "" t t markers) "-")))
2347 (if (string-match "\\^" vmarkers)
2348 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2349 (if (string-match "-" vmarkers)
2350 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2351 (if (> nl 0)
2352 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2353 (int-to-string nl) "\\}")))
2354 ;; Make the regexp
2355 (setq org-emph-re
2356 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2357 "\\("
2358 "\\([" markers "]\\)"
2359 "\\("
2360 "[^" border "]\\|"
2361 "[^" border (if (and nil stacked) markers) "]"
2362 body1
2363 "[^" border (if (and nil stacked) markers) "]"
2364 "\\)"
2365 "\\3\\)"
2366 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2367 (setq org-verbatim-re
2368 (concat "\\([" pre "]\\|^\\)"
2369 "\\("
2370 "\\([" vmarkers "]\\)"
2371 "\\("
2372 "[^" border "]\\|"
2373 "[^" border "]"
2374 body1
2375 "[^" border "]"
2376 "\\)"
2377 "\\3\\)"
2378 "\\([" post "]\\|$\\)")))))
2380 (defcustom org-emphasis-regexp-components
2381 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2382 "Components used to build the regular expression for emphasis.
2383 This is a list with 6 entries. Terminology: In an emphasis string
2384 like \" *strong word* \", we call the initial space PREMATCH, the final
2385 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2386 and \"trong wor\" is the body. The different components in this variable
2387 specify what is allowed/forbidden in each part:
2389 pre Chars allowed as prematch. Beginning of line will be allowed too.
2390 post Chars allowed as postmatch. End of line will be allowed too.
2391 border The chars *forbidden* as border characters.
2392 body-regexp A regexp like \".\" to match a body character. Don't use
2393 non-shy groups here, and don't allow newline here.
2394 newline The maximum number of newlines allowed in an emphasis exp.
2396 Use customize to modify this, or restart Emacs after changing it."
2397 :group 'org-font-lock
2398 :set 'org-set-emph-re
2399 :type '(list
2400 (sexp :tag "Allowed chars in pre ")
2401 (sexp :tag "Allowed chars in post ")
2402 (sexp :tag "Forbidden chars in border ")
2403 (sexp :tag "Regexp for body ")
2404 (integer :tag "number of newlines allowed")
2405 (option (boolean :tag "Please ignore this button"))))
2407 (defcustom org-emphasis-alist
2408 `(("*" bold "<b>" "</b>")
2409 ("/" italic "<i>" "</i>")
2410 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2411 ("=" org-code "<code>" "</code>" verbatim)
2412 ("~" org-verbatim "<code>" "</code>" verbatim)
2413 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2414 "<del>" "</del>")
2416 "Special syntax for emphasized text.
2417 Text starting and ending with a special character will be emphasized, for
2418 example *bold*, _underlined_ and /italic/. This variable sets the marker
2419 characters, the face to be used by font-lock for highlighting in Org-mode
2420 Emacs buffers, and the HTML tags to be used for this.
2421 Use customize to modify this, or restart Emacs after changing it."
2422 :group 'org-font-lock
2423 :set 'org-set-emph-re
2424 :type '(repeat
2425 (list
2426 (string :tag "Marker character")
2427 (choice
2428 (face :tag "Font-lock-face")
2429 (plist :tag "Face property list"))
2430 (string :tag "HTML start tag")
2431 (string :tag "HTML end tag")
2432 (option (const verbatim)))))
2434 ;;; Miscellaneous options
2436 (defgroup org-completion nil
2437 "Completion in Org-mode."
2438 :tag "Org Completion"
2439 :group 'org)
2441 (defcustom org-completion-use-ido nil
2442 "Non-nil means, use ido completion wherever possible.
2443 Note that `ido-mode' must be active for this variable to be relevant.
2444 If you decide to turn this variable on, you might well want to turn off
2445 `org-outline-path-complete-in-steps'."
2446 :group 'org-completion
2447 :type 'boolean)
2449 (defcustom org-completion-fallback-command 'hippie-expand
2450 "The expansion command called by \\[org-complete] in normal context.
2451 Normal means, no org-mode-specific context."
2452 :group 'org-completion
2453 :type 'function)
2455 ;;; Functions and variables from ther packages
2456 ;; Declared here to avoid compiler warnings
2458 ;; XEmacs only
2459 (defvar outline-mode-menu-heading)
2460 (defvar outline-mode-menu-show)
2461 (defvar outline-mode-menu-hide)
2462 (defvar zmacs-regions) ; XEmacs regions
2464 ;; Emacs only
2465 (defvar mark-active)
2467 ;; Various packages
2468 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2469 (declare-function calendar-forward-day "cal-move" (arg))
2470 (declare-function calendar-goto-date "cal-move" (date))
2471 (declare-function calendar-goto-today "cal-move" ())
2472 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2473 (defvar calc-embedded-close-formula)
2474 (defvar calc-embedded-open-formula)
2475 (declare-function cdlatex-tab "ext:cdlatex" ())
2476 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2477 (defvar font-lock-unfontify-region-function)
2478 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2479 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2480 (defvar iswitchb-temp-buflist)
2481 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2482 (declare-function org-agenda-skip "org-agenda" ())
2483 (declare-function org-format-agenda-item "org-agenda"
2484 (extra txt &optional category tags dotime noprefix remove-re))
2485 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2486 (declare-function org-agenda-change-all-lines "org-agenda"
2487 (newhead hdmarker &optional fixface just-this))
2488 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2489 (declare-function org-agenda-maybe-redo "org-agenda" ())
2490 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2491 (beg end))
2492 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2493 (declare-function parse-time-string "parse-time" (string))
2494 (declare-function remember "remember" (&optional initial))
2495 (declare-function remember-buffer-desc "remember" ())
2496 (declare-function remember-finalize "remember" ())
2497 (defvar remember-save-after-remembering)
2498 (defvar remember-data-file)
2499 (defvar remember-register)
2500 (defvar remember-buffer)
2501 (defvar remember-handler-functions)
2502 (defvar remember-annotation-functions)
2503 (defvar texmathp-why)
2504 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2505 (declare-function table--at-cell-p "table" (position &optional object at-column))
2507 (defvar w3m-current-url)
2508 (defvar w3m-current-title)
2510 (defvar org-latex-regexps)
2512 ;;; Autoload and prepare some org modules
2514 ;; Some table stuff that needs to be defined here, because it is used
2515 ;; by the functions setting up org-mode or checking for table context.
2517 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2518 "Detects an org-type or table-type table.")
2519 (defconst org-table-line-regexp "^[ \t]*|"
2520 "Detects an org-type table line.")
2521 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2522 "Detects an org-type table line.")
2523 (defconst org-table-hline-regexp "^[ \t]*|-"
2524 "Detects an org-type table hline.")
2525 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2526 "Detects a table-type table hline.")
2527 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2528 "Searching from within a table (any type) this finds the first line
2529 outside the table.")
2531 ;; Autoload the functions in org-table.el that are needed by functions here.
2533 (eval-and-compile
2534 (org-autoload "org-table"
2535 '(org-table-align org-table-begin org-table-blank-field
2536 org-table-convert org-table-convert-region org-table-copy-down
2537 org-table-copy-region org-table-create
2538 org-table-create-or-convert-from-region
2539 org-table-create-with-table.el org-table-current-dline
2540 org-table-cut-region org-table-delete-column org-table-edit-field
2541 org-table-edit-formulas org-table-end org-table-eval-formula
2542 org-table-export org-table-field-info
2543 org-table-get-stored-formulas org-table-goto-column
2544 org-table-hline-and-move org-table-import org-table-insert-column
2545 org-table-insert-hline org-table-insert-row org-table-iterate
2546 org-table-justify-field-maybe org-table-kill-row
2547 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2548 org-table-move-column org-table-move-column-left
2549 org-table-move-column-right org-table-move-row
2550 org-table-move-row-down org-table-move-row-up
2551 org-table-next-field org-table-next-row org-table-paste-rectangle
2552 org-table-previous-field org-table-recalculate
2553 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2554 org-table-toggle-coordinate-overlays
2555 org-table-toggle-formula-debugger org-table-wrap-region
2556 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2558 (defun org-at-table-p (&optional table-type)
2559 "Return t if the cursor is inside an org-type table.
2560 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2561 (if org-enable-table-editor
2562 (save-excursion
2563 (beginning-of-line 1)
2564 (looking-at (if table-type org-table-any-line-regexp
2565 org-table-line-regexp)))
2566 nil))
2567 (defsubst org-table-p () (org-at-table-p))
2569 (defun org-at-table.el-p ()
2570 "Return t if and only if we are at a table.el table."
2571 (and (org-at-table-p 'any)
2572 (save-excursion
2573 (goto-char (org-table-begin 'any))
2574 (looking-at org-table1-hline-regexp))))
2575 (defun org-table-recognize-table.el ()
2576 "If there is a table.el table nearby, recognize it and move into it."
2577 (if org-table-tab-recognizes-table.el
2578 (if (org-at-table.el-p)
2579 (progn
2580 (beginning-of-line 1)
2581 (if (looking-at org-table-dataline-regexp)
2583 (if (looking-at org-table1-hline-regexp)
2584 (progn
2585 (beginning-of-line 2)
2586 (if (looking-at org-table-any-border-regexp)
2587 (beginning-of-line -1)))))
2588 (if (re-search-forward "|" (org-table-end t) t)
2589 (progn
2590 (require 'table)
2591 (if (table--at-cell-p (point))
2593 (message "recognizing table.el table...")
2594 (table-recognize-table)
2595 (message "recognizing table.el table...done")))
2596 (error "This should not happen..."))
2598 nil)
2599 nil))
2601 (defun org-at-table-hline-p ()
2602 "Return t if the cursor is inside a hline in a table."
2603 (if org-enable-table-editor
2604 (save-excursion
2605 (beginning-of-line 1)
2606 (looking-at org-table-hline-regexp))
2607 nil))
2609 (defvar org-table-clean-did-remove-column nil)
2611 (defun org-table-map-tables (function)
2612 "Apply FUNCTION to the start of all tables in the buffer."
2613 (save-excursion
2614 (save-restriction
2615 (widen)
2616 (goto-char (point-min))
2617 (while (re-search-forward org-table-any-line-regexp nil t)
2618 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2619 (beginning-of-line 1)
2620 (if (looking-at org-table-line-regexp)
2621 (save-excursion (funcall function)))
2622 (re-search-forward org-table-any-border-regexp nil 1))))
2623 (message "Mapping tables: done"))
2625 ;; Declare and autoload functions from org-exp.el
2627 (declare-function org-default-export-plist "org-exp")
2628 (declare-function org-infile-export-plist "org-exp")
2629 (declare-function org-get-current-options "org-exp")
2630 (eval-and-compile
2631 (org-autoload "org-exp"
2632 '(org-export org-export-as-ascii org-export-visible
2633 org-insert-export-options-template org-export-as-html-and-open
2634 org-export-as-html-batch org-export-as-html-to-buffer
2635 org-replace-region-by-html org-export-region-as-html
2636 org-export-as-html org-export-icalendar-this-file
2637 org-export-icalendar-all-agenda-files
2638 org-table-clean-before-export
2639 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2641 ;; Declare and autoload functions from org-agenda.el
2643 (eval-and-compile
2644 (org-autoload "org-agenda"
2645 '(org-agenda org-agenda-list org-search-view
2646 org-todo-list org-tags-view org-agenda-list-stuck-projects
2647 org-diary org-agenda-to-appt)))
2649 ;; Autoload org-remember
2651 (eval-and-compile
2652 (org-autoload "org-remember"
2653 '(org-remember-insinuate org-remember-annotation
2654 org-remember-apply-template org-remember org-remember-handler)))
2656 ;; Autoload org-clock.el
2659 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2660 (beg end))
2661 (declare-function org-update-mode-line "org-clock" ())
2662 (defvar org-clock-start-time)
2663 (defvar org-clock-marker (make-marker)
2664 "Marker recording the last clock-in.")
2666 (eval-and-compile
2667 (org-autoload
2668 "org-clock"
2669 '(org-clock-in org-clock-out org-clock-cancel
2670 org-clock-goto org-clock-sum org-clock-display
2671 org-remove-clock-overlays org-clock-report
2672 org-clocktable-shift org-dblock-write:clocktable
2673 org-get-clocktable)))
2675 (defun org-clock-update-time-maybe ()
2676 "If this is a CLOCK line, update it and return t.
2677 Otherwise, return nil."
2678 (interactive)
2679 (save-excursion
2680 (beginning-of-line 1)
2681 (skip-chars-forward " \t")
2682 (when (looking-at org-clock-string)
2683 (let ((re (concat "[ \t]*" org-clock-string
2684 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2685 "\\([ \t]*=>.*\\)?\\)?"))
2686 ts te h m s neg)
2687 (cond
2688 ((not (looking-at re))
2689 nil)
2690 ((not (match-end 2))
2691 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2692 (> org-clock-marker (point))
2693 (<= org-clock-marker (point-at-eol)))
2694 ;; The clock is running here
2695 (setq org-clock-start-time
2696 (apply 'encode-time
2697 (org-parse-time-string (match-string 1))))
2698 (org-update-mode-line)))
2700 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2701 (end-of-line 1)
2702 (setq ts (match-string 1)
2703 te (match-string 3))
2704 (setq s (- (time-to-seconds
2705 (apply 'encode-time (org-parse-time-string te)))
2706 (time-to-seconds
2707 (apply 'encode-time (org-parse-time-string ts))))
2708 neg (< s 0)
2709 s (abs s)
2710 h (floor (/ s 3600))
2711 s (- s (* 3600 h))
2712 m (floor (/ s 60))
2713 s (- s (* 60 s)))
2714 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2715 t))))))
2717 (defun org-check-running-clock ()
2718 "Check if the current buffer contains the running clock.
2719 If yes, offer to stop it and to save the buffer with the changes."
2720 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2721 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2722 (buffer-name))))
2723 (org-clock-out)
2724 (when (y-or-n-p "Save changed buffer?")
2725 (save-buffer))))
2727 (defun org-clocktable-try-shift (dir n)
2728 "Check if this line starts a clock table, if yes, shift the time block."
2729 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2730 (org-clocktable-shift dir n)))
2732 ;; Autoload org-timer.el
2734 ;(declare-function org-timer "org-timer")
2736 (eval-and-compile
2737 (org-autoload
2738 "org-timer"
2739 '(org-timer-start org-timer org-timer-item
2740 org-timer-change-times-in-region)))
2743 ;; Autoload archiving code
2744 ;; The stuff that is needed for cycling and tags has to be defined here.
2746 (defgroup org-archive nil
2747 "Options concerning archiving in Org-mode."
2748 :tag "Org Archive"
2749 :group 'org-structure)
2751 (defcustom org-archive-location "%s_archive::"
2752 "The location where subtrees should be archived.
2754 The value of this variable is a string, consisting of two parts,
2755 separated by a double-colon. The first part is a filename and
2756 the second part is a headline.
2758 When the filename is omitted, archiving happens in the same file.
2759 %s in the filename will be replaced by the current file
2760 name (without the directory part). Archiving to a different file
2761 is useful to keep archived entries from contributing to the
2762 Org-mode Agenda.
2764 The archived entries will be filed as subtrees of the specified
2765 headline. When the headline is omitted, the subtrees are simply
2766 filed away at the end of the file, as top-level entries.
2768 Here are a few examples:
2769 \"%s_archive::\"
2770 If the current file is Projects.org, archive in file
2771 Projects.org_archive, as top-level trees. This is the default.
2773 \"::* Archived Tasks\"
2774 Archive in the current file, under the top-level headline
2775 \"* Archived Tasks\".
2777 \"~/org/archive.org::\"
2778 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2780 \"basement::** Finished Tasks\"
2781 Archive in file ./basement (relative path), as level 3 trees
2782 below the level 2 heading \"** Finished Tasks\".
2784 You may set this option on a per-file basis by adding to the buffer a
2785 line like
2787 #+ARCHIVE: basement::** Finished Tasks
2789 You may also define it locally for a subtree by setting an ARCHIVE property
2790 in the entry. If such a property is found in an entry, or anywhere up
2791 the hierarchy, it will be used."
2792 :group 'org-archive
2793 :type 'string)
2795 (defcustom org-archive-tag "ARCHIVE"
2796 "The tag that marks a subtree as archived.
2797 An archived subtree does not open during visibility cycling, and does
2798 not contribute to the agenda listings.
2799 After changing this, font-lock must be restarted in the relevant buffers to
2800 get the proper fontification."
2801 :group 'org-archive
2802 :group 'org-keywords
2803 :type 'string)
2805 (defcustom org-agenda-skip-archived-trees t
2806 "Non-nil means, the agenda will skip any items located in archived trees.
2807 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2808 variable is no longer recommended, you should leave it at the value t.
2809 Instead, use the key `v' to cycle the archives-mode in the agenda."
2810 :group 'org-archive
2811 :group 'org-agenda-skip
2812 :type 'boolean)
2814 (defcustom org-cycle-open-archived-trees nil
2815 "Non-nil means, `org-cycle' will open archived trees.
2816 An archived tree is a tree marked with the tag ARCHIVE.
2817 When nil, archived trees will stay folded. You can still open them with
2818 normal outline commands like `show-all', but not with the cycling commands."
2819 :group 'org-archive
2820 :group 'org-cycle
2821 :type 'boolean)
2823 (defcustom org-sparse-tree-open-archived-trees nil
2824 "Non-nil means sparse tree construction shows matches in archived trees.
2825 When nil, matches in these trees are highlighted, but the trees are kept in
2826 collapsed state."
2827 :group 'org-archive
2828 :group 'org-sparse-trees
2829 :type 'boolean)
2831 (defun org-cycle-hide-archived-subtrees (state)
2832 "Re-hide all archived subtrees after a visibility state change."
2833 (when (and (not org-cycle-open-archived-trees)
2834 (not (memq state '(overview folded))))
2835 (save-excursion
2836 (let* ((globalp (memq state '(contents all)))
2837 (beg (if globalp (point-min) (point)))
2838 (end (if globalp (point-max) (org-end-of-subtree t))))
2839 (org-hide-archived-subtrees beg end)
2840 (goto-char beg)
2841 (if (looking-at (concat ".*:" org-archive-tag ":"))
2842 (message "%s" (substitute-command-keys
2843 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2845 (defun org-force-cycle-archived ()
2846 "Cycle subtree even if it is archived."
2847 (interactive)
2848 (setq this-command 'org-cycle)
2849 (let ((org-cycle-open-archived-trees t))
2850 (call-interactively 'org-cycle)))
2852 (defun org-hide-archived-subtrees (beg end)
2853 "Re-hide all archived subtrees after a visibility state change."
2854 (save-excursion
2855 (let* ((re (concat ":" org-archive-tag ":")))
2856 (goto-char beg)
2857 (while (re-search-forward re end t)
2858 (and (org-on-heading-p) (hide-subtree))
2859 (org-end-of-subtree t)))))
2861 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2863 (eval-and-compile
2864 (org-autoload "org-archive"
2865 '(org-add-archive-files org-archive-subtree
2866 org-archive-to-archive-sibling org-toggle-archive-tag)))
2868 ;; Autoload Column View Code
2870 (declare-function org-columns-number-to-string "org-colview")
2871 (declare-function org-columns-get-format-and-top-level "org-colview")
2872 (declare-function org-columns-compute "org-colview")
2874 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2875 '(org-columns-number-to-string org-columns-get-format-and-top-level
2876 org-columns-compute org-agenda-columns org-columns-remove-overlays
2877 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2879 ;; Autoload ID code
2881 (declare-function org-id-store-link "org-id")
2882 (org-autoload "org-id"
2883 '(org-id-get-create org-id-new org-id-copy org-id-get
2884 org-id-get-with-outline-path-completion
2885 org-id-get-with-outline-drilling
2886 org-id-goto org-id-find org-id-store-link))
2888 ;;; Variables for pre-computed regular expressions, all buffer local
2890 (defvar org-drawer-regexp nil
2891 "Matches first line of a hidden block.")
2892 (make-variable-buffer-local 'org-drawer-regexp)
2893 (defvar org-todo-regexp nil
2894 "Matches any of the TODO state keywords.")
2895 (make-variable-buffer-local 'org-todo-regexp)
2896 (defvar org-not-done-regexp nil
2897 "Matches any of the TODO state keywords except the last one.")
2898 (make-variable-buffer-local 'org-not-done-regexp)
2899 (defvar org-todo-line-regexp nil
2900 "Matches a headline and puts TODO state into group 2 if present.")
2901 (make-variable-buffer-local 'org-todo-line-regexp)
2902 (defvar org-complex-heading-regexp nil
2903 "Matches a headline and puts everything into groups:
2904 group 1: the stars
2905 group 2: The todo keyword, maybe
2906 group 3: Priority cookie
2907 group 4: True headline
2908 group 5: Tags")
2909 (make-variable-buffer-local 'org-complex-heading-regexp)
2910 (defvar org-todo-line-tags-regexp nil
2911 "Matches a headline and puts TODO state into group 2 if present.
2912 Also put tags into group 4 if tags are present.")
2913 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2914 (defvar org-nl-done-regexp nil
2915 "Matches newline followed by a headline with the DONE keyword.")
2916 (make-variable-buffer-local 'org-nl-done-regexp)
2917 (defvar org-looking-at-done-regexp nil
2918 "Matches the DONE keyword a point.")
2919 (make-variable-buffer-local 'org-looking-at-done-regexp)
2920 (defvar org-ds-keyword-length 12
2921 "Maximum length of the Deadline and SCHEDULED keywords.")
2922 (make-variable-buffer-local 'org-ds-keyword-length)
2923 (defvar org-deadline-regexp nil
2924 "Matches the DEADLINE keyword.")
2925 (make-variable-buffer-local 'org-deadline-regexp)
2926 (defvar org-deadline-time-regexp nil
2927 "Matches the DEADLINE keyword together with a time stamp.")
2928 (make-variable-buffer-local 'org-deadline-time-regexp)
2929 (defvar org-deadline-line-regexp nil
2930 "Matches the DEADLINE keyword and the rest of the line.")
2931 (make-variable-buffer-local 'org-deadline-line-regexp)
2932 (defvar org-scheduled-regexp nil
2933 "Matches the SCHEDULED keyword.")
2934 (make-variable-buffer-local 'org-scheduled-regexp)
2935 (defvar org-scheduled-time-regexp nil
2936 "Matches the SCHEDULED keyword together with a time stamp.")
2937 (make-variable-buffer-local 'org-scheduled-time-regexp)
2938 (defvar org-closed-time-regexp nil
2939 "Matches the CLOSED keyword together with a time stamp.")
2940 (make-variable-buffer-local 'org-closed-time-regexp)
2942 (defvar org-keyword-time-regexp nil
2943 "Matches any of the 4 keywords, together with the time stamp.")
2944 (make-variable-buffer-local 'org-keyword-time-regexp)
2945 (defvar org-keyword-time-not-clock-regexp nil
2946 "Matches any of the 3 keywords, together with the time stamp.")
2947 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2948 (defvar org-maybe-keyword-time-regexp nil
2949 "Matches a timestamp, possibly preceeded by a keyword.")
2950 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2951 (defvar org-planning-or-clock-line-re nil
2952 "Matches a line with planning or clock info.")
2953 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2955 (defconst org-plain-time-of-day-regexp
2956 (concat
2957 "\\(\\<[012]?[0-9]"
2958 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2959 "\\(--?"
2960 "\\(\\<[012]?[0-9]"
2961 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2962 "\\)?")
2963 "Regular expression to match a plain time or time range.
2964 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2965 groups carry important information:
2966 0 the full match
2967 1 the first time, range or not
2968 8 the second time, if it is a range.")
2970 (defconst org-plain-time-extension-regexp
2971 (concat
2972 "\\(\\<[012]?[0-9]"
2973 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2974 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2975 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2976 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2977 groups carry important information:
2978 0 the full match
2979 7 hours of duration
2980 9 minutes of duration")
2982 (defconst org-stamp-time-of-day-regexp
2983 (concat
2984 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2985 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2986 "\\(--?"
2987 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2988 "Regular expression to match a timestamp time or time range.
2989 After a match, the following groups carry important information:
2990 0 the full match
2991 1 date plus weekday, for backreferencing to make sure both times on same day
2992 2 the first time, range or not
2993 4 the second time, if it is a range.")
2995 (defconst org-startup-options
2996 '(("fold" org-startup-folded t)
2997 ("overview" org-startup-folded t)
2998 ("nofold" org-startup-folded nil)
2999 ("showall" org-startup-folded nil)
3000 ("content" org-startup-folded content)
3001 ("hidestars" org-hide-leading-stars t)
3002 ("showstars" org-hide-leading-stars nil)
3003 ("odd" org-odd-levels-only t)
3004 ("oddeven" org-odd-levels-only nil)
3005 ("align" org-startup-align-all-tables t)
3006 ("noalign" org-startup-align-all-tables nil)
3007 ("customtime" org-display-custom-times t)
3008 ("logdone" org-log-done time)
3009 ("lognotedone" org-log-done note)
3010 ("nologdone" org-log-done nil)
3011 ("lognoteclock-out" org-log-note-clock-out t)
3012 ("nolognoteclock-out" org-log-note-clock-out nil)
3013 ("logrepeat" org-log-repeat state)
3014 ("lognoterepeat" org-log-repeat note)
3015 ("nologrepeat" org-log-repeat nil)
3016 ("fninline" org-footnote-define-inline t)
3017 ("nofninline" org-footnote-define-inline nil)
3018 ("fnlocal" org-footnote-section nil)
3019 ("fnauto" org-footnote-auto-label t)
3020 ("fnprompt" org-footnote-auto-label nil)
3021 ("fnconfirm" org-footnote-auto-label confirm)
3022 ("fnplain" org-footnote-auto-label plain)
3023 ("constcgs" constants-unit-system cgs)
3024 ("constSI" constants-unit-system SI))
3025 "Variable associated with STARTUP options for org-mode.
3026 Each element is a list of three items: The startup options as written
3027 in the #+STARTUP line, the corresponding variable, and the value to
3028 set this variable to if the option is found. An optional forth element PUSH
3029 means to push this value onto the list in the variable.")
3031 (defun org-set-regexps-and-options ()
3032 "Precompute regular expressions for current buffer."
3033 (when (org-mode-p)
3034 (org-set-local 'org-todo-kwd-alist nil)
3035 (org-set-local 'org-todo-key-alist nil)
3036 (org-set-local 'org-todo-key-trigger nil)
3037 (org-set-local 'org-todo-keywords-1 nil)
3038 (org-set-local 'org-done-keywords nil)
3039 (org-set-local 'org-todo-heads nil)
3040 (org-set-local 'org-todo-sets nil)
3041 (org-set-local 'org-todo-log-states nil)
3042 (org-set-local 'org-file-properties nil)
3043 (org-set-local 'org-file-tags nil)
3044 (let ((re (org-make-options-regexp
3045 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3046 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3047 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3048 (splitre "[ \t]+")
3049 kwds kws0 kwsa key log value cat arch tags const links hw dws
3050 tail sep kws1 prio props ftags drawers
3051 ext-setup-or-nil setup-contents (start 0))
3052 (save-excursion
3053 (save-restriction
3054 (widen)
3055 (goto-char (point-min))
3056 (while (or (and ext-setup-or-nil
3057 (string-match re ext-setup-or-nil start)
3058 (setq start (match-end 0)))
3059 (and (setq ext-setup-or-nil nil start 0)
3060 (re-search-forward re nil t)))
3061 (setq key (upcase (match-string 1 ext-setup-or-nil))
3062 value (org-match-string-no-properties 2 ext-setup-or-nil))
3063 (cond
3064 ((equal key "CATEGORY")
3065 (if (string-match "[ \t]+$" value)
3066 (setq value (replace-match "" t t value)))
3067 (setq cat value))
3068 ((member key '("SEQ_TODO" "TODO"))
3069 (push (cons 'sequence (org-split-string value splitre)) kwds))
3070 ((equal key "TYP_TODO")
3071 (push (cons 'type (org-split-string value splitre)) kwds))
3072 ((equal key "TAGS")
3073 (setq tags (append tags (org-split-string value splitre))))
3074 ((equal key "COLUMNS")
3075 (org-set-local 'org-columns-default-format value))
3076 ((equal key "LINK")
3077 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3078 (push (cons (match-string 1 value)
3079 (org-trim (match-string 2 value)))
3080 links)))
3081 ((equal key "PRIORITIES")
3082 (setq prio (org-split-string value " +")))
3083 ((equal key "PROPERTY")
3084 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3085 (push (cons (match-string 1 value) (match-string 2 value))
3086 props)))
3087 ((equal key "FILETAGS")
3088 (when (string-match "\\S-" value)
3089 (setq ftags
3090 (append
3091 ftags
3092 (apply 'append
3093 (mapcar (lambda (x) (org-split-string x ":"))
3094 (org-split-string value)))))))
3095 ((equal key "DRAWERS")
3096 (setq drawers (org-split-string value splitre)))
3097 ((equal key "CONSTANTS")
3098 (setq const (append const (org-split-string value splitre))))
3099 ((equal key "STARTUP")
3100 (let ((opts (org-split-string value splitre))
3101 l var val)
3102 (while (setq l (pop opts))
3103 (when (setq l (assoc l org-startup-options))
3104 (setq var (nth 1 l) val (nth 2 l))
3105 (if (not (nth 3 l))
3106 (set (make-local-variable var) val)
3107 (if (not (listp (symbol-value var)))
3108 (set (make-local-variable var) nil))
3109 (set (make-local-variable var) (symbol-value var))
3110 (add-to-list var val))))))
3111 ((equal key "ARCHIVE")
3112 (string-match " *$" value)
3113 (setq arch (replace-match "" t t value))
3114 (remove-text-properties 0 (length arch)
3115 '(face t fontified t) arch))
3116 ((equal key "SETUPFILE")
3117 (setq setup-contents (org-file-contents
3118 (expand-file-name
3119 (org-remove-double-quotes value))
3120 'noerror))
3121 (if (not ext-setup-or-nil)
3122 (setq ext-setup-or-nil setup-contents start 0)
3123 (setq ext-setup-or-nil
3124 (concat (substring ext-setup-or-nil 0 start)
3125 "\n" setup-contents "\n"
3126 (substring ext-setup-or-nil start)))))
3127 ))))
3128 (when cat
3129 (org-set-local 'org-category (intern cat))
3130 (push (cons "CATEGORY" cat) props))
3131 (when prio
3132 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3133 (setq prio (mapcar 'string-to-char prio))
3134 (org-set-local 'org-highest-priority (nth 0 prio))
3135 (org-set-local 'org-lowest-priority (nth 1 prio))
3136 (org-set-local 'org-default-priority (nth 2 prio)))
3137 (and props (org-set-local 'org-file-properties (nreverse props)))
3138 (and ftags (org-set-local 'org-file-tags ftags))
3139 (and drawers (org-set-local 'org-drawers drawers))
3140 (and arch (org-set-local 'org-archive-location arch))
3141 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3142 ;; Process the TODO keywords
3143 (unless kwds
3144 ;; Use the global values as if they had been given locally.
3145 (setq kwds (default-value 'org-todo-keywords))
3146 (if (stringp (car kwds))
3147 (setq kwds (list (cons org-todo-interpretation
3148 (default-value 'org-todo-keywords)))))
3149 (setq kwds (reverse kwds)))
3150 (setq kwds (nreverse kwds))
3151 (let (inter kws kw)
3152 (while (setq kws (pop kwds))
3153 (setq inter (pop kws) sep (member "|" kws)
3154 kws0 (delete "|" (copy-sequence kws))
3155 kwsa nil
3156 kws1 (mapcar
3157 (lambda (x)
3158 ;; 1 2
3159 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3160 (progn
3161 (setq kw (match-string 1 x)
3162 key (and (match-end 2) (match-string 2 x))
3163 log (org-extract-log-state-settings x))
3164 (push (cons kw (and key (string-to-char key))) kwsa)
3165 (and log (push log org-todo-log-states))
3167 (error "Invalid TODO keyword %s" x)))
3168 kws0)
3169 kwsa (if kwsa (append '((:startgroup))
3170 (nreverse kwsa)
3171 '((:endgroup))))
3172 hw (car kws1)
3173 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3174 tail (list inter hw (car dws) (org-last dws)))
3175 (add-to-list 'org-todo-heads hw 'append)
3176 (push kws1 org-todo-sets)
3177 (setq org-done-keywords (append org-done-keywords dws nil))
3178 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3179 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3180 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3181 (setq org-todo-sets (nreverse org-todo-sets)
3182 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3183 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3184 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3185 ;; Process the constants
3186 (when const
3187 (let (e cst)
3188 (while (setq e (pop const))
3189 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3190 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3191 (setq org-table-formula-constants-local cst)))
3193 ;; Process the tags.
3194 (when tags
3195 (let (e tgs)
3196 (while (setq e (pop tags))
3197 (cond
3198 ((equal e "{") (push '(:startgroup) tgs))
3199 ((equal e "}") (push '(:endgroup) tgs))
3200 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3201 (push (cons (match-string 1 e)
3202 (string-to-char (match-string 2 e)))
3203 tgs))
3204 (t (push (list e) tgs))))
3205 (org-set-local 'org-tag-alist nil)
3206 (while (setq e (pop tgs))
3207 (or (and (stringp (car e))
3208 (assoc (car e) org-tag-alist))
3209 (push e org-tag-alist)))))
3211 ;; Compute the regular expressions and other local variables
3212 (if (not org-done-keywords)
3213 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3214 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3215 (length org-scheduled-string)
3216 (length org-clock-string)
3217 (length org-closed-string)))
3218 org-drawer-regexp
3219 (concat "^[ \t]*:\\("
3220 (mapconcat 'regexp-quote org-drawers "\\|")
3221 "\\):[ \t]*$")
3222 org-not-done-keywords
3223 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3224 org-todo-regexp
3225 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3226 "\\|") "\\)\\>")
3227 org-not-done-regexp
3228 (concat "\\<\\("
3229 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3230 "\\)\\>")
3231 org-todo-line-regexp
3232 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3233 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3234 "\\)\\>\\)?[ \t]*\\(.*\\)")
3235 org-complex-heading-regexp
3236 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3237 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3238 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3239 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3240 org-nl-done-regexp
3241 (concat "\n\\*+[ \t]+"
3242 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3243 "\\)" "\\>")
3244 org-todo-line-tags-regexp
3245 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3246 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3247 (org-re
3248 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3249 org-looking-at-done-regexp
3250 (concat "^" "\\(?:"
3251 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3252 "\\>")
3253 org-deadline-regexp (concat "\\<" org-deadline-string)
3254 org-deadline-time-regexp
3255 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3256 org-deadline-line-regexp
3257 (concat "\\<\\(" org-deadline-string "\\).*")
3258 org-scheduled-regexp
3259 (concat "\\<" org-scheduled-string)
3260 org-scheduled-time-regexp
3261 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3262 org-closed-time-regexp
3263 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3264 org-keyword-time-regexp
3265 (concat "\\<\\(" org-scheduled-string
3266 "\\|" org-deadline-string
3267 "\\|" org-closed-string
3268 "\\|" org-clock-string "\\)"
3269 " *[[<]\\([^]>]+\\)[]>]")
3270 org-keyword-time-not-clock-regexp
3271 (concat "\\<\\(" org-scheduled-string
3272 "\\|" org-deadline-string
3273 "\\|" org-closed-string
3274 "\\)"
3275 " *[[<]\\([^]>]+\\)[]>]")
3276 org-maybe-keyword-time-regexp
3277 (concat "\\(\\<\\(" org-scheduled-string
3278 "\\|" org-deadline-string
3279 "\\|" org-closed-string
3280 "\\|" org-clock-string "\\)\\)?"
3281 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3282 org-planning-or-clock-line-re
3283 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3284 "\\|" org-deadline-string
3285 "\\|" org-closed-string "\\|" org-clock-string
3286 "\\)\\>\\)")
3288 (org-compute-latex-and-specials-regexp)
3289 (org-set-font-lock-defaults))))
3291 (defun org-file-contents (file &optional noerror)
3292 "Return the contents of FILE, as a string."
3293 (if (or (not file)
3294 (not (file-readable-p file)))
3295 (if noerror
3296 (progn
3297 (message "Cannot read file %s" file)
3298 (ding) (sit-for 2)
3300 (error "Cannot read file %s" file))
3301 (with-temp-buffer
3302 (insert-file-contents file)
3303 (buffer-string))))
3305 (defun org-extract-log-state-settings (x)
3306 "Extract the log state setting from a TODO keyword string.
3307 This will extract info from a string like \"WAIT(w@/!)\"."
3308 (let (kw key log1 log2)
3309 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3310 (setq kw (match-string 1 x)
3311 key (and (match-end 2) (match-string 2 x))
3312 log1 (and (match-end 3) (match-string 3 x))
3313 log2 (and (match-end 4) (match-string 4 x)))
3314 (and (or log1 log2)
3315 (list kw
3316 (and log1 (if (equal log1 "!") 'time 'note))
3317 (and log2 (if (equal log2 "!") 'time 'note)))))))
3319 (defun org-remove-keyword-keys (list)
3320 "Remove a pair of parenthesis at the end of each string in LIST."
3321 (mapcar (lambda (x)
3322 (if (string-match "(.*)$" x)
3323 (substring x 0 (match-beginning 0))
3325 list))
3327 ;; FIXME: this could be done much better, using second characters etc.
3328 (defun org-assign-fast-keys (alist)
3329 "Assign fast keys to a keyword-key alist.
3330 Respect keys that are already there."
3331 (let (new e k c c1 c2 (char ?a))
3332 (while (setq e (pop alist))
3333 (cond
3334 ((equal e '(:startgroup)) (push e new))
3335 ((equal e '(:endgroup)) (push e new))
3337 (setq k (car e) c2 nil)
3338 (if (cdr e)
3339 (setq c (cdr e))
3340 ;; automatically assign a character.
3341 (setq c1 (string-to-char
3342 (downcase (substring
3343 k (if (= (string-to-char k) ?@) 1 0)))))
3344 (if (or (rassoc c1 new) (rassoc c1 alist))
3345 (while (or (rassoc char new) (rassoc char alist))
3346 (setq char (1+ char)))
3347 (setq c2 c1))
3348 (setq c (or c2 char)))
3349 (push (cons k c) new))))
3350 (nreverse new)))
3352 ;;; Some variables used in various places
3354 (defvar org-window-configuration nil
3355 "Used in various places to store a window configuration.")
3356 (defvar org-finish-function nil
3357 "Function to be called when `C-c C-c' is used.
3358 This is for getting out of special buffers like remember.")
3361 ;; FIXME: Occasionally check by commenting these, to make sure
3362 ;; no other functions uses these, forgetting to let-bind them.
3363 (defvar entry)
3364 (defvar state)
3365 (defvar last-state)
3366 (defvar date)
3367 (defvar description)
3369 ;; Defined somewhere in this file, but used before definition.
3370 (defvar org-html-entities)
3371 (defvar org-struct-menu)
3372 (defvar org-org-menu)
3373 (defvar org-tbl-menu)
3374 (defvar org-agenda-keymap)
3376 ;;;; Define the Org-mode
3378 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3379 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
3382 ;; We use a before-change function to check if a table might need
3383 ;; an update.
3384 (defvar org-table-may-need-update t
3385 "Indicates that a table might need an update.
3386 This variable is set by `org-before-change-function'.
3387 `org-table-align' sets it back to nil.")
3388 (defun org-before-change-function (beg end)
3389 "Every change indicates that a table might need an update."
3390 (setq org-table-may-need-update t))
3391 (defvar org-mode-map)
3392 (defvar org-mode-hook nil
3393 "Mode hook for Org-mode, run after the mode was turned on.")
3394 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3395 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3396 (defvar org-table-buffer-is-an nil)
3397 (defconst org-outline-regexp "\\*+ ")
3399 ;;;###autoload
3400 (define-derived-mode org-mode outline-mode "Org"
3401 "Outline-based notes management and organizer, alias
3402 \"Carsten's outline-mode for keeping track of everything.\"
3404 Org-mode develops organizational tasks around a NOTES file which
3405 contains information about projects as plain text. Org-mode is
3406 implemented on top of outline-mode, which is ideal to keep the content
3407 of large files well structured. It supports ToDo items, deadlines and
3408 time stamps, which magically appear in the diary listing of the Emacs
3409 calendar. Tables are easily created with a built-in table editor.
3410 Plain text URL-like links connect to websites, emails (VM), Usenet
3411 messages (Gnus), BBDB entries, and any files related to the project.
3412 For printing and sharing of notes, an Org-mode file (or a part of it)
3413 can be exported as a structured ASCII or HTML file.
3415 The following commands are available:
3417 \\{org-mode-map}"
3419 ;; Get rid of Outline menus, they are not needed
3420 ;; Need to do this here because define-derived-mode sets up
3421 ;; the keymap so late. Still, it is a waste to call this each time
3422 ;; we switch another buffer into org-mode.
3423 (if (featurep 'xemacs)
3424 (when (boundp 'outline-mode-menu-heading)
3425 ;; Assume this is Greg's port, it used easymenu
3426 (easy-menu-remove outline-mode-menu-heading)
3427 (easy-menu-remove outline-mode-menu-show)
3428 (easy-menu-remove outline-mode-menu-hide))
3429 (define-key org-mode-map [menu-bar headings] 'undefined)
3430 (define-key org-mode-map [menu-bar hide] 'undefined)
3431 (define-key org-mode-map [menu-bar show] 'undefined))
3433 (org-load-modules-maybe)
3434 (easy-menu-add org-org-menu)
3435 (easy-menu-add org-tbl-menu)
3436 (org-install-agenda-files-menu)
3437 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3438 (org-add-to-invisibility-spec '(org-cwidth))
3439 (when (featurep 'xemacs)
3440 (org-set-local 'line-move-ignore-invisible t))
3441 (org-set-local 'outline-regexp org-outline-regexp)
3442 (org-set-local 'outline-level 'org-outline-level)
3443 (when (and org-ellipsis
3444 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3445 (fboundp 'make-glyph-code))
3446 (unless org-display-table
3447 (setq org-display-table (make-display-table)))
3448 (set-display-table-slot
3449 org-display-table 4
3450 (vconcat (mapcar
3451 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3452 org-ellipsis)))
3453 (if (stringp org-ellipsis) org-ellipsis "..."))))
3454 (setq buffer-display-table org-display-table))
3455 (org-set-regexps-and-options)
3456 (when (and org-tag-faces (not org-tags-special-faces-re))
3457 ;; tag faces set outside customize.... force initialization.
3458 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3459 ;; Calc embedded
3460 (org-set-local 'calc-embedded-open-mode "# ")
3461 (modify-syntax-entry ?# "<")
3462 (modify-syntax-entry ?@ "w")
3463 (if org-startup-truncated (setq truncate-lines t))
3464 (org-set-local 'font-lock-unfontify-region-function
3465 'org-unfontify-region)
3466 ;; Activate before-change-function
3467 (org-set-local 'org-table-may-need-update t)
3468 (org-add-hook 'before-change-functions 'org-before-change-function nil
3469 'local)
3470 ;; Check for running clock before killing a buffer
3471 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3472 ;; Paragraphs and auto-filling
3473 (org-set-autofill-regexps)
3474 (setq indent-line-function 'org-indent-line-function)
3475 (org-update-radio-target-regexp)
3477 ;; Comment characters
3478 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3479 (org-set-local 'comment-padding " ")
3481 ;; Align options lines
3482 (org-set-local
3483 'align-mode-rules-list
3484 '((org-in-buffer-settings
3485 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3486 (modes . '(org-mode)))))
3488 ;; Imenu
3489 (org-set-local 'imenu-create-index-function
3490 'org-imenu-get-tree)
3492 ;; Make isearch reveal context
3493 (if (or (featurep 'xemacs)
3494 (not (boundp 'outline-isearch-open-invisible-function)))
3495 ;; Emacs 21 and XEmacs make use of the hook
3496 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3497 ;; Emacs 22 deals with this through a special variable
3498 (org-set-local 'outline-isearch-open-invisible-function
3499 (lambda (&rest ignore) (org-show-context 'isearch))))
3501 ;; If empty file that did not turn on org-mode automatically, make it to.
3502 (if (and org-insert-mode-line-in-empty-file
3503 (interactive-p)
3504 (= (point-min) (point-max)))
3505 (insert "# -*- mode: org -*-\n\n"))
3507 (unless org-inhibit-startup
3508 (when org-startup-align-all-tables
3509 (let ((bmp (buffer-modified-p)))
3510 (org-table-map-tables 'org-table-align)
3511 (set-buffer-modified-p bmp)))
3512 (org-set-startup-visibility)))
3514 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3516 (defun org-current-time ()
3517 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3518 (if (> (car org-time-stamp-rounding-minutes) 1)
3519 (let ((r (car org-time-stamp-rounding-minutes))
3520 (time (decode-time)))
3521 (apply 'encode-time
3522 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3523 (nthcdr 2 time))))
3524 (current-time)))
3526 ;;;; Font-Lock stuff, including the activators
3528 (defvar org-mouse-map (make-sparse-keymap))
3529 (org-defkey org-mouse-map
3530 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3531 (org-defkey org-mouse-map
3532 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3533 (when org-mouse-1-follows-link
3534 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3535 (when org-tab-follows-link
3536 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3537 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3538 (when org-return-follows-link
3539 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3540 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3542 (require 'font-lock)
3544 (defconst org-non-link-chars "]\t\n\r<>")
3545 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3546 "shell" "elisp"))
3547 (defvar org-link-types-re nil
3548 "Matches a link that has a url-like prefix like \"http:\"")
3549 (defvar org-link-re-with-space nil
3550 "Matches a link with spaces, optional angular brackets around it.")
3551 (defvar org-link-re-with-space2 nil
3552 "Matches a link with spaces, optional angular brackets around it.")
3553 (defvar org-link-re-with-space3 nil
3554 "Matches a link with spaces, only for internal part in bracket links.")
3555 (defvar org-angle-link-re nil
3556 "Matches link with angular brackets, spaces are allowed.")
3557 (defvar org-plain-link-re nil
3558 "Matches plain link, without spaces.")
3559 (defvar org-bracket-link-regexp nil
3560 "Matches a link in double brackets.")
3561 (defvar org-bracket-link-analytic-regexp nil
3562 "Regular expression used to analyze links.
3563 Here is what the match groups contain after a match:
3564 1: http:
3565 2: http
3566 3: path
3567 4: [desc]
3568 5: desc")
3569 (defvar org-bracket-link-analytic-regexp++ nil
3570 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3571 (defvar org-any-link-re nil
3572 "Regular expression matching any link.")
3574 (defun org-make-link-regexps ()
3575 "Update the link regular expressions.
3576 This should be called after the variable `org-link-types' has changed."
3577 (setq org-link-types-re
3578 (concat
3579 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3580 org-link-re-with-space
3581 (concat
3582 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3583 "\\([^" org-non-link-chars " ]"
3584 "[^" org-non-link-chars "]*"
3585 "[^" org-non-link-chars " ]\\)>?")
3586 org-link-re-with-space2
3587 (concat
3588 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3589 "\\([^" org-non-link-chars " ]"
3590 "[^\t\n\r]*"
3591 "[^" org-non-link-chars " ]\\)>?")
3592 org-link-re-with-space3
3593 (concat
3594 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3595 "\\([^" org-non-link-chars " ]"
3596 "[^\t\n\r]*\\)")
3597 org-angle-link-re
3598 (concat
3599 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3600 "\\([^" org-non-link-chars " ]"
3601 "[^" org-non-link-chars "]*"
3602 "\\)>")
3603 org-plain-link-re
3604 (concat
3605 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3606 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3607 org-bracket-link-regexp
3608 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3609 org-bracket-link-analytic-regexp
3610 (concat
3611 "\\[\\["
3612 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3613 "\\([^]]+\\)"
3614 "\\]"
3615 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3616 "\\]")
3617 org-bracket-link-analytic-regexp++
3618 (concat
3619 "\\[\\["
3620 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3621 "\\([^]]+\\)"
3622 "\\]"
3623 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3624 "\\]")
3625 org-any-link-re
3626 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3627 org-angle-link-re "\\)\\|\\("
3628 org-plain-link-re "\\)")))
3630 (org-make-link-regexps)
3632 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3633 "Regular expression for fast time stamp matching.")
3634 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3635 "Regular expression for fast time stamp matching.")
3636 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3637 "Regular expression matching time strings for analysis.
3638 This one does not require the space after the date, so it can be used
3639 on a string that terminates immediately after the date.")
3640 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3641 "Regular expression matching time strings for analysis.")
3642 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3643 "Regular expression matching time stamps, with groups.")
3644 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3645 "Regular expression matching time stamps (also [..]), with groups.")
3646 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3647 "Regular expression matching a time stamp range.")
3648 (defconst org-tr-regexp-both
3649 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3650 "Regular expression matching a time stamp range.")
3651 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3652 org-ts-regexp "\\)?")
3653 "Regular expression matching a time stamp or time stamp range.")
3654 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3655 org-ts-regexp-both "\\)?")
3656 "Regular expression matching a time stamp or time stamp range.
3657 The time stamps may be either active or inactive.")
3659 (defvar org-emph-face nil)
3661 (defun org-do-emphasis-faces (limit)
3662 "Run through the buffer and add overlays to links."
3663 (let (rtn)
3664 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3665 (if (not (= (char-after (match-beginning 3))
3666 (char-after (match-beginning 4))))
3667 (progn
3668 (setq rtn t)
3669 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3670 'face
3671 (nth 1 (assoc (match-string 3)
3672 org-emphasis-alist)))
3673 (add-text-properties (match-beginning 2) (match-end 2)
3674 '(font-lock-multiline t))
3675 (when org-hide-emphasis-markers
3676 (add-text-properties (match-end 4) (match-beginning 5)
3677 '(invisible org-link))
3678 (add-text-properties (match-beginning 3) (match-end 3)
3679 '(invisible org-link)))))
3680 (backward-char 1))
3681 rtn))
3683 (defun org-emphasize (&optional char)
3684 "Insert or change an emphasis, i.e. a font like bold or italic.
3685 If there is an active region, change that region to a new emphasis.
3686 If there is no region, just insert the marker characters and position
3687 the cursor between them.
3688 CHAR should be either the marker character, or the first character of the
3689 HTML tag associated with that emphasis. If CHAR is a space, the means
3690 to remove the emphasis of the selected region.
3691 If char is not given (for example in an interactive call) it
3692 will be prompted for."
3693 (interactive)
3694 (let ((eal org-emphasis-alist) e det
3695 (erc org-emphasis-regexp-components)
3696 (prompt "")
3697 (string "") beg end move tag c s)
3698 (if (org-region-active-p)
3699 (setq beg (region-beginning) end (region-end)
3700 string (buffer-substring beg end))
3701 (setq move t))
3703 (while (setq e (pop eal))
3704 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3705 c (aref tag 0))
3706 (push (cons c (string-to-char (car e))) det)
3707 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3708 (substring tag 1)))))
3709 (setq det (nreverse det))
3710 (unless char
3711 (message "%s" (concat "Emphasis marker or tag:" prompt))
3712 (setq char (read-char-exclusive)))
3713 (setq char (or (cdr (assoc char det)) char))
3714 (if (equal char ?\ )
3715 (setq s "" move nil)
3716 (unless (assoc (char-to-string char) org-emphasis-alist)
3717 (error "No such emphasis marker: \"%c\"" char))
3718 (setq s (char-to-string char)))
3719 (while (and (> (length string) 1)
3720 (equal (substring string 0 1) (substring string -1))
3721 (assoc (substring string 0 1) org-emphasis-alist))
3722 (setq string (substring string 1 -1)))
3723 (setq string (concat s string s))
3724 (if beg (delete-region beg end))
3725 (unless (or (bolp)
3726 (string-match (concat "[" (nth 0 erc) "\n]")
3727 (char-to-string (char-before (point)))))
3728 (insert " "))
3729 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3730 (char-to-string (char-after (point))))
3731 (insert " ") (backward-char 1))
3732 (insert string)
3733 (and move (backward-char 1))))
3735 (defconst org-nonsticky-props
3736 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3739 (defun org-activate-plain-links (limit)
3740 "Run through the buffer and add overlays to links."
3741 (catch 'exit
3742 (let (f)
3743 (while (re-search-forward org-plain-link-re limit t)
3744 (setq f (get-text-property (match-beginning 0) 'face))
3745 (if (or (eq f 'org-tag)
3746 (and (listp f) (memq 'org-tag f)))
3748 (add-text-properties (match-beginning 0) (match-end 0)
3749 (list 'mouse-face 'highlight
3750 'rear-nonsticky org-nonsticky-props
3751 'keymap org-mouse-map
3753 (throw 'exit t))))))
3755 (defun org-activate-code (limit)
3756 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3757 (progn
3758 (remove-text-properties (match-beginning 0) (match-end 0)
3759 '(display t invisible t intangible t))
3760 t)))
3762 (defun org-activate-angle-links (limit)
3763 "Run through the buffer and add overlays to links."
3764 (if (re-search-forward org-angle-link-re limit t)
3765 (progn
3766 (add-text-properties (match-beginning 0) (match-end 0)
3767 (list 'mouse-face 'highlight
3768 'rear-nonsticky org-nonsticky-props
3769 'keymap org-mouse-map
3771 t)))
3773 (defun org-activate-footnote-links (limit)
3774 "Run through the buffer and add overlays to links."
3775 (if (re-search-forward "\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)"
3776 limit t)
3777 (progn
3778 (add-text-properties (match-beginning 0) (match-end 0)
3779 (list 'mouse-face 'highlight
3780 'rear-nonsticky org-nonsticky-props
3781 'keymap org-mouse-map
3782 'help-echo
3783 (if (= (point-at-bol) (match-beginning 0))
3784 "Footnote definition"
3785 "Footnote reference")
3787 t)))
3789 (defun org-activate-bracket-links (limit)
3790 "Run through the buffer and add overlays to bracketed links."
3791 (if (re-search-forward org-bracket-link-regexp limit t)
3792 (let* ((help (concat "LINK: "
3793 (org-match-string-no-properties 1)))
3794 ;; FIXME: above we should remove the escapes.
3795 ;; but that requires another match, protecting match data,
3796 ;; a lot of overhead for font-lock.
3797 (ip (org-maybe-intangible
3798 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3799 'keymap org-mouse-map 'mouse-face 'highlight
3800 'font-lock-multiline t 'help-echo help)))
3801 (vp (list 'rear-nonsticky org-nonsticky-props
3802 'keymap org-mouse-map 'mouse-face 'highlight
3803 ' font-lock-multiline t 'help-echo help)))
3804 ;; We need to remove the invisible property here. Table narrowing
3805 ;; may have made some of this invisible.
3806 (remove-text-properties (match-beginning 0) (match-end 0)
3807 '(invisible nil))
3808 (if (match-end 3)
3809 (progn
3810 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3811 (add-text-properties (match-beginning 3) (match-end 3) vp)
3812 (add-text-properties (match-end 3) (match-end 0) ip))
3813 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3814 (add-text-properties (match-beginning 1) (match-end 1) vp)
3815 (add-text-properties (match-end 1) (match-end 0) ip))
3816 t)))
3818 (defun org-activate-dates (limit)
3819 "Run through the buffer and add overlays to dates."
3820 (if (re-search-forward org-tsr-regexp-both limit t)
3821 (progn
3822 (add-text-properties (match-beginning 0) (match-end 0)
3823 (list 'mouse-face 'highlight
3824 'rear-nonsticky org-nonsticky-props
3825 'keymap org-mouse-map))
3826 (when org-display-custom-times
3827 (if (match-end 3)
3828 (org-display-custom-time (match-beginning 3) (match-end 3)))
3829 (org-display-custom-time (match-beginning 1) (match-end 1)))
3830 t)))
3832 (defvar org-target-link-regexp nil
3833 "Regular expression matching radio targets in plain text.")
3834 (make-variable-buffer-local 'org-target-link-regexp)
3835 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3836 "Regular expression matching a link target.")
3837 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3838 "Regular expression matching a radio target.")
3839 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3840 "Regular expression matching any target.")
3842 (defun org-activate-target-links (limit)
3843 "Run through the buffer and add overlays to target matches."
3844 (when org-target-link-regexp
3845 (let ((case-fold-search t))
3846 (if (re-search-forward org-target-link-regexp limit t)
3847 (progn
3848 (add-text-properties (match-beginning 0) (match-end 0)
3849 (list 'mouse-face 'highlight
3850 'rear-nonsticky org-nonsticky-props
3851 'keymap org-mouse-map
3852 'help-echo "Radio target link"
3853 'org-linked-text t))
3854 t)))))
3856 (defun org-update-radio-target-regexp ()
3857 "Find all radio targets in this file and update the regular expression."
3858 (interactive)
3859 (when (memq 'radio org-activate-links)
3860 (setq org-target-link-regexp
3861 (org-make-target-link-regexp (org-all-targets 'radio)))
3862 (org-restart-font-lock)))
3864 (defun org-hide-wide-columns (limit)
3865 (let (s e)
3866 (setq s (text-property-any (point) (or limit (point-max))
3867 'org-cwidth t))
3868 (when s
3869 (setq e (next-single-property-change s 'org-cwidth))
3870 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3871 (goto-char e)
3872 t)))
3874 (defvar org-latex-and-specials-regexp nil
3875 "Regular expression for highlighting export special stuff.")
3876 (defvar org-match-substring-regexp)
3877 (defvar org-match-substring-with-braces-regexp)
3878 (defvar org-export-html-special-string-regexps)
3880 (defun org-compute-latex-and-specials-regexp ()
3881 "Compute regular expression for stuff treated specially by exporters."
3882 (if (not org-highlight-latex-fragments-and-specials)
3883 (org-set-local 'org-latex-and-specials-regexp nil)
3884 (require 'org-exp)
3885 (let*
3886 ((matchers (plist-get org-format-latex-options :matchers))
3887 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3888 org-latex-regexps)))
3889 (options (org-combine-plists (org-default-export-plist)
3890 (org-infile-export-plist)))
3891 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3892 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3893 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3894 (org-export-html-expand (plist-get options :expand-quoted-html))
3895 (org-export-with-special-strings (plist-get options :special-strings))
3896 (re-sub
3897 (cond
3898 ((equal org-export-with-sub-superscripts '{})
3899 (list org-match-substring-with-braces-regexp))
3900 (org-export-with-sub-superscripts
3901 (list org-match-substring-regexp))
3902 (t nil)))
3903 (re-latex
3904 (if org-export-with-LaTeX-fragments
3905 (mapcar (lambda (x) (nth 1 x)) latexs)))
3906 (re-macros
3907 (if org-export-with-TeX-macros
3908 (list (concat "\\\\"
3909 (regexp-opt
3910 (append (mapcar 'car org-html-entities)
3911 (if (boundp 'org-latex-entities)
3912 org-latex-entities nil))
3913 'words))) ; FIXME
3915 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3916 (re-special (if org-export-with-special-strings
3917 (mapcar (lambda (x) (car x))
3918 org-export-html-special-string-regexps)))
3919 (re-rest
3920 (delq nil
3921 (list
3922 (if org-export-html-expand "@<[^>\n]+>")
3923 ))))
3924 (org-set-local
3925 'org-latex-and-specials-regexp
3926 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3927 re-rest) "\\|")))))
3929 (defun org-do-latex-and-special-faces (limit)
3930 "Run through the buffer and add overlays to links."
3931 (when org-latex-and-specials-regexp
3932 (let (rtn d)
3933 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3934 limit t))
3935 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3936 'face))
3937 '(org-code org-verbatim underline)))
3938 (progn
3939 (setq rtn t
3940 d (cond ((member (char-after (1+ (match-beginning 0)))
3941 '(?_ ?^)) 1)
3942 (t 0)))
3943 (font-lock-prepend-text-property
3944 (+ d (match-beginning 0)) (match-end 0)
3945 'face 'org-latex-and-export-specials)
3946 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3947 '(font-lock-multiline t)))))
3948 rtn)))
3950 (defun org-restart-font-lock ()
3951 "Restart font-lock-mode, to force refontification."
3952 (when (and (boundp 'font-lock-mode) font-lock-mode)
3953 (font-lock-mode -1)
3954 (font-lock-mode 1)))
3956 (defun org-all-targets (&optional radio)
3957 "Return a list of all targets in this file.
3958 With optional argument RADIO, only find radio targets."
3959 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3960 rtn)
3961 (save-excursion
3962 (goto-char (point-min))
3963 (while (re-search-forward re nil t)
3964 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3965 rtn)))
3967 (defun org-make-target-link-regexp (targets)
3968 "Make regular expression matching all strings in TARGETS.
3969 The regular expression finds the targets also if there is a line break
3970 between words."
3971 (and targets
3972 (concat
3973 "\\<\\("
3974 (mapconcat
3975 (lambda (x)
3976 (while (string-match " +" x)
3977 (setq x (replace-match "\\s-+" t t x)))
3979 targets
3980 "\\|")
3981 "\\)\\>")))
3983 (defun org-activate-tags (limit)
3984 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3985 (progn
3986 (add-text-properties (match-beginning 1) (match-end 1)
3987 (list 'mouse-face 'highlight
3988 'rear-nonsticky org-nonsticky-props
3989 'keymap org-mouse-map))
3990 t)))
3992 (defun org-outline-level ()
3993 (save-excursion
3994 (looking-at outline-regexp)
3995 (if (match-beginning 1)
3996 (+ (org-get-string-indentation (match-string 1)) 1000)
3997 (1- (- (match-end 0) (match-beginning 0))))))
3999 (defvar org-font-lock-keywords nil)
4001 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4002 "Regular expression matching a property line.")
4004 (defvar org-font-lock-hook nil
4005 "Functions to be called for special font lock stuff.")
4007 (defun org-font-lock-hook (limit)
4008 (run-hook-with-args 'org-font-lock-hook limit))
4010 (defun org-set-font-lock-defaults ()
4011 (let* ((em org-fontify-emphasized-text)
4012 (lk org-activate-links)
4013 (org-font-lock-extra-keywords
4014 (list
4015 ;; Call the hook
4016 '(org-font-lock-hook)
4017 ;; Headlines
4018 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4019 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4020 ;; Table lines
4021 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4022 (1 'org-table t))
4023 ;; Table internals
4024 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4025 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4026 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4027 ;; Drawers
4028 (list org-drawer-regexp '(0 'org-special-keyword t))
4029 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4030 ;; Properties
4031 (list org-property-re
4032 '(1 'org-special-keyword t)
4033 '(3 'org-property-value t))
4034 (if org-format-transports-properties-p
4035 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4036 ;; Links
4037 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4038 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4039 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4040 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4041 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4042 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4043 (if (memq 'footnote lk) '(org-activate-footnote-links
4044 (0 'org-footnote t)))
4045 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4046 '(org-hide-wide-columns (0 nil append))
4047 ;; TODO lines
4048 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4049 '(1 (org-get-todo-face 1) t))
4050 ;; DONE
4051 (if org-fontify-done-headline
4052 (list (concat "^[*]+ +\\<\\("
4053 (mapconcat 'regexp-quote org-done-keywords "\\|")
4054 "\\)\\(.*\\)")
4055 '(2 'org-headline-done t))
4056 nil)
4057 ;; Priorities
4058 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4059 ;; Tags
4060 '(org-font-lock-add-tag-faces)
4061 ;; Special keywords
4062 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4063 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4064 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4065 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4066 ;; Emphasis
4067 (if em
4068 (if (featurep 'xemacs)
4069 '(org-do-emphasis-faces (0 nil append))
4070 '(org-do-emphasis-faces)))
4071 ;; Checkboxes
4072 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4073 2 'bold prepend)
4074 (if org-provide-checkbox-statistics
4075 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4076 (0 (org-get-checkbox-statistics-face) t)))
4077 ;; Description list items
4078 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4079 2 'bold prepend)
4080 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4081 '(1 'org-archived prepend))
4082 ;; Specials
4083 '(org-do-latex-and-special-faces)
4084 ;; Code
4085 '(org-activate-code (1 'org-code t))
4086 ;; COMMENT
4087 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4088 "\\|" org-quote-string "\\)\\>")
4089 '(1 'org-special-keyword t))
4090 '("^#.*" (0 'font-lock-comment-face t))
4092 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4093 ;; Now set the full font-lock-keywords
4094 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4095 (org-set-local 'font-lock-defaults
4096 '(org-font-lock-keywords t nil nil backward-paragraph))
4097 (kill-local-variable 'font-lock-keywords) nil))
4099 (defvar org-m nil)
4100 (defvar org-l nil)
4101 (defvar org-f nil)
4102 (defun org-get-level-face (n)
4103 "Get the right face for match N in font-lock matching of headlines."
4104 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4105 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4106 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4107 (cond
4108 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4109 ((eq n 2) org-f)
4110 (t (if org-level-color-stars-only nil org-f))))
4112 (defun org-get-todo-face (kwd)
4113 "Get the right face for a TODO keyword KWD.
4114 If KWD is a number, get the corresponding match group."
4115 (if (numberp kwd) (setq kwd (match-string kwd)))
4116 (or (cdr (assoc kwd org-todo-keyword-faces))
4117 (and (member kwd org-done-keywords) 'org-done)
4118 'org-todo))
4120 (defun org-font-lock-add-tag-faces (limit)
4121 "Add the special tag faces."
4122 (when (and org-tag-faces org-tags-special-faces-re)
4123 (while (re-search-forward org-tags-special-faces-re limit t)
4124 (add-text-properties (match-beginning 1) (match-end 1)
4125 (list 'face (org-get-tag-face 1)
4126 'font-lock-fontified t))
4127 (backward-char 1))))
4129 (defun org-get-tag-face (kwd)
4130 "Get the right face for a TODO keyword KWD.
4131 If KWD is a number, get the corresponding match group."
4132 (if (numberp kwd) (setq kwd (match-string kwd)))
4133 (or (cdr (assoc kwd org-tag-faces))
4134 'org-tag))
4136 (defun org-unfontify-region (beg end &optional maybe_loudly)
4137 "Remove fontification and activation overlays from links."
4138 (font-lock-default-unfontify-region beg end)
4139 (let* ((buffer-undo-list t)
4140 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4141 (inhibit-modification-hooks t)
4142 deactivate-mark buffer-file-name buffer-file-truename)
4143 (remove-text-properties beg end
4144 '(mouse-face t keymap t org-linked-text t
4145 invisible t intangible t))))
4147 ;;;; Visibility cycling, including org-goto and indirect buffer
4149 ;;; Cycling
4151 (defvar org-cycle-global-status nil)
4152 (make-variable-buffer-local 'org-cycle-global-status)
4153 (defvar org-cycle-subtree-status nil)
4154 (make-variable-buffer-local 'org-cycle-subtree-status)
4156 ;;;###autoload
4157 (defun org-cycle (&optional arg)
4158 "Visibility cycling for Org-mode.
4160 - When this function is called with a prefix argument, rotate the entire
4161 buffer through 3 states (global cycling)
4162 1. OVERVIEW: Show only top-level headlines.
4163 2. CONTENTS: Show all headlines of all levels, but no body text.
4164 3. SHOW ALL: Show everything.
4165 When called with two C-u C-u prefixes, switch to the startup visibility,
4166 determined by the variable `org-startup-folded', and by any VISIBILITY
4167 properties in the buffer.
4168 When called with three C-u C-u C-u prefixed, show the entire buffer,
4169 including drawers.
4171 - When point is at the beginning of a headline, rotate the subtree started
4172 by this line through 3 different states (local cycling)
4173 1. FOLDED: Only the main headline is shown.
4174 2. CHILDREN: The main headline and the direct children are shown.
4175 From this state, you can move to one of the children
4176 and zoom in further.
4177 3. SUBTREE: Show the entire subtree, including body text.
4179 - When there is a numeric prefix, go up to a heading with level ARG, do
4180 a `show-subtree' and return to the previous cursor position. If ARG
4181 is negative, go up that many levels.
4183 - When point is not at the beginning of a headline, execute the global
4184 binding for TAB, which is re-indenting the line. See the option
4185 `org-cycle-emulate-tab' for details.
4187 - Special case: if point is at the beginning of the buffer and there is
4188 no headline in line 1, this function will act as if called with prefix arg.
4189 But only if also the variable `org-cycle-global-at-bob' is t."
4190 (interactive "P")
4191 (org-load-modules-maybe)
4192 (let* ((outline-regexp
4193 (if (and (org-mode-p) org-cycle-include-plain-lists)
4194 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4195 outline-regexp))
4196 (bob-special (and org-cycle-global-at-bob (bobp)
4197 (not (looking-at outline-regexp))))
4198 (org-cycle-hook
4199 (if bob-special
4200 (delq 'org-optimize-window-after-visibility-change
4201 (copy-sequence org-cycle-hook))
4202 org-cycle-hook))
4203 (pos (point)))
4205 (if (or bob-special (equal arg '(4)))
4206 ;; special case: use global cycling
4207 (setq arg t))
4209 (cond
4211 ((equal arg '(16))
4212 (org-set-startup-visibility)
4213 (message "Startup visibility, plus VISIBILITY properties"))
4215 ((equal arg '(64))
4216 (show-all)
4217 (message "Entire buffer visible, including drawers"))
4219 ((org-at-table-p 'any)
4220 ;; Enter the table or move to the next field in the table
4221 (or (org-table-recognize-table.el)
4222 (progn
4223 (if arg (org-table-edit-field t)
4224 (org-table-justify-field-maybe)
4225 (call-interactively 'org-table-next-field)))))
4227 ((eq arg t) ;; Global cycling
4229 (cond
4230 ((and (eq last-command this-command)
4231 (eq org-cycle-global-status 'overview))
4232 ;; We just created the overview - now do table of contents
4233 ;; This can be slow in very large buffers, so indicate action
4234 (message "CONTENTS...")
4235 (org-content)
4236 (message "CONTENTS...done")
4237 (setq org-cycle-global-status 'contents)
4238 (run-hook-with-args 'org-cycle-hook 'contents))
4240 ((and (eq last-command this-command)
4241 (eq org-cycle-global-status 'contents))
4242 ;; We just showed the table of contents - now show everything
4243 (show-all)
4244 (message "SHOW ALL")
4245 (setq org-cycle-global-status 'all)
4246 (run-hook-with-args 'org-cycle-hook 'all))
4249 ;; Default action: go to overview
4250 (org-overview)
4251 (message "OVERVIEW")
4252 (setq org-cycle-global-status 'overview)
4253 (run-hook-with-args 'org-cycle-hook 'overview))))
4255 ((and org-drawers org-drawer-regexp
4256 (save-excursion
4257 (beginning-of-line 1)
4258 (looking-at org-drawer-regexp)))
4259 ;; Toggle block visibility
4260 (org-flag-drawer
4261 (not (get-char-property (match-end 0) 'invisible))))
4263 ((integerp arg)
4264 ;; Show-subtree, ARG levels up from here.
4265 (save-excursion
4266 (org-back-to-heading)
4267 (outline-up-heading (if (< arg 0) (- arg)
4268 (- (funcall outline-level) arg)))
4269 (org-show-subtree)))
4271 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4272 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4273 ;; At a heading: rotate between three different views
4274 (org-back-to-heading)
4275 (let ((goal-column 0) eoh eol eos)
4276 ;; First, some boundaries
4277 (save-excursion
4278 (org-back-to-heading)
4279 (save-excursion
4280 (beginning-of-line 2)
4281 (while (and (not (eobp)) ;; this is like `next-line'
4282 (get-char-property (1- (point)) 'invisible))
4283 (beginning-of-line 2)) (setq eol (point)))
4284 (outline-end-of-heading) (setq eoh (point))
4285 (org-end-of-subtree t)
4286 (unless (eobp)
4287 (skip-chars-forward " \t\n")
4288 (beginning-of-line 1) ; in case this is an item
4290 (setq eos (1- (point))))
4291 ;; Find out what to do next and set `this-command'
4292 (cond
4293 ((= eos eoh)
4294 ;; Nothing is hidden behind this heading
4295 (message "EMPTY ENTRY")
4296 (setq org-cycle-subtree-status nil)
4297 (save-excursion
4298 (goto-char eos)
4299 (outline-next-heading)
4300 (if (org-invisible-p) (org-flag-heading nil))))
4301 ((or (>= eol eos)
4302 (not (string-match "\\S-" (buffer-substring eol eos))))
4303 ;; Entire subtree is hidden in one line: open it
4304 (org-show-entry)
4305 (show-children)
4306 (message "CHILDREN")
4307 (save-excursion
4308 (goto-char eos)
4309 (outline-next-heading)
4310 (if (org-invisible-p) (org-flag-heading nil)))
4311 (setq org-cycle-subtree-status 'children)
4312 (run-hook-with-args 'org-cycle-hook 'children))
4313 ((and (eq last-command this-command)
4314 (eq org-cycle-subtree-status 'children))
4315 ;; We just showed the children, now show everything.
4316 (org-show-subtree)
4317 (message "SUBTREE")
4318 (setq org-cycle-subtree-status 'subtree)
4319 (run-hook-with-args 'org-cycle-hook 'subtree))
4321 ;; Default action: hide the subtree.
4322 (hide-subtree)
4323 (message "FOLDED")
4324 (setq org-cycle-subtree-status 'folded)
4325 (run-hook-with-args 'org-cycle-hook 'folded)))))
4327 ;; TAB emulation and template completion
4328 (buffer-read-only (org-back-to-heading))
4330 ((org-try-structure-completion))
4332 ((org-try-cdlatex-tab))
4334 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4335 (or (not (bolp))
4336 (not (looking-at outline-regexp))))
4337 (call-interactively (global-key-binding "\t")))
4339 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4340 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4341 (or (and (eq org-cycle-emulate-tab 'white)
4342 (= (match-end 0) (point-at-eol)))
4343 (and (eq org-cycle-emulate-tab 'whitestart)
4344 (>= (match-end 0) pos))))
4346 (eq org-cycle-emulate-tab t))
4347 (call-interactively (global-key-binding "\t")))
4349 (t (save-excursion
4350 (org-back-to-heading)
4351 (org-cycle))))))
4353 ;;;###autoload
4354 (defun org-global-cycle (&optional arg)
4355 "Cycle the global visibility. For details see `org-cycle'.
4356 With C-u prefix arg, switch to startup visibility.
4357 With a numeric prefix, show all headlines up to that level."
4358 (interactive "P")
4359 (let ((org-cycle-include-plain-lists
4360 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4361 (cond
4362 ((integerp arg)
4363 (show-all)
4364 (hide-sublevels arg)
4365 (setq org-cycle-global-status 'contents))
4366 ((equal arg '(4))
4367 (org-set-startup-visibility)
4368 (message "Startup visibility, plus VISIBILITY properties."))
4370 (org-cycle '(4))))))
4372 (defun org-set-startup-visibility ()
4373 "Set the visibility required by startup options and properties."
4374 (cond
4375 ((eq org-startup-folded t)
4376 (org-cycle '(4)))
4377 ((eq org-startup-folded 'content)
4378 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4379 (org-cycle '(4)) (org-cycle '(4)))))
4380 (org-set-visibility-according-to-property 'no-cleanup)
4381 (org-cycle-hide-archived-subtrees 'all)
4382 (org-cycle-hide-drawers 'all)
4383 (org-cycle-show-empty-lines 'all))
4385 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4386 "Switch subtree visibilities according to :VISIBILITY: property."
4387 (interactive)
4388 (let (state)
4389 (save-excursion
4390 (goto-char (point-min))
4391 (while (re-search-forward
4392 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4393 nil t)
4394 (setq state (match-string 1))
4395 (save-excursion
4396 (org-back-to-heading t)
4397 (hide-subtree)
4398 (org-reveal)
4399 (cond
4400 ((equal state '("fold" "folded"))
4401 (hide-subtree))
4402 ((equal state "children")
4403 (org-show-hidden-entry)
4404 (show-children))
4405 ((equal state "content")
4406 (save-excursion
4407 (save-restriction
4408 (org-narrow-to-subtree)
4409 (org-content))))
4410 ((member state '("all" "showall"))
4411 (show-subtree)))))
4412 (unless no-cleanup
4413 (org-cycle-hide-archived-subtrees 'all)
4414 (org-cycle-hide-drawers 'all)
4415 (org-cycle-show-empty-lines 'all)))))
4417 (defun org-overview ()
4418 "Switch to overview mode, showing only top-level headlines.
4419 Really, this shows all headlines with level equal or greater than the level
4420 of the first headline in the buffer. This is important, because if the
4421 first headline is not level one, then (hide-sublevels 1) gives confusing
4422 results."
4423 (interactive)
4424 (let ((level (save-excursion
4425 (goto-char (point-min))
4426 (if (re-search-forward (concat "^" outline-regexp) nil t)
4427 (progn
4428 (goto-char (match-beginning 0))
4429 (funcall outline-level))))))
4430 (and level (hide-sublevels level))))
4432 (defun org-content (&optional arg)
4433 "Show all headlines in the buffer, like a table of contents.
4434 With numerical argument N, show content up to level N."
4435 (interactive "P")
4436 (save-excursion
4437 ;; Visit all headings and show their offspring
4438 (and (integerp arg) (org-overview))
4439 (goto-char (point-max))
4440 (catch 'exit
4441 (while (and (progn (condition-case nil
4442 (outline-previous-visible-heading 1)
4443 (error (goto-char (point-min))))
4445 (looking-at outline-regexp))
4446 (if (integerp arg)
4447 (show-children (1- arg))
4448 (show-branches))
4449 (if (bobp) (throw 'exit nil))))))
4452 (defun org-optimize-window-after-visibility-change (state)
4453 "Adjust the window after a change in outline visibility.
4454 This function is the default value of the hook `org-cycle-hook'."
4455 (when (get-buffer-window (current-buffer))
4456 (cond
4457 ; ((eq state 'overview) (org-first-headline-recenter 1))
4458 ; ((eq state 'overview) (org-beginning-of-line))
4459 ((eq state 'content) nil)
4460 ((eq state 'all) nil)
4461 ((eq state 'folded) nil)
4462 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4463 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4465 (defun org-compact-display-after-subtree-move ()
4466 (let (beg end)
4467 (save-excursion
4468 (if (org-up-heading-safe)
4469 (progn
4470 (hide-subtree)
4471 (show-entry)
4472 (show-children)
4473 (org-cycle-show-empty-lines 'children)
4474 (org-cycle-hide-drawers 'children))
4475 (org-overview)))))
4477 (defun org-cycle-show-empty-lines (state)
4478 "Show empty lines above all visible headlines.
4479 The region to be covered depends on STATE when called through
4480 `org-cycle-hook'. Lisp program can use t for STATE to get the
4481 entire buffer covered. Note that an empty line is only shown if there
4482 are at least `org-cycle-separator-lines' empty lines before the headline."
4483 (when (> org-cycle-separator-lines 0)
4484 (save-excursion
4485 (let* ((n org-cycle-separator-lines)
4486 (re (cond
4487 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4488 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4489 (t (let ((ns (number-to-string (- n 2))))
4490 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4491 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4492 beg end)
4493 (cond
4494 ((memq state '(overview contents t))
4495 (setq beg (point-min) end (point-max)))
4496 ((memq state '(children folded))
4497 (setq beg (point) end (progn (org-end-of-subtree t t)
4498 (beginning-of-line 2)
4499 (point)))))
4500 (when beg
4501 (goto-char beg)
4502 (while (re-search-forward re end t)
4503 (if (not (get-char-property (match-end 1) 'invisible))
4504 (outline-flag-region
4505 (match-beginning 1) (match-end 1) nil)))))))
4506 ;; Never hide empty lines at the end of the file.
4507 (save-excursion
4508 (goto-char (point-max))
4509 (outline-previous-heading)
4510 (outline-end-of-heading)
4511 (if (and (looking-at "[ \t\n]+")
4512 (= (match-end 0) (point-max)))
4513 (outline-flag-region (point) (match-end 0) nil))))
4515 (defun org-show-empty-lines-in-parent ()
4516 "Move to the parent and re-show empty lines before visible headlines."
4517 (save-excursion
4518 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4519 (org-cycle-show-empty-lines context))))
4521 (defun org-cycle-hide-drawers (state)
4522 "Re-hide all drawers after a visibility state change."
4523 (when (and (org-mode-p)
4524 (not (memq state '(overview folded))))
4525 (save-excursion
4526 (let* ((globalp (memq state '(contents all)))
4527 (beg (if globalp (point-min) (point)))
4528 (end (if globalp (point-max) (org-end-of-subtree t))))
4529 (goto-char beg)
4530 (while (re-search-forward org-drawer-regexp end t)
4531 (org-flag-drawer t))))))
4533 (defun org-flag-drawer (flag)
4534 (save-excursion
4535 (beginning-of-line 1)
4536 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4537 (let ((b (match-end 0))
4538 (outline-regexp org-outline-regexp))
4539 (if (re-search-forward
4540 "^[ \t]*:END:"
4541 (save-excursion (outline-next-heading) (point)) t)
4542 (outline-flag-region b (point-at-eol) flag)
4543 (error ":END: line missing"))))))
4545 (defun org-subtree-end-visible-p ()
4546 "Is the end of the current subtree visible?"
4547 (pos-visible-in-window-p
4548 (save-excursion (org-end-of-subtree t) (point))))
4550 (defun org-first-headline-recenter (&optional N)
4551 "Move cursor to the first headline and recenter the headline.
4552 Optional argument N means, put the headline into the Nth line of the window."
4553 (goto-char (point-min))
4554 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4555 (beginning-of-line)
4556 (recenter (prefix-numeric-value N))))
4558 ;;; Org-goto
4560 (defvar org-goto-window-configuration nil)
4561 (defvar org-goto-marker nil)
4562 (defvar org-goto-map
4563 (let ((map (make-sparse-keymap)))
4564 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4565 (while (setq cmd (pop cmds))
4566 (substitute-key-definition cmd cmd map global-map)))
4567 (suppress-keymap map)
4568 (org-defkey map "\C-m" 'org-goto-ret)
4569 (org-defkey map [(return)] 'org-goto-ret)
4570 (org-defkey map [(left)] 'org-goto-left)
4571 (org-defkey map [(right)] 'org-goto-right)
4572 (org-defkey map [(control ?g)] 'org-goto-quit)
4573 (org-defkey map "\C-i" 'org-cycle)
4574 (org-defkey map [(tab)] 'org-cycle)
4575 (org-defkey map [(down)] 'outline-next-visible-heading)
4576 (org-defkey map [(up)] 'outline-previous-visible-heading)
4577 (if org-goto-auto-isearch
4578 (if (fboundp 'define-key-after)
4579 (define-key-after map [t] 'org-goto-local-auto-isearch)
4580 nil)
4581 (org-defkey map "q" 'org-goto-quit)
4582 (org-defkey map "n" 'outline-next-visible-heading)
4583 (org-defkey map "p" 'outline-previous-visible-heading)
4584 (org-defkey map "f" 'outline-forward-same-level)
4585 (org-defkey map "b" 'outline-backward-same-level)
4586 (org-defkey map "u" 'outline-up-heading))
4587 (org-defkey map "/" 'org-occur)
4588 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4589 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4590 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4591 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4592 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4593 map))
4595 (defconst org-goto-help
4596 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4597 RET=jump to location [Q]uit and return to previous location
4598 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4600 (defvar org-goto-start-pos) ; dynamically scoped parameter
4602 ;; FIXME: Docstring doe not mention both interfaces
4603 (defun org-goto (&optional alternative-interface)
4604 "Look up a different location in the current file, keeping current visibility.
4606 When you want look-up or go to a different location in a document, the
4607 fastest way is often to fold the entire buffer and then dive into the tree.
4608 This method has the disadvantage, that the previous location will be folded,
4609 which may not be what you want.
4611 This command works around this by showing a copy of the current buffer
4612 in an indirect buffer, in overview mode. You can dive into the tree in
4613 that copy, use org-occur and incremental search to find a location.
4614 When pressing RET or `Q', the command returns to the original buffer in
4615 which the visibility is still unchanged. After RET is will also jump to
4616 the location selected in the indirect buffer and expose the
4617 the headline hierarchy above."
4618 (interactive "P")
4619 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4620 (org-refile-use-outline-path t)
4621 (interface
4622 (if (not alternative-interface)
4623 org-goto-interface
4624 (if (eq org-goto-interface 'outline)
4625 'outline-path-completion
4626 'outline)))
4627 (org-goto-start-pos (point))
4628 (selected-point
4629 (if (eq interface 'outline)
4630 (car (org-get-location (current-buffer) org-goto-help))
4631 (nth 3 (org-refile-get-location "Goto: ")))))
4632 (if selected-point
4633 (progn
4634 (org-mark-ring-push org-goto-start-pos)
4635 (goto-char selected-point)
4636 (if (or (org-invisible-p) (org-invisible-p2))
4637 (org-show-context 'org-goto)))
4638 (message "Quit"))))
4640 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4641 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4642 (defvar org-goto-local-auto-isearch-map) ; defined below
4644 (defun org-get-location (buf help)
4645 "Let the user select a location in the Org-mode buffer BUF.
4646 This function uses a recursive edit. It returns the selected position
4647 or nil."
4648 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4649 (isearch-hide-immediately nil)
4650 (isearch-search-fun-function
4651 (lambda () 'org-goto-local-search-headings))
4652 (org-goto-selected-point org-goto-exit-command))
4653 (save-excursion
4654 (save-window-excursion
4655 (delete-other-windows)
4656 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4657 (switch-to-buffer
4658 (condition-case nil
4659 (make-indirect-buffer (current-buffer) "*org-goto*")
4660 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4661 (with-output-to-temp-buffer "*Help*"
4662 (princ help))
4663 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4664 (setq buffer-read-only nil)
4665 (let ((org-startup-truncated t)
4666 (org-startup-folded nil)
4667 (org-startup-align-all-tables nil))
4668 (org-mode)
4669 (org-overview))
4670 (setq buffer-read-only t)
4671 (if (and (boundp 'org-goto-start-pos)
4672 (integer-or-marker-p org-goto-start-pos))
4673 (let ((org-show-hierarchy-above t)
4674 (org-show-siblings t)
4675 (org-show-following-heading t))
4676 (goto-char org-goto-start-pos)
4677 (and (org-invisible-p) (org-show-context)))
4678 (goto-char (point-min)))
4679 (org-beginning-of-line)
4680 (message "Select location and press RET")
4681 (use-local-map org-goto-map)
4682 (recursive-edit)
4684 (kill-buffer "*org-goto*")
4685 (cons org-goto-selected-point org-goto-exit-command)))
4687 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4688 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4689 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4690 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4692 (defun org-goto-local-search-headings (string bound noerror)
4693 "Search and make sure that any matches are in headlines."
4694 (catch 'return
4695 (while (if isearch-forward
4696 (search-forward string bound noerror)
4697 (search-backward string bound noerror))
4698 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4699 (and (member :headline context)
4700 (not (member :tags context))))
4701 (throw 'return (point))))))
4703 (defun org-goto-local-auto-isearch ()
4704 "Start isearch."
4705 (interactive)
4706 (goto-char (point-min))
4707 (let ((keys (this-command-keys)))
4708 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4709 (isearch-mode t)
4710 (isearch-process-search-char (string-to-char keys)))))
4712 (defun org-goto-ret (&optional arg)
4713 "Finish `org-goto' by going to the new location."
4714 (interactive "P")
4715 (setq org-goto-selected-point (point)
4716 org-goto-exit-command 'return)
4717 (throw 'exit nil))
4719 (defun org-goto-left ()
4720 "Finish `org-goto' by going to the new location."
4721 (interactive)
4722 (if (org-on-heading-p)
4723 (progn
4724 (beginning-of-line 1)
4725 (setq org-goto-selected-point (point)
4726 org-goto-exit-command 'left)
4727 (throw 'exit nil))
4728 (error "Not on a heading")))
4730 (defun org-goto-right ()
4731 "Finish `org-goto' by going to the new location."
4732 (interactive)
4733 (if (org-on-heading-p)
4734 (progn
4735 (setq org-goto-selected-point (point)
4736 org-goto-exit-command 'right)
4737 (throw 'exit nil))
4738 (error "Not on a heading")))
4740 (defun org-goto-quit ()
4741 "Finish `org-goto' without cursor motion."
4742 (interactive)
4743 (setq org-goto-selected-point nil)
4744 (setq org-goto-exit-command 'quit)
4745 (throw 'exit nil))
4747 ;;; Indirect buffer display of subtrees
4749 (defvar org-indirect-dedicated-frame nil
4750 "This is the frame being used for indirect tree display.")
4751 (defvar org-last-indirect-buffer nil)
4753 (defun org-tree-to-indirect-buffer (&optional arg)
4754 "Create indirect buffer and narrow it to current subtree.
4755 With numerical prefix ARG, go up to this level and then take that tree.
4756 If ARG is negative, go up that many levels.
4757 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4758 indirect buffer previously made with this command, to avoid proliferation of
4759 indirect buffers. However, when you call the command with a `C-u' prefix, or
4760 when `org-indirect-buffer-display' is `new-frame', the last buffer
4761 is kept so that you can work with several indirect buffers at the same time.
4762 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4763 requests that a new frame be made for the new buffer, so that the dedicated
4764 frame is not changed."
4765 (interactive "P")
4766 (let ((cbuf (current-buffer))
4767 (cwin (selected-window))
4768 (pos (point))
4769 beg end level heading ibuf)
4770 (save-excursion
4771 (org-back-to-heading t)
4772 (when (numberp arg)
4773 (setq level (org-outline-level))
4774 (if (< arg 0) (setq arg (+ level arg)))
4775 (while (> (setq level (org-outline-level)) arg)
4776 (outline-up-heading 1 t)))
4777 (setq beg (point)
4778 heading (org-get-heading))
4779 (org-end-of-subtree t) (setq end (point)))
4780 (if (and (buffer-live-p org-last-indirect-buffer)
4781 (not (eq org-indirect-buffer-display 'new-frame))
4782 (not arg))
4783 (kill-buffer org-last-indirect-buffer))
4784 (setq ibuf (org-get-indirect-buffer cbuf)
4785 org-last-indirect-buffer ibuf)
4786 (cond
4787 ((or (eq org-indirect-buffer-display 'new-frame)
4788 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4789 (select-frame (make-frame))
4790 (delete-other-windows)
4791 (switch-to-buffer ibuf)
4792 (org-set-frame-title heading))
4793 ((eq org-indirect-buffer-display 'dedicated-frame)
4794 (raise-frame
4795 (select-frame (or (and org-indirect-dedicated-frame
4796 (frame-live-p org-indirect-dedicated-frame)
4797 org-indirect-dedicated-frame)
4798 (setq org-indirect-dedicated-frame (make-frame)))))
4799 (delete-other-windows)
4800 (switch-to-buffer ibuf)
4801 (org-set-frame-title (concat "Indirect: " heading)))
4802 ((eq org-indirect-buffer-display 'current-window)
4803 (switch-to-buffer ibuf))
4804 ((eq org-indirect-buffer-display 'other-window)
4805 (pop-to-buffer ibuf))
4806 (t (error "Invalid value.")))
4807 (if (featurep 'xemacs)
4808 (save-excursion (org-mode) (turn-on-font-lock)))
4809 (narrow-to-region beg end)
4810 (show-all)
4811 (goto-char pos)
4812 (and (window-live-p cwin) (select-window cwin))))
4814 (defun org-get-indirect-buffer (&optional buffer)
4815 (setq buffer (or buffer (current-buffer)))
4816 (let ((n 1) (base (buffer-name buffer)) bname)
4817 (while (buffer-live-p
4818 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4819 (setq n (1+ n)))
4820 (condition-case nil
4821 (make-indirect-buffer buffer bname 'clone)
4822 (error (make-indirect-buffer buffer bname)))))
4824 (defun org-set-frame-title (title)
4825 "Set the title of the current frame to the string TITLE."
4826 ;; FIXME: how to name a single frame in XEmacs???
4827 (unless (featurep 'xemacs)
4828 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4830 ;;;; Structure editing
4832 ;;; Inserting headlines
4834 (defun org-insert-heading (&optional force-heading)
4835 "Insert a new heading or item with same depth at point.
4836 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4837 If point is at the beginning of a headline, insert a sibling before the
4838 current headline. If point is not at the beginning, do not split the line,
4839 but create the new headline after the current line."
4840 (interactive "P")
4841 (if (= (buffer-size) 0)
4842 (insert "\n* ")
4843 (when (or force-heading (not (org-insert-item)))
4844 (let* ((head (save-excursion
4845 (condition-case nil
4846 (progn
4847 (org-back-to-heading)
4848 (match-string 0))
4849 (error "*"))))
4850 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4851 pos hide-previous previous-pos)
4852 (cond
4853 ((and (org-on-heading-p) (bolp)
4854 (or (bobp)
4855 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4856 ;; insert before the current line
4857 (open-line (if blank 2 1)))
4858 ((and (bolp)
4859 (or (bobp)
4860 (save-excursion
4861 (backward-char 1) (not (org-invisible-p)))))
4862 ;; insert right here
4863 nil)
4865 ;; somewhere in the line
4866 (save-excursion
4867 (setq previous-pos (point-at-bol))
4868 (end-of-line)
4869 (setq hide-previous (org-invisible-p)))
4870 (and org-insert-heading-respect-content (org-show-subtree))
4871 (let ((split
4872 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4873 (save-excursion
4874 (let ((p (point)))
4875 (goto-char (point-at-bol))
4876 (and (looking-at org-complex-heading-regexp)
4877 (> p (match-beginning 4)))))))
4878 tags pos)
4879 (cond
4880 (org-insert-heading-respect-content
4881 (org-end-of-subtree nil t)
4882 (or (bolp) (newline))
4883 (open-line 1))
4884 ((org-on-heading-p)
4885 (when hide-previous
4886 (show-children)
4887 (org-show-entry))
4888 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4889 (setq tags (and (match-end 2) (match-string 2)))
4890 (and (match-end 1)
4891 (delete-region (match-beginning 1) (match-end 1)))
4892 (setq pos (point-at-bol))
4893 (or split (end-of-line 1))
4894 (delete-horizontal-space)
4895 (newline (if blank 2 1))
4896 (when tags
4897 (save-excursion
4898 (goto-char pos)
4899 (end-of-line 1)
4900 (insert " " tags)
4901 (org-set-tags nil 'align))))
4903 (or split (end-of-line 1))
4904 (newline (if blank 2 1)))))))
4905 (insert head) (just-one-space)
4906 (setq pos (point))
4907 (end-of-line 1)
4908 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4909 (when (and org-insert-heading-respect-content hide-previous)
4910 (save-excursion
4911 (goto-char previous-pos)
4912 (hide-subtree)))
4913 (run-hooks 'org-insert-heading-hook)))))
4915 (defun org-get-heading (&optional no-tags)
4916 "Return the heading of the current entry, without the stars."
4917 (save-excursion
4918 (org-back-to-heading t)
4919 (if (looking-at
4920 (if no-tags
4921 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4922 "\\*+[ \t]+\\([^\r\n]*\\)"))
4923 (match-string 1) "")))
4925 (defun org-insert-heading-after-current ()
4926 "Insert a new heading with same level as current, after current subtree."
4927 (interactive)
4928 (org-back-to-heading)
4929 (org-insert-heading)
4930 (org-move-subtree-down)
4931 (end-of-line 1))
4933 (defun org-insert-heading-respect-content ()
4934 (interactive)
4935 (let ((org-insert-heading-respect-content t))
4936 (org-insert-heading t)))
4938 (defun org-insert-todo-heading-respect-content (&optional force-state)
4939 (interactive "P")
4940 (let ((org-insert-heading-respect-content t))
4941 (org-insert-todo-heading force-state t)))
4943 (defun org-insert-todo-heading (arg &optional force-heading)
4944 "Insert a new heading with the same level and TODO state as current heading.
4945 If the heading has no TODO state, or if the state is DONE, use the first
4946 state (TODO by default). Also with prefix arg, force first state."
4947 (interactive "P")
4948 (when (or force-heading (not (org-insert-item 'checkbox)))
4949 (org-insert-heading force-heading)
4950 (save-excursion
4951 (org-back-to-heading)
4952 (outline-previous-heading)
4953 (looking-at org-todo-line-regexp))
4954 (if (or arg
4955 (not (match-beginning 2))
4956 (member (match-string 2) org-done-keywords))
4957 (insert (car org-todo-keywords-1) " ")
4958 (insert (match-string 2) " "))
4959 (when org-provide-todo-statistics
4960 (org-update-parent-todo-statistics))))
4962 (defun org-insert-subheading (arg)
4963 "Insert a new subheading and demote it.
4964 Works for outline headings and for plain lists alike."
4965 (interactive "P")
4966 (org-insert-heading arg)
4967 (cond
4968 ((org-on-heading-p) (org-do-demote))
4969 ((org-at-item-p) (org-indent-item 1))))
4971 (defun org-insert-todo-subheading (arg)
4972 "Insert a new subheading with TODO keyword or checkbox and demote it.
4973 Works for outline headings and for plain lists alike."
4974 (interactive "P")
4975 (org-insert-todo-heading arg)
4976 (cond
4977 ((org-on-heading-p) (org-do-demote))
4978 ((org-at-item-p) (org-indent-item 1))))
4980 ;;; Promotion and Demotion
4982 (defun org-promote-subtree ()
4983 "Promote the entire subtree.
4984 See also `org-promote'."
4985 (interactive)
4986 (save-excursion
4987 (org-map-tree 'org-promote))
4988 (org-fix-position-after-promote))
4990 (defun org-demote-subtree ()
4991 "Demote the entire subtree. See `org-demote'.
4992 See also `org-promote'."
4993 (interactive)
4994 (save-excursion
4995 (org-map-tree 'org-demote))
4996 (org-fix-position-after-promote))
4999 (defun org-do-promote ()
5000 "Promote the current heading higher up the tree.
5001 If the region is active in `transient-mark-mode', promote all headings
5002 in the region."
5003 (interactive)
5004 (save-excursion
5005 (if (org-region-active-p)
5006 (org-map-region 'org-promote (region-beginning) (region-end))
5007 (org-promote)))
5008 (org-fix-position-after-promote))
5010 (defun org-do-demote ()
5011 "Demote the current heading lower down the tree.
5012 If the region is active in `transient-mark-mode', demote all headings
5013 in the region."
5014 (interactive)
5015 (save-excursion
5016 (if (org-region-active-p)
5017 (org-map-region 'org-demote (region-beginning) (region-end))
5018 (org-demote)))
5019 (org-fix-position-after-promote))
5021 (defun org-fix-position-after-promote ()
5022 "Make sure that after pro/demotion cursor position is right."
5023 (let ((pos (point)))
5024 (when (save-excursion
5025 (beginning-of-line 1)
5026 (looking-at org-todo-line-regexp)
5027 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5028 (cond ((eobp) (insert " "))
5029 ((eolp) (insert " "))
5030 ((equal (char-after) ?\ ) (forward-char 1))))))
5032 (defun org-reduced-level (l)
5033 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5035 (defun org-get-valid-level (level &optional change)
5036 "Rectify a level change under the influence of `org-odd-levels-only'
5037 LEVEL is a current level, CHANGE is by how much the level should be
5038 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5039 even level numbers will become the next higher odd number."
5040 (if org-odd-levels-only
5041 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5042 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5043 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5044 (max 1 (+ level change))))
5046 (if (boundp 'define-obsolete-function-alias)
5047 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5048 (define-obsolete-function-alias 'org-get-legal-level
5049 'org-get-valid-level)
5050 (define-obsolete-function-alias 'org-get-legal-level
5051 'org-get-valid-level "23.1")))
5053 (defun org-promote ()
5054 "Promote the current heading higher up the tree.
5055 If the region is active in `transient-mark-mode', promote all headings
5056 in the region."
5057 (org-back-to-heading t)
5058 (let* ((level (save-match-data (funcall outline-level)))
5059 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5060 (diff (abs (- level (length up-head) -1))))
5061 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5062 (replace-match up-head nil t)
5063 ;; Fixup tag positioning
5064 (and org-auto-align-tags (org-set-tags nil t))
5065 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5067 (defun org-demote ()
5068 "Demote the current heading lower down the tree.
5069 If the region is active in `transient-mark-mode', demote all headings
5070 in the region."
5071 (org-back-to-heading t)
5072 (let* ((level (save-match-data (funcall outline-level)))
5073 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5074 (diff (abs (- level (length down-head) -1))))
5075 (replace-match down-head nil t)
5076 ;; Fixup tag positioning
5077 (and org-auto-align-tags (org-set-tags nil t))
5078 (if org-adapt-indentation (org-fixup-indentation diff))))
5080 (defun org-map-tree (fun)
5081 "Call FUN for every heading underneath the current one."
5082 (org-back-to-heading)
5083 (let ((level (funcall outline-level)))
5084 (save-excursion
5085 (funcall fun)
5086 (while (and (progn
5087 (outline-next-heading)
5088 (> (funcall outline-level) level))
5089 (not (eobp)))
5090 (funcall fun)))))
5092 (defun org-map-region (fun beg end)
5093 "Call FUN for every heading between BEG and END."
5094 (let ((org-ignore-region t))
5095 (save-excursion
5096 (setq end (copy-marker end))
5097 (goto-char beg)
5098 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5099 (< (point) end))
5100 (funcall fun))
5101 (while (and (progn
5102 (outline-next-heading)
5103 (< (point) end))
5104 (not (eobp)))
5105 (funcall fun)))))
5107 (defun org-fixup-indentation (diff)
5108 "Change the indentation in the current entry by DIFF
5109 However, if any line in the current entry has no indentation, or if it
5110 would end up with no indentation after the change, nothing at all is done."
5111 (save-excursion
5112 (let ((end (save-excursion (outline-next-heading)
5113 (point-marker)))
5114 (prohibit (if (> diff 0)
5115 "^\\S-"
5116 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5117 col)
5118 (unless (save-excursion (end-of-line 1)
5119 (re-search-forward prohibit end t))
5120 (while (and (< (point) end)
5121 (re-search-forward "^[ \t]+" end t))
5122 (goto-char (match-end 0))
5123 (setq col (current-column))
5124 (if (< diff 0) (replace-match ""))
5125 (org-indent-to-column (+ diff col))))
5126 (move-marker end nil))))
5128 (defun org-convert-to-odd-levels ()
5129 "Convert an org-mode file with all levels allowed to one with odd levels.
5130 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5131 level 5 etc."
5132 (interactive)
5133 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5134 (let ((org-odd-levels-only nil) n)
5135 (save-excursion
5136 (goto-char (point-min))
5137 (while (re-search-forward "^\\*\\*+ " nil t)
5138 (setq n (- (length (match-string 0)) 2))
5139 (while (>= (setq n (1- n)) 0)
5140 (org-demote))
5141 (end-of-line 1))))))
5144 (defun org-convert-to-oddeven-levels ()
5145 "Convert an org-mode file with only odd levels to one with odd and even levels.
5146 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5147 section with an even level, conversion would destroy the structure of the file. An error
5148 is signaled in this case."
5149 (interactive)
5150 (goto-char (point-min))
5151 ;; First check if there are no even levels
5152 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5153 (org-show-context t)
5154 (error "Not all levels are odd in this file. Conversion not possible."))
5155 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5156 (let ((org-odd-levels-only nil) n)
5157 (save-excursion
5158 (goto-char (point-min))
5159 (while (re-search-forward "^\\*\\*+ " nil t)
5160 (setq n (/ (1- (length (match-string 0))) 2))
5161 (while (>= (setq n (1- n)) 0)
5162 (org-promote))
5163 (end-of-line 1))))))
5165 (defun org-tr-level (n)
5166 "Make N odd if required."
5167 (if org-odd-levels-only (1+ (/ n 2)) n))
5169 ;;; Vertical tree motion, cutting and pasting of subtrees
5171 (defun org-move-subtree-up (&optional arg)
5172 "Move the current subtree up past ARG headlines of the same level."
5173 (interactive "p")
5174 (org-move-subtree-down (- (prefix-numeric-value arg))))
5176 (defun org-move-subtree-down (&optional arg)
5177 "Move the current subtree down past ARG headlines of the same level."
5178 (interactive "p")
5179 (setq arg (prefix-numeric-value arg))
5180 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5181 'outline-get-last-sibling))
5182 (ins-point (make-marker))
5183 (cnt (abs arg))
5184 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5185 ;; Select the tree
5186 (org-back-to-heading)
5187 (setq beg0 (point))
5188 (save-excursion
5189 (setq ne-beg (org-back-over-empty-lines))
5190 (setq beg (point)))
5191 (save-match-data
5192 (save-excursion (outline-end-of-heading)
5193 (setq folded (org-invisible-p)))
5194 (outline-end-of-subtree))
5195 (outline-next-heading)
5196 (setq ne-end (org-back-over-empty-lines))
5197 (setq end (point))
5198 (goto-char beg0)
5199 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5200 ;; include less whitespace
5201 (save-excursion
5202 (goto-char beg)
5203 (forward-line (- ne-beg ne-end))
5204 (setq beg (point))))
5205 ;; Find insertion point, with error handling
5206 (while (> cnt 0)
5207 (or (and (funcall movfunc) (looking-at outline-regexp))
5208 (progn (goto-char beg0)
5209 (error "Cannot move past superior level or buffer limit")))
5210 (setq cnt (1- cnt)))
5211 (if (> arg 0)
5212 ;; Moving forward - still need to move over subtree
5213 (progn (org-end-of-subtree t t)
5214 (save-excursion
5215 (org-back-over-empty-lines)
5216 (or (bolp) (newline)))))
5217 (setq ne-ins (org-back-over-empty-lines))
5218 (move-marker ins-point (point))
5219 (setq txt (buffer-substring beg end))
5220 (org-save-markers-in-region beg end)
5221 (delete-region beg end)
5222 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5223 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5224 (let ((bbb (point)))
5225 (insert-before-markers txt)
5226 (org-reinstall-markers-in-region bbb)
5227 (move-marker ins-point bbb))
5228 (or (bolp) (insert "\n"))
5229 (setq ins-end (point))
5230 (goto-char ins-point)
5231 (org-skip-whitespace)
5232 (when (and (< arg 0)
5233 (org-first-sibling-p)
5234 (> ne-ins ne-beg))
5235 ;; Move whitespace back to beginning
5236 (save-excursion
5237 (goto-char ins-end)
5238 (let ((kill-whole-line t))
5239 (kill-line (- ne-ins ne-beg)) (point)))
5240 (insert (make-string (- ne-ins ne-beg) ?\n)))
5241 (move-marker ins-point nil)
5242 (org-compact-display-after-subtree-move)
5243 (org-show-empty-lines-in-parent)
5244 (unless folded
5245 (org-show-entry)
5246 (show-children)
5247 (org-cycle-hide-drawers 'children))))
5249 (defvar org-subtree-clip ""
5250 "Clipboard for cut and paste of subtrees.
5251 This is actually only a copy of the kill, because we use the normal kill
5252 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5254 (defvar org-subtree-clip-folded nil
5255 "Was the last copied subtree folded?
5256 This is used to fold the tree back after pasting.")
5258 (defun org-cut-subtree (&optional n)
5259 "Cut the current subtree into the clipboard.
5260 With prefix arg N, cut this many sequential subtrees.
5261 This is a short-hand for marking the subtree and then cutting it."
5262 (interactive "p")
5263 (org-copy-subtree n 'cut))
5265 (defun org-copy-subtree (&optional n cut force-store-markers)
5266 "Cut the current subtree into the clipboard.
5267 With prefix arg N, cut this many sequential subtrees.
5268 This is a short-hand for marking the subtree and then copying it.
5269 If CUT is non-nil, actually cut the subtree.
5270 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5271 of some markers in the region, even if CUT is non-nil. This is
5272 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5273 (interactive "p")
5274 (let (beg end folded (beg0 (point)))
5275 (if (interactive-p)
5276 (org-back-to-heading nil) ; take what looks like a subtree
5277 (org-back-to-heading t)) ; take what is really there
5278 (org-back-over-empty-lines)
5279 (setq beg (point))
5280 (skip-chars-forward " \t\r\n")
5281 (save-match-data
5282 (save-excursion (outline-end-of-heading)
5283 (setq folded (org-invisible-p)))
5284 (condition-case nil
5285 (outline-forward-same-level (1- n))
5286 (error nil))
5287 (org-end-of-subtree t t))
5288 (org-back-over-empty-lines)
5289 (setq end (point))
5290 (goto-char beg0)
5291 (when (> end beg)
5292 (setq org-subtree-clip-folded folded)
5293 (when (or cut force-store-markers)
5294 (org-save-markers-in-region beg end))
5295 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5296 (setq org-subtree-clip (current-kill 0))
5297 (message "%s: Subtree(s) with %d characters"
5298 (if cut "Cut" "Copied")
5299 (length org-subtree-clip)))))
5301 (defun org-paste-subtree (&optional level tree for-yank)
5302 "Paste the clipboard as a subtree, with modification of headline level.
5303 The entire subtree is promoted or demoted in order to match a new headline
5304 level.
5306 If the cursor is at the beginning of a headline, the same level as
5307 that headline is used to paste the tree
5309 If not, the new level is derived from the *visible* headings
5310 before and after the insertion point, and taken to be the inferior headline
5311 level of the two. So if the previous visible heading is level 3 and the
5312 next is level 4 (or vice versa), level 4 will be used for insertion.
5313 This makes sure that the subtree remains an independent subtree and does
5314 not swallow low level entries.
5316 You can also force a different level, either by using a numeric prefix
5317 argument, or by inserting the heading marker by hand. For example, if the
5318 cursor is after \"*****\", then the tree will be shifted to level 5.
5320 If optional TREE is given, use this text instead of the kill ring.
5322 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5323 move back over whitespace before inserting, and move point to the end of
5324 the inserted text when done."
5325 (interactive "P")
5326 (unless (org-kill-is-subtree-p tree)
5327 (error "%s"
5328 (substitute-command-keys
5329 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5330 (let* ((visp (not (org-invisible-p)))
5331 (txt (or tree (and kill-ring (current-kill 0))))
5332 (^re (concat "^\\(" outline-regexp "\\)"))
5333 (re (concat "\\(" outline-regexp "\\)"))
5334 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5336 (old-level (if (string-match ^re txt)
5337 (- (match-end 0) (match-beginning 0) 1)
5338 -1))
5339 (force-level (cond (level (prefix-numeric-value level))
5340 ((and (looking-at "[ \t]*$")
5341 (string-match
5342 ^re_ (buffer-substring
5343 (point-at-bol) (point))))
5344 (- (match-end 1) (match-beginning 1)))
5345 ((and (bolp)
5346 (looking-at org-outline-regexp))
5347 (- (match-end 0) (point) 1))
5348 (t nil)))
5349 (previous-level (save-excursion
5350 (condition-case nil
5351 (progn
5352 (outline-previous-visible-heading 1)
5353 (if (looking-at re)
5354 (- (match-end 0) (match-beginning 0) 1)
5356 (error 1))))
5357 (next-level (save-excursion
5358 (condition-case nil
5359 (progn
5360 (or (looking-at outline-regexp)
5361 (outline-next-visible-heading 1))
5362 (if (looking-at re)
5363 (- (match-end 0) (match-beginning 0) 1)
5365 (error 1))))
5366 (new-level (or force-level (max previous-level next-level)))
5367 (shift (if (or (= old-level -1)
5368 (= new-level -1)
5369 (= old-level new-level))
5371 (- new-level old-level)))
5372 (delta (if (> shift 0) -1 1))
5373 (func (if (> shift 0) 'org-demote 'org-promote))
5374 (org-odd-levels-only nil)
5375 beg end newend)
5376 ;; Remove the forced level indicator
5377 (if force-level
5378 (delete-region (point-at-bol) (point)))
5379 ;; Paste
5380 (beginning-of-line 1)
5381 (unless for-yank (org-back-over-empty-lines))
5382 (setq beg (point))
5383 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5384 (insert-before-markers txt)
5385 (unless (string-match "\n\\'" txt) (insert "\n"))
5386 (setq newend (point))
5387 (org-reinstall-markers-in-region beg)
5388 (setq end (point))
5389 (goto-char beg)
5390 (skip-chars-forward " \t\n\r")
5391 (setq beg (point))
5392 (if (and (org-invisible-p) visp)
5393 (save-excursion (outline-show-heading)))
5394 ;; Shift if necessary
5395 (unless (= shift 0)
5396 (save-restriction
5397 (narrow-to-region beg end)
5398 (while (not (= shift 0))
5399 (org-map-region func (point-min) (point-max))
5400 (setq shift (+ delta shift)))
5401 (goto-char (point-min))
5402 (setq newend (point-max))))
5403 (when (or (interactive-p) for-yank)
5404 (message "Clipboard pasted as level %d subtree" new-level))
5405 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5406 kill-ring
5407 (eq org-subtree-clip (current-kill 0))
5408 org-subtree-clip-folded)
5409 ;; The tree was folded before it was killed/copied
5410 (hide-subtree))
5411 (and for-yank (goto-char newend))))
5413 (defun org-kill-is-subtree-p (&optional txt)
5414 "Check if the current kill is an outline subtree, or a set of trees.
5415 Returns nil if kill does not start with a headline, or if the first
5416 headline level is not the largest headline level in the tree.
5417 So this will actually accept several entries of equal levels as well,
5418 which is OK for `org-paste-subtree'.
5419 If optional TXT is given, check this string instead of the current kill."
5420 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5421 (start-level (and kill
5422 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5423 org-outline-regexp "\\)")
5424 kill)
5425 (- (match-end 2) (match-beginning 2) 1)))
5426 (re (concat "^" org-outline-regexp))
5427 (start (1+ (or (match-beginning 2) -1))))
5428 (if (not start-level)
5429 (progn
5430 nil) ;; does not even start with a heading
5431 (catch 'exit
5432 (while (setq start (string-match re kill (1+ start)))
5433 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5434 (throw 'exit nil)))
5435 t))))
5437 (defvar org-markers-to-move nil
5438 "Markers that should be moved with a cut-and-paste operation.
5439 Those markers are stored together with their positions relative to
5440 the start of the region.")
5442 (defun org-save-markers-in-region (beg end)
5443 "Check markers in region.
5444 If these markers are between BEG and END, record their position relative
5445 to BEG, so that after moving the block of text, we can put the markers back
5446 into place.
5447 This function gets called just before an entry or tree gets cut from the
5448 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5449 called immediately, to move the markers with the entries."
5450 (setq org-markers-to-move nil)
5451 (when (featurep 'org-clock)
5452 (org-clock-save-markers-for-cut-and-paste beg end))
5453 (when (featurep 'org-agenda)
5454 (org-agenda-save-markers-for-cut-and-paste beg end)))
5456 (defun org-check-and-save-marker (marker beg end)
5457 "Check if MARKER is between BEG and END.
5458 If yes, remember the marker and the distance to BEG."
5459 (when (and (marker-buffer marker)
5460 (equal (marker-buffer marker) (current-buffer)))
5461 (if (and (>= marker beg) (< marker end))
5462 (push (cons marker (- marker beg)) org-markers-to-move))))
5464 (defun org-reinstall-markers-in-region (beg)
5465 "Move all remembered markers to their position relative to BEG."
5466 (mapc (lambda (x)
5467 (move-marker (car x) (+ beg (cdr x))))
5468 org-markers-to-move)
5469 (setq org-markers-to-move nil))
5471 (defun org-narrow-to-subtree ()
5472 "Narrow buffer to the current subtree."
5473 (interactive)
5474 (save-excursion
5475 (save-match-data
5476 (narrow-to-region
5477 (progn (org-back-to-heading) (point))
5478 (progn (org-end-of-subtree t) (point))))))
5481 ;;; Outline Sorting
5483 (defun org-sort (with-case)
5484 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5485 Optional argument WITH-CASE means sort case-sensitively."
5486 (interactive "P")
5487 (if (org-at-table-p)
5488 (org-call-with-arg 'org-table-sort-lines with-case)
5489 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5491 (defun org-sort-remove-invisible (s)
5492 (remove-text-properties 0 (length s) org-rm-props s)
5493 (while (string-match org-bracket-link-regexp s)
5494 (setq s (replace-match (if (match-end 2)
5495 (match-string 3 s)
5496 (match-string 1 s)) t t s)))
5499 (defvar org-priority-regexp) ; defined later in the file
5501 (defun org-sort-entries-or-items
5502 (&optional with-case sorting-type getkey-func compare-func property)
5503 "Sort entries on a certain level of an outline tree.
5504 If there is an active region, the entries in the region are sorted.
5505 Else, if the cursor is before the first entry, sort the top-level items.
5506 Else, the children of the entry at point are sorted.
5508 Sorting can be alphabetically, numerically, and by date/time as given by
5509 the first time stamp in the entry. The command prompts for the sorting
5510 type unless it has been given to the function through the SORTING-TYPE
5511 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5512 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5513 called with point at the beginning of the record. It must return either
5514 a string or a number that should serve as the sorting key for that record.
5516 Comparing entries ignores case by default. However, with an optional argument
5517 WITH-CASE, the sorting considers case as well."
5518 (interactive "P")
5519 (let ((case-func (if with-case 'identity 'downcase))
5520 start beg end stars re re2
5521 txt what tmp plain-list-p)
5522 ;; Find beginning and end of region to sort
5523 (cond
5524 ((org-region-active-p)
5525 ;; we will sort the region
5526 (setq end (region-end)
5527 what "region")
5528 (goto-char (region-beginning))
5529 (if (not (org-on-heading-p)) (outline-next-heading))
5530 (setq start (point)))
5531 ((org-at-item-p)
5532 ;; we will sort this plain list
5533 (org-beginning-of-item-list) (setq start (point))
5534 (org-end-of-item-list) (setq end (point))
5535 (goto-char start)
5536 (setq plain-list-p t
5537 what "plain list"))
5538 ((or (org-on-heading-p)
5539 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5540 ;; we will sort the children of the current headline
5541 (org-back-to-heading)
5542 (setq start (point)
5543 end (progn (org-end-of-subtree t t)
5544 (org-back-over-empty-lines)
5545 (point))
5546 what "children")
5547 (goto-char start)
5548 (show-subtree)
5549 (outline-next-heading))
5551 ;; we will sort the top-level entries in this file
5552 (goto-char (point-min))
5553 (or (org-on-heading-p) (outline-next-heading))
5554 (setq start (point) end (point-max) what "top-level")
5555 (goto-char start)
5556 (show-all)))
5558 (setq beg (point))
5559 (if (>= beg end) (error "Nothing to sort"))
5561 (unless plain-list-p
5562 (looking-at "\\(\\*+\\)")
5563 (setq stars (match-string 1)
5564 re (concat "^" (regexp-quote stars) " +")
5565 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5566 txt (buffer-substring beg end))
5567 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5568 (if (and (not (equal stars "*")) (string-match re2 txt))
5569 (error "Region to sort contains a level above the first entry")))
5571 (unless sorting-type
5572 (message
5573 (if plain-list-p
5574 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5575 "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:")
5576 what)
5577 (setq sorting-type (read-char-exclusive))
5579 (and (= (downcase sorting-type) ?f)
5580 (setq getkey-func
5581 (org-ido-completing-read "Sort using function: "
5582 obarray 'fboundp t nil nil))
5583 (setq getkey-func (intern getkey-func)))
5585 (and (= (downcase sorting-type) ?r)
5586 (setq property
5587 (org-ido-completing-read "Property: "
5588 (mapcar 'list (org-buffer-property-keys t))
5589 nil t))))
5591 (message "Sorting entries...")
5593 (save-restriction
5594 (narrow-to-region start end)
5596 (let ((dcst (downcase sorting-type))
5597 (now (current-time)))
5598 (sort-subr
5599 (/= dcst sorting-type)
5600 ;; This function moves to the beginning character of the "record" to
5601 ;; be sorted.
5602 (if plain-list-p
5603 (lambda nil
5604 (if (org-at-item-p) t (goto-char (point-max))))
5605 (lambda nil
5606 (if (re-search-forward re nil t)
5607 (goto-char (match-beginning 0))
5608 (goto-char (point-max)))))
5609 ;; This function moves to the last character of the "record" being
5610 ;; sorted.
5611 (if plain-list-p
5612 'org-end-of-item
5613 (lambda nil
5614 (save-match-data
5615 (condition-case nil
5616 (outline-forward-same-level 1)
5617 (error
5618 (goto-char (point-max)))))))
5620 ;; This function returns the value that gets sorted against.
5621 (if plain-list-p
5622 (lambda nil
5623 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5624 (cond
5625 ((= dcst ?n)
5626 (string-to-number (buffer-substring (match-end 0)
5627 (point-at-eol))))
5628 ((= dcst ?a)
5629 (buffer-substring (match-end 0) (point-at-eol)))
5630 ((= dcst ?t)
5631 (if (re-search-forward org-ts-regexp
5632 (point-at-eol) t)
5633 (org-time-string-to-time (match-string 0))
5634 now))
5635 ((= dcst ?f)
5636 (if getkey-func
5637 (progn
5638 (setq tmp (funcall getkey-func))
5639 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5640 tmp)
5641 (error "Invalid key function `%s'" getkey-func)))
5642 (t (error "Invalid sorting type `%c'" sorting-type)))))
5643 (lambda nil
5644 (cond
5645 ((= dcst ?n)
5646 (if (looking-at org-complex-heading-regexp)
5647 (string-to-number (match-string 4))
5648 nil))
5649 ((= dcst ?a)
5650 (if (looking-at org-complex-heading-regexp)
5651 (funcall case-func (match-string 4))
5652 nil))
5653 ((= dcst ?t)
5654 (if (re-search-forward org-ts-regexp
5655 (save-excursion
5656 (forward-line 2)
5657 (point)) t)
5658 (org-time-string-to-time (match-string 0))
5659 now))
5660 ((= dcst ?p)
5661 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5662 (string-to-char (match-string 2))
5663 org-default-priority))
5664 ((= dcst ?r)
5665 (or (org-entry-get nil property) ""))
5666 ((= dcst ?o)
5667 (if (looking-at org-complex-heading-regexp)
5668 (- 9999 (length (member (match-string 2)
5669 org-todo-keywords-1)))))
5670 ((= dcst ?f)
5671 (if getkey-func
5672 (progn
5673 (setq tmp (funcall getkey-func))
5674 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5675 tmp)
5676 (error "Invalid key function `%s'" getkey-func)))
5677 (t (error "Invalid sorting type `%c'" sorting-type)))))
5679 (cond
5680 ((= dcst ?a) 'string<)
5681 ((= dcst ?t) 'time-less-p)
5682 ((= dcst ?f) compare-func)
5683 (t nil)))))
5684 (message "Sorting entries...done")))
5686 (defun org-do-sort (table what &optional with-case sorting-type)
5687 "Sort TABLE of WHAT according to SORTING-TYPE.
5688 The user will be prompted for the SORTING-TYPE if the call to this
5689 function does not specify it. WHAT is only for the prompt, to indicate
5690 what is being sorted. The sorting key will be extracted from
5691 the car of the elements of the table.
5692 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5693 (unless sorting-type
5694 (message
5695 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5696 what)
5697 (setq sorting-type (read-char-exclusive)))
5698 (let ((dcst (downcase sorting-type))
5699 extractfun comparefun)
5700 ;; Define the appropriate functions
5701 (cond
5702 ((= dcst ?n)
5703 (setq extractfun 'string-to-number
5704 comparefun (if (= dcst sorting-type) '< '>)))
5705 ((= dcst ?a)
5706 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5707 (lambda(x) (downcase (org-sort-remove-invisible x))))
5708 comparefun (if (= dcst sorting-type)
5709 'string<
5710 (lambda (a b) (and (not (string< a b))
5711 (not (string= a b)))))))
5712 ((= dcst ?t)
5713 (setq extractfun
5714 (lambda (x)
5715 (if (string-match org-ts-regexp x)
5716 (time-to-seconds
5717 (org-time-string-to-time (match-string 0 x)))
5719 comparefun (if (= dcst sorting-type) '< '>)))
5720 (t (error "Invalid sorting type `%c'" sorting-type)))
5722 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5723 table)
5724 (lambda (a b) (funcall comparefun (car a) (car b))))))
5726 ;;; Editing source examples
5728 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5729 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5730 (defvar org-edit-src-force-single-line nil)
5731 (defvar org-edit-src-from-org-mode nil)
5732 (defvar org-edit-src-picture nil)
5734 (define-minor-mode org-exit-edit-mode
5735 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5737 (defun org-edit-src-code ()
5738 "Edit the source code example at point.
5739 An indirect buffer is created, and that buffer is then narrowed to the
5740 example at point and switched to the correct language mode. When done,
5741 exit by killing the buffer with \\[org-edit-src-exit]."
5742 (interactive)
5743 (let ((line (org-current-line))
5744 (case-fold-search t)
5745 (msg (substitute-command-keys
5746 "Edit, then exit with C-c ' (C-c and single quote)"))
5747 (info (org-edit-src-find-region-and-lang))
5748 (org-mode-p (eq major-mode 'org-mode))
5749 beg end lang lang-f single lfmt)
5750 (if (not info)
5752 (setq beg (nth 0 info)
5753 end (nth 1 info)
5754 lang (nth 2 info)
5755 single (nth 3 info)
5756 lfmt (nth 4 info)
5757 lang-f (intern (concat lang "-mode")))
5758 (unless (functionp lang-f)
5759 (error "No such language mode: %s" lang-f))
5760 (goto-line line)
5761 (if (get-buffer "*Org Edit Src Example*")
5762 (kill-buffer "*Org Edit Src Example*"))
5763 (switch-to-buffer (make-indirect-buffer (current-buffer)
5764 "*Org Edit Src Example*"))
5765 (narrow-to-region beg end)
5766 (remove-text-properties beg end '(display nil invisible nil
5767 intangible nil))
5768 (let ((org-inhibit-startup t))
5769 (funcall lang-f))
5770 (set (make-local-variable 'org-edit-src-force-single-line) single)
5771 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5772 (when lfmt
5773 (set (make-local-variable 'org-coderef-label-format) lfmt))
5774 (when org-mode-p
5775 (goto-char (point-min))
5776 (while (re-search-forward "^," nil t)
5777 (replace-match "")))
5778 (goto-line line)
5779 (org-exit-edit-mode)
5780 (org-set-local 'header-line-format msg)
5781 (message "%s" msg)
5782 t)))
5784 (defun org-edit-fixed-width-region ()
5785 "Edit the fixed-width ascii drawing at point.
5786 This must be a region where each line starts with a colon followed by
5787 a space character.
5788 An indirect buffer is created, and that buffer is then narrowed to the
5789 example at point and switched to artist-mode. When done,
5790 exit by killing the buffer with \\[org-edit-src-exit]."
5791 (interactive)
5792 (let ((line (org-current-line))
5793 (case-fold-search t)
5794 (msg (substitute-command-keys
5795 "Edit, then exit with C-c ' (C-c and single quote)"))
5796 (org-mode-p (eq major-mode 'org-mode))
5797 beg end lang lang-f)
5798 (beginning-of-line 1)
5799 (if (looking-at "[ \t]*[^:\n \t]")
5801 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5802 (setq beg (point) end beg)
5803 (save-excursion
5804 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5805 (setq beg (point-at-bol 2))
5806 (setq beg (point))))
5807 (save-excursion
5808 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5809 (setq end (1- (match-beginning 0)))
5810 (setq end (point))))
5811 (goto-line line))
5812 (if (get-buffer "*Org Edit Picture*")
5813 (kill-buffer "*Org Edit Picture*"))
5814 (switch-to-buffer (make-indirect-buffer (current-buffer)
5815 "*Org Edit Picture*"))
5816 (narrow-to-region beg end)
5817 (remove-text-properties beg end '(display nil invisible nil
5818 intangible nil))
5819 (when (fboundp 'font-lock-unfontify-region)
5820 (font-lock-unfontify-region (point-min) (point-max)))
5821 (cond
5822 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5823 (fundamental-mode)
5824 (artist-mode 1))
5825 (t (funcall org-edit-fixed-width-region-mode)))
5826 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5827 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5828 (set (make-local-variable 'org-edit-src-picture) t)
5829 (goto-char (point-min))
5830 (while (re-search-forward "^[ \t]*: ?" nil t)
5831 (replace-match ""))
5832 (goto-line line)
5833 (org-exit-edit-mode)
5834 (org-set-local 'header-line-format msg)
5835 (message "%s" msg)
5836 t)))
5839 (defun org-edit-src-find-region-and-lang ()
5840 "Find the region and language for a local edit.
5841 Return a list with beginning and end of the region, a string representing
5842 the language, a switch telling of the content should be in a single line."
5843 (let ((re-list
5844 (append
5845 org-edit-src-region-extra
5847 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5848 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5849 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5850 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5851 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5852 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5853 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5854 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5855 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5856 ("^#\\+html:" "\n" "html" single-line)
5857 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5858 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5859 ("^#\\+latex:" "\n" "latex" single-line)
5860 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5861 ("^#\\+ascii:" "\n" "ascii" single-line)
5863 (pos (point))
5864 re re1 re2 single beg end lang lfmt match-re1)
5865 (catch 'exit
5866 (while (setq entry (pop re-list))
5867 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5868 single (nth 3 entry))
5869 (save-excursion
5870 (if (or (looking-at re1)
5871 (re-search-backward re1 nil t))
5872 (progn
5873 (setq match-re1 (match-string 0))
5874 (setq beg (match-end 0)
5875 lang (org-edit-src-get-lang lang)
5876 lfmt (org-edit-src-get-label-format match-re1))
5877 (if (and (re-search-forward re2 nil t)
5878 (>= (match-end 0) pos))
5879 (throw 'exit (list beg (match-beginning 0)
5880 lang single lfmt))))
5881 (if (or (looking-at re2)
5882 (re-search-forward re2 nil t))
5883 (progn
5884 (setq end (match-beginning 0))
5885 (if (and (re-search-backward re1 nil t)
5886 (<= (match-beginning 0) pos))
5887 (progn
5888 (setq lfmt (org-edit-src-get-label-format
5889 (match-string 0)))
5890 (throw 'exit
5891 (list (match-end 0) end
5892 (org-edit-src-get-lang lang)
5893 single lfmt))))))))))))
5895 (defun org-edit-src-get-lang (lang)
5896 "Extract the src language."
5897 (let ((m (match-string 0)))
5898 (cond
5899 ((stringp lang) lang)
5900 ((integerp lang) (match-string lang))
5901 ((and (eq lang 'lang)
5902 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5903 (match-string 1 m))
5904 ((and (eq lang 'style)
5905 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5906 (match-string 1 m))
5907 (t "fundamental"))))
5909 (defun org-edit-src-get-label-format (s)
5910 "Extract the label format."
5911 (save-match-data
5912 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
5913 (match-string 1 s))))
5915 (defun org-edit-src-exit ()
5916 "Exit special edit and protect problematic lines."
5917 (interactive)
5918 (unless (buffer-base-buffer (current-buffer))
5919 (error "This is not an indirect buffer, something is wrong..."))
5920 (unless (> (point-min) 1)
5921 (error "This buffer is not narrowed, something is wrong..."))
5922 (goto-char (point-min))
5923 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5924 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5925 (when (org-bound-and-true-p org-edit-src-force-single-line)
5926 (goto-char (point-min))
5927 (while (re-search-forward "\n" nil t)
5928 (replace-match " "))
5929 (goto-char (point-min))
5930 (if (looking-at "\\s-*") (replace-match " "))
5931 (if (re-search-forward "\\s-+\\'" nil t)
5932 (replace-match "")))
5933 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5934 (goto-char (point-min))
5935 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5936 (replace-match ",\\1"))
5937 (when font-lock-mode
5938 (font-lock-unfontify-region (point-min) (point-max)))
5939 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5940 (when (org-bound-and-true-p org-edit-src-picture)
5941 (untabify (point-min) (point-max))
5942 (goto-char (point-min))
5943 (while (re-search-forward "^" nil t)
5944 (replace-match ": "))
5945 (when font-lock-mode
5946 (font-lock-unfontify-region (point-min) (point-max)))
5947 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5948 (kill-buffer (current-buffer))
5949 (and (org-mode-p) (org-restart-font-lock)))
5952 ;;; The orgstruct minor mode
5954 ;; Define a minor mode which can be used in other modes in order to
5955 ;; integrate the org-mode structure editing commands.
5957 ;; This is really a hack, because the org-mode structure commands use
5958 ;; keys which normally belong to the major mode. Here is how it
5959 ;; works: The minor mode defines all the keys necessary to operate the
5960 ;; structure commands, but wraps the commands into a function which
5961 ;; tests if the cursor is currently at a headline or a plain list
5962 ;; item. If that is the case, the structure command is used,
5963 ;; temporarily setting many Org-mode variables like regular
5964 ;; expressions for filling etc. However, when any of those keys is
5965 ;; used at a different location, function uses `key-binding' to look
5966 ;; up if the key has an associated command in another currently active
5967 ;; keymap (minor modes, major mode, global), and executes that
5968 ;; command. There might be problems if any of the keys is otherwise
5969 ;; used as a prefix key.
5971 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5972 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5973 ;; addresses this by checking explicitly for both bindings.
5975 (defvar orgstruct-mode-map (make-sparse-keymap)
5976 "Keymap for the minor `orgstruct-mode'.")
5978 (defvar org-local-vars nil
5979 "List of local variables, for use by `orgstruct-mode'")
5981 ;;;###autoload
5982 (define-minor-mode orgstruct-mode
5983 "Toggle the minor more `orgstruct-mode'.
5984 This mode is for using Org-mode structure commands in other modes.
5985 The following key behave as if Org-mode was active, if the cursor
5986 is on a headline, or on a plain list item (both in the definition
5987 of Org-mode).
5989 M-up Move entry/item up
5990 M-down Move entry/item down
5991 M-left Promote
5992 M-right Demote
5993 M-S-up Move entry/item up
5994 M-S-down Move entry/item down
5995 M-S-left Promote subtree
5996 M-S-right Demote subtree
5997 M-q Fill paragraph and items like in Org-mode
5998 C-c ^ Sort entries
5999 C-c - Cycle list bullet
6000 TAB Cycle item visibility
6001 M-RET Insert new heading/item
6002 S-M-RET Insert new TODO heading / Checkbox item
6003 C-c C-c Set tags / toggle checkbox"
6004 nil " OrgStruct" nil
6005 (org-load-modules-maybe)
6006 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6008 ;;;###autoload
6009 (defun turn-on-orgstruct ()
6010 "Unconditionally turn on `orgstruct-mode'."
6011 (orgstruct-mode 1))
6013 ;;;###autoload
6014 (defun turn-on-orgstruct++ ()
6015 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6016 In addition to setting orgstruct-mode, this also exports all indentation and
6017 autofilling variables from org-mode into the buffer. Note that turning
6018 off orgstruct-mode will *not* remove these additional settings."
6019 (orgstruct-mode 1)
6020 (let (var val)
6021 (mapc
6022 (lambda (x)
6023 (when (string-match
6024 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6025 (symbol-name (car x)))
6026 (setq var (car x) val (nth 1 x))
6027 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6028 org-local-vars)))
6030 (defun orgstruct-error ()
6031 "Error when there is no default binding for a structure key."
6032 (interactive)
6033 (error "This key has no function outside structure elements"))
6035 (defun orgstruct-setup ()
6036 "Setup orgstruct keymaps."
6037 (let ((nfunc 0)
6038 (bindings
6039 (list
6040 '([(meta up)] org-metaup)
6041 '([(meta down)] org-metadown)
6042 '([(meta left)] org-metaleft)
6043 '([(meta right)] org-metaright)
6044 '([(meta shift up)] org-shiftmetaup)
6045 '([(meta shift down)] org-shiftmetadown)
6046 '([(meta shift left)] org-shiftmetaleft)
6047 '([(meta shift right)] org-shiftmetaright)
6048 '([(shift up)] org-shiftup)
6049 '([(shift down)] org-shiftdown)
6050 '([(shift left)] org-shiftleft)
6051 '([(shift right)] org-shiftright)
6052 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6053 '("\M-q" fill-paragraph)
6054 '("\C-c^" org-sort)
6055 '("\C-c-" org-cycle-list-bullet)))
6056 elt key fun cmd)
6057 (while (setq elt (pop bindings))
6058 (setq nfunc (1+ nfunc))
6059 (setq key (org-key (car elt))
6060 fun (nth 1 elt)
6061 cmd (orgstruct-make-binding fun nfunc key))
6062 (org-defkey orgstruct-mode-map key cmd))
6064 ;; Special treatment needed for TAB and RET
6065 (org-defkey orgstruct-mode-map [(tab)]
6066 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6067 (org-defkey orgstruct-mode-map "\C-i"
6068 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6070 (org-defkey orgstruct-mode-map "\M-\C-m"
6071 (orgstruct-make-binding 'org-insert-heading 105
6072 "\M-\C-m" [(meta return)]))
6073 (org-defkey orgstruct-mode-map [(meta return)]
6074 (orgstruct-make-binding 'org-insert-heading 106
6075 [(meta return)] "\M-\C-m"))
6077 (org-defkey orgstruct-mode-map [(shift meta return)]
6078 (orgstruct-make-binding 'org-insert-todo-heading 107
6079 [(meta return)] "\M-\C-m"))
6081 (unless org-local-vars
6082 (setq org-local-vars (org-get-local-variables)))
6086 (defun orgstruct-make-binding (fun n &rest keys)
6087 "Create a function for binding in the structure minor mode.
6088 FUN is the command to call inside a table. N is used to create a unique
6089 command name. KEYS are keys that should be checked in for a command
6090 to execute outside of tables."
6091 (eval
6092 (list 'defun
6093 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6094 '(arg)
6095 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6096 "Outside of structure, run the binding of `"
6097 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6098 "'.")
6099 '(interactive "p")
6100 (list 'if
6101 '(org-context-p 'headline 'item)
6102 (list 'org-run-like-in-org-mode (list 'quote fun))
6103 (list 'let '(orgstruct-mode)
6104 (list 'call-interactively
6105 (append '(or)
6106 (mapcar (lambda (k)
6107 (list 'key-binding k))
6108 keys)
6109 '('orgstruct-error))))))))
6111 (defun org-context-p (&rest contexts)
6112 "Check if local context is any of CONTEXTS.
6113 Possible values in the list of contexts are `table', `headline', and `item'."
6114 (let ((pos (point)))
6115 (goto-char (point-at-bol))
6116 (prog1 (or (and (memq 'table contexts)
6117 (looking-at "[ \t]*|"))
6118 (and (memq 'headline contexts)
6119 ;;????????? (looking-at "\\*+"))
6120 (looking-at outline-regexp))
6121 (and (memq 'item contexts)
6122 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6123 (goto-char pos))))
6125 (defun org-get-local-variables ()
6126 "Return a list of all local variables in an org-mode buffer."
6127 (let (varlist)
6128 (with-current-buffer (get-buffer-create "*Org tmp*")
6129 (erase-buffer)
6130 (org-mode)
6131 (setq varlist (buffer-local-variables)))
6132 (kill-buffer "*Org tmp*")
6133 (delq nil
6134 (mapcar
6135 (lambda (x)
6136 (setq x
6137 (if (symbolp x)
6138 (list x)
6139 (list (car x) (list 'quote (cdr x)))))
6140 (if (string-match
6141 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6142 (symbol-name (car x)))
6143 x nil))
6144 varlist))))
6146 ;;;###autoload
6147 (defun org-run-like-in-org-mode (cmd)
6148 (org-load-modules-maybe)
6149 (unless org-local-vars
6150 (setq org-local-vars (org-get-local-variables)))
6151 (eval (list 'let org-local-vars
6152 (list 'call-interactively (list 'quote cmd)))))
6154 ;;;; Archiving
6156 (defun org-get-category (&optional pos)
6157 "Get the category applying to position POS."
6158 (get-text-property (or pos (point)) 'org-category))
6160 (defun org-refresh-category-properties ()
6161 "Refresh category text properties in the buffer."
6162 (let ((def-cat (cond
6163 ((null org-category)
6164 (if buffer-file-name
6165 (file-name-sans-extension
6166 (file-name-nondirectory buffer-file-name))
6167 "???"))
6168 ((symbolp org-category) (symbol-name org-category))
6169 (t org-category)))
6170 beg end cat pos optionp)
6171 (org-unmodified
6172 (save-excursion
6173 (save-restriction
6174 (widen)
6175 (goto-char (point-min))
6176 (put-text-property (point) (point-max) 'org-category def-cat)
6177 (while (re-search-forward
6178 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6179 (setq pos (match-end 0)
6180 optionp (equal (char-after (match-beginning 0)) ?#)
6181 cat (org-trim (match-string 2)))
6182 (if optionp
6183 (setq beg (point-at-bol) end (point-max))
6184 (org-back-to-heading t)
6185 (setq beg (point) end (org-end-of-subtree t t)))
6186 (put-text-property beg end 'org-category cat)
6187 (goto-char pos)))))))
6190 ;;;; Link Stuff
6192 ;;; Link abbreviations
6194 (defun org-link-expand-abbrev (link)
6195 "Apply replacements as defined in `org-link-abbrev-alist."
6196 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6197 (let* ((key (match-string 1 link))
6198 (as (or (assoc key org-link-abbrev-alist-local)
6199 (assoc key org-link-abbrev-alist)))
6200 (tag (and (match-end 2) (match-string 3 link)))
6201 rpl)
6202 (if (not as)
6203 link
6204 (setq rpl (cdr as))
6205 (cond
6206 ((symbolp rpl) (funcall rpl tag))
6207 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6208 ((string-match "%h" rpl)
6209 (replace-match (url-hexify-string (or tag "")) t t rpl))
6210 (t (concat rpl tag)))))
6211 link))
6213 ;;; Storing and inserting links
6215 (defvar org-insert-link-history nil
6216 "Minibuffer history for links inserted with `org-insert-link'.")
6218 (defvar org-stored-links nil
6219 "Contains the links stored with `org-store-link'.")
6221 (defvar org-store-link-plist nil
6222 "Plist with info about the most recently link created with `org-store-link'.")
6224 (defvar org-link-protocols nil
6225 "Link protocols added to Org-mode using `org-add-link-type'.")
6227 (defvar org-store-link-functions nil
6228 "List of functions that are called to create and store a link.
6229 Each function will be called in turn until one returns a non-nil
6230 value. Each function should check if it is responsible for creating
6231 this link (for example by looking at the major mode).
6232 If not, it must exit and return nil.
6233 If yes, it should return a non-nil value after a calling
6234 `org-store-link-props' with a list of properties and values.
6235 Special properties are:
6237 :type The link prefix. like \"http\". This must be given.
6238 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6239 This is obligatory as well.
6240 :description Optional default description for the second pair
6241 of brackets in an Org-mode link. The user can still change
6242 this when inserting this link into an Org-mode buffer.
6244 In addition to these, any additional properties can be specified
6245 and then used in remember templates.")
6247 (defun org-add-link-type (type &optional follow export)
6248 "Add TYPE to the list of `org-link-types'.
6249 Re-compute all regular expressions depending on `org-link-types'
6251 FOLLOW and EXPORT are two functions.
6253 FOLLOW should take the link path as the single argument and do whatever
6254 is necessary to follow the link, for example find a file or display
6255 a mail message.
6257 EXPORT should format the link path for export to one of the export formats.
6258 It should be a function accepting three arguments:
6260 path the path of the link, the text after the prefix (like \"http:\")
6261 desc the description of the link, if any, nil if there was no description
6262 format the export format, a symbol like `html' or `latex'.
6264 The function may use the FORMAT information to return different values
6265 depending on the format. The return value will be put literally into
6266 the exported file.
6267 Org-mode has a built-in default for exporting links. If you are happy with
6268 this default, there is no need to define an export function for the link
6269 type. For a simple example of an export function, see `org-bbdb.el'."
6270 (add-to-list 'org-link-types type t)
6271 (org-make-link-regexps)
6272 (if (assoc type org-link-protocols)
6273 (setcdr (assoc type org-link-protocols) (list follow export))
6274 (push (list type follow export) org-link-protocols)))
6276 ;;;###autoload
6277 (defun org-store-link (arg)
6278 "\\<org-mode-map>Store an org-link to the current location.
6279 This link is added to `org-stored-links' and can later be inserted
6280 into an org-buffer with \\[org-insert-link].
6282 For some link types, a prefix arg is interpreted:
6283 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6284 For file links, arg negates `org-context-in-file-links'."
6285 (interactive "P")
6286 (org-load-modules-maybe)
6287 (setq org-store-link-plist nil) ; reset
6288 (let (link cpltxt desc description search txt)
6289 (cond
6291 ((run-hook-with-args-until-success 'org-store-link-functions)
6292 (setq link (plist-get org-store-link-plist :link)
6293 desc (or (plist-get org-store-link-plist :description) link)))
6295 ((equal (buffer-name) "*Org Edit Src Example*")
6296 (let (label gc)
6297 (while (or (not label)
6298 (save-excursion
6299 (save-restriction
6300 (widen)
6301 (goto-char (point-min))
6302 (re-search-forward
6303 (regexp-quote (format org-coderef-label-format label))
6304 nil t))))
6305 (when label (message "Label exists already") (sit-for 2))
6306 (setq label (read-string "Code line label: " label)))
6307 (end-of-line 1)
6308 (setq link (format org-coderef-label-format label))
6309 (setq gc (- 79 (length link)))
6310 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6311 (insert link)
6312 (setq link (concat "(" label ")") desc nil)))
6314 ((eq major-mode 'calendar-mode)
6315 (let ((cd (calendar-cursor-to-date)))
6316 (setq link
6317 (format-time-string
6318 (car org-time-stamp-formats)
6319 (apply 'encode-time
6320 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6321 nil nil nil))))
6322 (org-store-link-props :type "calendar" :date cd)))
6324 ((eq major-mode 'w3-mode)
6325 (setq cpltxt (url-view-url t)
6326 link (org-make-link cpltxt))
6327 (org-store-link-props :type "w3" :url (url-view-url t)))
6329 ((eq major-mode 'w3m-mode)
6330 (setq cpltxt (or w3m-current-title w3m-current-url)
6331 link (org-make-link w3m-current-url))
6332 (org-store-link-props :type "w3m" :url (url-view-url t)))
6334 ((setq search (run-hook-with-args-until-success
6335 'org-create-file-search-functions))
6336 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6337 "::" search))
6338 (setq cpltxt (or description link)))
6340 ((eq major-mode 'image-mode)
6341 (setq cpltxt (concat "file:"
6342 (abbreviate-file-name buffer-file-name))
6343 link (org-make-link cpltxt))
6344 (org-store-link-props :type "image" :file buffer-file-name))
6346 ((eq major-mode 'dired-mode)
6347 ;; link to the file in the current line
6348 (setq cpltxt (concat "file:"
6349 (abbreviate-file-name
6350 (expand-file-name
6351 (dired-get-filename nil t))))
6352 link (org-make-link cpltxt)))
6354 ((and buffer-file-name (org-mode-p))
6355 (cond
6356 ((org-in-regexp "<<\\(.*?\\)>>")
6357 (setq cpltxt
6358 (concat "file:"
6359 (abbreviate-file-name buffer-file-name)
6360 "::" (match-string 1))
6361 link (org-make-link cpltxt)))
6362 ((and (featurep 'org-id)
6363 (or (eq org-link-to-org-use-id t)
6364 (and (eq org-link-to-org-use-id 'create-if-interactive)
6365 (interactive-p))
6366 (and org-link-to-org-use-id
6367 (condition-case nil
6368 (org-entry-get nil "ID")
6369 (error nil)))))
6370 ;; We can make a link using the ID.
6371 (setq link (condition-case nil
6372 (prog1 (org-id-store-link)
6373 (setq desc (plist-get org-store-link-plist
6374 :description)))
6375 (error
6376 ;; probably before first headline, link to file only
6377 (concat "file:"
6378 (abbreviate-file-name buffer-file-name))))))
6380 ;; Just link to current headline
6381 (setq cpltxt (concat "file:"
6382 (abbreviate-file-name buffer-file-name)))
6383 ;; Add a context search string
6384 (when (org-xor org-context-in-file-links arg)
6385 (setq txt (cond
6386 ((org-on-heading-p) nil)
6387 ((org-region-active-p)
6388 (buffer-substring (region-beginning) (region-end)))
6389 (t nil)))
6390 (when (or (null txt) (string-match "\\S-" txt))
6391 (setq cpltxt
6392 (concat cpltxt "::"
6393 (condition-case nil
6394 (org-make-org-heading-search-string txt)
6395 (error "")))
6396 desc "NONE")))
6397 (if (string-match "::\\'" cpltxt)
6398 (setq cpltxt (substring cpltxt 0 -2)))
6399 (setq link (org-make-link cpltxt)))))
6401 ((buffer-file-name (buffer-base-buffer))
6402 ;; Just link to this file here.
6403 (setq cpltxt (concat "file:"
6404 (abbreviate-file-name
6405 (buffer-file-name (buffer-base-buffer)))))
6406 ;; Add a context string
6407 (when (org-xor org-context-in-file-links arg)
6408 (setq txt (if (org-region-active-p)
6409 (buffer-substring (region-beginning) (region-end))
6410 (buffer-substring (point-at-bol) (point-at-eol))))
6411 ;; Only use search option if there is some text.
6412 (when (string-match "\\S-" txt)
6413 (setq cpltxt
6414 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6415 desc "NONE")))
6416 (setq link (org-make-link cpltxt)))
6418 ((interactive-p)
6419 (error "Cannot link to a buffer which is not visiting a file"))
6421 (t (setq link nil)))
6423 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6424 (setq link (or link cpltxt)
6425 desc (or desc cpltxt))
6426 (if (equal desc "NONE") (setq desc nil))
6428 (if (and (interactive-p) link)
6429 (progn
6430 (setq org-stored-links
6431 (cons (list link desc) org-stored-links))
6432 (message "Stored: %s" (or desc link)))
6433 (and link (org-make-link-string link desc)))))
6435 (defun org-store-link-props (&rest plist)
6436 "Store link properties, extract names and addresses."
6437 (let (x adr)
6438 (when (setq x (plist-get plist :from))
6439 (setq adr (mail-extract-address-components x))
6440 (setq plist (plist-put plist :fromname (car adr)))
6441 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6442 (when (setq x (plist-get plist :to))
6443 (setq adr (mail-extract-address-components x))
6444 (setq plist (plist-put plist :toname (car adr)))
6445 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6446 (let ((from (plist-get plist :from))
6447 (to (plist-get plist :to)))
6448 (when (and from to org-from-is-user-regexp)
6449 (setq plist
6450 (plist-put plist :fromto
6451 (if (string-match org-from-is-user-regexp from)
6452 (concat "to %t")
6453 (concat "from %f"))))))
6454 (setq org-store-link-plist plist))
6456 (defun org-add-link-props (&rest plist)
6457 "Add these properties to the link property list."
6458 (let (key value)
6459 (while plist
6460 (setq key (pop plist) value (pop plist))
6461 (setq org-store-link-plist
6462 (plist-put org-store-link-plist key value)))))
6464 (defun org-email-link-description (&optional fmt)
6465 "Return the description part of an email link.
6466 This takes information from `org-store-link-plist' and formats it
6467 according to FMT (default from `org-email-link-description-format')."
6468 (setq fmt (or fmt org-email-link-description-format))
6469 (let* ((p org-store-link-plist)
6470 (to (plist-get p :toaddress))
6471 (from (plist-get p :fromaddress))
6472 (table
6473 (list
6474 (cons "%c" (plist-get p :fromto))
6475 (cons "%F" (plist-get p :from))
6476 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6477 (cons "%T" (plist-get p :to))
6478 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6479 (cons "%s" (plist-get p :subject))
6480 (cons "%m" (plist-get p :message-id)))))
6481 (when (string-match "%c" fmt)
6482 ;; Check if the user wrote this message
6483 (if (and org-from-is-user-regexp from to
6484 (save-match-data (string-match org-from-is-user-regexp from)))
6485 (setq fmt (replace-match "to %t" t t fmt))
6486 (setq fmt (replace-match "from %f" t t fmt))))
6487 (org-replace-escapes fmt table)))
6489 (defun org-make-org-heading-search-string (&optional string heading)
6490 "Make search string for STRING or current headline."
6491 (interactive)
6492 (let ((s (or string (org-get-heading))))
6493 (unless (and string (not heading))
6494 ;; We are using a headline, clean up garbage in there.
6495 (if (string-match org-todo-regexp s)
6496 (setq s (replace-match "" t t s)))
6497 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6498 (setq s (replace-match "" t t s)))
6499 (setq s (org-trim s))
6500 (if (string-match (concat "^\\(" org-quote-string "\\|"
6501 org-comment-string "\\)") s)
6502 (setq s (replace-match "" t t s)))
6503 (while (string-match org-ts-regexp s)
6504 (setq s (replace-match "" t t s))))
6505 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6506 (setq s (replace-match " " t t s)))
6507 (or string (setq s (concat "*" s))) ; Add * for headlines
6508 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6510 (defun org-make-link (&rest strings)
6511 "Concatenate STRINGS."
6512 (apply 'concat strings))
6514 (defun org-make-link-string (link &optional description)
6515 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6516 (unless (string-match "\\S-" link)
6517 (error "Empty link"))
6518 (when (stringp description)
6519 ;; Remove brackets from the description, they are fatal.
6520 (while (string-match "\\[" description)
6521 (setq description (replace-match "{" t t description)))
6522 (while (string-match "\\]" description)
6523 (setq description (replace-match "}" t t description))))
6524 (when (equal (org-link-escape link) description)
6525 ;; No description needed, it is identical
6526 (setq description nil))
6527 (when (and (not description)
6528 (not (equal link (org-link-escape link))))
6529 (setq description (org-extract-attributes link)))
6530 (concat "[[" (org-link-escape link) "]"
6531 (if description (concat "[" description "]") "")
6532 "]"))
6534 (defconst org-link-escape-chars
6535 '((?\ . "%20")
6536 (?\[ . "%5B")
6537 (?\] . "%5D")
6538 (?\340 . "%E0") ; `a
6539 (?\342 . "%E2") ; ^a
6540 (?\347 . "%E7") ; ,c
6541 (?\350 . "%E8") ; `e
6542 (?\351 . "%E9") ; 'e
6543 (?\352 . "%EA") ; ^e
6544 (?\356 . "%EE") ; ^i
6545 (?\364 . "%F4") ; ^o
6546 (?\371 . "%F9") ; `u
6547 (?\373 . "%FB") ; ^u
6548 (?\; . "%3B")
6549 (?? . "%3F")
6550 (?= . "%3D")
6551 (?+ . "%2B")
6553 "Association list of escapes for some characters problematic in links.
6554 This is the list that is used for internal purposes.")
6556 (defconst org-link-escape-chars-browser
6557 '((?\ . "%20")) ; 32 for the SPC char
6558 "Association list of escapes for some characters problematic in links.
6559 This is the list that is used before handing over to the browser.")
6561 (defun org-link-escape (text &optional table)
6562 "Escape characters in TEXT that are problematic for links."
6563 (setq table (or table org-link-escape-chars))
6564 (when text
6565 (let ((re (mapconcat (lambda (x) (regexp-quote
6566 (char-to-string (car x))))
6567 table "\\|")))
6568 (while (string-match re text)
6569 (setq text
6570 (replace-match
6571 (cdr (assoc (string-to-char (match-string 0 text))
6572 table))
6573 t t text)))
6574 text)))
6576 (defun org-link-unescape (text &optional table)
6577 "Reverse the action of `org-link-escape'."
6578 (setq table (or table org-link-escape-chars))
6579 (when text
6580 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6581 table "\\|")))
6582 (while (string-match re text)
6583 (setq text
6584 (replace-match
6585 (char-to-string (car (rassoc (match-string 0 text) table)))
6586 t t text)))
6587 text)))
6589 (defun org-xor (a b)
6590 "Exclusive or."
6591 (if a (not b) b))
6593 (defun org-get-header (header)
6594 "Find a header field in the current buffer."
6595 (save-excursion
6596 (goto-char (point-min))
6597 (let ((case-fold-search t) s)
6598 (cond
6599 ((eq header 'from)
6600 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6601 (setq s (match-string 1)))
6602 (while (string-match "\"" s)
6603 (setq s (replace-match "" t t s)))
6604 (if (string-match "[<(].*" s)
6605 (setq s (replace-match "" t t s))))
6606 ((eq header 'message-id)
6607 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6608 (setq s (match-string 1))))
6609 ((eq header 'subject)
6610 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6611 (setq s (match-string 1)))))
6612 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6613 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6614 s)))
6617 (defun org-fixup-message-id-for-http (s)
6618 "Replace special characters in a message id, so it can be used in an http query."
6619 (while (string-match "<" s)
6620 (setq s (replace-match "%3C" t t s)))
6621 (while (string-match ">" s)
6622 (setq s (replace-match "%3E" t t s)))
6623 (while (string-match "@" s)
6624 (setq s (replace-match "%40" t t s)))
6627 ;;;###autoload
6628 (defun org-insert-link-global ()
6629 "Insert a link like Org-mode does.
6630 This command can be called in any mode to insert a link in Org-mode syntax."
6631 (interactive)
6632 (org-load-modules-maybe)
6633 (org-run-like-in-org-mode 'org-insert-link))
6635 (defun org-insert-link (&optional complete-file link-location)
6636 "Insert a link. At the prompt, enter the link.
6638 Completion can be used to insert any of the link protocol prefixes like
6639 http or ftp in use.
6641 The history can be used to select a link previously stored with
6642 `org-store-link'. When the empty string is entered (i.e. if you just
6643 press RET at the prompt), the link defaults to the most recently
6644 stored link. As SPC triggers completion in the minibuffer, you need to
6645 use M-SPC or C-q SPC to force the insertion of a space character.
6647 You will also be prompted for a description, and if one is given, it will
6648 be displayed in the buffer instead of the link.
6650 If there is already a link at point, this command will allow you to edit link
6651 and description parts.
6653 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6654 be selected using completion. The path to the file will be relative to the
6655 current directory if the file is in the current directory or a subdirectory.
6656 Otherwise, the link will be the absolute path as completed in the minibuffer
6657 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6658 option `org-link-file-path-type'.
6660 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6661 the current directory or below.
6663 With three \\[universal-argument] prefixes, negate the meaning of
6664 `org-keep-stored-link-after-insertion'.
6666 If `org-make-link-description-function' is non-nil, this function will be
6667 called with the link target, and the result will be the default
6668 link description.
6670 If the LINK-LOCATION parameter is non-nil, this value will be
6671 used as the link location instead of reading one interactively."
6672 (interactive "P")
6673 (let* ((wcf (current-window-configuration))
6674 (region (if (org-region-active-p)
6675 (buffer-substring (region-beginning) (region-end))))
6676 (remove (and region (list (region-beginning) (region-end))))
6677 (desc region)
6678 tmphist ; byte-compile incorrectly complains about this
6679 (link link-location)
6680 entry file)
6681 (cond
6682 (link-location) ; specified by arg, just use it.
6683 ((org-in-regexp org-bracket-link-regexp 1)
6684 ;; We do have a link at point, and we are going to edit it.
6685 (setq remove (list (match-beginning 0) (match-end 0)))
6686 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6687 (setq link (read-string "Link: "
6688 (org-link-unescape
6689 (org-match-string-no-properties 1)))))
6690 ((or (org-in-regexp org-angle-link-re)
6691 (org-in-regexp org-plain-link-re))
6692 ;; Convert to bracket link
6693 (setq remove (list (match-beginning 0) (match-end 0))
6694 link (read-string "Link: "
6695 (org-remove-angle-brackets (match-string 0)))))
6696 ((member complete-file '((4) (16)))
6697 ;; Completing read for file names.
6698 (setq file (read-file-name "File: "))
6699 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6700 (pwd1 (file-name-as-directory (abbreviate-file-name
6701 (expand-file-name ".")))))
6702 (cond
6703 ((equal complete-file '(16))
6704 (setq link (org-make-link
6705 "file:"
6706 (abbreviate-file-name (expand-file-name file)))))
6707 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6708 (setq link (org-make-link "file:" (match-string 1 file))))
6709 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6710 (expand-file-name file))
6711 (setq link (org-make-link
6712 "file:" (match-string 1 (expand-file-name file)))))
6713 (t (setq link (org-make-link "file:" file))))))
6715 ;; Read link, with completion for stored links.
6716 (with-output-to-temp-buffer "*Org Links*"
6717 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6718 (when org-stored-links
6719 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6720 (princ (mapconcat
6721 (lambda (x)
6722 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6723 (reverse org-stored-links) "\n"))))
6724 (let ((cw (selected-window)))
6725 (select-window (get-buffer-window "*Org Links*"))
6726 (setq truncate-lines t)
6727 (org-fit-window-to-buffer)
6728 (select-window cw))
6729 ;; Fake a link history, containing the stored links.
6730 (setq tmphist (append (mapcar 'car org-stored-links)
6731 org-insert-link-history))
6732 (unwind-protect
6733 (setq link
6734 (let ((org-completion-use-ido nil))
6735 (org-completing-read
6736 "Link: "
6737 (append
6738 (mapcar (lambda (x) (list (concat (car x) ":")))
6739 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6740 (mapcar (lambda (x) (list (concat x ":")))
6741 org-link-types))
6742 nil nil nil
6743 'tmphist
6744 (or (car (car org-stored-links))))))
6745 (set-window-configuration wcf)
6746 (kill-buffer "*Org Links*"))
6747 (setq entry (assoc link org-stored-links))
6748 (or entry (push link org-insert-link-history))
6749 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6750 (not org-keep-stored-link-after-insertion))
6751 (setq org-stored-links (delq (assoc link org-stored-links)
6752 org-stored-links)))
6753 (setq desc (or desc (nth 1 entry)))))
6755 (if (string-match org-plain-link-re link)
6756 ;; URL-like link, normalize the use of angular brackets.
6757 (setq link (org-make-link (org-remove-angle-brackets link))))
6759 ;; Check if we are linking to the current file with a search option
6760 ;; If yes, simplify the link by using only the search option.
6761 (when (and buffer-file-name
6762 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6763 (let* ((path (match-string 1 link))
6764 (case-fold-search nil)
6765 (search (match-string 2 link)))
6766 (save-match-data
6767 (if (equal (file-truename buffer-file-name) (file-truename path))
6768 ;; We are linking to this same file, with a search option
6769 (setq link search)))))
6771 ;; Check if we can/should use a relative path. If yes, simplify the link
6772 (when (string-match "^file:\\(.*\\)" link)
6773 (let* ((path (match-string 1 link))
6774 (origpath path)
6775 (case-fold-search nil))
6776 (cond
6777 ((or (eq org-link-file-path-type 'absolute)
6778 (equal complete-file '(16)))
6779 (setq path (abbreviate-file-name (expand-file-name path))))
6780 ((eq org-link-file-path-type 'noabbrev)
6781 (setq path (expand-file-name path)))
6782 ((eq org-link-file-path-type 'relative)
6783 (setq path (file-relative-name path)))
6785 (save-match-data
6786 (if (string-match (concat "^" (regexp-quote
6787 (file-name-as-directory
6788 (expand-file-name "."))))
6789 (expand-file-name path))
6790 ;; We are linking a file with relative path name.
6791 (setq path (substring (expand-file-name path)
6792 (match-end 0)))
6793 (setq path (abbreviate-file-name (expand-file-name path)))))))
6794 (setq link (concat "file:" path))
6795 (if (equal desc origpath)
6796 (setq desc path))))
6798 (if org-make-link-description-function
6799 (setq desc (funcall org-make-link-description-function link desc)))
6801 (setq desc (read-string "Description: " desc))
6802 (unless (string-match "\\S-" desc) (setq desc nil))
6803 (if remove (apply 'delete-region remove))
6804 (insert (org-make-link-string link desc))))
6806 (defun org-completing-read (&rest args)
6807 "Completing-read with SPACE being a normal character."
6808 (let ((minibuffer-local-completion-map
6809 (copy-keymap minibuffer-local-completion-map)))
6810 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6811 (apply 'org-ido-completing-read args)))
6813 (defun org-ido-completing-read (&rest args)
6814 "Completing-read using `ido-mode' speedups if available"
6815 (if (and org-completion-use-ido
6816 (fboundp 'ido-completing-read)
6817 (boundp 'ido-mode) ido-mode
6818 (listp (second args)))
6819 (apply 'ido-completing-read (concat (car args)) (cdr args))
6820 (apply 'completing-read args)))
6822 (defun org-extract-attributes (s)
6823 "Extract the attributes cookie from a string and set as text property."
6824 (let (a attr (start 0) key value)
6825 (save-match-data
6826 (when (string-match "{{\\([^}]+\\)}}$" s)
6827 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6828 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6829 (setq key (match-string 1 a) value (match-string 2 a)
6830 start (match-end 0)
6831 attr (plist-put attr (intern key) value))))
6832 (org-add-props s nil 'org-attr attr))
6835 (defun org-attributes-to-string (plist)
6836 "Format a property list into an HTML attribute list."
6837 (let ((s "") key value)
6838 (while plist
6839 (setq key (pop plist) value (pop plist))
6840 (and value
6841 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6844 ;;; Opening/following a link
6846 (defvar org-link-search-failed nil)
6848 (defun org-next-link ()
6849 "Move forward to the next link.
6850 If the link is in hidden text, expose it."
6851 (interactive)
6852 (when (and org-link-search-failed (eq this-command last-command))
6853 (goto-char (point-min))
6854 (message "Link search wrapped back to beginning of buffer"))
6855 (setq org-link-search-failed nil)
6856 (let* ((pos (point))
6857 (ct (org-context))
6858 (a (assoc :link ct)))
6859 (if a (goto-char (nth 2 a)))
6860 (if (re-search-forward org-any-link-re nil t)
6861 (progn
6862 (goto-char (match-beginning 0))
6863 (if (org-invisible-p) (org-show-context)))
6864 (goto-char pos)
6865 (setq org-link-search-failed t)
6866 (error "No further link found"))))
6868 (defun org-previous-link ()
6869 "Move backward to the previous link.
6870 If the link is in hidden text, expose it."
6871 (interactive)
6872 (when (and org-link-search-failed (eq this-command last-command))
6873 (goto-char (point-max))
6874 (message "Link search wrapped back to end of buffer"))
6875 (setq org-link-search-failed nil)
6876 (let* ((pos (point))
6877 (ct (org-context))
6878 (a (assoc :link ct)))
6879 (if a (goto-char (nth 1 a)))
6880 (if (re-search-backward org-any-link-re nil t)
6881 (progn
6882 (goto-char (match-beginning 0))
6883 (if (org-invisible-p) (org-show-context)))
6884 (goto-char pos)
6885 (setq org-link-search-failed t)
6886 (error "No further link found"))))
6888 (defun org-translate-link (s)
6889 "Translate a link string if a translation function has been defined."
6890 (if (and org-link-translation-function
6891 (fboundp org-link-translation-function)
6892 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6893 (progn
6894 (setq s (funcall org-link-translation-function
6895 (match-string 1) (match-string 2)))
6896 (concat (car s) ":" (cdr s)))
6899 (defun org-translate-link-from-planner (type path)
6900 "Translate a link from Emacs Planner syntax so that Org can follow it.
6901 This is still an experimental function, your mileage may vary."
6902 (cond
6903 ((member type '("http" "https" "news" "ftp"))
6904 ;; standard Internet links are the same.
6905 nil)
6906 ((and (equal type "irc") (string-match "^//" path))
6907 ;; Planner has two / at the beginning of an irc link, we have 1.
6908 ;; We should have zero, actually....
6909 (setq path (substring path 1)))
6910 ((and (equal type "lisp") (string-match "^/" path))
6911 ;; Planner has a slash, we do not.
6912 (setq type "elisp" path (substring path 1)))
6913 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6914 ;; A typical message link. Planner has the id after the fina slash,
6915 ;; we separate it with a hash mark
6916 (setq path (concat (match-string 1 path) "#"
6917 (org-remove-angle-brackets (match-string 2 path)))))
6919 (cons type path))
6921 (defun org-find-file-at-mouse (ev)
6922 "Open file link or URL at mouse."
6923 (interactive "e")
6924 (mouse-set-point ev)
6925 (org-open-at-point 'in-emacs))
6927 (defun org-open-at-mouse (ev)
6928 "Open file link or URL at mouse."
6929 (interactive "e")
6930 (mouse-set-point ev)
6931 (if (eq major-mode 'org-agenda-mode)
6932 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6933 (org-open-at-point))
6935 (defvar org-window-config-before-follow-link nil
6936 "The window configuration before following a link.
6937 This is saved in case the need arises to restore it.")
6939 (defvar org-open-link-marker (make-marker)
6940 "Marker pointing to the location where `org-open-at-point; was called.")
6942 ;;;###autoload
6943 (defun org-open-at-point-global ()
6944 "Follow a link like Org-mode does.
6945 This command can be called in any mode to follow a link that has
6946 Org-mode syntax."
6947 (interactive)
6948 (org-run-like-in-org-mode 'org-open-at-point))
6950 ;;;###autoload
6951 (defun org-open-link-from-string (s &optional arg)
6952 "Open a link in the string S, as if it was in Org-mode."
6953 (interactive "sLink: \nP")
6954 (with-temp-buffer
6955 (let ((org-inhibit-startup t))
6956 (org-mode)
6957 (insert s)
6958 (goto-char (point-min))
6959 (org-open-at-point arg))))
6961 (defun org-open-at-point (&optional in-emacs)
6962 "Open link at or after point.
6963 If there is no link at point, this function will search forward up to
6964 the end of the current subtree.
6965 Normally, files will be opened by an appropriate application. If the
6966 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6967 With a double prefix argument, try to open outside of Emacs, in the
6968 application the system uses for this file type."
6969 (interactive "P")
6970 (org-load-modules-maybe)
6971 (move-marker org-open-link-marker (point))
6972 (setq org-window-config-before-follow-link (current-window-configuration))
6973 (org-remove-occur-highlights nil nil t)
6974 (cond
6975 ((org-at-timestamp-p t) (org-follow-timestamp-link))
6976 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
6977 (org-footnote-action))
6979 (let (type path link line search (pos (point)))
6980 (catch 'match
6981 (save-excursion
6982 (skip-chars-forward "^]\n\r")
6983 (when (org-in-regexp org-bracket-link-regexp)
6984 (setq link (org-extract-attributes
6985 (org-link-unescape (org-match-string-no-properties 1))))
6986 (while (string-match " *\n *" link)
6987 (setq link (replace-match " " t t link)))
6988 (setq link (org-link-expand-abbrev link))
6989 (cond
6990 ((or (file-name-absolute-p link)
6991 (string-match "^\\.\\.?/" link))
6992 (setq type "file" path link))
6993 ((string-match org-link-re-with-space3 link)
6994 (setq type (match-string 1 link) path (match-string 2 link)))
6995 (t (setq type "thisfile" path link)))
6996 (throw 'match t)))
6998 (when (get-text-property (point) 'org-linked-text)
6999 (setq type "thisfile"
7000 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7001 (1+ (point)) (point))
7002 path (buffer-substring
7003 (previous-single-property-change pos 'org-linked-text)
7004 (next-single-property-change pos 'org-linked-text)))
7005 (throw 'match t))
7007 (save-excursion
7008 (when (or (org-in-regexp org-angle-link-re)
7009 (org-in-regexp org-plain-link-re))
7010 (setq type (match-string 1) path (match-string 2))
7011 (throw 'match t)))
7012 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7013 (setq type "tree-match"
7014 path (match-string 1))
7015 (throw 'match t))
7016 (save-excursion
7017 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7018 (setq type "tags"
7019 path (match-string 1))
7020 (while (string-match ":" path)
7021 (setq path (replace-match "+" t t path)))
7022 (throw 'match t))))
7023 (unless path
7024 (error "No link found"))
7025 ;; Remove any trailing spaces in path
7026 (if (string-match " +\\'" path)
7027 (setq path (replace-match "" t t path)))
7028 (if (and org-link-translation-function
7029 (fboundp org-link-translation-function))
7030 ;; Check if we need to translate the link
7031 (let ((tmp (funcall org-link-translation-function type path)))
7032 (setq type (car tmp) path (cdr tmp))))
7034 (cond
7036 ((assoc type org-link-protocols)
7037 (funcall (nth 1 (assoc type org-link-protocols)) path))
7039 ((equal type "mailto")
7040 (let ((cmd (car org-link-mailto-program))
7041 (args (cdr org-link-mailto-program)) args1
7042 (address path) (subject "") a)
7043 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7044 (setq address (match-string 1 path)
7045 subject (org-link-escape (match-string 2 path))))
7046 (while args
7047 (cond
7048 ((not (stringp (car args))) (push (pop args) args1))
7049 (t (setq a (pop args))
7050 (if (string-match "%a" a)
7051 (setq a (replace-match address t t a)))
7052 (if (string-match "%s" a)
7053 (setq a (replace-match subject t t a)))
7054 (push a args1))))
7055 (apply cmd (nreverse args1))))
7057 ((member type '("http" "https" "ftp" "news"))
7058 (browse-url (concat type ":" (org-link-escape
7059 path org-link-escape-chars-browser))))
7061 ((member type '("message"))
7062 (browse-url (concat type ":" path)))
7064 ((string= type "tags")
7065 (org-tags-view in-emacs path))
7066 ((string= type "thisfile")
7067 (if in-emacs
7068 (switch-to-buffer-other-window
7069 (org-get-buffer-for-internal-link (current-buffer)))
7070 (org-mark-ring-push))
7071 (let ((cmd `(org-link-search
7072 ,path
7073 ,(cond ((equal in-emacs '(4)) 'occur)
7074 ((equal in-emacs '(16)) 'org-occur)
7075 (t nil))
7076 ,pos)))
7077 (condition-case nil (eval cmd)
7078 (error (progn (widen) (eval cmd))))))
7080 ((string= type "tree-match")
7081 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7083 ((string= type "file")
7084 (if (string-match "::\\([0-9]+\\)\\'" path)
7085 (setq line (string-to-number (match-string 1 path))
7086 path (substring path 0 (match-beginning 0)))
7087 (if (string-match "::\\(.+\\)\\'" path)
7088 (setq search (match-string 1 path)
7089 path (substring path 0 (match-beginning 0)))))
7090 (if (string-match "[*?{]" (file-name-nondirectory path))
7091 (dired path)
7092 (org-open-file path in-emacs line search)))
7094 ((string= type "news")
7095 (require 'org-gnus)
7096 (org-gnus-follow-link path))
7098 ((string= type "shell")
7099 (let ((cmd path))
7100 (if (or (not org-confirm-shell-link-function)
7101 (funcall org-confirm-shell-link-function
7102 (format "Execute \"%s\" in shell? "
7103 (org-add-props cmd nil
7104 'face 'org-warning))))
7105 (progn
7106 (message "Executing %s" cmd)
7107 (shell-command cmd))
7108 (error "Abort"))))
7110 ((string= type "elisp")
7111 (let ((cmd path))
7112 (if (or (not org-confirm-elisp-link-function)
7113 (funcall org-confirm-elisp-link-function
7114 (format "Execute \"%s\" as elisp? "
7115 (org-add-props cmd nil
7116 'face 'org-warning))))
7117 (message "%s => %s" cmd
7118 (if (equal (string-to-char cmd) ?\()
7119 (eval (read cmd))
7120 (call-interactively (read cmd))))
7121 (error "Abort"))))
7124 (browse-url-at-point))))))
7125 (move-marker org-open-link-marker nil)
7126 (run-hook-with-args 'org-follow-link-hook))
7128 ;;;; Time estimates
7130 (defun org-get-effort (&optional pom)
7131 "Get the effort estimate for the current entry."
7132 (org-entry-get pom org-effort-property))
7134 ;;; File search
7136 (defvar org-create-file-search-functions nil
7137 "List of functions to construct the right search string for a file link.
7138 These functions are called in turn with point at the location to
7139 which the link should point.
7141 A function in the hook should first test if it would like to
7142 handle this file type, for example by checking the major-mode or
7143 the file extension. If it decides not to handle this file, it
7144 should just return nil to give other functions a chance. If it
7145 does handle the file, it must return the search string to be used
7146 when following the link. The search string will be part of the
7147 file link, given after a double colon, and `org-open-at-point'
7148 will automatically search for it. If special measures must be
7149 taken to make the search successful, another function should be
7150 added to the companion hook `org-execute-file-search-functions',
7151 which see.
7153 A function in this hook may also use `setq' to set the variable
7154 `description' to provide a suggestion for the descriptive text to
7155 be used for this link when it gets inserted into an Org-mode
7156 buffer with \\[org-insert-link].")
7158 (defvar org-execute-file-search-functions nil
7159 "List of functions to execute a file search triggered by a link.
7161 Functions added to this hook must accept a single argument, the
7162 search string that was part of the file link, the part after the
7163 double colon. The function must first check if it would like to
7164 handle this search, for example by checking the major-mode or the
7165 file extension. If it decides not to handle this search, it
7166 should just return nil to give other functions a chance. If it
7167 does handle the search, it must return a non-nil value to keep
7168 other functions from trying.
7170 Each function can access the current prefix argument through the
7171 variable `current-prefix-argument'. Note that a single prefix is
7172 used to force opening a link in Emacs, so it may be good to only
7173 use a numeric or double prefix to guide the search function.
7175 In case this is needed, a function in this hook can also restore
7176 the window configuration before `org-open-at-point' was called using:
7178 (set-window-configuration org-window-config-before-follow-link)")
7180 (defun org-link-search (s &optional type avoid-pos)
7181 "Search for a link search option.
7182 If S is surrounded by forward slashes, it is interpreted as a
7183 regular expression. In org-mode files, this will create an `org-occur'
7184 sparse tree. In ordinary files, `occur' will be used to list matches.
7185 If the current buffer is in `dired-mode', grep will be used to search
7186 in all files. If AVOID-POS is given, ignore matches near that position."
7187 (let ((case-fold-search t)
7188 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7189 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7190 (append '(("") (" ") ("\t") ("\n"))
7191 org-emphasis-alist)
7192 "\\|") "\\)"))
7193 (pos (point))
7194 (pre nil) (post nil)
7195 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7196 (cond
7197 ;; First check if there are any special
7198 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7199 ;; Now try the builtin stuff
7200 ((save-excursion
7201 (goto-char (point-min))
7202 (and
7203 (re-search-forward
7204 (concat "<<" (regexp-quote s0) ">>") nil t)
7205 (setq type 'dedicated
7206 pos (match-beginning 0))))
7207 ;; There is an exact target for this
7208 (goto-char pos))
7209 ((and (string-match "^(\\(.*\\))$" s0)
7210 (save-excursion
7211 (goto-char (point-min))
7212 (and
7213 (re-search-forward
7214 (concat "[^[]" (regexp-quote
7215 (format org-coderef-label-format
7216 (match-string 1 s0))))
7217 nil t)
7218 (setq type 'dedicated
7219 pos (1+ (match-beginning 0))))))
7220 ;; There is a coderef target for this
7221 (goto-char pos))
7222 ((string-match "^/\\(.*\\)/$" s)
7223 ;; A regular expression
7224 (cond
7225 ((org-mode-p)
7226 (org-occur (match-string 1 s)))
7227 ;;((eq major-mode 'dired-mode)
7228 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7229 (t (org-do-occur (match-string 1 s)))))
7231 ;; A normal search strings
7232 (when (equal (string-to-char s) ?*)
7233 ;; Anchor on headlines, post may include tags.
7234 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7235 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7236 s (substring s 1)))
7237 (remove-text-properties
7238 0 (length s)
7239 '(face nil mouse-face nil keymap nil fontified nil) s)
7240 ;; Make a series of regular expressions to find a match
7241 (setq words (org-split-string s "[ \n\r\t]+")
7243 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7244 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7245 "\\)" markers)
7246 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7247 re2a (concat "[ \t\r\n]" re2a_)
7248 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7249 re4 (concat "[^a-zA-Z_]" re4_)
7251 re1 (concat pre re2 post)
7252 re3 (concat pre (if pre re4_ re4) post)
7253 re5 (concat pre ".*" re4)
7254 re2 (concat pre re2)
7255 re2a (concat pre (if pre re2a_ re2a))
7256 re4 (concat pre (if pre re4_ re4))
7257 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7258 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7259 re5 "\\)"
7261 (cond
7262 ((eq type 'org-occur) (org-occur reall))
7263 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7264 (t (goto-char (point-min))
7265 (setq type 'fuzzy)
7266 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7267 (org-search-not-self 1 re1 nil t)
7268 (org-search-not-self 1 re2 nil t)
7269 (org-search-not-self 1 re2a nil t)
7270 (org-search-not-self 1 re3 nil t)
7271 (org-search-not-self 1 re4 nil t)
7272 (org-search-not-self 1 re5 nil t)
7274 (goto-char (match-beginning 1))
7275 (goto-char pos)
7276 (error "No match")))))
7278 ;; Normal string-search
7279 (goto-char (point-min))
7280 (if (search-forward s nil t)
7281 (goto-char (match-beginning 0))
7282 (error "No match"))))
7283 (and (org-mode-p) (org-show-context 'link-search))
7284 type))
7286 (defun org-search-not-self (group &rest args)
7287 "Execute `re-search-forward', but only accept matches that do not
7288 enclose the position of `org-open-link-marker'."
7289 (let ((m org-open-link-marker))
7290 (catch 'exit
7291 (while (apply 're-search-forward args)
7292 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7293 (goto-char (match-end group))
7294 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7295 (> (match-beginning 0) (marker-position m))
7296 (< (match-end 0) (marker-position m)))
7297 (save-match-data
7298 (or (not (org-in-regexp
7299 org-bracket-link-analytic-regexp 1))
7300 (not (match-end 4)) ; no description
7301 (and (<= (match-beginning 4) (point))
7302 (>= (match-end 4) (point))))))
7303 (throw 'exit (point))))))))
7305 (defun org-get-buffer-for-internal-link (buffer)
7306 "Return a buffer to be used for displaying the link target of internal links."
7307 (cond
7308 ((not org-display-internal-link-with-indirect-buffer)
7309 buffer)
7310 ((string-match "(Clone)$" (buffer-name buffer))
7311 (message "Buffer is already a clone, not making another one")
7312 ;; we also do not modify visibility in this case
7313 buffer)
7314 (t ; make a new indirect buffer for displaying the link
7315 (let* ((bn (buffer-name buffer))
7316 (ibn (concat bn "(Clone)"))
7317 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7318 (with-current-buffer ib (org-overview))
7319 ib))))
7321 (defun org-do-occur (regexp &optional cleanup)
7322 "Call the Emacs command `occur'.
7323 If CLEANUP is non-nil, remove the printout of the regular expression
7324 in the *Occur* buffer. This is useful if the regex is long and not useful
7325 to read."
7326 (occur regexp)
7327 (when cleanup
7328 (let ((cwin (selected-window)) win beg end)
7329 (when (setq win (get-buffer-window "*Occur*"))
7330 (select-window win))
7331 (goto-char (point-min))
7332 (when (re-search-forward "match[a-z]+" nil t)
7333 (setq beg (match-end 0))
7334 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7335 (setq end (1- (match-beginning 0)))))
7336 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7337 (goto-char (point-min))
7338 (select-window cwin))))
7340 ;;; The mark ring for links jumps
7342 (defvar org-mark-ring nil
7343 "Mark ring for positions before jumps in Org-mode.")
7344 (defvar org-mark-ring-last-goto nil
7345 "Last position in the mark ring used to go back.")
7346 ;; Fill and close the ring
7347 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7348 (loop for i from 1 to org-mark-ring-length do
7349 (push (make-marker) org-mark-ring))
7350 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7351 org-mark-ring)
7353 (defun org-mark-ring-push (&optional pos buffer)
7354 "Put the current position or POS into the mark ring and rotate it."
7355 (interactive)
7356 (setq pos (or pos (point)))
7357 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7358 (move-marker (car org-mark-ring)
7359 (or pos (point))
7360 (or buffer (current-buffer)))
7361 (message "%s"
7362 (substitute-command-keys
7363 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7365 (defun org-mark-ring-goto (&optional n)
7366 "Jump to the previous position in the mark ring.
7367 With prefix arg N, jump back that many stored positions. When
7368 called several times in succession, walk through the entire ring.
7369 Org-mode commands jumping to a different position in the current file,
7370 or to another Org-mode file, automatically push the old position
7371 onto the ring."
7372 (interactive "p")
7373 (let (p m)
7374 (if (eq last-command this-command)
7375 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7376 (setq p org-mark-ring))
7377 (setq org-mark-ring-last-goto p)
7378 (setq m (car p))
7379 (switch-to-buffer (marker-buffer m))
7380 (goto-char m)
7381 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7383 (defun org-remove-angle-brackets (s)
7384 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7385 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7387 (defun org-add-angle-brackets (s)
7388 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7389 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7391 (defun org-remove-double-quotes (s)
7392 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7393 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7396 ;;; Following specific links
7398 (defun org-follow-timestamp-link ()
7399 (cond
7400 ((org-at-date-range-p t)
7401 (let ((org-agenda-start-on-weekday)
7402 (t1 (match-string 1))
7403 (t2 (match-string 2)))
7404 (setq t1 (time-to-days (org-time-string-to-time t1))
7405 t2 (time-to-days (org-time-string-to-time t2)))
7406 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7407 ((org-at-timestamp-p t)
7408 (org-agenda-list nil (time-to-days (org-time-string-to-time
7409 (substring (match-string 1) 0 10)))
7411 (t (error "This should not happen"))))
7414 ;;; Following file links
7415 (defvar org-wait nil)
7416 (defun org-open-file (path &optional in-emacs line search)
7417 "Open the file at PATH.
7418 First, this expands any special file name abbreviations. Then the
7419 configuration variable `org-file-apps' is checked if it contains an
7420 entry for this file type, and if yes, the corresponding command is launched.
7422 If no application is found, Emacs simply visits the file.
7424 With optional prefix argument IN-EMACS, Emacs will visit the file.
7425 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7426 and o use an external application to visit the file.
7428 Optional LINE specifies a line to go to, optional SEARCH a string to
7429 search for. If LINE or SEARCH is given, the file will always be
7430 opened in Emacs.
7431 If the file does not exist, an error is thrown."
7432 (setq in-emacs (or in-emacs line search))
7433 (let* ((file (if (equal path "")
7434 buffer-file-name
7435 (substitute-in-file-name (expand-file-name path))))
7436 (apps (append org-file-apps (org-default-apps)))
7437 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7438 (dirp (if remp nil (file-directory-p file)))
7439 (file (if (and dirp org-open-directory-means-index-dot-org)
7440 (concat (file-name-as-directory file) "index.org")
7441 file))
7442 (a-m-a-p (assq 'auto-mode apps))
7443 (dfile (downcase file))
7444 (old-buffer (current-buffer))
7445 (old-pos (point))
7446 (old-mode major-mode)
7447 ext cmd)
7448 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7449 (setq ext (match-string 1 dfile))
7450 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7451 (setq ext (match-string 1 dfile))))
7452 (cond
7453 ((equal in-emacs '(16))
7454 (setq cmd (cdr (assoc 'system apps))))
7455 (in-emacs (setq cmd 'emacs))
7457 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7458 (and dirp (cdr (assoc 'directory apps)))
7459 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7460 'string-match)
7461 (cdr (assoc ext apps))
7462 (cdr (assoc t apps))))))
7463 (when (eq cmd 'system)
7464 (setq cmd (cdr (assoc 'system apps))))
7465 (when (eq cmd 'default)
7466 (setq cmd (cdr (assoc t apps))))
7467 (when (eq cmd 'mailcap)
7468 (require 'mailcap)
7469 (mailcap-parse-mailcaps)
7470 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7471 (command (mailcap-mime-info mime-type)))
7472 (if (stringp command)
7473 (setq cmd command)
7474 (setq cmd 'emacs))))
7475 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7476 (not (file-exists-p file))
7477 (not org-open-non-existing-files))
7478 (error "No such file: %s" file))
7479 (cond
7480 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7481 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7482 (while (string-match "['\"]%s['\"]" cmd)
7483 (setq cmd (replace-match "%s" t t cmd)))
7484 (while (string-match "%s" cmd)
7485 (setq cmd (replace-match
7486 (save-match-data
7487 (shell-quote-argument
7488 (convert-standard-filename file)))
7489 t t cmd)))
7490 (save-window-excursion
7491 (start-process-shell-command cmd nil cmd)
7492 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7494 ((or (stringp cmd)
7495 (eq cmd 'emacs))
7496 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7497 (widen)
7498 (if line (goto-line line)
7499 (if search (org-link-search search))))
7500 ((consp cmd)
7501 (let ((file (convert-standard-filename file)))
7502 (eval cmd)))
7503 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7504 (and (org-mode-p) (eq old-mode 'org-mode)
7505 (or (not (equal old-buffer (current-buffer)))
7506 (not (equal old-pos (point))))
7507 (org-mark-ring-push old-pos old-buffer))))
7509 (defun org-default-apps ()
7510 "Return the default applications for this operating system."
7511 (cond
7512 ((eq system-type 'darwin)
7513 org-file-apps-defaults-macosx)
7514 ((eq system-type 'windows-nt)
7515 org-file-apps-defaults-windowsnt)
7516 (t org-file-apps-defaults-gnu)))
7518 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7519 "Convert extensions to regular expressions in the cars of LIST.
7520 Also, weed out any non-string entries, because the return value is used
7521 only for regexp matching.
7522 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7523 point to the symbol `emacs', indicating that the file should
7524 be opened in Emacs."
7525 (append
7526 (delq nil
7527 (mapcar (lambda (x)
7528 (if (not (stringp (car x)))
7530 (if (string-match "\\W" (car x))
7532 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7533 list))
7534 (if add-auto-mode
7535 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7537 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7538 (defun org-file-remote-p (file)
7539 "Test whether FILE specifies a location on a remote system.
7540 Return non-nil if the location is indeed remote.
7542 For example, the filename \"/user@host:/foo\" specifies a location
7543 on the system \"/user@host:\"."
7544 (cond ((fboundp 'file-remote-p)
7545 (file-remote-p file))
7546 ((fboundp 'tramp-handle-file-remote-p)
7547 (tramp-handle-file-remote-p file))
7548 ((and (boundp 'ange-ftp-name-format)
7549 (string-match (car ange-ftp-name-format) file))
7551 (t nil)))
7554 ;;;; Refiling
7556 (defun org-get-org-file ()
7557 "Read a filename, with default directory `org-directory'."
7558 (let ((default (or org-default-notes-file remember-data-file)))
7559 (read-file-name (format "File name [%s]: " default)
7560 (file-name-as-directory org-directory)
7561 default)))
7563 (defun org-notes-order-reversed-p ()
7564 "Check if the current file should receive notes in reversed order."
7565 (cond
7566 ((not org-reverse-note-order) nil)
7567 ((eq t org-reverse-note-order) t)
7568 ((not (listp org-reverse-note-order)) nil)
7569 (t (catch 'exit
7570 (let ((all org-reverse-note-order)
7571 entry)
7572 (while (setq entry (pop all))
7573 (if (string-match (car entry) buffer-file-name)
7574 (throw 'exit (cdr entry))))
7575 nil)))))
7577 (defvar org-refile-target-table nil
7578 "The list of refile targets, created by `org-refile'.")
7580 (defvar org-agenda-new-buffers nil
7581 "Buffers created to visit agenda files.")
7583 (defun org-get-refile-targets (&optional default-buffer)
7584 "Produce a table with refile targets."
7585 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7586 targets txt re files f desc descre fast-path-p level)
7587 (message "Getting targets...")
7588 (with-current-buffer (or default-buffer (current-buffer))
7589 (while (setq entry (pop entries))
7590 (setq files (car entry) desc (cdr entry))
7591 (setq fast-path-p nil)
7592 (cond
7593 ((null files) (setq files (list (current-buffer))))
7594 ((eq files 'org-agenda-files)
7595 (setq files (org-agenda-files 'unrestricted)))
7596 ((and (symbolp files) (fboundp files))
7597 (setq files (funcall files)))
7598 ((and (symbolp files) (boundp files))
7599 (setq files (symbol-value files))))
7600 (if (stringp files) (setq files (list files)))
7601 (cond
7602 ((eq (car desc) :tag)
7603 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7604 ((eq (car desc) :todo)
7605 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7606 ((eq (car desc) :regexp)
7607 (setq descre (cdr desc)))
7608 ((eq (car desc) :level)
7609 (setq descre (concat "^\\*\\{" (number-to-string
7610 (if org-odd-levels-only
7611 (1- (* 2 (cdr desc)))
7612 (cdr desc)))
7613 "\\}[ \t]")))
7614 ((eq (car desc) :maxlevel)
7615 (setq fast-path-p t)
7616 (setq descre (concat "^\\*\\{1," (number-to-string
7617 (if org-odd-levels-only
7618 (1- (* 2 (cdr desc)))
7619 (cdr desc)))
7620 "\\}[ \t]")))
7621 (t (error "Bad refiling target description %s" desc)))
7622 (while (setq f (pop files))
7623 (save-excursion
7624 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7625 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7626 (setq f (expand-file-name f))
7627 (save-excursion
7628 (save-restriction
7629 (widen)
7630 (goto-char (point-min))
7631 (while (re-search-forward descre nil t)
7632 (goto-char (point-at-bol))
7633 (when (looking-at org-complex-heading-regexp)
7634 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7635 txt (org-link-display-format (match-string 4))
7636 re (concat "^" (regexp-quote
7637 (buffer-substring (match-beginning 1)
7638 (match-end 4)))))
7639 (if (match-end 5) (setq re (concat re "[ \t]+"
7640 (regexp-quote
7641 (match-string 5)))))
7642 (setq re (concat re "[ \t]*$"))
7643 (when org-refile-use-outline-path
7644 (setq txt (mapconcat 'org-protect-slash
7645 (append
7646 (if (eq org-refile-use-outline-path 'file)
7647 (list (file-name-nondirectory
7648 (buffer-file-name (buffer-base-buffer))))
7649 (if (eq org-refile-use-outline-path 'full-file-path)
7650 (list (buffer-file-name (buffer-base-buffer)))))
7651 (org-get-outline-path fast-path-p level txt)
7652 (list txt))
7653 "/")))
7654 (push (list txt f re (point)) targets))
7655 (goto-char (point-at-eol))))))))
7656 (message "Getting targets...done")
7657 (nreverse targets))))
7659 (defun org-protect-slash (s)
7660 (while (string-match "/" s)
7661 (setq s (replace-match "\\" t t s)))
7664 (defvar org-olpa (make-vector 20 nil))
7666 (defun org-get-outline-path (&optional fastp level heading)
7667 "Return the outline path to the current entry, as a list."
7668 (if fastp
7669 (progn
7670 (if (> level 19)
7671 (error "Outline path failure, more than 19 levels."))
7672 (loop for i from level upto 19 do
7673 (aset org-olpa i nil))
7674 (prog1
7675 (delq nil (append org-olpa nil))
7676 (aset org-olpa level heading)))
7677 (let (rtn)
7678 (save-excursion
7679 (while (org-up-heading-safe)
7680 (when (looking-at org-complex-heading-regexp)
7681 (push (org-match-string-no-properties 4) rtn)))
7682 rtn))))
7684 (defvar org-refile-history nil
7685 "History for refiling operations.")
7687 (defun org-refile (&optional goto default-buffer)
7688 "Move the entry at point to another heading.
7689 The list of target headings is compiled using the information in
7690 `org-refile-targets', which see. This list is created before each use
7691 and will therefore always be up-to-date.
7693 At the target location, the entry is filed as a subitem of the target heading.
7694 Depending on `org-reverse-note-order', the new subitem will either be the
7695 first or the last subitem.
7697 If there is an active region, all entries in that region will be moved.
7698 However, the region must fulfil the requirement that the first heading
7699 is the first one sets the top-level of the moved text - at most siblings
7700 below it are allowed.
7702 With prefix arg GOTO, the command will only visit the target location,
7703 not actually move anything.
7704 With a double prefix `C-u C-u', go to the location where the last refiling
7705 operation has put the subtree."
7706 (interactive "P")
7707 (let* ((cbuf (current-buffer))
7708 (regionp (org-region-active-p))
7709 (region-start (and regionp (region-beginning)))
7710 (region-end (and regionp (region-end)))
7711 (region-length (and regionp (- region-end region-start)))
7712 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7713 pos it nbuf file re level reversed)
7714 (when regionp (goto-char region-start)
7715 (unless (org-kill-is-subtree-p
7716 (buffer-substring region-start region-end))
7717 (error "The region is not a (sequence of) subtree(s)")))
7718 (if (equal goto '(16))
7719 (org-refile-goto-last-stored)
7720 (when (setq it (org-refile-get-location
7721 (if goto "Goto: " "Refile to: ") default-buffer))
7722 (setq file (nth 1 it)
7723 re (nth 2 it)
7724 pos (nth 3 it))
7725 (if (and (equal (buffer-file-name) file)
7726 (if regionp
7727 (and (>= pos region-start)
7728 (<= pos region-end))
7729 (and (>= pos (point))
7730 (< pos (save-excursion
7731 (org-end-of-subtree t t))))))
7732 (error "Cannot refile to position inside the tree or region"))
7734 (setq nbuf (or (find-buffer-visiting file)
7735 (find-file-noselect file)))
7736 (if goto
7737 (progn
7738 (switch-to-buffer nbuf)
7739 (goto-char pos)
7740 (org-show-context 'org-goto))
7741 (if regionp
7742 (progn
7743 (kill-new (buffer-substring region-start region-end))
7744 (org-save-markers-in-region region-start region-end))
7745 (org-copy-subtree 1 nil t))
7746 (save-excursion
7747 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7748 (find-file-noselect file))))
7749 (setq reversed (org-notes-order-reversed-p))
7750 (save-excursion
7751 (save-restriction
7752 (widen)
7753 (goto-char pos)
7754 (looking-at outline-regexp)
7755 (setq level (org-get-valid-level (funcall outline-level) 1))
7756 (goto-char
7757 (if reversed
7758 (or (outline-next-heading) (point-max))
7759 (or (save-excursion (outline-get-next-sibling))
7760 (org-end-of-subtree t t)
7761 (point-max))))
7762 (if (not (bolp)) (newline))
7763 (bookmark-set "org-refile-last-stored")
7764 (org-paste-subtree level))))
7765 (if regionp
7766 (delete-region (point) (+ (point) region-length))
7767 (org-cut-subtree))
7768 (setq org-markers-to-move nil)
7769 (message "Refiled to \"%s\"" (car it)))))))
7771 (defun org-refile-goto-last-stored ()
7772 "Go to the location where the last refile was stored."
7773 (interactive)
7774 (bookmark-jump "org-refile-last-stored")
7775 (message "This is the location of the last refile"))
7777 (defun org-refile-get-location (&optional prompt default-buffer)
7778 "Prompt the user for a refile location, using PROMPT."
7779 (let ((org-refile-targets org-refile-targets)
7780 (org-refile-use-outline-path org-refile-use-outline-path))
7781 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7782 (unless org-refile-target-table
7783 (error "No refile targets"))
7784 (let* ((cbuf (current-buffer))
7785 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7786 (cfunc (if (and org-refile-use-outline-path
7787 org-outline-path-complete-in-steps)
7788 'org-olpath-completing-read
7789 'org-ido-completing-read))
7790 (extra (if org-refile-use-outline-path "/" ""))
7791 (filename (and cfn (expand-file-name cfn)))
7792 (tbl (mapcar
7793 (lambda (x)
7794 (if (not (equal filename (nth 1 x)))
7795 (cons (concat (car x) extra " ("
7796 (file-name-nondirectory (nth 1 x)) ")")
7797 (cdr x))
7798 (cons (concat (car x) extra) (cdr x))))
7799 org-refile-target-table))
7800 (completion-ignore-case t))
7801 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7802 tbl)))
7804 (defun org-olpath-completing-read (prompt collection &rest args)
7805 "Read an outline path like a file name."
7806 (let ((thetable collection))
7807 (apply
7808 'org-ido-completing-read prompt
7809 (lambda (string predicate &optional flag)
7810 (let (rtn r s f (l (length string)))
7811 (cond
7812 ((eq flag nil)
7813 ;; try completion
7814 (try-completion string thetable))
7815 ((eq flag t)
7816 ;; all-completions
7817 (setq rtn (all-completions string thetable predicate))
7818 (mapcar
7819 (lambda (x)
7820 (setq r (substring x l))
7821 (if (string-match " ([^)]*)$" x)
7822 (setq f (match-string 0 x))
7823 (setq f ""))
7824 (if (string-match "/" r)
7825 (concat string (substring r 0 (match-end 0)) f)
7827 rtn))
7828 ((eq flag 'lambda)
7829 ;; exact match?
7830 (assoc string thetable)))
7832 args)))
7834 ;;;; Dynamic blocks
7836 (defun org-find-dblock (name)
7837 "Find the first dynamic block with name NAME in the buffer.
7838 If not found, stay at current position and return nil."
7839 (let (pos)
7840 (save-excursion
7841 (goto-char (point-min))
7842 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7843 nil t)
7844 (match-beginning 0))))
7845 (if pos (goto-char pos))
7846 pos))
7848 (defconst org-dblock-start-re
7849 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7850 "Matches the startline of a dynamic block, with parameters.")
7852 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7853 "Matches the end of a dynamic block.")
7855 (defun org-create-dblock (plist)
7856 "Create a dynamic block section, with parameters taken from PLIST.
7857 PLIST must contain a :name entry which is used as name of the block."
7858 (unless (bolp) (newline))
7859 (let ((name (plist-get plist :name)))
7860 (insert "#+BEGIN: " name)
7861 (while plist
7862 (if (eq (car plist) :name)
7863 (setq plist (cddr plist))
7864 (insert " " (prin1-to-string (pop plist)))))
7865 (insert "\n\n#+END:\n")
7866 (beginning-of-line -2)))
7868 (defun org-prepare-dblock ()
7869 "Prepare dynamic block for refresh.
7870 This empties the block, puts the cursor at the insert position and returns
7871 the property list including an extra property :name with the block name."
7872 (unless (looking-at org-dblock-start-re)
7873 (error "Not at a dynamic block"))
7874 (let* ((begdel (1+ (match-end 0)))
7875 (name (org-no-properties (match-string 1)))
7876 (params (append (list :name name)
7877 (read (concat "(" (match-string 3) ")")))))
7878 (unless (re-search-forward org-dblock-end-re nil t)
7879 (error "Dynamic block not terminated"))
7880 (setq params
7881 (append params
7882 (list :content (buffer-substring
7883 begdel (match-beginning 0)))))
7884 (delete-region begdel (match-beginning 0))
7885 (goto-char begdel)
7886 (open-line 1)
7887 params))
7889 (defun org-map-dblocks (&optional command)
7890 "Apply COMMAND to all dynamic blocks in the current buffer.
7891 If COMMAND is not given, use `org-update-dblock'."
7892 (let ((cmd (or command 'org-update-dblock))
7893 pos)
7894 (save-excursion
7895 (goto-char (point-min))
7896 (while (re-search-forward org-dblock-start-re nil t)
7897 (goto-char (setq pos (match-beginning 0)))
7898 (condition-case nil
7899 (funcall cmd)
7900 (error (message "Error during update of dynamic block")))
7901 (goto-char pos)
7902 (unless (re-search-forward org-dblock-end-re nil t)
7903 (error "Dynamic block not terminated"))))))
7905 (defun org-dblock-update (&optional arg)
7906 "User command for updating dynamic blocks.
7907 Update the dynamic block at point. With prefix ARG, update all dynamic
7908 blocks in the buffer."
7909 (interactive "P")
7910 (if arg
7911 (org-update-all-dblocks)
7912 (or (looking-at org-dblock-start-re)
7913 (org-beginning-of-dblock))
7914 (org-update-dblock)))
7916 (defun org-update-dblock ()
7917 "Update the dynamic block at point
7918 This means to empty the block, parse for parameters and then call
7919 the correct writing function."
7920 (save-window-excursion
7921 (let* ((pos (point))
7922 (line (org-current-line))
7923 (params (org-prepare-dblock))
7924 (name (plist-get params :name))
7925 (cmd (intern (concat "org-dblock-write:" name))))
7926 (message "Updating dynamic block `%s' at line %d..." name line)
7927 (funcall cmd params)
7928 (message "Updating dynamic block `%s' at line %d...done" name line)
7929 (goto-char pos))))
7931 (defun org-beginning-of-dblock ()
7932 "Find the beginning of the dynamic block at point.
7933 Error if there is no such block at point."
7934 (let ((pos (point))
7935 beg)
7936 (end-of-line 1)
7937 (if (and (re-search-backward org-dblock-start-re nil t)
7938 (setq beg (match-beginning 0))
7939 (re-search-forward org-dblock-end-re nil t)
7940 (> (match-end 0) pos))
7941 (goto-char beg)
7942 (goto-char pos)
7943 (error "Not in a dynamic block"))))
7945 (defun org-update-all-dblocks ()
7946 "Update all dynamic blocks in the buffer.
7947 This function can be used in a hook."
7948 (when (org-mode-p)
7949 (org-map-dblocks 'org-update-dblock)))
7952 ;;;; Completion
7954 (defconst org-additional-option-like-keywords
7955 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7956 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7957 "BEGIN_EXAMPLE" "END_EXAMPLE"
7958 "BEGIN_QUOTE" "END_QUOTE"
7959 "BEGIN_VERSE" "END_VERSE"
7960 "BEGIN_SRC" "END_SRC"
7961 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7963 (defcustom org-structure-template-alist
7965 ("s" "#+begin_src ?\n\n#+end_src"
7966 "<src lang=\"?\">\n\n</src>")
7967 ("e" "#+begin_example\n?\n#+end_example"
7968 "<example>\n?\n</example>")
7969 ("q" "#+begin_quote\n?\n#+end_quote"
7970 "<quote>\n?\n</quote>")
7971 ("v" "#+begin_verse\n?\n#+end_verse"
7972 "<verse>\n?\n/verse>")
7973 ("l" "#+begin_latex\n?\n#+end_latex"
7974 "<literal style=\"latex\">\n?\n</literal>")
7975 ("L" "#+latex: "
7976 "<literal style=\"latex\">?</literal>")
7977 ("h" "#+begin_html\n?\n#+end_html"
7978 "<literal style=\"html\">\n?\n</literal>")
7979 ("H" "#+html: "
7980 "<literal style=\"html\">?</literal>")
7981 ("a" "#+begin_ascii\n?\n#+end_ascii")
7982 ("A" "#+ascii: ")
7983 ("i" "#+include %file ?"
7984 "<include file=%file markup=\"?\">")
7986 "Structure completion elements.
7987 This is a list of abbreviation keys and values. The value gets inserted
7988 it you type @samp{.} followed by the key and then the completion key,
7989 usually `M-TAB'. %file will be replaced by a file name after prompting
7990 for the file using completion.
7991 There are two templates for each key, the first uses the original Org syntax,
7992 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7993 the default when the /org-mtags.el/ module has been loaded. See also the
7994 variable `org-mtags-prefer-muse-templates'.
7995 This is an experimental feature, it is undecided if it is going to stay in."
7996 :group 'org-completion
7997 :type '(repeat
7998 (string :tag "Key")
7999 (string :tag "Template")
8000 (string :tag "Muse Template")))
8002 (defun org-try-structure-completion ()
8003 "Try to complete a structure template before point.
8004 This looks for strings like \"<e\" on an otherwise empty line and
8005 expands them."
8006 (let ((l (buffer-substring (point-at-bol) (point)))
8008 (when (and (looking-at "[ \t]*$")
8009 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8010 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8011 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8012 (match-beginning 1)) a)
8013 t)))
8015 (defun org-complete-expand-structure-template (start cell)
8016 "Expand a structure template."
8017 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8018 (rpl (nth (if musep 2 1) cell)))
8019 (delete-region start (point))
8020 (when (string-match "\\`#\\+" rpl)
8021 (cond
8022 ((bolp))
8023 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8024 (delete-region (point-at-bol) (point)))
8025 (t (newline))))
8026 (setq start (point))
8027 (if (string-match "%file" rpl)
8028 (setq rpl (replace-match
8029 (concat
8030 "\""
8031 (save-match-data
8032 (abbreviate-file-name (read-file-name "Include file: ")))
8033 "\"")
8034 t t rpl)))
8035 (insert rpl)
8036 (if (re-search-backward "\\?" start t) (delete-char 1))))
8039 (defun org-complete (&optional arg)
8040 "Perform completion on word at point.
8041 At the beginning of a headline, this completes TODO keywords as given in
8042 `org-todo-keywords'.
8043 If the current word is preceded by a backslash, completes the TeX symbols
8044 that are supported for HTML support.
8045 If the current word is preceded by \"#+\", completes special words for
8046 setting file options.
8047 In the line after \"#+STARTUP:, complete valid keywords.\"
8048 At all other locations, this simply calls the value of
8049 `org-completion-fallback-command'."
8050 (interactive "P")
8051 (org-without-partial-completion
8052 (catch 'exit
8053 (let* ((a nil)
8054 (end (point))
8055 (beg1 (save-excursion
8056 (skip-chars-backward (org-re "[:alnum:]_@"))
8057 (point)))
8058 (beg (save-excursion
8059 (skip-chars-backward "a-zA-Z0-9_:$")
8060 (point)))
8061 (confirm (lambda (x) (stringp (car x))))
8062 (searchhead (equal (char-before beg) ?*))
8063 (struct
8064 (when (and (member (char-before beg1) '(?. ?<))
8065 (setq a (assoc (buffer-substring beg1 (point))
8066 org-structure-template-alist)))
8067 (org-complete-expand-structure-template (1- beg1) a)
8068 (throw 'exit t)))
8069 (tag (and (equal (char-before beg1) ?:)
8070 (equal (char-after (point-at-bol)) ?*)))
8071 (prop (and (equal (char-before beg1) ?:)
8072 (not (equal (char-after (point-at-bol)) ?*))))
8073 (texp (equal (char-before beg) ?\\))
8074 (link (equal (char-before beg) ?\[))
8075 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8076 beg)
8077 "#+"))
8078 (startup (string-match "^#\\+STARTUP:.*"
8079 (buffer-substring (point-at-bol) (point))))
8080 (completion-ignore-case opt)
8081 (type nil)
8082 (tbl nil)
8083 (table (cond
8084 (opt
8085 (setq type :opt)
8086 (require 'org-exp)
8087 (append
8088 (mapcar
8089 (lambda (x)
8090 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8091 (cons (match-string 2 x) (match-string 1 x)))
8092 (org-split-string (org-get-current-options) "\n"))
8093 (mapcar 'list org-additional-option-like-keywords)))
8094 (startup
8095 (setq type :startup)
8096 org-startup-options)
8097 (link (append org-link-abbrev-alist-local
8098 org-link-abbrev-alist))
8099 (texp
8100 (setq type :tex)
8101 org-html-entities)
8102 ((string-match "\\`\\*+[ \t]+\\'"
8103 (buffer-substring (point-at-bol) beg))
8104 (setq type :todo)
8105 (mapcar 'list org-todo-keywords-1))
8106 (searchhead
8107 (setq type :searchhead)
8108 (save-excursion
8109 (goto-char (point-min))
8110 (while (re-search-forward org-todo-line-regexp nil t)
8111 (push (list
8112 (org-make-org-heading-search-string
8113 (match-string 3) t))
8114 tbl)))
8115 tbl)
8116 (tag (setq type :tag beg beg1)
8117 (or org-tag-alist (org-get-buffer-tags)))
8118 (prop (setq type :prop beg beg1)
8119 (mapcar 'list (org-buffer-property-keys nil t t)))
8120 (t (progn
8121 (call-interactively org-completion-fallback-command)
8122 (throw 'exit nil)))))
8123 (pattern (buffer-substring-no-properties beg end))
8124 (completion (try-completion pattern table confirm)))
8125 (cond ((eq completion t)
8126 (if (not (assoc (upcase pattern) table))
8127 (message "Already complete")
8128 (if (and (equal type :opt)
8129 (not (member (car (assoc (upcase pattern) table))
8130 org-additional-option-like-keywords)))
8131 (insert (substring (cdr (assoc (upcase pattern) table))
8132 (length pattern)))
8133 (if (memq type '(:tag :prop)) (insert ":")))))
8134 ((null completion)
8135 (message "Can't find completion for \"%s\"" pattern)
8136 (ding))
8137 ((not (string= pattern completion))
8138 (delete-region beg end)
8139 (if (string-match " +$" completion)
8140 (setq completion (replace-match "" t t completion)))
8141 (insert completion)
8142 (if (get-buffer-window "*Completions*")
8143 (delete-window (get-buffer-window "*Completions*")))
8144 (if (assoc completion table)
8145 (if (eq type :todo) (insert " ")
8146 (if (memq type '(:tag :prop)) (insert ":"))))
8147 (if (and (equal type :opt) (assoc completion table))
8148 (message "%s" (substitute-command-keys
8149 "Press \\[org-complete] again to insert example settings"))))
8151 (message "Making completion list...")
8152 (let ((list (sort (all-completions pattern table confirm)
8153 'string<)))
8154 (with-output-to-temp-buffer "*Completions*"
8155 (condition-case nil
8156 ;; Protection needed for XEmacs and emacs 21
8157 (display-completion-list list pattern)
8158 (error (display-completion-list list)))))
8159 (message "Making completion list...%s" "done")))))))
8161 ;;;; TODO, DEADLINE, Comments
8163 (defun org-toggle-comment ()
8164 "Change the COMMENT state of an entry."
8165 (interactive)
8166 (save-excursion
8167 (org-back-to-heading)
8168 (let (case-fold-search)
8169 (if (looking-at (concat outline-regexp
8170 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8171 (replace-match "" t t nil 1)
8172 (if (looking-at outline-regexp)
8173 (progn
8174 (goto-char (match-end 0))
8175 (insert org-comment-string " ")))))))
8177 (defvar org-last-todo-state-is-todo nil
8178 "This is non-nil when the last TODO state change led to a TODO state.
8179 If the last change removed the TODO tag or switched to DONE, then
8180 this is nil.")
8182 (defvar org-setting-tags nil) ; dynamically skipped
8184 (defun org-parse-local-options (string var)
8185 "Parse STRING for startup setting relevant for variable VAR."
8186 (let ((rtn (symbol-value var))
8187 e opts)
8188 (save-match-data
8189 (if (or (not string) (not (string-match "\\S-" string)))
8191 (setq opts (delq nil (mapcar (lambda (x)
8192 (setq e (assoc x org-startup-options))
8193 (if (eq (nth 1 e) var) e nil))
8194 (org-split-string string "[ \t]+"))))
8195 (if (not opts)
8197 (setq rtn nil)
8198 (while (setq e (pop opts))
8199 (if (not (nth 3 e))
8200 (setq rtn (nth 2 e))
8201 (if (not (listp rtn)) (setq rtn nil))
8202 (push (nth 2 e) rtn)))
8203 rtn)))))
8205 (defvar org-blocker-hook nil
8206 "Hook for functions that are allowed to block a state change.
8208 Each function gets as its single argument a property list, see
8209 `org-trigger-hook' for more information about this list.
8211 If any of the functions in this hook returns nil, the state change
8212 is blocked.")
8214 (defvar org-trigger-hook nil
8215 "Hook for functions that are triggered by a state change.
8217 Each function gets as its single argument a property list with at least
8218 the following elements:
8220 (:type type-of-change :position pos-at-entry-start
8221 :from old-state :to new-state)
8223 Depending on the type, more properties may be present.
8225 This mechanism is currently implemented for:
8227 TODO state changes
8228 ------------------
8229 :type todo-state-change
8230 :from previous state (keyword as a string), or nil
8231 :to new state (keyword as a string), or nil")
8233 (defvar org-agenda-headline-snapshot-before-repeat)
8234 (defun org-todo (&optional arg)
8235 "Change the TODO state of an item.
8236 The state of an item is given by a keyword at the start of the heading,
8237 like
8238 *** TODO Write paper
8239 *** DONE Call mom
8241 The different keywords are specified in the variable `org-todo-keywords'.
8242 By default the available states are \"TODO\" and \"DONE\".
8243 So for this example: when the item starts with TODO, it is changed to DONE.
8244 When it starts with DONE, the DONE is removed. And when neither TODO nor
8245 DONE are present, add TODO at the beginning of the heading.
8247 With C-u prefix arg, use completion to determine the new state.
8248 With numeric prefix arg, switch to that state.
8250 For calling through lisp, arg is also interpreted in the following way:
8251 'none -> empty state
8252 \"\"(empty string) -> switch to empty state
8253 'done -> switch to DONE
8254 'nextset -> switch to the next set of keywords
8255 'previousset -> switch to the previous set of keywords
8256 \"WAITING\" -> switch to the specified keyword, but only if it
8257 really is a member of `org-todo-keywords'."
8258 (interactive "P")
8259 (save-excursion
8260 (catch 'exit
8261 (org-back-to-heading)
8262 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8263 (or (looking-at (concat " +" org-todo-regexp " *"))
8264 (looking-at " *"))
8265 (let* ((match-data (match-data))
8266 (startpos (point-at-bol))
8267 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8268 (org-log-done org-log-done)
8269 (org-log-repeat org-log-repeat)
8270 (org-todo-log-states org-todo-log-states)
8271 (this (match-string 1))
8272 (hl-pos (match-beginning 0))
8273 (head (org-get-todo-sequence-head this))
8274 (ass (assoc head org-todo-kwd-alist))
8275 (interpret (nth 1 ass))
8276 (done-word (nth 3 ass))
8277 (final-done-word (nth 4 ass))
8278 (last-state (or this ""))
8279 (completion-ignore-case t)
8280 (member (member this org-todo-keywords-1))
8281 (tail (cdr member))
8282 (state (cond
8283 ((and org-todo-key-trigger
8284 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8285 (and (not arg) org-use-fast-todo-selection
8286 (not (eq org-use-fast-todo-selection 'prefix)))))
8287 ;; Use fast selection
8288 (org-fast-todo-selection))
8289 ((and (equal arg '(4))
8290 (or (not org-use-fast-todo-selection)
8291 (not org-todo-key-trigger)))
8292 ;; Read a state with completion
8293 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8294 org-todo-keywords-1)
8295 nil t))
8296 ((eq arg 'right)
8297 (if this
8298 (if tail (car tail) nil)
8299 (car org-todo-keywords-1)))
8300 ((eq arg 'left)
8301 (if (equal member org-todo-keywords-1)
8303 (if this
8304 (nth (- (length org-todo-keywords-1) (length tail) 2)
8305 org-todo-keywords-1)
8306 (org-last org-todo-keywords-1))))
8307 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8308 (setq arg nil))) ; hack to fall back to cycling
8309 (arg
8310 ;; user or caller requests a specific state
8311 (cond
8312 ((equal arg "") nil)
8313 ((eq arg 'none) nil)
8314 ((eq arg 'done) (or done-word (car org-done-keywords)))
8315 ((eq arg 'nextset)
8316 (or (car (cdr (member head org-todo-heads)))
8317 (car org-todo-heads)))
8318 ((eq arg 'previousset)
8319 (let ((org-todo-heads (reverse org-todo-heads)))
8320 (or (car (cdr (member head org-todo-heads)))
8321 (car org-todo-heads))))
8322 ((car (member arg org-todo-keywords-1)))
8323 ((nth (1- (prefix-numeric-value arg))
8324 org-todo-keywords-1))))
8325 ((null member) (or head (car org-todo-keywords-1)))
8326 ((equal this final-done-word) nil) ;; -> make empty
8327 ((null tail) nil) ;; -> first entry
8328 ((eq interpret 'sequence)
8329 (car tail))
8330 ((memq interpret '(type priority))
8331 (if (eq this-command last-command)
8332 (car tail)
8333 (if (> (length tail) 0)
8334 (or done-word (car org-done-keywords))
8335 nil)))
8336 (t nil)))
8337 (next (if state (concat " " state " ") " "))
8338 (change-plist (list :type 'todo-state-change :from this :to state
8339 :position startpos))
8340 dolog now-done-p)
8341 (when org-blocker-hook
8342 (unless (save-excursion
8343 (save-match-data
8344 (run-hook-with-args-until-failure
8345 'org-blocker-hook change-plist)))
8346 (if (interactive-p)
8347 (error "TODO state change from %s to %s blocked" this state)
8348 ;; fail silently
8349 (message "TODO state change from %s to %s blocked" this state)
8350 (throw 'exit nil))))
8351 (store-match-data match-data)
8352 (replace-match next t t)
8353 (unless (pos-visible-in-window-p hl-pos)
8354 (message "TODO state changed to %s" (org-trim next)))
8355 (unless head
8356 (setq head (org-get-todo-sequence-head state)
8357 ass (assoc head org-todo-kwd-alist)
8358 interpret (nth 1 ass)
8359 done-word (nth 3 ass)
8360 final-done-word (nth 4 ass)))
8361 (when (memq arg '(nextset previousset))
8362 (message "Keyword-Set %d/%d: %s"
8363 (- (length org-todo-sets) -1
8364 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8365 (length org-todo-sets)
8366 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8367 (setq org-last-todo-state-is-todo
8368 (not (member state org-done-keywords)))
8369 (setq now-done-p (and (member state org-done-keywords)
8370 (not (member this org-done-keywords))))
8371 (and logging (org-local-logging logging))
8372 (when (and (or org-todo-log-states org-log-done)
8373 (not (memq arg '(nextset previousset))))
8374 ;; we need to look at recording a time and note
8375 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8376 (nth 2 (assoc this org-todo-log-states))))
8377 (when (and state
8378 (member state org-not-done-keywords)
8379 (not (member this org-not-done-keywords)))
8380 ;; This is now a todo state and was not one before
8381 ;; If there was a CLOSED time stamp, get rid of it.
8382 (org-add-planning-info nil nil 'closed))
8383 (when (and now-done-p org-log-done)
8384 ;; It is now done, and it was not done before
8385 (org-add-planning-info 'closed (org-current-time))
8386 (if (and (not dolog) (eq 'note org-log-done))
8387 (org-add-log-setup 'done state 'findpos 'note)))
8388 (when (and state dolog)
8389 ;; This is a non-nil state, and we need to log it
8390 (org-add-log-setup 'state state 'findpos dolog)))
8391 ;; Fixup tag positioning
8392 (org-todo-trigger-tag-changes state)
8393 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8394 (when org-provide-todo-statistics
8395 (org-update-parent-todo-statistics))
8396 (run-hooks 'org-after-todo-state-change-hook)
8397 (if (and arg (not (member state org-done-keywords)))
8398 (setq head (org-get-todo-sequence-head state)))
8399 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8400 ;; Do we need to trigger a repeat?
8401 (when now-done-p
8402 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8403 ;; This is for the agenda, take a snapshot of the headline.
8404 (save-match-data
8405 (setq org-agenda-headline-snapshot-before-repeat
8406 (org-get-heading))))
8407 (org-auto-repeat-maybe state))
8408 ;; Fixup cursor location if close to the keyword
8409 (if (and (outline-on-heading-p)
8410 (not (bolp))
8411 (save-excursion (beginning-of-line 1)
8412 (looking-at org-todo-line-regexp))
8413 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8414 (progn
8415 (goto-char (or (match-end 2) (match-end 1)))
8416 (just-one-space)))
8417 (when org-trigger-hook
8418 (save-excursion
8419 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8421 (defun org-update-parent-todo-statistics ()
8422 "Update any statistics cookie in the parent of the current headline."
8423 (interactive)
8424 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8425 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8426 (catch 'exit
8427 (save-excursion
8428 (setq level (org-up-heading-safe))
8429 (unless (and level
8430 (re-search-forward box-re (point-at-eol) t))
8431 (throw 'exit nil))
8432 (setq is-percent (match-end 2))
8433 (save-match-data
8434 (unless (outline-next-heading) (throw 'exit nil))
8435 (while (looking-at org-todo-line-regexp)
8436 (setq kwd (match-string 2))
8437 (and kwd (setq cnt-all (1+ cnt-all)))
8438 (and (member kwd org-done-keywords)
8439 (setq cnt-done (1+ cnt-done)))
8440 (condition-case nil
8441 (org-forward-same-level 1)
8442 (error (end-of-line 1)))))
8443 (replace-match
8444 (if is-percent
8445 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8446 (format "[%d/%d]" cnt-done cnt-all)))
8447 (run-hook-with-args 'org-after-todo-statistics-hook
8448 cnt-done (- cnt-all cnt-done))))))
8450 (defvar org-after-todo-statistics-hook nil
8451 "Hook that is called after a TODO statistics cookie has been updated.
8452 Each function is called with two arguments: the number of not-done entries
8453 and the number of done entries.
8455 For example, the following function, when added to this hook, will switch
8456 an entry to DONE when all children are done, and back to TODO when new
8457 entries are set to a TODO status. Note that this hook is only called
8458 when there is a statistics cookie in the headline!
8460 (defun org-summary-todo (n-done n-not-done)
8461 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8462 (let (org-log-done org-log-states) ; turn off logging
8463 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8466 (defun org-todo-trigger-tag-changes (state)
8467 "Apply the changes defined in `org-todo-state-tags-triggers'."
8468 (let ((l org-todo-state-tags-triggers)
8469 changes)
8470 (when (or (not state) (equal state ""))
8471 (setq changes (append changes (cdr (assoc "" l)))))
8472 (when (and (stringp state) (> (length state) 0))
8473 (setq changes (append changes (cdr (assoc state l)))))
8474 (when (member state org-not-done-keywords)
8475 (setq changes (append changes (cdr (assoc 'todo l)))))
8476 (when (member state org-done-keywords)
8477 (setq changes (append changes (cdr (assoc 'done l)))))
8478 (dolist (c changes)
8479 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8481 (defun org-local-logging (value)
8482 "Get logging settings from a property VALUE."
8483 (let* (words w a)
8484 ;; directly set the variables, they are already local.
8485 (setq org-log-done nil
8486 org-log-repeat nil
8487 org-todo-log-states nil)
8488 (setq words (org-split-string value))
8489 (while (setq w (pop words))
8490 (cond
8491 ((setq a (assoc w org-startup-options))
8492 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8493 (set (nth 1 a) (nth 2 a))))
8494 ((setq a (org-extract-log-state-settings w))
8495 (and (member (car a) org-todo-keywords-1)
8496 (push a org-todo-log-states)))))))
8498 (defun org-get-todo-sequence-head (kwd)
8499 "Return the head of the TODO sequence to which KWD belongs.
8500 If KWD is not set, check if there is a text property remembering the
8501 right sequence."
8502 (let (p)
8503 (cond
8504 ((not kwd)
8505 (or (get-text-property (point-at-bol) 'org-todo-head)
8506 (progn
8507 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8508 nil (point-at-eol)))
8509 (get-text-property p 'org-todo-head))))
8510 ((not (member kwd org-todo-keywords-1))
8511 (car org-todo-keywords-1))
8512 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8514 (defun org-fast-todo-selection ()
8515 "Fast TODO keyword selection with single keys.
8516 Returns the new TODO keyword, or nil if no state change should occur."
8517 (let* ((fulltable org-todo-key-alist)
8518 (done-keywords org-done-keywords) ;; needed for the faces.
8519 (maxlen (apply 'max (mapcar
8520 (lambda (x)
8521 (if (stringp (car x)) (string-width (car x)) 0))
8522 fulltable)))
8523 (expert nil)
8524 (fwidth (+ maxlen 3 1 3))
8525 (ncol (/ (- (window-width) 4) fwidth))
8526 tg cnt e c tbl
8527 groups ingroup)
8528 (save-window-excursion
8529 (if expert
8530 (set-buffer (get-buffer-create " *Org todo*"))
8531 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8532 (erase-buffer)
8533 (org-set-local 'org-done-keywords done-keywords)
8534 (setq tbl fulltable cnt 0)
8535 (while (setq e (pop tbl))
8536 (cond
8537 ((equal e '(:startgroup))
8538 (push '() groups) (setq ingroup t)
8539 (when (not (= cnt 0))
8540 (setq cnt 0)
8541 (insert "\n"))
8542 (insert "{ "))
8543 ((equal e '(:endgroup))
8544 (setq ingroup nil cnt 0)
8545 (insert "}\n"))
8547 (setq tg (car e) c (cdr e))
8548 (if ingroup (push tg (car groups)))
8549 (setq tg (org-add-props tg nil 'face
8550 (org-get-todo-face tg)))
8551 (if (and (= cnt 0) (not ingroup)) (insert " "))
8552 (insert "[" c "] " tg (make-string
8553 (- fwidth 4 (length tg)) ?\ ))
8554 (when (= (setq cnt (1+ cnt)) ncol)
8555 (insert "\n")
8556 (if ingroup (insert " "))
8557 (setq cnt 0)))))
8558 (insert "\n")
8559 (goto-char (point-min))
8560 (if (not expert) (org-fit-window-to-buffer))
8561 (message "[a-z..]:Set [SPC]:clear")
8562 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8563 (cond
8564 ((or (= c ?\C-g)
8565 (and (= c ?q) (not (rassoc c fulltable))))
8566 (setq quit-flag t))
8567 ((= c ?\ ) nil)
8568 ((setq e (rassoc c fulltable) tg (car e))
8570 (t (setq quit-flag t))))))
8572 (defun org-entry-is-todo-p ()
8573 (member (org-get-todo-state) org-not-done-keywords))
8575 (defun org-entry-is-done-p ()
8576 (member (org-get-todo-state) org-done-keywords))
8578 (defun org-get-todo-state ()
8579 (save-excursion
8580 (org-back-to-heading t)
8581 (and (looking-at org-todo-line-regexp)
8582 (match-end 2)
8583 (match-string 2))))
8585 (defun org-at-date-range-p (&optional inactive-ok)
8586 "Is the cursor inside a date range?"
8587 (interactive)
8588 (save-excursion
8589 (catch 'exit
8590 (let ((pos (point)))
8591 (skip-chars-backward "^[<\r\n")
8592 (skip-chars-backward "<[")
8593 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8594 (>= (match-end 0) pos)
8595 (throw 'exit t))
8596 (skip-chars-backward "^<[\r\n")
8597 (skip-chars-backward "<[")
8598 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8599 (>= (match-end 0) pos)
8600 (throw 'exit t)))
8601 nil)))
8603 (defun org-get-repeat ()
8604 "Check if there is a deadline/schedule with repeater in this entry."
8605 (save-match-data
8606 (save-excursion
8607 (org-back-to-heading t)
8608 (if (re-search-forward
8609 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8610 (match-string 1)))))
8612 (defvar org-last-changed-timestamp)
8613 (defvar org-last-inserted-timestamp)
8614 (defvar org-log-post-message)
8615 (defvar org-log-note-purpose)
8616 (defvar org-log-note-how)
8617 (defvar org-log-note-extra)
8618 (defun org-auto-repeat-maybe (done-word)
8619 "Check if the current headline contains a repeated deadline/schedule.
8620 If yes, set TODO state back to what it was and change the base date
8621 of repeating deadline/scheduled time stamps to new date.
8622 This function is run automatically after each state change to a DONE state."
8623 ;; last-state is dynamically scoped into this function
8624 (let* ((repeat (org-get-repeat))
8625 (aa (assoc last-state org-todo-kwd-alist))
8626 (interpret (nth 1 aa))
8627 (head (nth 2 aa))
8628 (whata '(("d" . day) ("m" . month) ("y" . year)))
8629 (msg "Entry repeats: ")
8630 (org-log-done nil)
8631 (org-todo-log-states nil)
8632 (nshiftmax 10) (nshift 0)
8633 re type n what ts mb0 time)
8634 (when repeat
8635 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8636 (org-todo (if (eq interpret 'type) last-state head))
8637 (when org-log-repeat
8638 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8639 (memq 'org-add-log-note post-command-hook))
8640 ;; OK, we are already setup for some record
8641 (if (eq org-log-repeat 'note)
8642 ;; make sure we take a note, not only a time stamp
8643 (setq org-log-note-how 'note))
8644 ;; Set up for taking a record
8645 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8646 'findpos org-log-repeat)))
8647 (org-back-to-heading t)
8648 (org-add-planning-info nil nil 'closed)
8649 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8650 org-deadline-time-regexp "\\)\\|\\("
8651 org-ts-regexp "\\)"))
8652 (while (re-search-forward
8653 re (save-excursion (outline-next-heading) (point)) t)
8654 (setq type (if (match-end 1) org-scheduled-string
8655 (if (match-end 3) org-deadline-string "Plain:"))
8656 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8657 mb0 (match-beginning 0))
8658 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8659 (setq n (string-to-number (match-string 2 ts))
8660 what (match-string 3 ts))
8661 (if (equal what "w") (setq n (* n 7) what "d"))
8662 ;; Preparation, see if we need to modify the start date for the change
8663 (when (match-end 1)
8664 (setq time (save-match-data (org-time-string-to-time ts)))
8665 (cond
8666 ((equal (match-string 1 ts) ".")
8667 ;; Shift starting date to today
8668 (org-timestamp-change
8669 (- (time-to-days (current-time)) (time-to-days time))
8670 'day))
8671 ((equal (match-string 1 ts) "+")
8672 (while (or (= nshift 0)
8673 (<= (time-to-days time) (time-to-days (current-time))))
8674 (when (= (incf nshift) nshiftmax)
8675 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8676 (error "Abort")))
8677 (org-timestamp-change n (cdr (assoc what whata)))
8678 (org-at-timestamp-p t)
8679 (setq ts (match-string 1))
8680 (setq time (save-match-data (org-time-string-to-time ts))))
8681 (org-timestamp-change (- n) (cdr (assoc what whata)))
8682 ;; rematch, so that we have everything in place for the real shift
8683 (org-at-timestamp-p t)
8684 (setq ts (match-string 1))
8685 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8686 (org-timestamp-change n (cdr (assoc what whata)))
8687 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8688 (setq org-log-post-message msg)
8689 (message "%s" msg))))
8691 (defun org-show-todo-tree (arg)
8692 "Make a compact tree which shows all headlines marked with TODO.
8693 The tree will show the lines where the regexp matches, and all higher
8694 headlines above the match.
8695 With a \\[universal-argument] prefix, also show the DONE entries.
8696 With a numeric prefix N, construct a sparse tree for the Nth element
8697 of `org-todo-keywords-1'."
8698 (interactive "P")
8699 (let ((case-fold-search nil)
8700 (kwd-re
8701 (cond ((null arg) org-not-done-regexp)
8702 ((equal arg '(4))
8703 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8704 (mapcar 'list org-todo-keywords-1))))
8705 (concat "\\("
8706 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8707 "\\)\\>")))
8708 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8709 (regexp-quote (nth (1- (prefix-numeric-value arg))
8710 org-todo-keywords-1)))
8711 (t (error "Invalid prefix argument: %s" arg)))))
8712 (message "%d TODO entries found"
8713 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8715 (defun org-deadline (&optional remove time)
8716 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8717 With argument REMOVE, remove any deadline from the item.
8718 When TIME is set, it should be an internal time specification, and the
8719 scheduling will use the corresponding date."
8720 (interactive "P")
8721 (if remove
8722 (progn
8723 (org-remove-timestamp-with-keyword org-deadline-string)
8724 (message "Item no longer has a deadline."))
8725 (if (org-get-repeat)
8726 (error "Cannot change deadline on task with repeater, please do that by hand")
8727 (org-add-planning-info 'deadline time 'closed)
8728 (message "Deadline on %s" org-last-inserted-timestamp))))
8730 (defun org-schedule (&optional remove time)
8731 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8732 With argument REMOVE, remove any scheduling date from the item.
8733 When TIME is set, it should be an internal time specification, and the
8734 scheduling will use the corresponding date."
8735 (interactive "P")
8736 (if remove
8737 (progn
8738 (org-remove-timestamp-with-keyword org-scheduled-string)
8739 (message "Item is no longer scheduled."))
8740 (if (org-get-repeat)
8741 (error "Cannot reschedule task with repeater, please do that by hand")
8742 (org-add-planning-info 'scheduled time 'closed)
8743 (message "Scheduled to %s" org-last-inserted-timestamp))))
8745 (defun org-remove-timestamp-with-keyword (keyword)
8746 "Remove all time stamps with KEYWORD in the current entry."
8747 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8748 beg)
8749 (save-excursion
8750 (org-back-to-heading t)
8751 (setq beg (point))
8752 (org-end-of-subtree t t)
8753 (while (re-search-backward re beg t)
8754 (replace-match "")
8755 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8756 (equal (char-before) ?\ ))
8757 (backward-delete-char 1)
8758 (if (string-match "^[ \t]*$" (buffer-substring
8759 (point-at-bol) (point-at-eol)))
8760 (delete-region (point-at-bol)
8761 (min (point-max) (1+ (point-at-eol))))))))))
8763 (defun org-add-planning-info (what &optional time &rest remove)
8764 "Insert new timestamp with keyword in the line directly after the headline.
8765 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8766 If non is given, the user is prompted for a date.
8767 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8768 be removed."
8769 (interactive)
8770 (let (org-time-was-given org-end-time-was-given ts
8771 end default-time default-input)
8773 (when (and (not time) (memq what '(scheduled deadline)))
8774 ;; Try to get a default date/time from existing timestamp
8775 (save-excursion
8776 (org-back-to-heading t)
8777 (setq end (save-excursion (outline-next-heading) (point)))
8778 (when (re-search-forward (if (eq what 'scheduled)
8779 org-scheduled-time-regexp
8780 org-deadline-time-regexp)
8781 end t)
8782 (setq ts (match-string 1)
8783 default-time
8784 (apply 'encode-time (org-parse-time-string ts))
8785 default-input (and ts (org-get-compact-tod ts))))))
8786 (when what
8787 ;; If necessary, get the time from the user
8788 (setq time (or time (org-read-date nil 'to-time nil nil
8789 default-time default-input))))
8791 (when (and org-insert-labeled-timestamps-at-point
8792 (member what '(scheduled deadline)))
8793 (insert
8794 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8795 (org-insert-time-stamp time org-time-was-given
8796 nil nil nil (list org-end-time-was-given))
8797 (setq what nil))
8798 (save-excursion
8799 (save-restriction
8800 (let (col list elt ts buffer-invisibility-spec)
8801 (org-back-to-heading t)
8802 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8803 (goto-char (match-end 1))
8804 (setq col (current-column))
8805 (goto-char (match-end 0))
8806 (if (eobp) (insert "\n") (forward-char 1))
8807 (if (and (not (looking-at outline-regexp))
8808 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8809 "[^\r\n]*"))
8810 (not (equal (match-string 1) org-clock-string)))
8811 (narrow-to-region (match-beginning 0) (match-end 0))
8812 (insert-before-markers "\n")
8813 (backward-char 1)
8814 (narrow-to-region (point) (point))
8815 (and org-adapt-indentation (org-indent-to-column col)))
8816 ;; Check if we have to remove something.
8817 (setq list (cons what remove))
8818 (while list
8819 (setq elt (pop list))
8820 (goto-char (point-min))
8821 (when (or (and (eq elt 'scheduled)
8822 (re-search-forward org-scheduled-time-regexp nil t))
8823 (and (eq elt 'deadline)
8824 (re-search-forward org-deadline-time-regexp nil t))
8825 (and (eq elt 'closed)
8826 (re-search-forward org-closed-time-regexp nil t)))
8827 (replace-match "")
8828 (if (looking-at "--+<[^>]+>") (replace-match ""))
8829 (if (looking-at " +") (replace-match ""))))
8830 (goto-char (point-max))
8831 (when what
8832 (insert
8833 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8834 (cond ((eq what 'scheduled) org-scheduled-string)
8835 ((eq what 'deadline) org-deadline-string)
8836 ((eq what 'closed) org-closed-string))
8837 " ")
8838 (setq ts (org-insert-time-stamp
8839 time
8840 (or org-time-was-given
8841 (and (eq what 'closed) org-log-done-with-time))
8842 (eq what 'closed)
8843 nil nil (list org-end-time-was-given)))
8844 (end-of-line 1))
8845 (goto-char (point-min))
8846 (widen)
8847 (if (and (looking-at "[ \t]+\n")
8848 (equal (char-before) ?\n))
8849 (delete-region (1- (point)) (point-at-eol)))
8850 ts)))))
8852 (defvar org-log-note-marker (make-marker))
8853 (defvar org-log-note-purpose nil)
8854 (defvar org-log-note-state nil)
8855 (defvar org-log-note-how nil)
8856 (defvar org-log-note-extra nil)
8857 (defvar org-log-note-window-configuration nil)
8858 (defvar org-log-note-return-to (make-marker))
8859 (defvar org-log-post-message nil
8860 "Message to be displayed after a log note has been stored.
8861 The auto-repeater uses this.")
8863 (defun org-add-note ()
8864 "Add a note to the current entry.
8865 This is done in the same way as adding a state change note."
8866 (interactive)
8867 (org-add-log-setup 'note nil 'findpos nil))
8869 (defvar org-property-end-re)
8870 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8871 "Set up the post command hook to take a note.
8872 If this is about to TODO state change, the new state is expected in STATE.
8873 When FINDPOS is non-nil, find the correct position for the note in
8874 the current entry. If not, assume that it can be inserted at point.
8875 HOW is an indicator what kind of note should be created.
8876 EXTRA is additional text that will be inserted into the notes buffer."
8877 (save-restriction
8878 (save-excursion
8879 (when findpos
8880 (org-back-to-heading t)
8881 (narrow-to-region (point) (save-excursion
8882 (outline-next-heading) (point)))
8883 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8884 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8885 "[^\r\n]*\\)?"))
8886 (goto-char (match-end 0))
8887 (when (and org-log-state-notes-insert-after-drawers
8888 (save-excursion
8889 (forward-line) (looking-at org-drawer-regexp)))
8890 (progn (forward-line)
8891 (while (looking-at org-drawer-regexp)
8892 (goto-char (match-end 0))
8893 (re-search-forward org-property-end-re (point-max) t)
8894 (forward-line))
8895 (forward-line -1)))
8896 (unless org-log-states-order-reversed
8897 (and (= (char-after) ?\n) (forward-char 1))
8898 (org-skip-over-state-notes)
8899 (skip-chars-backward " \t\n\r")))
8900 (move-marker org-log-note-marker (point))
8901 (setq org-log-note-purpose purpose
8902 org-log-note-state state
8903 org-log-note-how how
8904 org-log-note-extra extra)
8905 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8907 (defun org-skip-over-state-notes ()
8908 "Skip past the list of State notes in an entry."
8909 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8910 (while (looking-at "[ \t]*- State")
8911 (condition-case nil
8912 (org-next-item)
8913 (error (org-end-of-item)))))
8915 (defun org-add-log-note (&optional purpose)
8916 "Pop up a window for taking a note, and add this note later at point."
8917 (remove-hook 'post-command-hook 'org-add-log-note)
8918 (setq org-log-note-window-configuration (current-window-configuration))
8919 (delete-other-windows)
8920 (move-marker org-log-note-return-to (point))
8921 (switch-to-buffer (marker-buffer org-log-note-marker))
8922 (goto-char org-log-note-marker)
8923 (org-switch-to-buffer-other-window "*Org Note*")
8924 (erase-buffer)
8925 (if (memq org-log-note-how '(time state))
8926 (let (current-prefix-arg) (org-store-log-note))
8927 (let ((org-inhibit-startup t)) (org-mode))
8928 (insert (format "# Insert note for %s.
8929 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8930 (cond
8931 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8932 ((eq org-log-note-purpose 'done) "closed todo item")
8933 ((eq org-log-note-purpose 'state)
8934 (format "state change to \"%s\"" org-log-note-state))
8935 ((eq org-log-note-purpose 'note)
8936 "this entry")
8937 (t (error "This should not happen")))))
8938 (if org-log-note-extra (insert org-log-note-extra))
8939 (org-set-local 'org-finish-function 'org-store-log-note)))
8941 (defvar org-note-abort nil) ; dynamically scoped
8942 (defun org-store-log-note ()
8943 "Finish taking a log note, and insert it to where it belongs."
8944 (let ((txt (buffer-string))
8945 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8946 lines ind)
8947 (kill-buffer (current-buffer))
8948 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8949 (setq txt (replace-match "" t t txt)))
8950 (if (string-match "\\s-+\\'" txt)
8951 (setq txt (replace-match "" t t txt)))
8952 (setq lines (org-split-string txt "\n"))
8953 (when (and note (string-match "\\S-" note))
8954 (setq note
8955 (org-replace-escapes
8956 note
8957 (list (cons "%u" (user-login-name))
8958 (cons "%U" user-full-name)
8959 (cons "%t" (format-time-string
8960 (org-time-stamp-format 'long 'inactive)
8961 (current-time)))
8962 (cons "%s" (if org-log-note-state
8963 (concat "\"" org-log-note-state "\"")
8964 "")))))
8965 (if lines (setq note (concat note " \\\\")))
8966 (push note lines))
8967 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8968 (when lines
8969 (save-excursion
8970 (set-buffer (marker-buffer org-log-note-marker))
8971 (save-excursion
8972 (goto-char org-log-note-marker)
8973 (move-marker org-log-note-marker nil)
8974 (end-of-line 1)
8975 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8976 (indent-relative nil)
8977 (insert "- " (pop lines))
8978 (org-indent-line-function)
8979 (beginning-of-line 1)
8980 (looking-at "[ \t]*")
8981 (setq ind (concat (match-string 0) " "))
8982 (end-of-line 1)
8983 (while lines (insert "\n" ind (pop lines)))))))
8984 (set-window-configuration org-log-note-window-configuration)
8985 (with-current-buffer (marker-buffer org-log-note-return-to)
8986 (goto-char org-log-note-return-to))
8987 (move-marker org-log-note-return-to nil)
8988 (and org-log-post-message (message "%s" org-log-post-message)))
8990 (defun org-sparse-tree (&optional arg)
8991 "Create a sparse tree, prompt for the details.
8992 This command can create sparse trees. You first need to select the type
8993 of match used to create the tree:
8995 t Show entries with a specific TODO keyword.
8996 T Show entries selected by a tags match.
8997 p Enter a property name and its value (both with completion on existing
8998 names/values) and show entries with that property.
8999 r Show entries matching a regular expression
9000 d Show deadlines due within `org-deadline-warning-days'."
9001 (interactive "P")
9002 (let (ans kwd value)
9003 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9004 (setq ans (read-char-exclusive))
9005 (cond
9006 ((equal ans ?d)
9007 (call-interactively 'org-check-deadlines))
9008 ((equal ans ?b)
9009 (call-interactively 'org-check-before-date))
9010 ((equal ans ?t)
9011 (org-show-todo-tree '(4)))
9012 ((equal ans ?T)
9013 (call-interactively 'org-tags-sparse-tree))
9014 ((member ans '(?p ?P))
9015 (setq kwd (org-ido-completing-read "Property: "
9016 (mapcar 'list (org-buffer-property-keys))))
9017 (setq value (org-ido-completing-read "Value: "
9018 (mapcar 'list (org-property-values kwd))))
9019 (unless (string-match "\\`{.*}\\'" value)
9020 (setq value (concat "\"" value "\"")))
9021 (org-tags-sparse-tree arg (concat kwd "=" value)))
9022 ((member ans '(?r ?R ?/))
9023 (call-interactively 'org-occur))
9024 (t (error "No such sparse tree command \"%c\"" ans)))))
9026 (defvar org-occur-highlights nil
9027 "List of overlays used for occur matches.")
9028 (make-variable-buffer-local 'org-occur-highlights)
9029 (defvar org-occur-parameters nil
9030 "Parameters of the active org-occur calls.
9031 This is a list, each call to org-occur pushes as cons cell,
9032 containing the regular expression and the callback, onto the list.
9033 The list can contain several entries if `org-occur' has been called
9034 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9035 will only contain one set of parameters. When the highlights are
9036 removed (for example with `C-c C-c', or with the next edit (depending
9037 on `org-remove-highlights-with-change'), this variable is emptied
9038 as well.")
9039 (make-variable-buffer-local 'org-occur-parameters)
9041 (defun org-occur (regexp &optional keep-previous callback)
9042 "Make a compact tree which shows all matches of REGEXP.
9043 The tree will show the lines where the regexp matches, and all higher
9044 headlines above the match. It will also show the heading after the match,
9045 to make sure editing the matching entry is easy.
9046 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9047 call to `org-occur' will be kept, to allow stacking of calls to this
9048 command.
9049 If CALLBACK is non-nil, it is a function which is called to confirm
9050 that the match should indeed be shown."
9051 (interactive "sRegexp: \nP")
9052 (unless keep-previous
9053 (org-remove-occur-highlights nil nil t))
9054 (push (cons regexp callback) org-occur-parameters)
9055 (let ((cnt 0))
9056 (save-excursion
9057 (goto-char (point-min))
9058 (if (or (not keep-previous) ; do not want to keep
9059 (not org-occur-highlights)) ; no previous matches
9060 ;; hide everything
9061 (org-overview))
9062 (while (re-search-forward regexp nil t)
9063 (when (or (not callback)
9064 (save-match-data (funcall callback)))
9065 (setq cnt (1+ cnt))
9066 (when org-highlight-sparse-tree-matches
9067 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9068 (org-show-context 'occur-tree))))
9069 (when org-remove-highlights-with-change
9070 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9071 nil 'local))
9072 (unless org-sparse-tree-open-archived-trees
9073 (org-hide-archived-subtrees (point-min) (point-max)))
9074 (run-hooks 'org-occur-hook)
9075 (if (interactive-p)
9076 (message "%d match(es) for regexp %s" cnt regexp))
9077 cnt))
9079 (defun org-show-context (&optional key)
9080 "Make sure point and context and visible.
9081 How much context is shown depends upon the variables
9082 `org-show-hierarchy-above', `org-show-following-heading'. and
9083 `org-show-siblings'."
9084 (let ((heading-p (org-on-heading-p t))
9085 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9086 (following-p (org-get-alist-option org-show-following-heading key))
9087 (entry-p (org-get-alist-option org-show-entry-below key))
9088 (siblings-p (org-get-alist-option org-show-siblings key)))
9089 (catch 'exit
9090 ;; Show heading or entry text
9091 (if (and heading-p (not entry-p))
9092 (org-flag-heading nil) ; only show the heading
9093 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9094 (org-show-hidden-entry))) ; show entire entry
9095 (when following-p
9096 ;; Show next sibling, or heading below text
9097 (save-excursion
9098 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9099 (org-flag-heading nil))))
9100 (when siblings-p (org-show-siblings))
9101 (when hierarchy-p
9102 ;; show all higher headings, possibly with siblings
9103 (save-excursion
9104 (while (and (condition-case nil
9105 (progn (org-up-heading-all 1) t)
9106 (error nil))
9107 (not (bobp)))
9108 (org-flag-heading nil)
9109 (when siblings-p (org-show-siblings))))))))
9111 (defun org-reveal (&optional siblings)
9112 "Show current entry, hierarchy above it, and the following headline.
9113 This can be used to show a consistent set of context around locations
9114 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9115 not t for the search context.
9117 With optional argument SIBLINGS, on each level of the hierarchy all
9118 siblings are shown. This repairs the tree structure to what it would
9119 look like when opened with hierarchical calls to `org-cycle'."
9120 (interactive "P")
9121 (let ((org-show-hierarchy-above t)
9122 (org-show-following-heading t)
9123 (org-show-siblings (if siblings t org-show-siblings)))
9124 (org-show-context nil)))
9126 (defun org-highlight-new-match (beg end)
9127 "Highlight from BEG to END and mark the highlight is an occur headline."
9128 (let ((ov (org-make-overlay beg end)))
9129 (org-overlay-put ov 'face 'secondary-selection)
9130 (push ov org-occur-highlights)))
9132 (defun org-remove-occur-highlights (&optional beg end noremove)
9133 "Remove the occur highlights from the buffer.
9134 BEG and END are ignored. If NOREMOVE is nil, remove this function
9135 from the `before-change-functions' in the current buffer."
9136 (interactive)
9137 (unless org-inhibit-highlight-removal
9138 (mapc 'org-delete-overlay org-occur-highlights)
9139 (setq org-occur-highlights nil)
9140 (setq org-occur-parameters nil)
9141 (unless noremove
9142 (remove-hook 'before-change-functions
9143 'org-remove-occur-highlights 'local))))
9145 ;;;; Priorities
9147 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9148 "Regular expression matching the priority indicator.")
9150 (defvar org-remove-priority-next-time nil)
9152 (defun org-priority-up ()
9153 "Increase the priority of the current item."
9154 (interactive)
9155 (org-priority 'up))
9157 (defun org-priority-down ()
9158 "Decrease the priority of the current item."
9159 (interactive)
9160 (org-priority 'down))
9162 (defun org-priority (&optional action)
9163 "Change the priority of an item by ARG.
9164 ACTION can be `set', `up', `down', or a character."
9165 (interactive)
9166 (setq action (or action 'set))
9167 (let (current new news have remove)
9168 (save-excursion
9169 (org-back-to-heading)
9170 (if (looking-at org-priority-regexp)
9171 (setq current (string-to-char (match-string 2))
9172 have t)
9173 (setq current org-default-priority))
9174 (cond
9175 ((or (eq action 'set)
9176 (if (featurep 'xemacs) (characterp action) (integerp action)))
9177 (if (not (eq action 'set))
9178 (setq new action)
9179 (message "Priority %c-%c, SPC to remove: "
9180 org-highest-priority org-lowest-priority)
9181 (setq new (read-char-exclusive)))
9182 (if (and (= (upcase org-highest-priority) org-highest-priority)
9183 (= (upcase org-lowest-priority) org-lowest-priority))
9184 (setq new (upcase new)))
9185 (cond ((equal new ?\ ) (setq remove t))
9186 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9187 (error "Priority must be between `%c' and `%c'"
9188 org-highest-priority org-lowest-priority))))
9189 ((eq action 'up)
9190 (if (and (not have) (eq last-command this-command))
9191 (setq new org-lowest-priority)
9192 (setq new (if (and org-priority-start-cycle-with-default (not have))
9193 org-default-priority (1- current)))))
9194 ((eq action 'down)
9195 (if (and (not have) (eq last-command this-command))
9196 (setq new org-highest-priority)
9197 (setq new (if (and org-priority-start-cycle-with-default (not have))
9198 org-default-priority (1+ current)))))
9199 (t (error "Invalid action")))
9200 (if (or (< (upcase new) org-highest-priority)
9201 (> (upcase new) org-lowest-priority))
9202 (setq remove t))
9203 (setq news (format "%c" new))
9204 (if have
9205 (if remove
9206 (replace-match "" t t nil 1)
9207 (replace-match news t t nil 2))
9208 (if remove
9209 (error "No priority cookie found in line")
9210 (looking-at org-todo-line-regexp)
9211 (if (match-end 2)
9212 (progn
9213 (goto-char (match-end 2))
9214 (insert " [#" news "]"))
9215 (goto-char (match-beginning 3))
9216 (insert "[#" news "] ")))))
9217 (org-preserve-lc (org-set-tags nil 'align))
9218 (if remove
9219 (message "Priority removed")
9220 (message "Priority of current item set to %s" news))))
9223 (defun org-get-priority (s)
9224 "Find priority cookie and return priority."
9225 (save-match-data
9226 (if (not (string-match org-priority-regexp s))
9227 (* 1000 (- org-lowest-priority org-default-priority))
9228 (* 1000 (- org-lowest-priority
9229 (string-to-char (match-string 2 s)))))))
9231 ;;;; Tags
9233 (defvar org-agenda-archives-mode)
9234 (defun org-scan-tags (action matcher &optional todo-only)
9235 "Scan headline tags with inheritance and produce output ACTION.
9237 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9238 or `agenda' to produce an entry list for an agenda view. It can also be
9239 a Lisp form or a function that should be called at each matched headline, in
9240 this case the return value is a list of all return values from these calls.
9242 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9243 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9244 only lines with a TODO keyword are included in the output."
9245 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9246 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9247 (org-re
9248 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9249 (props (list 'face 'default
9250 'done-face 'org-done
9251 'undone-face 'default
9252 'mouse-face 'highlight
9253 'org-not-done-regexp org-not-done-regexp
9254 'org-todo-regexp org-todo-regexp
9255 'keymap org-agenda-keymap
9256 'help-echo
9257 (format "mouse-2 or RET jump to org file %s"
9258 (abbreviate-file-name
9259 (or (buffer-file-name (buffer-base-buffer))
9260 (buffer-name (buffer-base-buffer)))))))
9261 (case-fold-search nil)
9262 lspos tags tags-list
9263 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9264 (llast 0) rtn rtn1 level category i txt
9265 todo marker entry priority)
9266 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9267 (setq action (list 'lambda nil action)))
9268 (save-excursion
9269 (goto-char (point-min))
9270 (when (eq action 'sparse-tree)
9271 (org-overview)
9272 (org-remove-occur-highlights))
9273 (while (re-search-forward re nil t)
9274 (catch :skip
9275 (setq todo (if (match-end 1) (match-string 2))
9276 tags (if (match-end 4) (match-string 4)))
9277 (goto-char (setq lspos (1+ (match-beginning 0))))
9278 (setq level (org-reduced-level (funcall outline-level))
9279 category (org-get-category))
9280 (setq i llast llast level)
9281 ;; remove tag lists from same and sublevels
9282 (while (>= i level)
9283 (when (setq entry (assoc i tags-alist))
9284 (setq tags-alist (delete entry tags-alist)))
9285 (setq i (1- i)))
9286 ;; add the next tags
9287 (when tags
9288 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9289 tags-alist
9290 (cons (cons level tags) tags-alist)))
9291 ;; compile tags for current headline
9292 (setq tags-list
9293 (if org-use-tag-inheritance
9294 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9295 tags))
9296 (when org-use-tag-inheritance
9297 (setcdr (car tags-alist)
9298 (mapcar (lambda (x)
9299 (setq x (copy-sequence x))
9300 (org-add-prop-inherited x))
9301 (cdar tags-alist))))
9302 (when (and tags org-use-tag-inheritance
9303 (not (eq t org-use-tag-inheritance)))
9304 ;; selective inheritance, remove uninherited ones
9305 (setcdr (car tags-alist)
9306 (org-remove-uniherited-tags (cdar tags-alist))))
9307 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9308 (let ((case-fold-search t)) (eval matcher))
9310 (not (member org-archive-tag tags-list))
9311 ;; we have an archive tag, should we use this anyway?
9312 (or (not org-agenda-skip-archived-trees)
9313 (and (eq action 'agenda) org-agenda-archives-mode))))
9314 (unless (eq action 'sparse-tree) (org-agenda-skip))
9316 ;; select this headline
9318 (cond
9319 ((eq action 'sparse-tree)
9320 (and org-highlight-sparse-tree-matches
9321 (org-get-heading) (match-end 0)
9322 (org-highlight-new-match
9323 (match-beginning 0) (match-beginning 1)))
9324 (org-show-context 'tags-tree))
9325 ((eq action 'agenda)
9326 (setq txt (org-format-agenda-item
9328 (concat
9329 (if org-tags-match-list-sublevels
9330 (make-string (1- level) ?.) "")
9331 (org-get-heading))
9332 category (org-get-tags-at))
9333 priority (org-get-priority txt))
9334 (goto-char lspos)
9335 (setq marker (org-agenda-new-marker))
9336 (org-add-props txt props
9337 'org-marker marker 'org-hd-marker marker 'org-category category
9338 'priority priority 'type "tagsmatch")
9339 (push txt rtn))
9340 ((functionp action)
9341 (save-excursion
9342 (setq rtn1 (funcall action))
9343 (push rtn1 rtn))
9344 (goto-char (point-at-eol)))
9345 (t (error "Invalid action")))
9347 ;; if we are to skip sublevels, jump to end of subtree
9348 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9349 (when (and (eq action 'sparse-tree)
9350 (not org-sparse-tree-open-archived-trees))
9351 (org-hide-archived-subtrees (point-min) (point-max)))
9352 (nreverse rtn)))
9354 (defun org-remove-uniherited-tags (tags)
9355 "Remove all tags that are not inherited from the list TAGS."
9356 (cond
9357 ((eq org-use-tag-inheritance t)
9358 (if org-tags-exclude-from-inheritance
9359 (org-delete-all org-tags-exclude-from-inheritance tags)
9360 tags))
9361 ((not org-use-tag-inheritance) nil)
9362 ((stringp org-use-tag-inheritance)
9363 (delq nil (mapcar
9364 (lambda (x)
9365 (if (and (string-match org-use-tag-inheritance x)
9366 (not (member x org-tags-exclude-from-inheritance)))
9367 x nil))
9368 tags)))
9369 ((listp org-use-tag-inheritance)
9370 (delq nil (mapcar
9371 (lambda (x)
9372 (if (member x org-use-tag-inheritance) x nil))
9373 tags)))))
9375 (defvar todo-only) ;; dynamically scoped
9377 (defun org-tags-sparse-tree (&optional todo-only match)
9378 "Create a sparse tree according to tags string MATCH.
9379 MATCH can contain positive and negative selection of tags, like
9380 \"+WORK+URGENT-WITHBOSS\".
9381 If optional argument TODO-ONLY is non-nil, only select lines that are
9382 also TODO lines."
9383 (interactive "P")
9384 (org-prepare-agenda-buffers (list (current-buffer)))
9385 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9387 (defvar org-cached-props nil)
9388 (defun org-cached-entry-get (pom property)
9389 (if (or (eq t org-use-property-inheritance)
9390 (and (stringp org-use-property-inheritance)
9391 (string-match org-use-property-inheritance property))
9392 (and (listp org-use-property-inheritance)
9393 (member property org-use-property-inheritance)))
9394 ;; Caching is not possible, check it directly
9395 (org-entry-get pom property 'inherit)
9396 ;; Get all properties, so that we can do complicated checks easily
9397 (cdr (assoc property (or org-cached-props
9398 (setq org-cached-props
9399 (org-entry-properties pom)))))))
9401 (defun org-global-tags-completion-table (&optional files)
9402 "Return the list of all tags in all agenda buffer/files."
9403 (save-excursion
9404 (org-uniquify
9405 (delq nil
9406 (apply 'append
9407 (mapcar
9408 (lambda (file)
9409 (set-buffer (find-file-noselect file))
9410 (append (org-get-buffer-tags)
9411 (mapcar (lambda (x) (if (stringp (car-safe x))
9412 (list (car-safe x)) nil))
9413 org-tag-alist)))
9414 (if (and files (car files))
9415 files
9416 (org-agenda-files))))))))
9418 (defun org-make-tags-matcher (match)
9419 "Create the TAGS//TODO matcher form for the selection string MATCH."
9420 ;; todo-only is scoped dynamically into this function, and the function
9421 ;; may change it if the matcher asks for it.
9422 (unless match
9423 ;; Get a new match request, with completion
9424 (let ((org-last-tags-completion-table
9425 (org-global-tags-completion-table)))
9426 (setq match (org-ido-completing-read
9427 "Match: " 'org-tags-completion-function nil nil nil
9428 'org-tags-history))))
9430 ;; Parse the string and create a lisp form
9431 (let ((match0 match)
9432 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9433 minus tag mm
9434 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9435 orterms term orlist re-p str-p level-p level-op time-p
9436 prop-p pn pv po cat-p gv rest)
9437 (if (string-match "/+" match)
9438 ;; match contains also a todo-matching request
9439 (progn
9440 (setq tagsmatch (substring match 0 (match-beginning 0))
9441 todomatch (substring match (match-end 0)))
9442 (if (string-match "^!" todomatch)
9443 (setq todo-only t todomatch (substring todomatch 1)))
9444 (if (string-match "^\\s-*$" todomatch)
9445 (setq todomatch nil)))
9446 ;; only matching tags
9447 (setq tagsmatch match todomatch nil))
9449 ;; Make the tags matcher
9450 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9451 (setq tagsmatcher t)
9452 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9453 (while (setq term (pop orterms))
9454 (while (and (equal (substring term -1) "\\") orterms)
9455 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9456 (while (string-match re term)
9457 (setq rest (substring term (match-end 0))
9458 minus (and (match-end 1)
9459 (equal (match-string 1 term) "-"))
9460 tag (match-string 2 term)
9461 re-p (equal (string-to-char tag) ?{)
9462 level-p (match-end 4)
9463 prop-p (match-end 5)
9464 mm (cond
9465 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9466 (level-p
9467 (setq level-op (org-op-to-function (match-string 3 term)))
9468 `(,level-op level ,(string-to-number
9469 (match-string 4 term))))
9470 (prop-p
9471 (setq pn (match-string 5 term)
9472 po (match-string 6 term)
9473 pv (match-string 7 term)
9474 cat-p (equal pn "CATEGORY")
9475 re-p (equal (string-to-char pv) ?{)
9476 str-p (equal (string-to-char pv) ?\")
9477 time-p (save-match-data
9478 (string-match "^\"[[<].*[]>]\"$" pv))
9479 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9480 (if time-p (setq pv (org-matcher-time pv)))
9481 (setq po (org-op-to-function po (if time-p 'time str-p)))
9482 (cond
9483 ((equal pn "CATEGORY")
9484 (setq gv '(get-text-property (point) 'org-category)))
9485 ((equal pn "TODO")
9486 (setq gv 'todo))
9488 (setq gv `(org-cached-entry-get nil ,pn))))
9489 (if re-p
9490 (if (eq po 'org<>)
9491 `(not (string-match ,pv (or ,gv "")))
9492 `(string-match ,pv (or ,gv "")))
9493 (if str-p
9494 `(,po (or ,gv "") ,pv)
9495 `(,po (string-to-number (or ,gv ""))
9496 ,(string-to-number pv) ))))
9497 (t `(member ,(downcase tag) tags-list)))
9498 mm (if minus (list 'not mm) mm)
9499 term rest)
9500 (push mm tagsmatcher))
9501 (push (if (> (length tagsmatcher) 1)
9502 (cons 'and tagsmatcher)
9503 (car tagsmatcher))
9504 orlist)
9505 (setq tagsmatcher nil))
9506 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9507 (setq tagsmatcher
9508 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9509 ;; Make the todo matcher
9510 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9511 (setq todomatcher t)
9512 (setq orterms (org-split-string todomatch "|") orlist nil)
9513 (while (setq term (pop orterms))
9514 (while (string-match re term)
9515 (setq minus (and (match-end 1)
9516 (equal (match-string 1 term) "-"))
9517 kwd (match-string 2 term)
9518 re-p (equal (string-to-char kwd) ?{)
9519 term (substring term (match-end 0))
9520 mm (if re-p
9521 `(string-match ,(substring kwd 1 -1) todo)
9522 (list 'equal 'todo kwd))
9523 mm (if minus (list 'not mm) mm))
9524 (push mm todomatcher))
9525 (push (if (> (length todomatcher) 1)
9526 (cons 'and todomatcher)
9527 (car todomatcher))
9528 orlist)
9529 (setq todomatcher nil))
9530 (setq todomatcher (if (> (length orlist) 1)
9531 (cons 'or orlist) (car orlist))))
9533 ;; Return the string and lisp forms of the matcher
9534 (setq matcher (if todomatcher
9535 (list 'and tagsmatcher todomatcher)
9536 tagsmatcher))
9537 (cons match0 matcher)))
9539 (defun org-op-to-function (op &optional stringp)
9540 "Turn an operator into the appropriate function."
9541 (setq op
9542 (cond
9543 ((equal op "<" ) '(< string< org-time<))
9544 ((equal op ">" ) '(> org-string> org-time>))
9545 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9546 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9547 ((member op '("=" "==")) '(= string= org-time=))
9548 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9549 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9551 (defun org<> (a b) (not (= a b)))
9552 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9553 (defun org-string>= (a b) (not (string< a b)))
9554 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9555 (defun org-string<> (a b) (not (string= a b)))
9556 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9557 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9558 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9559 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9560 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9561 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9562 (defun org-2ft (s)
9563 "Convert S to a floating point time.
9564 If S is already a number, just return it. If it is a string, parse
9565 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9566 (cond
9567 ((numberp s) s)
9568 ((stringp s)
9569 (condition-case nil
9570 (float-time (apply 'encode-time (org-parse-time-string s)))
9571 (error 0.)))
9572 (t 0.)))
9574 (defun org-time-today ()
9575 "Time in seconds today at 0:00.
9576 Returns the float number of seconds since the beginning of the
9577 epoch to the beginning of today (00:00)."
9578 (float-time (apply 'encode-time
9579 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9581 (defun org-matcher-time (s)
9582 "Interpret a time comparison value."
9583 (save-match-data
9584 (cond
9585 ((string= s "<now>") (float-time))
9586 ((string= s "<today>") (org-time-today))
9587 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9588 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9589 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9590 (+ (org-time-today)
9591 (* (string-to-number (match-string 1 s))
9592 (cdr (assoc (match-string 2 s)
9593 '(("d" . 86400.0) ("w" . 604800.0)
9594 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9595 (t (org-2ft s)))))
9597 (defun org-match-any-p (re list)
9598 "Does re match any element of list?"
9599 (setq list (mapcar (lambda (x) (string-match re x)) list))
9600 (delq nil list))
9602 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9603 (defvar org-tags-overlay (org-make-overlay 1 1))
9604 (org-detach-overlay org-tags-overlay)
9606 (defun org-get-local-tags-at (&optional pos)
9607 "Get a list of tags defined in the current headline."
9608 (org-get-tags-at pos 'local))
9610 (defun org-get-local-tags ()
9611 "Get a list of tags defined in the current headline."
9612 (org-get-tags-at nil 'local))
9614 (defun org-get-tags-at (&optional pos local)
9615 "Get a list of all headline tags applicable at POS.
9616 POS defaults to point. If tags are inherited, the list contains
9617 the targets in the same sequence as the headlines appear, i.e.
9618 the tags of the current headline come last.
9619 When LOCAL is non-nil, only return tags from the current headline,
9620 ignore inherited ones."
9621 (interactive)
9622 (let (tags ltags lastpos parent)
9623 (save-excursion
9624 (save-restriction
9625 (widen)
9626 (goto-char (or pos (point)))
9627 (save-match-data
9628 (catch 'done
9629 (condition-case nil
9630 (progn
9631 (org-back-to-heading t)
9632 (while (not (equal lastpos (point)))
9633 (setq lastpos (point))
9634 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9635 (setq ltags (org-split-string
9636 (org-match-string-no-properties 1) ":"))
9637 (when parent
9638 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9639 (setq tags (append
9640 (if parent
9641 (org-remove-uniherited-tags ltags)
9642 ltags)
9643 tags)))
9644 (or org-use-tag-inheritance (throw 'done t))
9645 (if local (throw 'done t))
9646 (org-up-heading-all 1)
9647 (setq parent t)))
9648 (error nil)))))
9649 (append (org-remove-uniherited-tags org-file-tags) tags))))
9651 (defun org-add-prop-inherited (s)
9652 (add-text-properties 0 (length s) '(inherited t) s)
9655 (defun org-toggle-tag (tag &optional onoff)
9656 "Toggle the tag TAG for the current line.
9657 If ONOFF is `on' or `off', don't toggle but set to this state."
9658 (let (res current)
9659 (save-excursion
9660 (org-back-to-heading t)
9661 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9662 (point-at-eol) t)
9663 (progn
9664 (setq current (match-string 1))
9665 (replace-match ""))
9666 (setq current ""))
9667 (setq current (nreverse (org-split-string current ":")))
9668 (cond
9669 ((eq onoff 'on)
9670 (setq res t)
9671 (or (member tag current) (push tag current)))
9672 ((eq onoff 'off)
9673 (or (not (member tag current)) (setq current (delete tag current))))
9674 (t (if (member tag current)
9675 (setq current (delete tag current))
9676 (setq res t)
9677 (push tag current))))
9678 (end-of-line 1)
9679 (if current
9680 (progn
9681 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9682 (org-set-tags nil t))
9683 (delete-horizontal-space))
9684 (run-hooks 'org-after-tags-change-hook))
9685 res))
9687 (defun org-align-tags-here (to-col)
9688 ;; Assumes that this is a headline
9689 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9690 (beginning-of-line 1)
9691 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9692 (< pos (match-beginning 2)))
9693 (progn
9694 (setq tags-l (- (match-end 2) (match-beginning 2)))
9695 (goto-char (match-beginning 1))
9696 (insert " ")
9697 (delete-region (point) (1+ (match-beginning 2)))
9698 (setq ncol (max (1+ (current-column))
9699 (1+ col)
9700 (if (> to-col 0)
9701 to-col
9702 (- (abs to-col) tags-l))))
9703 (setq p (point))
9704 (insert (make-string (- ncol (current-column)) ?\ ))
9705 (setq ncol (current-column))
9706 (when indent-tabs-mode (tabify p (point-at-eol)))
9707 (org-move-to-column (min ncol col) t))
9708 (goto-char pos))))
9710 (defun org-set-tags-command (&optional arg just-align)
9711 "Call the set-tags command for the current entry."
9712 (interactive "P")
9713 (if (org-on-heading-p)
9714 (org-set-tags arg just-align)
9715 (save-excursion
9716 (org-back-to-heading t)
9717 (org-set-tags arg just-align))))
9719 (defun org-set-tags (&optional arg just-align)
9720 "Set the tags for the current headline.
9721 With prefix ARG, realign all tags in headings in the current buffer."
9722 (interactive "P")
9723 (let* ((re (concat "^" outline-regexp))
9724 (current (org-get-tags-string))
9725 (col (current-column))
9726 (org-setting-tags t)
9727 table current-tags inherited-tags ; computed below when needed
9728 tags p0 c0 c1 rpl)
9729 (if arg
9730 (save-excursion
9731 (goto-char (point-min))
9732 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9733 (while (re-search-forward re nil t)
9734 (org-set-tags nil t)
9735 (end-of-line 1)))
9736 (message "All tags realigned to column %d" org-tags-column))
9737 (if just-align
9738 (setq tags current)
9739 ;; Get a new set of tags from the user
9740 (save-excursion
9741 (setq table (or org-tag-alist (org-get-buffer-tags))
9742 org-last-tags-completion-table table
9743 current-tags (org-split-string current ":")
9744 inherited-tags (nreverse
9745 (nthcdr (length current-tags)
9746 (nreverse (org-get-tags-at))))
9747 tags
9748 (if (or (eq t org-use-fast-tag-selection)
9749 (and org-use-fast-tag-selection
9750 (delq nil (mapcar 'cdr table))))
9751 (org-fast-tag-selection
9752 current-tags inherited-tags table
9753 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9754 (let ((org-add-colon-after-tag-completion t))
9755 (org-trim
9756 (org-without-partial-completion
9757 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9758 nil nil current 'org-tags-history)))))))
9759 (while (string-match "[-+&]+" tags)
9760 ;; No boolean logic, just a list
9761 (setq tags (replace-match ":" t t tags))))
9763 (if (string-match "\\`[\t ]*\\'" tags)
9764 (setq tags "")
9765 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9766 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9768 ;; Insert new tags at the correct column
9769 (beginning-of-line 1)
9770 (cond
9771 ((and (equal current "") (equal tags "")))
9772 ((re-search-forward
9773 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9774 (point-at-eol) t)
9775 (if (equal tags "")
9776 (setq rpl "")
9777 (goto-char (match-beginning 0))
9778 (setq c0 (current-column) p0 (point)
9779 c1 (max (1+ c0) (if (> org-tags-column 0)
9780 org-tags-column
9781 (- (- org-tags-column) (length tags))))
9782 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9783 (replace-match rpl t t)
9784 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9785 tags)
9786 (t (error "Tags alignment failed")))
9787 (org-move-to-column col)
9788 (unless just-align
9789 (run-hooks 'org-after-tags-change-hook)))))
9791 (defun org-change-tag-in-region (beg end tag off)
9792 "Add or remove TAG for each entry in the region.
9793 This works in the agenda, and also in an org-mode buffer."
9794 (interactive
9795 (list (region-beginning) (region-end)
9796 (let ((org-last-tags-completion-table
9797 (if (org-mode-p)
9798 (org-get-buffer-tags)
9799 (org-global-tags-completion-table))))
9800 (org-ido-completing-read
9801 "Tag: " 'org-tags-completion-function nil nil nil
9802 'org-tags-history))
9803 (progn
9804 (message "[s]et or [r]emove? ")
9805 (equal (read-char-exclusive) ?r))))
9806 (if (fboundp 'deactivate-mark) (deactivate-mark))
9807 (let ((agendap (equal major-mode 'org-agenda-mode))
9808 l1 l2 m buf pos newhead (cnt 0))
9809 (goto-char end)
9810 (setq l2 (1- (org-current-line)))
9811 (goto-char beg)
9812 (setq l1 (org-current-line))
9813 (loop for l from l1 to l2 do
9814 (goto-line l)
9815 (setq m (get-text-property (point) 'org-hd-marker))
9816 (when (or (and (org-mode-p) (org-on-heading-p))
9817 (and agendap m))
9818 (setq buf (if agendap (marker-buffer m) (current-buffer))
9819 pos (if agendap m (point)))
9820 (with-current-buffer buf
9821 (save-excursion
9822 (save-restriction
9823 (goto-char pos)
9824 (setq cnt (1+ cnt))
9825 (org-toggle-tag tag (if off 'off 'on))
9826 (setq newhead (org-get-heading)))))
9827 (and agendap (org-agenda-change-all-lines newhead m))))
9828 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9830 (defun org-tags-completion-function (string predicate &optional flag)
9831 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9832 (confirm (lambda (x) (stringp (car x)))))
9833 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9834 (setq s1 (match-string 1 string)
9835 s2 (match-string 2 string))
9836 (setq s1 "" s2 string))
9837 (cond
9838 ((eq flag nil)
9839 ;; try completion
9840 (setq rtn (try-completion s2 ctable confirm))
9841 (if (stringp rtn)
9842 (setq rtn
9843 (concat s1 s2 (substring rtn (length s2))
9844 (if (and org-add-colon-after-tag-completion
9845 (assoc rtn ctable))
9846 ":" ""))))
9847 rtn)
9848 ((eq flag t)
9849 ;; all-completions
9850 (all-completions s2 ctable confirm)
9852 ((eq flag 'lambda)
9853 ;; exact match?
9854 (assoc s2 ctable)))
9857 (defun org-fast-tag-insert (kwd tags face &optional end)
9858 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9859 (insert (format "%-12s" (concat kwd ":"))
9860 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9861 (or end "")))
9863 (defun org-fast-tag-show-exit (flag)
9864 (save-excursion
9865 (goto-line 3)
9866 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9867 (replace-match ""))
9868 (when flag
9869 (end-of-line 1)
9870 (org-move-to-column (- (window-width) 19) t)
9871 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9873 (defun org-set-current-tags-overlay (current prefix)
9874 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9875 (if (featurep 'xemacs)
9876 (org-overlay-display org-tags-overlay (concat prefix s)
9877 'secondary-selection)
9878 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9879 (org-overlay-display org-tags-overlay (concat prefix s)))))
9881 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9882 "Fast tag selection with single keys.
9883 CURRENT is the current list of tags in the headline, INHERITED is the
9884 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9885 possibly with grouping information. TODO-TABLE is a similar table with
9886 TODO keywords, should these have keys assigned to them.
9887 If the keys are nil, a-z are automatically assigned.
9888 Returns the new tags string, or nil to not change the current settings."
9889 (let* ((fulltable (append table todo-table))
9890 (maxlen (apply 'max (mapcar
9891 (lambda (x)
9892 (if (stringp (car x)) (string-width (car x)) 0))
9893 fulltable)))
9894 (buf (current-buffer))
9895 (expert (eq org-fast-tag-selection-single-key 'expert))
9896 (buffer-tags nil)
9897 (fwidth (+ maxlen 3 1 3))
9898 (ncol (/ (- (window-width) 4) fwidth))
9899 (i-face 'org-done)
9900 (c-face 'org-todo)
9901 tg cnt e c char c1 c2 ntable tbl rtn
9902 ov-start ov-end ov-prefix
9903 (exit-after-next org-fast-tag-selection-single-key)
9904 (done-keywords org-done-keywords)
9905 groups ingroup)
9906 (save-excursion
9907 (beginning-of-line 1)
9908 (if (looking-at
9909 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9910 (setq ov-start (match-beginning 1)
9911 ov-end (match-end 1)
9912 ov-prefix "")
9913 (setq ov-start (1- (point-at-eol))
9914 ov-end (1+ ov-start))
9915 (skip-chars-forward "^\n\r")
9916 (setq ov-prefix
9917 (concat
9918 (buffer-substring (1- (point)) (point))
9919 (if (> (current-column) org-tags-column)
9921 (make-string (- org-tags-column (current-column)) ?\ ))))))
9922 (org-move-overlay org-tags-overlay ov-start ov-end)
9923 (save-window-excursion
9924 (if expert
9925 (set-buffer (get-buffer-create " *Org tags*"))
9926 (delete-other-windows)
9927 (split-window-vertically)
9928 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9929 (erase-buffer)
9930 (org-set-local 'org-done-keywords done-keywords)
9931 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9932 (org-fast-tag-insert "Current" current c-face "\n\n")
9933 (org-fast-tag-show-exit exit-after-next)
9934 (org-set-current-tags-overlay current ov-prefix)
9935 (setq tbl fulltable char ?a cnt 0)
9936 (while (setq e (pop tbl))
9937 (cond
9938 ((equal e '(:startgroup))
9939 (push '() groups) (setq ingroup t)
9940 (when (not (= cnt 0))
9941 (setq cnt 0)
9942 (insert "\n"))
9943 (insert "{ "))
9944 ((equal e '(:endgroup))
9945 (setq ingroup nil cnt 0)
9946 (insert "}\n"))
9948 (setq tg (car e) c2 nil)
9949 (if (cdr e)
9950 (setq c (cdr e))
9951 ;; automatically assign a character.
9952 (setq c1 (string-to-char
9953 (downcase (substring
9954 tg (if (= (string-to-char tg) ?@) 1 0)))))
9955 (if (or (rassoc c1 ntable) (rassoc c1 table))
9956 (while (or (rassoc char ntable) (rassoc char table))
9957 (setq char (1+ char)))
9958 (setq c2 c1))
9959 (setq c (or c2 char)))
9960 (if ingroup (push tg (car groups)))
9961 (setq tg (org-add-props tg nil 'face
9962 (cond
9963 ((not (assoc tg table))
9964 (org-get-todo-face tg))
9965 ((member tg current) c-face)
9966 ((member tg inherited) i-face)
9967 (t nil))))
9968 (if (and (= cnt 0) (not ingroup)) (insert " "))
9969 (insert "[" c "] " tg (make-string
9970 (- fwidth 4 (length tg)) ?\ ))
9971 (push (cons tg c) ntable)
9972 (when (= (setq cnt (1+ cnt)) ncol)
9973 (insert "\n")
9974 (if ingroup (insert " "))
9975 (setq cnt 0)))))
9976 (setq ntable (nreverse ntable))
9977 (insert "\n")
9978 (goto-char (point-min))
9979 (if (not expert) (org-fit-window-to-buffer))
9980 (setq rtn
9981 (catch 'exit
9982 (while t
9983 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9984 (if groups " [!] no groups" " [!]groups")
9985 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9986 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9987 (cond
9988 ((= c ?\r) (throw 'exit t))
9989 ((= c ?!)
9990 (setq groups (not groups))
9991 (goto-char (point-min))
9992 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9993 ((= c ?\C-c)
9994 (if (not expert)
9995 (org-fast-tag-show-exit
9996 (setq exit-after-next (not exit-after-next)))
9997 (setq expert nil)
9998 (delete-other-windows)
9999 (split-window-vertically)
10000 (org-switch-to-buffer-other-window " *Org tags*")
10001 (org-fit-window-to-buffer)))
10002 ((or (= c ?\C-g)
10003 (and (= c ?q) (not (rassoc c ntable))))
10004 (org-detach-overlay org-tags-overlay)
10005 (setq quit-flag t))
10006 ((= c ?\ )
10007 (setq current nil)
10008 (if exit-after-next (setq exit-after-next 'now)))
10009 ((= c ?\t)
10010 (condition-case nil
10011 (setq tg (org-ido-completing-read
10012 "Tag: "
10013 (or buffer-tags
10014 (with-current-buffer buf
10015 (org-get-buffer-tags)))))
10016 (quit (setq tg "")))
10017 (when (string-match "\\S-" tg)
10018 (add-to-list 'buffer-tags (list tg))
10019 (if (member tg current)
10020 (setq current (delete tg current))
10021 (push tg current)))
10022 (if exit-after-next (setq exit-after-next 'now)))
10023 ((setq e (rassoc c todo-table) tg (car e))
10024 (with-current-buffer buf
10025 (save-excursion (org-todo tg)))
10026 (if exit-after-next (setq exit-after-next 'now)))
10027 ((setq e (rassoc c ntable) tg (car e))
10028 (if (member tg current)
10029 (setq current (delete tg current))
10030 (loop for g in groups do
10031 (if (member tg g)
10032 (mapc (lambda (x)
10033 (setq current (delete x current)))
10034 g)))
10035 (push tg current))
10036 (if exit-after-next (setq exit-after-next 'now))))
10038 ;; Create a sorted list
10039 (setq current
10040 (sort current
10041 (lambda (a b)
10042 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10043 (if (eq exit-after-next 'now) (throw 'exit t))
10044 (goto-char (point-min))
10045 (beginning-of-line 2)
10046 (delete-region (point) (point-at-eol))
10047 (org-fast-tag-insert "Current" current c-face)
10048 (org-set-current-tags-overlay current ov-prefix)
10049 (while (re-search-forward
10050 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10051 (setq tg (match-string 1))
10052 (add-text-properties
10053 (match-beginning 1) (match-end 1)
10054 (list 'face
10055 (cond
10056 ((member tg current) c-face)
10057 ((member tg inherited) i-face)
10058 (t (get-text-property (match-beginning 1) 'face))))))
10059 (goto-char (point-min)))))
10060 (org-detach-overlay org-tags-overlay)
10061 (if rtn
10062 (mapconcat 'identity current ":")
10063 nil))))
10065 (defun org-get-tags-string ()
10066 "Get the TAGS string in the current headline."
10067 (unless (org-on-heading-p t)
10068 (error "Not on a heading"))
10069 (save-excursion
10070 (beginning-of-line 1)
10071 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10072 (org-match-string-no-properties 1)
10073 "")))
10075 (defun org-get-tags ()
10076 "Get the list of tags specified in the current headline."
10077 (org-split-string (org-get-tags-string) ":"))
10079 (defun org-get-buffer-tags ()
10080 "Get a table of all tags used in the buffer, for completion."
10081 (let (tags)
10082 (save-excursion
10083 (goto-char (point-min))
10084 (while (re-search-forward
10085 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10086 (when (equal (char-after (point-at-bol 0)) ?*)
10087 (mapc (lambda (x) (add-to-list 'tags x))
10088 (org-split-string (org-match-string-no-properties 1) ":")))))
10089 (mapcar 'list tags)))
10091 ;;;; The mapping API
10093 ;;;###autoload
10094 (defun org-map-entries (func &optional match scope &rest skip)
10095 "Call FUNC at each headline selected by MATCH in SCOPE.
10097 FUNC is a function or a lisp form. The function will be called without
10098 arguments, with the cursor positioned at the beginning of the headline.
10099 The return values of all calls to the function will be collected and
10100 returned as a list.
10102 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10103 Only headlines that are matched by this query will be considered during
10104 the iteration. When MATCH is nil or t, all headlines will be
10105 visited by the iteration.
10107 SCOPE determines the scope of this command. It can be any of:
10109 nil The current buffer, respecting the restriction if any
10110 tree The subtree started with the entry at point
10111 file The current buffer, without restriction
10112 file-with-archives
10113 The current buffer, and any archives associated with it
10114 agenda All agenda files
10115 agenda-with-archives
10116 All agenda files with any archive files associated with them
10117 \(file1 file2 ...)
10118 If this is a list, all files in the list will be scanned
10120 The remaining args are treated as settings for the skipping facilities of
10121 the scanner. The following items can be given here:
10123 archive skip trees with the archive tag.
10124 comment skip trees with the COMMENT keyword
10125 function or Emacs Lisp form:
10126 will be used as value for `org-agenda-skip-function', so whenever
10127 the the function returns t, FUNC will not be called for that
10128 entry and search will continue from the point where the
10129 function leaves it."
10130 (let* ((org-agenda-archives-mode nil) ; just to make sure
10131 (org-agenda-skip-archived-trees (memq 'archive skip))
10132 (org-agenda-skip-comment-trees (memq 'comment skip))
10133 (org-agenda-skip-function
10134 (car (org-delete-all '(comment archive) skip)))
10135 (org-tags-match-list-sublevels t)
10136 matcher pos file res
10137 org-todo-keywords-for-agenda
10138 org-done-keywords-for-agenda
10139 org-todo-keyword-alist-for-agenda
10140 org-tag-alist-for-agenda)
10142 (cond
10143 ((eq match t) (setq matcher t))
10144 ((eq match nil) (setq matcher t))
10145 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10147 (when (eq scope 'tree)
10148 (org-back-to-heading t)
10149 (org-narrow-to-subtree)
10150 (setq scope nil))
10152 (if (not scope)
10153 (progn
10154 (org-prepare-agenda-buffers
10155 (list (buffer-file-name (current-buffer))))
10156 (org-scan-tags func matcher))
10157 ;; Get the right scope
10158 (setq pos (point))
10159 (cond
10160 ((and scope (listp scope) (symbolp (car scope)))
10161 (setq scope (eval scope)))
10162 ((eq scope 'agenda)
10163 (setq scope (org-agenda-files t)))
10164 ((eq scope 'agenda-with-archives)
10165 (setq scope (org-agenda-files t))
10166 (setq scope (org-add-archive-files scope)))
10167 ((eq scope 'file)
10168 (setq scope (list (buffer-file-name))))
10169 ((eq scope 'file-with-archives)
10170 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10171 (org-prepare-agenda-buffers scope)
10172 (while (setq file (pop scope))
10173 (with-current-buffer (org-find-base-buffer-visiting file)
10174 (save-excursion
10175 (save-restriction
10176 (widen)
10177 (goto-char (point-min))
10178 (setq res (append res (org-scan-tags func matcher)))))))
10179 res)))
10181 ;;;; Properties
10183 ;;; Setting and retrieving properties
10185 (defconst org-special-properties
10186 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10187 "TIMESTAMP" "TIMESTAMP_IA")
10188 "The special properties valid in Org-mode.
10190 These are properties that are not defined in the property drawer,
10191 but in some other way.")
10193 (defconst org-default-properties
10194 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10195 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10196 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10197 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10198 "Some properties that are used by Org-mode for various purposes.
10199 Being in this list makes sure that they are offered for completion.")
10201 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10202 "Regular expression matching the first line of a property drawer.")
10204 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10205 "Regular expression matching the first line of a property drawer.")
10207 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10208 "Regular expression matching the first line of a property drawer.")
10210 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10211 "Regular expression matching the first line of a property drawer.")
10213 (defconst org-property-drawer-re
10214 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10215 org-property-end-re "\\)\n?")
10216 "Matches an entire property drawer.")
10218 (defconst org-clock-drawer-re
10219 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10220 org-property-end-re "\\)\n?")
10221 "Matches an entire clock drawer.")
10223 (defun org-property-action ()
10224 "Do an action on properties."
10225 (interactive)
10226 (let (c)
10227 (org-at-property-p)
10228 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10229 (setq c (read-char-exclusive))
10230 (cond
10231 ((equal c ?s)
10232 (call-interactively 'org-set-property))
10233 ((equal c ?d)
10234 (call-interactively 'org-delete-property))
10235 ((equal c ?D)
10236 (call-interactively 'org-delete-property-globally))
10237 ((equal c ?c)
10238 (call-interactively 'org-compute-property-at-point))
10239 (t (error "No such property action %c" c)))))
10241 (defun org-at-property-p ()
10242 "Is the cursor in a property line?"
10243 ;; FIXME: Does not check if we are actually in the drawer.
10244 ;; FIXME: also returns true on any drawers.....
10245 ;; This is used by C-c C-c for property action.
10246 (save-excursion
10247 (beginning-of-line 1)
10248 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10250 (defun org-get-property-block (&optional beg end force)
10251 "Return the (beg . end) range of the body of the property drawer.
10252 BEG and END can be beginning and end of subtree, if not given
10253 they will be found.
10254 If the drawer does not exist and FORCE is non-nil, create the drawer."
10255 (catch 'exit
10256 (save-excursion
10257 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10258 (end (or end (progn (outline-next-heading) (point)))))
10259 (goto-char beg)
10260 (if (re-search-forward org-property-start-re end t)
10261 (setq beg (1+ (match-end 0)))
10262 (if force
10263 (save-excursion
10264 (org-insert-property-drawer)
10265 (setq end (progn (outline-next-heading) (point))))
10266 (throw 'exit nil))
10267 (goto-char beg)
10268 (if (re-search-forward org-property-start-re end t)
10269 (setq beg (1+ (match-end 0)))))
10270 (if (re-search-forward org-property-end-re end t)
10271 (setq end (match-beginning 0))
10272 (or force (throw 'exit nil))
10273 (goto-char beg)
10274 (setq end beg)
10275 (org-indent-line-function)
10276 (insert ":END:\n"))
10277 (cons beg end)))))
10279 (defun org-entry-properties (&optional pom which)
10280 "Get all properties of the entry at point-or-marker POM.
10281 This includes the TODO keyword, the tags, time strings for deadline,
10282 scheduled, and clocking, and any additional properties defined in the
10283 entry. The return value is an alist, keys may occur multiple times
10284 if the property key was used several times.
10285 POM may also be nil, in which case the current entry is used.
10286 If WHICH is nil or `all', get all properties. If WHICH is
10287 `special' or `standard', only get that subclass."
10288 (setq which (or which 'all))
10289 (org-with-point-at pom
10290 (let ((clockstr (substring org-clock-string 0 -1))
10291 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10292 beg end range props sum-props key value string clocksum)
10293 (save-excursion
10294 (when (condition-case nil (org-back-to-heading t) (error nil))
10295 (setq beg (point))
10296 (setq sum-props (get-text-property (point) 'org-summaries))
10297 (setq clocksum (get-text-property (point) :org-clock-minutes))
10298 (outline-next-heading)
10299 (setq end (point))
10300 (when (memq which '(all special))
10301 ;; Get the special properties, like TODO and tags
10302 (goto-char beg)
10303 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10304 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10305 (when (looking-at org-priority-regexp)
10306 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10307 (when (and (setq value (org-get-tags-string))
10308 (string-match "\\S-" value))
10309 (push (cons "TAGS" value) props))
10310 (when (setq value (org-get-tags-at))
10311 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10312 props))
10313 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10314 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10315 string (if (equal key clockstr)
10316 (org-no-properties
10317 (org-trim
10318 (buffer-substring
10319 (match-beginning 3) (goto-char (point-at-eol)))))
10320 (substring (org-match-string-no-properties 3) 1 -1)))
10321 (unless key
10322 (if (= (char-after (match-beginning 3)) ?\[)
10323 (setq key "TIMESTAMP_IA")
10324 (setq key "TIMESTAMP")))
10325 (when (or (equal key clockstr) (not (assoc key props)))
10326 (push (cons key string) props)))
10330 (when (memq which '(all standard))
10331 ;; Get the standard properties, like :PORP: ...
10332 (setq range (org-get-property-block beg end))
10333 (when range
10334 (goto-char (car range))
10335 (while (re-search-forward
10336 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10337 (cdr range) t)
10338 (setq key (org-match-string-no-properties 1)
10339 value (org-trim (or (org-match-string-no-properties 2) "")))
10340 (unless (member key excluded)
10341 (push (cons key (or value "")) props)))))
10342 (if clocksum
10343 (push (cons "CLOCKSUM"
10344 (org-columns-number-to-string (/ (float clocksum) 60.)
10345 'add_times))
10346 props))
10347 (unless (assoc "CATEGORY" props)
10348 (setq value (or (org-get-category)
10349 (progn (org-refresh-category-properties)
10350 (org-get-category))))
10351 (push (cons "CATEGORY" value) props))
10352 (append sum-props (nreverse props)))))))
10354 (defun org-entry-get (pom property &optional inherit)
10355 "Get value of PROPERTY for entry at point-or-marker POM.
10356 If INHERIT is non-nil and the entry does not have the property,
10357 then also check higher levels of the hierarchy.
10358 If INHERIT is the symbol `selective', use inheritance only if the setting
10359 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10360 If the property is present but empty, the return value is the empty string.
10361 If the property is not present at all, nil is returned."
10362 (org-with-point-at pom
10363 (if (and inherit (if (eq inherit 'selective)
10364 (org-property-inherit-p property)
10366 (org-entry-get-with-inheritance property)
10367 (if (member property org-special-properties)
10368 ;; We need a special property. Use brute force, get all properties.
10369 (cdr (assoc property (org-entry-properties nil 'special)))
10370 (let ((range (org-get-property-block)))
10371 (if (and range
10372 (goto-char (car range))
10373 (re-search-forward
10374 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10375 (cdr range) t))
10376 ;; Found the property, return it.
10377 (if (match-end 1)
10378 (org-match-string-no-properties 1)
10379 "")))))))
10381 (defun org-property-or-variable-value (var &optional inherit)
10382 "Check if there is a property fixing the value of VAR.
10383 If yes, return this value. If not, return the current value of the variable."
10384 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10385 (if (and prop (stringp prop) (string-match "\\S-" prop))
10386 (read prop)
10387 (symbol-value var))))
10389 (defun org-entry-delete (pom property)
10390 "Delete the property PROPERTY from entry at point-or-marker POM."
10391 (org-with-point-at pom
10392 (if (member property org-special-properties)
10393 nil ; cannot delete these properties.
10394 (let ((range (org-get-property-block)))
10395 (if (and range
10396 (goto-char (car range))
10397 (re-search-forward
10398 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10399 (cdr range) t))
10400 (progn
10401 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10403 nil)))))
10405 ;; Multi-values properties are properties that contain multiple values
10406 ;; These values are assumed to be single words, separated by whitespace.
10407 (defun org-entry-add-to-multivalued-property (pom property value)
10408 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10409 (let* ((old (org-entry-get pom property))
10410 (values (and old (org-split-string old "[ \t]"))))
10411 (setq value (org-entry-protect-space value))
10412 (unless (member value values)
10413 (setq values (cons value values))
10414 (org-entry-put pom property
10415 (mapconcat 'identity values " ")))))
10417 (defun org-entry-remove-from-multivalued-property (pom property value)
10418 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10419 (let* ((old (org-entry-get pom property))
10420 (values (and old (org-split-string old "[ \t]"))))
10421 (setq value (org-entry-protect-space value))
10422 (when (member value values)
10423 (setq values (delete value values))
10424 (org-entry-put pom property
10425 (mapconcat 'identity values " ")))))
10427 (defun org-entry-member-in-multivalued-property (pom property value)
10428 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10429 (let* ((old (org-entry-get pom property))
10430 (values (and old (org-split-string old "[ \t]"))))
10431 (setq value (org-entry-protect-space value))
10432 (member value values)))
10434 (defun org-entry-get-multivalued-property (pom property)
10435 "Return a list of values in a multivalued property."
10436 (let* ((value (org-entry-get pom property))
10437 (values (and value (org-split-string value "[ \t]"))))
10438 (mapcar 'org-entry-restore-space values)))
10440 (defun org-entry-put-multivalued-property (pom property &rest values)
10441 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10442 VALUES should be a list of strings. Spaces will be protected."
10443 (org-entry-put pom property
10444 (mapconcat 'org-entry-protect-space values " "))
10445 (let* ((value (org-entry-get pom property))
10446 (values (and value (org-split-string value "[ \t]"))))
10447 (mapcar 'org-entry-restore-space values)))
10449 (defun org-entry-protect-space (s)
10450 "Protect spaces and newline in string S."
10451 (while (string-match " " s)
10452 (setq s (replace-match "%20" t t s)))
10453 (while (string-match "\n" s)
10454 (setq s (replace-match "%0A" t t s)))
10457 (defun org-entry-restore-space (s)
10458 "Restore spaces and newline in string S."
10459 (while (string-match "%20" s)
10460 (setq s (replace-match " " t t s)))
10461 (while (string-match "%0A" s)
10462 (setq s (replace-match "\n" t t s)))
10465 (defvar org-entry-property-inherited-from (make-marker)
10466 "Marker pointing to the entry from where a property was inherited.
10467 Each call to `org-entry-get-with-inheritance' will set this marker to the
10468 location of the entry where the inheritance search matched. If there was
10469 no match, the marker will point nowhere.
10470 Note that also `org-entry-get' calls this function, if the INHERIT flag
10471 is set.")
10473 (defun org-entry-get-with-inheritance (property)
10474 "Get entry property, and search higher levels if not present."
10475 (move-marker org-entry-property-inherited-from nil)
10476 (let (tmp)
10477 (save-excursion
10478 (save-restriction
10479 (widen)
10480 (catch 'ex
10481 (while t
10482 (when (setq tmp (org-entry-get nil property))
10483 (org-back-to-heading t)
10484 (move-marker org-entry-property-inherited-from (point))
10485 (throw 'ex tmp))
10486 (or (org-up-heading-safe) (throw 'ex nil)))))
10487 (or tmp
10488 (cdr (assoc property org-file-properties))
10489 (cdr (assoc property org-global-properties))
10490 (cdr (assoc property org-global-properties-fixed))))))
10492 (defun org-entry-put (pom property value)
10493 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10494 (org-with-point-at pom
10495 (org-back-to-heading t)
10496 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10497 range)
10498 (cond
10499 ((equal property "TODO")
10500 (when (and (stringp value) (string-match "\\S-" value)
10501 (not (member value org-todo-keywords-1)))
10502 (error "\"%s\" is not a valid TODO state" value))
10503 (if (or (not value)
10504 (not (string-match "\\S-" value)))
10505 (setq value 'none))
10506 (org-todo value)
10507 (org-set-tags nil 'align))
10508 ((equal property "PRIORITY")
10509 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10510 (string-to-char value) ?\ ))
10511 (org-set-tags nil 'align))
10512 ((equal property "SCHEDULED")
10513 (if (re-search-forward org-scheduled-time-regexp end t)
10514 (cond
10515 ((eq value 'earlier) (org-timestamp-change -1 'day))
10516 ((eq value 'later) (org-timestamp-change 1 'day))
10517 (t (call-interactively 'org-schedule)))
10518 (call-interactively 'org-schedule)))
10519 ((equal property "DEADLINE")
10520 (if (re-search-forward org-deadline-time-regexp end t)
10521 (cond
10522 ((eq value 'earlier) (org-timestamp-change -1 'day))
10523 ((eq value 'later) (org-timestamp-change 1 'day))
10524 (t (call-interactively 'org-deadline)))
10525 (call-interactively 'org-deadline)))
10526 ((member property org-special-properties)
10527 (error "The %s property can not yet be set with `org-entry-put'"
10528 property))
10529 (t ; a non-special property
10530 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10531 (setq range (org-get-property-block beg end 'force))
10532 (goto-char (car range))
10533 (if (re-search-forward
10534 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10535 (progn
10536 (delete-region (match-beginning 1) (match-end 1))
10537 (goto-char (match-beginning 1)))
10538 (goto-char (cdr range))
10539 (insert "\n")
10540 (backward-char 1)
10541 (org-indent-line-function)
10542 (insert ":" property ":"))
10543 (and value (insert " " value))
10544 (org-indent-line-function)))))))
10546 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10547 "Get all property keys in the current buffer.
10548 With INCLUDE-SPECIALS, also list the special properties that reflect things
10549 like tags and TODO state.
10550 With INCLUDE-DEFAULTS, also include properties that has special meaning
10551 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10552 With INCLUDE-COLUMNS, also include property names given in COLUMN
10553 formats in the current buffer."
10554 (let (rtn range cfmt cols s p)
10555 (save-excursion
10556 (save-restriction
10557 (widen)
10558 (goto-char (point-min))
10559 (while (re-search-forward org-property-start-re nil t)
10560 (setq range (org-get-property-block))
10561 (goto-char (car range))
10562 (while (re-search-forward
10563 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10564 (cdr range) t)
10565 (add-to-list 'rtn (org-match-string-no-properties 1)))
10566 (outline-next-heading))))
10568 (when include-specials
10569 (setq rtn (append org-special-properties rtn)))
10571 (when include-defaults
10572 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10574 (when include-columns
10575 (save-excursion
10576 (save-restriction
10577 (widen)
10578 (goto-char (point-min))
10579 (while (re-search-forward
10580 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10581 nil t)
10582 (setq cfmt (match-string 2) s 0)
10583 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10584 cfmt s)
10585 (setq s (match-end 0)
10586 p (match-string 1 cfmt))
10587 (unless (or (equal p "ITEM")
10588 (member p org-special-properties))
10589 (add-to-list 'rtn (match-string 1 cfmt))))))))
10591 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10593 (defun org-property-values (key)
10594 "Return a list of all values of property KEY."
10595 (save-excursion
10596 (save-restriction
10597 (widen)
10598 (goto-char (point-min))
10599 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10600 values)
10601 (while (re-search-forward re nil t)
10602 (add-to-list 'values (org-trim (match-string 1))))
10603 (delete "" values)))))
10605 (defun org-insert-property-drawer ()
10606 "Insert a property drawer into the current entry."
10607 (interactive)
10608 (org-back-to-heading t)
10609 (looking-at outline-regexp)
10610 (let ((indent (- (match-end 0)(match-beginning 0)))
10611 (beg (point))
10612 (re (concat "^[ \t]*" org-keyword-time-regexp))
10613 end hiddenp)
10614 (outline-next-heading)
10615 (setq end (point))
10616 (goto-char beg)
10617 (while (re-search-forward re end t))
10618 (setq hiddenp (org-invisible-p))
10619 (end-of-line 1)
10620 (and (equal (char-after) ?\n) (forward-char 1))
10621 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10622 (beginning-of-line 2))
10623 (org-skip-over-state-notes)
10624 (skip-chars-backward " \t\n\r")
10625 (if (eq (char-before) ?*) (forward-char 1))
10626 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10627 (beginning-of-line 0)
10628 (org-indent-to-column indent)
10629 (beginning-of-line 2)
10630 (org-indent-to-column indent)
10631 (beginning-of-line 0)
10632 (if hiddenp
10633 (save-excursion
10634 (org-back-to-heading t)
10635 (hide-entry))
10636 (org-flag-drawer t))))
10638 (defun org-set-property (property value)
10639 "In the current entry, set PROPERTY to VALUE.
10640 When called interactively, this will prompt for a property name, offering
10641 completion on existing and default properties. And then it will prompt
10642 for a value, offering completion either on allowed values (via an inherited
10643 xxx_ALL property) or on existing values in other instances of this property
10644 in the current file."
10645 (interactive
10646 (let* ((completion-ignore-case t)
10647 (keys (org-buffer-property-keys nil t t))
10648 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10649 (prop (if (member prop0 keys)
10650 prop0
10651 (or (cdr (assoc (downcase prop0)
10652 (mapcar (lambda (x) (cons (downcase x) x))
10653 keys)))
10654 prop0)))
10655 (cur (org-entry-get nil prop))
10656 (allowed (org-property-get-allowed-values nil prop 'table))
10657 (existing (mapcar 'list (org-property-values prop)))
10658 (val (if allowed
10659 (org-completing-read "Value: " allowed nil 'req-match)
10660 (org-completing-read
10661 (concat "Value" (if (and cur (string-match "\\S-" cur))
10662 (concat "[" cur "]") "")
10663 ": ")
10664 existing nil nil "" nil cur))))
10665 (list prop (if (equal val "") cur val))))
10666 (unless (equal (org-entry-get nil property) value)
10667 (org-entry-put nil property value)))
10669 (defun org-delete-property (property)
10670 "In the current entry, delete PROPERTY."
10671 (interactive
10672 (let* ((completion-ignore-case t)
10673 (prop (org-ido-completing-read
10674 "Property: " (org-entry-properties nil 'standard))))
10675 (list prop)))
10676 (message "Property %s %s" property
10677 (if (org-entry-delete nil property)
10678 "deleted"
10679 "was not present in the entry")))
10681 (defun org-delete-property-globally (property)
10682 "Remove PROPERTY globally, from all entries."
10683 (interactive
10684 (let* ((completion-ignore-case t)
10685 (prop (org-ido-completing-read
10686 "Globally remove property: "
10687 (mapcar 'list (org-buffer-property-keys)))))
10688 (list prop)))
10689 (save-excursion
10690 (save-restriction
10691 (widen)
10692 (goto-char (point-min))
10693 (let ((cnt 0))
10694 (while (re-search-forward
10695 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10696 nil t)
10697 (setq cnt (1+ cnt))
10698 (replace-match ""))
10699 (message "Property \"%s\" removed from %d entries" property cnt)))))
10701 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10703 (defun org-compute-property-at-point ()
10704 "Compute the property at point.
10705 This looks for an enclosing column format, extracts the operator and
10706 then applies it to the property in the column format's scope."
10707 (interactive)
10708 (unless (org-at-property-p)
10709 (error "Not at a property"))
10710 (let ((prop (org-match-string-no-properties 2)))
10711 (org-columns-get-format-and-top-level)
10712 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10713 (error "No operator defined for property %s" prop))
10714 (org-columns-compute prop)))
10716 (defun org-property-get-allowed-values (pom property &optional table)
10717 "Get allowed values for the property PROPERTY.
10718 When TABLE is non-nil, return an alist that can directly be used for
10719 completion."
10720 (let (vals)
10721 (cond
10722 ((equal property "TODO")
10723 (setq vals (org-with-point-at pom
10724 (append org-todo-keywords-1 '("")))))
10725 ((equal property "PRIORITY")
10726 (let ((n org-lowest-priority))
10727 (while (>= n org-highest-priority)
10728 (push (char-to-string n) vals)
10729 (setq n (1- n)))))
10730 ((member property org-special-properties))
10732 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10734 (when (and vals (string-match "\\S-" vals))
10735 (setq vals (car (read-from-string (concat "(" vals ")"))))
10736 (setq vals (mapcar (lambda (x)
10737 (cond ((stringp x) x)
10738 ((numberp x) (number-to-string x))
10739 ((symbolp x) (symbol-name x))
10740 (t "???")))
10741 vals)))))
10742 (if table (mapcar 'list vals) vals)))
10744 (defun org-property-previous-allowed-value (&optional previous)
10745 "Switch to the next allowed value for this property."
10746 (interactive)
10747 (org-property-next-allowed-value t))
10749 (defun org-property-next-allowed-value (&optional previous)
10750 "Switch to the next allowed value for this property."
10751 (interactive)
10752 (unless (org-at-property-p)
10753 (error "Not at a property"))
10754 (let* ((key (match-string 2))
10755 (value (match-string 3))
10756 (allowed (or (org-property-get-allowed-values (point) key)
10757 (and (member value '("[ ]" "[-]" "[X]"))
10758 '("[ ]" "[X]"))))
10759 nval)
10760 (unless allowed
10761 (error "Allowed values for this property have not been defined"))
10762 (if previous (setq allowed (reverse allowed)))
10763 (if (member value allowed)
10764 (setq nval (car (cdr (member value allowed)))))
10765 (setq nval (or nval (car allowed)))
10766 (if (equal nval value)
10767 (error "Only one allowed value for this property"))
10768 (org-at-property-p)
10769 (replace-match (concat " :" key ": " nval) t t)
10770 (org-indent-line-function)
10771 (beginning-of-line 1)
10772 (skip-chars-forward " \t")))
10774 (defun org-find-entry-with-id (ident)
10775 "Locate the entry that contains the ID property with exact value IDENT.
10776 IDENT can be a string, a symbol or a number, this function will search for
10777 the string representation of it.
10778 Return the position where this entry starts, or nil if there is no such entry."
10779 (interactive "sID: ")
10780 (let ((id (cond
10781 ((stringp ident) ident)
10782 ((symbol-name ident) (symbol-name ident))
10783 ((numberp ident) (number-to-string ident))
10784 (t (error "IDENT %s must be a string, symbol or number" ident))))
10785 (case-fold-search nil))
10786 (save-excursion
10787 (save-restriction
10788 (widen)
10789 (goto-char (point-min))
10790 (when (re-search-forward
10791 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10792 nil t)
10793 (org-back-to-heading)
10794 (point))))))
10796 ;;;; Timestamps
10798 (defvar org-last-changed-timestamp nil)
10799 (defvar org-last-inserted-timestamp nil
10800 "The last time stamp inserted with `org-insert-time-stamp'.")
10801 (defvar org-time-was-given) ; dynamically scoped parameter
10802 (defvar org-end-time-was-given) ; dynamically scoped parameter
10803 (defvar org-ts-what) ; dynamically scoped parameter
10805 (defun org-time-stamp (arg &optional inactive)
10806 "Prompt for a date/time and insert a time stamp.
10807 If the user specifies a time like HH:MM, or if this command is called
10808 with a prefix argument, the time stamp will contain date and time.
10809 Otherwise, only the date will be included. All parts of a date not
10810 specified by the user will be filled in from the current date/time.
10811 So if you press just return without typing anything, the time stamp
10812 will represent the current date/time. If there is already a timestamp
10813 at the cursor, it will be modified."
10814 (interactive "P")
10815 (let* ((ts nil)
10816 (default-time
10817 ;; Default time is either today, or, when entering a range,
10818 ;; the range start.
10819 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10820 (save-excursion
10821 (re-search-backward
10822 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10823 (- (point) 20) t)))
10824 (apply 'encode-time (org-parse-time-string (match-string 1)))
10825 (current-time)))
10826 (default-input (and ts (org-get-compact-tod ts)))
10827 org-time-was-given org-end-time-was-given time)
10828 (cond
10829 ((and (org-at-timestamp-p t)
10830 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10831 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10832 (insert "--")
10833 (setq time (let ((this-command this-command))
10834 (org-read-date arg 'totime nil nil
10835 default-time default-input)))
10836 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10837 ((org-at-timestamp-p t)
10838 (setq time (let ((this-command this-command))
10839 (org-read-date arg 'totime nil nil default-time default-input)))
10840 (when (org-at-timestamp-p t) ; just to get the match data
10841 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10842 (replace-match "")
10843 (setq org-last-changed-timestamp
10844 (org-insert-time-stamp
10845 time (or org-time-was-given arg)
10846 inactive nil nil (list org-end-time-was-given))))
10847 (message "Timestamp updated"))
10849 (setq time (let ((this-command this-command))
10850 (org-read-date arg 'totime nil nil default-time default-input)))
10851 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10852 nil nil (list org-end-time-was-given))))))
10854 ;; FIXME: can we use this for something else, like computing time differences?
10855 (defun org-get-compact-tod (s)
10856 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10857 (let* ((t1 (match-string 1 s))
10858 (h1 (string-to-number (match-string 2 s)))
10859 (m1 (string-to-number (match-string 3 s)))
10860 (t2 (and (match-end 4) (match-string 5 s)))
10861 (h2 (and t2 (string-to-number (match-string 6 s))))
10862 (m2 (and t2 (string-to-number (match-string 7 s))))
10863 dh dm)
10864 (if (not t2)
10866 (setq dh (- h2 h1) dm (- m2 m1))
10867 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10868 (concat t1 "+" (number-to-string dh)
10869 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10871 (defun org-time-stamp-inactive (&optional arg)
10872 "Insert an inactive time stamp.
10873 An inactive time stamp is enclosed in square brackets instead of angle
10874 brackets. It is inactive in the sense that it does not trigger agenda entries,
10875 does not link to the calendar and cannot be changed with the S-cursor keys.
10876 So these are more for recording a certain time/date."
10877 (interactive "P")
10878 (org-time-stamp arg 'inactive))
10880 (defvar org-date-ovl (org-make-overlay 1 1))
10881 (org-overlay-put org-date-ovl 'face 'org-warning)
10882 (org-detach-overlay org-date-ovl)
10884 (defvar org-ans1) ; dynamically scoped parameter
10885 (defvar org-ans2) ; dynamically scoped parameter
10887 (defvar org-plain-time-of-day-regexp) ; defined below
10889 (defvar org-overriding-default-time nil) ; dynamically scoped
10890 (defvar org-read-date-overlay nil)
10891 (defvar org-dcst nil) ; dynamically scoped
10893 (defun org-read-date (&optional with-time to-time from-string prompt
10894 default-time default-input)
10895 "Read a date, possibly a time, and make things smooth for the user.
10896 The prompt will suggest to enter an ISO date, but you can also enter anything
10897 which will at least partially be understood by `parse-time-string'.
10898 Unrecognized parts of the date will default to the current day, month, year,
10899 hour and minute. If this command is called to replace a timestamp at point,
10900 of to enter the second timestamp of a range, the default time is taken from the
10901 existing stamp. For example,
10902 3-2-5 --> 2003-02-05
10903 feb 15 --> currentyear-02-15
10904 sep 12 9 --> 2009-09-12
10905 12:45 --> today 12:45
10906 22 sept 0:34 --> currentyear-09-22 0:34
10907 12 --> currentyear-currentmonth-12
10908 Fri --> nearest Friday (today or later)
10909 etc.
10911 Furthermore you can specify a relative date by giving, as the *first* thing
10912 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10913 change in days weeks, months, years.
10914 With a single plus or minus, the date is relative to today. With a double
10915 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10916 +4d --> four days from today
10917 +4 --> same as above
10918 +2w --> two weeks from today
10919 ++5 --> five days from default date
10921 The function understands only English month and weekday abbreviations,
10922 but this can be configured with the variables `parse-time-months' and
10923 `parse-time-weekdays'.
10925 While prompting, a calendar is popped up - you can also select the
10926 date with the mouse (button 1). The calendar shows a period of three
10927 months. To scroll it to other months, use the keys `>' and `<'.
10928 If you don't like the calendar, turn it off with
10929 \(setq org-read-date-popup-calendar nil)
10931 With optional argument TO-TIME, the date will immediately be converted
10932 to an internal time.
10933 With an optional argument WITH-TIME, the prompt will suggest to also
10934 insert a time. Note that when WITH-TIME is not set, you can still
10935 enter a time, and this function will inform the calling routine about
10936 this change. The calling routine may then choose to change the format
10937 used to insert the time stamp into the buffer to include the time.
10938 With optional argument FROM-STRING, read from this string instead from
10939 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10940 the time/date that is used for everything that is not specified by the
10941 user."
10942 (require 'parse-time)
10943 (let* ((org-time-stamp-rounding-minutes
10944 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10945 (org-dcst org-display-custom-times)
10946 (ct (org-current-time))
10947 (def (or org-overriding-default-time default-time ct))
10948 (defdecode (decode-time def))
10949 (dummy (progn
10950 (when (< (nth 2 defdecode) org-extend-today-until)
10951 (setcar (nthcdr 2 defdecode) -1)
10952 (setcar (nthcdr 1 defdecode) 59)
10953 (setq def (apply 'encode-time defdecode)
10954 defdecode (decode-time def)))))
10955 (calendar-move-hook nil)
10956 (calendar-view-diary-initially-flag nil)
10957 (view-diary-entries-initially nil)
10958 (calendar-view-holidays-initially-flag nil)
10959 (view-calendar-holidays-initially nil)
10960 (timestr (format-time-string
10961 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10962 (prompt (concat (if prompt (concat prompt " ") "")
10963 (format "Date+time [%s]: " timestr)))
10964 ans (org-ans0 "") org-ans1 org-ans2 final)
10966 (cond
10967 (from-string (setq ans from-string))
10968 (org-read-date-popup-calendar
10969 (save-excursion
10970 (save-window-excursion
10971 (calendar)
10972 (calendar-forward-day (- (time-to-days def)
10973 (calendar-absolute-from-gregorian
10974 (calendar-current-date))))
10975 (org-eval-in-calendar nil t)
10976 (let* ((old-map (current-local-map))
10977 (map (copy-keymap calendar-mode-map))
10978 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10979 (org-defkey map (kbd "RET") 'org-calendar-select)
10980 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10981 'org-calendar-select-mouse)
10982 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10983 'org-calendar-select-mouse)
10984 (org-defkey minibuffer-local-map [(meta shift left)]
10985 (lambda () (interactive)
10986 (org-eval-in-calendar '(calendar-backward-month 1))))
10987 (org-defkey minibuffer-local-map [(meta shift right)]
10988 (lambda () (interactive)
10989 (org-eval-in-calendar '(calendar-forward-month 1))))
10990 (org-defkey minibuffer-local-map [(meta shift up)]
10991 (lambda () (interactive)
10992 (org-eval-in-calendar '(calendar-backward-year 1))))
10993 (org-defkey minibuffer-local-map [(meta shift down)]
10994 (lambda () (interactive)
10995 (org-eval-in-calendar '(calendar-forward-year 1))))
10996 (org-defkey minibuffer-local-map [(shift up)]
10997 (lambda () (interactive)
10998 (org-eval-in-calendar '(calendar-backward-week 1))))
10999 (org-defkey minibuffer-local-map [(shift down)]
11000 (lambda () (interactive)
11001 (org-eval-in-calendar '(calendar-forward-week 1))))
11002 (org-defkey minibuffer-local-map [(shift left)]
11003 (lambda () (interactive)
11004 (org-eval-in-calendar '(calendar-backward-day 1))))
11005 (org-defkey minibuffer-local-map [(shift right)]
11006 (lambda () (interactive)
11007 (org-eval-in-calendar '(calendar-forward-day 1))))
11008 (org-defkey minibuffer-local-map ">"
11009 (lambda () (interactive)
11010 (org-eval-in-calendar '(scroll-calendar-left 1))))
11011 (org-defkey minibuffer-local-map "<"
11012 (lambda () (interactive)
11013 (org-eval-in-calendar '(scroll-calendar-right 1))))
11014 (unwind-protect
11015 (progn
11016 (use-local-map map)
11017 (add-hook 'post-command-hook 'org-read-date-display)
11018 (setq org-ans0 (read-string prompt default-input nil nil))
11019 ;; org-ans0: from prompt
11020 ;; org-ans1: from mouse click
11021 ;; org-ans2: from calendar motion
11022 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11023 (remove-hook 'post-command-hook 'org-read-date-display)
11024 (use-local-map old-map)
11025 (when org-read-date-overlay
11026 (org-delete-overlay org-read-date-overlay)
11027 (setq org-read-date-overlay nil)))))))
11029 (t ; Naked prompt only
11030 (unwind-protect
11031 (setq ans (read-string prompt default-input nil timestr))
11032 (when org-read-date-overlay
11033 (org-delete-overlay org-read-date-overlay)
11034 (setq org-read-date-overlay nil)))))
11036 (setq final (org-read-date-analyze ans def defdecode))
11038 (if to-time
11039 (apply 'encode-time final)
11040 (if (and (boundp 'org-time-was-given) org-time-was-given)
11041 (format "%04d-%02d-%02d %02d:%02d"
11042 (nth 5 final) (nth 4 final) (nth 3 final)
11043 (nth 2 final) (nth 1 final))
11044 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11045 (defvar def)
11046 (defvar defdecode)
11047 (defvar with-time)
11048 (defun org-read-date-display ()
11049 "Display the current date prompt interpretation in the minibuffer."
11050 (when org-read-date-display-live
11051 (when org-read-date-overlay
11052 (org-delete-overlay org-read-date-overlay))
11053 (let ((p (point)))
11054 (end-of-line 1)
11055 (while (not (equal (buffer-substring
11056 (max (point-min) (- (point) 4)) (point))
11057 " "))
11058 (insert " "))
11059 (goto-char p))
11060 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11061 " " (or org-ans1 org-ans2)))
11062 (org-end-time-was-given nil)
11063 (f (org-read-date-analyze ans def defdecode))
11064 (fmts (if org-dcst
11065 org-time-stamp-custom-formats
11066 org-time-stamp-formats))
11067 (fmt (if (or with-time
11068 (and (boundp 'org-time-was-given) org-time-was-given))
11069 (cdr fmts)
11070 (car fmts)))
11071 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11072 (when (and org-end-time-was-given
11073 (string-match org-plain-time-of-day-regexp txt))
11074 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11075 org-end-time-was-given
11076 (substring txt (match-end 0)))))
11077 (setq org-read-date-overlay
11078 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11079 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11081 (defun org-read-date-analyze (ans def defdecode)
11082 "Analyse the combined answer of the date prompt."
11083 ;; FIXME: cleanup and comment
11084 (let (delta deltan deltaw deltadef year month day
11085 hour minute second wday pm h2 m2 tl wday1
11086 iso-year iso-weekday iso-week iso-year iso-date)
11088 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11089 (setq ans "+0"))
11091 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11092 (setq ans (replace-match "" t t ans)
11093 deltan (car delta)
11094 deltaw (nth 1 delta)
11095 deltadef (nth 2 delta)))
11097 ;; Check if there is an iso week date in there
11098 ;; If yes, sore the info and postpone interpreting it until the rest
11099 ;; of the parsing is done
11100 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11101 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11102 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11103 iso-week (string-to-number (match-string 2 ans)))
11104 (setq ans (replace-match "" t t ans)))
11106 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11107 (when (string-match
11108 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11109 (setq year (if (match-end 2)
11110 (string-to-number (match-string 2 ans))
11111 (string-to-number (format-time-string "%Y")))
11112 month (string-to-number (match-string 3 ans))
11113 day (string-to-number (match-string 4 ans)))
11114 (if (< year 100) (setq year (+ 2000 year)))
11115 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11116 t nil ans)))
11117 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11118 ;; If there is a time with am/pm, and *no* time without it, we convert
11119 ;; so that matching will be successful.
11120 (loop for i from 1 to 2 do ; twice, for end time as well
11121 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11122 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11123 (setq hour (string-to-number (match-string 1 ans))
11124 minute (if (match-end 3)
11125 (string-to-number (match-string 3 ans))
11127 pm (equal ?p
11128 (string-to-char (downcase (match-string 4 ans)))))
11129 (if (and (= hour 12) (not pm))
11130 (setq hour 0)
11131 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11132 (setq ans (replace-match (format "%02d:%02d" hour minute)
11133 t t ans))))
11135 ;; Check if a time range is given as a duration
11136 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11137 (setq hour (string-to-number (match-string 1 ans))
11138 h2 (+ hour (string-to-number (match-string 3 ans)))
11139 minute (string-to-number (match-string 2 ans))
11140 m2 (+ minute (if (match-end 5) (string-to-number
11141 (match-string 5 ans))0)))
11142 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11143 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11144 t t ans)))
11146 ;; Check if there is a time range
11147 (when (boundp 'org-end-time-was-given)
11148 (setq org-time-was-given nil)
11149 (when (and (string-match org-plain-time-of-day-regexp ans)
11150 (match-end 8))
11151 (setq org-end-time-was-given (match-string 8 ans))
11152 (setq ans (concat (substring ans 0 (match-beginning 7))
11153 (substring ans (match-end 7))))))
11155 (setq tl (parse-time-string ans)
11156 day (or (nth 3 tl) (nth 3 defdecode))
11157 month (or (nth 4 tl)
11158 (if (and org-read-date-prefer-future
11159 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11160 (1+ (nth 4 defdecode))
11161 (nth 4 defdecode)))
11162 year (or (nth 5 tl)
11163 (if (and org-read-date-prefer-future
11164 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11165 (1+ (nth 5 defdecode))
11166 (nth 5 defdecode)))
11167 hour (or (nth 2 tl) (nth 2 defdecode))
11168 minute (or (nth 1 tl) (nth 1 defdecode))
11169 second (or (nth 0 tl) 0)
11170 wday (nth 6 tl))
11172 ;; Special date definitions below
11173 (cond
11174 (iso-week
11175 ;; There was an iso week
11176 (setq year (or iso-year year)
11177 day (or iso-weekday wday 1)
11178 wday nil ; to make sure that the trigger below does not match
11179 iso-date (calendar-gregorian-from-absolute
11180 (calendar-absolute-from-iso
11181 (list iso-week day year))))
11182 ; FIXME: Should we also push ISO weeks into the future?
11183 ; (when (and org-read-date-prefer-future
11184 ; (not iso-year)
11185 ; (< (calendar-absolute-from-gregorian iso-date)
11186 ; (time-to-days (current-time))))
11187 ; (setq year (1+ year)
11188 ; iso-date (calendar-gregorian-from-absolute
11189 ; (calendar-absolute-from-iso
11190 ; (list iso-week day year)))))
11191 (setq month (car iso-date)
11192 year (nth 2 iso-date)
11193 day (nth 1 iso-date)))
11194 (deltan
11195 (unless deltadef
11196 (let ((now (decode-time (current-time))))
11197 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11198 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11199 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11200 ((equal deltaw "m") (setq month (+ month deltan)))
11201 ((equal deltaw "y") (setq year (+ year deltan)))))
11202 ((and wday (not (nth 3 tl)))
11203 ;; Weekday was given, but no day, so pick that day in the week
11204 ;; on or after the derived date.
11205 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11206 (unless (equal wday wday1)
11207 (setq day (+ day (% (- wday wday1 -7) 7))))))
11208 (if (and (boundp 'org-time-was-given)
11209 (nth 2 tl))
11210 (setq org-time-was-given t))
11211 (if (< year 100) (setq year (+ 2000 year)))
11212 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11213 (list second minute hour day month year)))
11215 (defvar parse-time-weekdays)
11217 (defun org-read-date-get-relative (s today default)
11218 "Check string S for special relative date string.
11219 TODAY and DEFAULT are internal times, for today and for a default.
11220 Return shift list (N what def-flag)
11221 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11222 N is the number of WHATs to shift.
11223 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11224 the DEFAULT date rather than TODAY."
11225 (when (and
11226 (string-match
11227 (concat
11228 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11229 "\\([0-9]+\\)?"
11230 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11231 "\\([ \t]\\|$\\)") s)
11232 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11233 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11234 (string-to-char (substring (match-string 1 s) -1))
11235 ?+))
11236 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11237 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11238 (what (if (match-end 3) (match-string 3 s) "d"))
11239 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11240 (date (if rel default today))
11241 (wday (nth 6 (decode-time date)))
11242 delta)
11243 (if wday1
11244 (progn
11245 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11246 (if (= dir ?-) (setq delta (- delta 7)))
11247 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11248 (list delta "d" rel))
11249 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11251 (defun org-eval-in-calendar (form &optional keepdate)
11252 "Eval FORM in the calendar window and return to current window.
11253 Also, store the cursor date in variable org-ans2."
11254 (let ((sw (selected-window)))
11255 (select-window (get-buffer-window "*Calendar*"))
11256 (eval form)
11257 (when (and (not keepdate) (calendar-cursor-to-date))
11258 (let* ((date (calendar-cursor-to-date))
11259 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11260 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11261 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11262 (select-window sw)))
11264 (defun org-calendar-select ()
11265 "Return to `org-read-date' with the date currently selected.
11266 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11267 (interactive)
11268 (when (calendar-cursor-to-date)
11269 (let* ((date (calendar-cursor-to-date))
11270 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11271 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11272 (if (active-minibuffer-window) (exit-minibuffer))))
11274 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11275 "Insert a date stamp for the date given by the internal TIME.
11276 WITH-HM means, use the stamp format that includes the time of the day.
11277 INACTIVE means use square brackets instead of angular ones, so that the
11278 stamp will not contribute to the agenda.
11279 PRE and POST are optional strings to be inserted before and after the
11280 stamp.
11281 The command returns the inserted time stamp."
11282 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11283 stamp)
11284 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11285 (insert-before-markers (or pre ""))
11286 (insert-before-markers (setq stamp (format-time-string fmt time)))
11287 (when (listp extra)
11288 (setq extra (car extra))
11289 (if (and (stringp extra)
11290 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11291 (setq extra (format "-%02d:%02d"
11292 (string-to-number (match-string 1 extra))
11293 (string-to-number (match-string 2 extra))))
11294 (setq extra nil)))
11295 (when extra
11296 (backward-char 1)
11297 (insert-before-markers extra)
11298 (forward-char 1))
11299 (insert-before-markers (or post ""))
11300 (setq org-last-inserted-timestamp stamp)))
11302 (defun org-toggle-time-stamp-overlays ()
11303 "Toggle the use of custom time stamp formats."
11304 (interactive)
11305 (setq org-display-custom-times (not org-display-custom-times))
11306 (unless org-display-custom-times
11307 (let ((p (point-min)) (bmp (buffer-modified-p)))
11308 (while (setq p (next-single-property-change p 'display))
11309 (if (and (get-text-property p 'display)
11310 (eq (get-text-property p 'face) 'org-date))
11311 (remove-text-properties
11312 p (setq p (next-single-property-change p 'display))
11313 '(display t))))
11314 (set-buffer-modified-p bmp)))
11315 (if (featurep 'xemacs)
11316 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11317 (org-restart-font-lock)
11318 (setq org-table-may-need-update t)
11319 (if org-display-custom-times
11320 (message "Time stamps are overlayed with custom format")
11321 (message "Time stamp overlays removed")))
11323 (defun org-display-custom-time (beg end)
11324 "Overlay modified time stamp format over timestamp between BEG and END."
11325 (let* ((ts (buffer-substring beg end))
11326 t1 w1 with-hm tf time str w2 (off 0))
11327 (save-match-data
11328 (setq t1 (org-parse-time-string ts t))
11329 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11330 (setq off (- (match-end 0) (match-beginning 0)))))
11331 (setq end (- end off))
11332 (setq w1 (- end beg)
11333 with-hm (and (nth 1 t1) (nth 2 t1))
11334 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11335 time (org-fix-decoded-time t1)
11336 str (org-add-props
11337 (format-time-string
11338 (substring tf 1 -1) (apply 'encode-time time))
11339 nil 'mouse-face 'highlight)
11340 w2 (length str))
11341 (if (not (= w2 w1))
11342 (add-text-properties (1+ beg) (+ 2 beg)
11343 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11344 (if (featurep 'xemacs)
11345 (progn
11346 (put-text-property beg end 'invisible t)
11347 (put-text-property beg end 'end-glyph (make-glyph str)))
11348 (put-text-property beg end 'display str))))
11350 (defun org-translate-time (string)
11351 "Translate all timestamps in STRING to custom format.
11352 But do this only if the variable `org-display-custom-times' is set."
11353 (when org-display-custom-times
11354 (save-match-data
11355 (let* ((start 0)
11356 (re org-ts-regexp-both)
11357 t1 with-hm inactive tf time str beg end)
11358 (while (setq start (string-match re string start))
11359 (setq beg (match-beginning 0)
11360 end (match-end 0)
11361 t1 (save-match-data
11362 (org-parse-time-string (substring string beg end) t))
11363 with-hm (and (nth 1 t1) (nth 2 t1))
11364 inactive (equal (substring string beg (1+ beg)) "[")
11365 tf (funcall (if with-hm 'cdr 'car)
11366 org-time-stamp-custom-formats)
11367 time (org-fix-decoded-time t1)
11368 str (format-time-string
11369 (concat
11370 (if inactive "[" "<") (substring tf 1 -1)
11371 (if inactive "]" ">"))
11372 (apply 'encode-time time))
11373 string (replace-match str t t string)
11374 start (+ start (length str)))))))
11375 string)
11377 (defun org-fix-decoded-time (time)
11378 "Set 0 instead of nil for the first 6 elements of time.
11379 Don't touch the rest."
11380 (let ((n 0))
11381 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11383 (defun org-days-to-time (timestamp-string)
11384 "Difference between TIMESTAMP-STRING and now in days."
11385 (- (time-to-days (org-time-string-to-time timestamp-string))
11386 (time-to-days (current-time))))
11388 (defun org-deadline-close (timestamp-string &optional ndays)
11389 "Is the time in TIMESTAMP-STRING close to the current date?"
11390 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11391 (and (< (org-days-to-time timestamp-string) ndays)
11392 (not (org-entry-is-done-p))))
11394 (defun org-get-wdays (ts)
11395 "Get the deadline lead time appropriate for timestring TS."
11396 (cond
11397 ((<= org-deadline-warning-days 0)
11398 ;; 0 or negative, enforce this value no matter what
11399 (- org-deadline-warning-days))
11400 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11401 ;; lead time is specified.
11402 (floor (* (string-to-number (match-string 1 ts))
11403 (cdr (assoc (match-string 2 ts)
11404 '(("d" . 1) ("w" . 7)
11405 ("m" . 30.4) ("y" . 365.25)))))))
11406 ;; go for the default.
11407 (t org-deadline-warning-days)))
11409 (defun org-calendar-select-mouse (ev)
11410 "Return to `org-read-date' with the date currently selected.
11411 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11412 (interactive "e")
11413 (mouse-set-point ev)
11414 (when (calendar-cursor-to-date)
11415 (let* ((date (calendar-cursor-to-date))
11416 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11417 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11418 (if (active-minibuffer-window) (exit-minibuffer))))
11420 (defun org-check-deadlines (ndays)
11421 "Check if there are any deadlines due or past due.
11422 A deadline is considered due if it happens within `org-deadline-warning-days'
11423 days from today's date. If the deadline appears in an entry marked DONE,
11424 it is not shown. The prefix arg NDAYS can be used to test that many
11425 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11426 (interactive "P")
11427 (let* ((org-warn-days
11428 (cond
11429 ((equal ndays '(4)) 100000)
11430 (ndays (prefix-numeric-value ndays))
11431 (t (abs org-deadline-warning-days))))
11432 (case-fold-search nil)
11433 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11434 (callback
11435 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11437 (message "%d deadlines past-due or due within %d days"
11438 (org-occur regexp nil callback)
11439 org-warn-days)))
11441 (defun org-check-before-date (date)
11442 "Check if there are deadlines or scheduled entries before DATE."
11443 (interactive (list (org-read-date)))
11444 (let ((case-fold-search nil)
11445 (regexp (concat "\\<\\(" org-deadline-string
11446 "\\|" org-scheduled-string
11447 "\\) *<\\([^>]+\\)>"))
11448 (callback
11449 (lambda () (time-less-p
11450 (org-time-string-to-time (match-string 2))
11451 (org-time-string-to-time date)))))
11452 (message "%d entries before %s"
11453 (org-occur regexp nil callback) date)))
11455 (defun org-evaluate-time-range (&optional to-buffer)
11456 "Evaluate a time range by computing the difference between start and end.
11457 Normally the result is just printed in the echo area, but with prefix arg
11458 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11459 If the time range is actually in a table, the result is inserted into the
11460 next column.
11461 For time difference computation, a year is assumed to be exactly 365
11462 days in order to avoid rounding problems."
11463 (interactive "P")
11465 (org-clock-update-time-maybe)
11466 (save-excursion
11467 (unless (org-at-date-range-p t)
11468 (goto-char (point-at-bol))
11469 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11470 (if (not (org-at-date-range-p t))
11471 (error "Not at a time-stamp range, and none found in current line")))
11472 (let* ((ts1 (match-string 1))
11473 (ts2 (match-string 2))
11474 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11475 (match-end (match-end 0))
11476 (time1 (org-time-string-to-time ts1))
11477 (time2 (org-time-string-to-time ts2))
11478 (t1 (time-to-seconds time1))
11479 (t2 (time-to-seconds time2))
11480 (diff (abs (- t2 t1)))
11481 (negative (< (- t2 t1) 0))
11482 ;; (ys (floor (* 365 24 60 60)))
11483 (ds (* 24 60 60))
11484 (hs (* 60 60))
11485 (fy "%dy %dd %02d:%02d")
11486 (fy1 "%dy %dd")
11487 (fd "%dd %02d:%02d")
11488 (fd1 "%dd")
11489 (fh "%02d:%02d")
11490 y d h m align)
11491 (if havetime
11492 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11494 d (floor (/ diff ds)) diff (mod diff ds)
11495 h (floor (/ diff hs)) diff (mod diff hs)
11496 m (floor (/ diff 60)))
11497 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11499 d (floor (+ (/ diff ds) 0.5))
11500 h 0 m 0))
11501 (if (not to-buffer)
11502 (message "%s" (org-make-tdiff-string y d h m))
11503 (if (org-at-table-p)
11504 (progn
11505 (goto-char match-end)
11506 (setq align t)
11507 (and (looking-at " *|") (goto-char (match-end 0))))
11508 (goto-char match-end))
11509 (if (looking-at
11510 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11511 (replace-match ""))
11512 (if negative (insert " -"))
11513 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11514 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11515 (insert " " (format fh h m))))
11516 (if align (org-table-align))
11517 (message "Time difference inserted")))))
11519 (defun org-make-tdiff-string (y d h m)
11520 (let ((fmt "")
11521 (l nil))
11522 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11523 l (push y l)))
11524 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11525 l (push d l)))
11526 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11527 l (push h l)))
11528 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11529 l (push m l)))
11530 (apply 'format fmt (nreverse l))))
11532 (defun org-time-string-to-time (s)
11533 (apply 'encode-time (org-parse-time-string s)))
11535 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11536 "Convert a time stamp to an absolute day number.
11537 If there is a specifyer for a cyclic time stamp, get the closest date to
11538 DAYNR.
11539 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11540 (cond
11541 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11542 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11543 daynr
11544 (+ daynr 1000)))
11545 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11546 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11547 (time-to-days (current-time))) (match-string 0 s)
11548 prefer show-all))
11549 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11551 (defun org-days-to-iso-week (days)
11552 "Return the iso week number."
11553 (require 'cal-iso)
11554 (car (calendar-iso-from-absolute days)))
11556 (defun org-small-year-to-year (year)
11557 "Convert 2-digit years into 4-digit years.
11558 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11559 The year 2000 cannot be abbreviated. Any year larger than 99
11560 is returned unchanged."
11561 (if (< year 38)
11562 (setq year (+ 2000 year))
11563 (if (< year 100)
11564 (setq year (+ 1900 year))))
11565 year)
11567 (defun org-time-from-absolute (d)
11568 "Return the time corresponding to date D.
11569 D may be an absolute day number, or a calendar-type list (month day year)."
11570 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11571 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11573 (defun org-calendar-holiday ()
11574 "List of holidays, for Diary display in Org-mode."
11575 (require 'holidays)
11576 (let ((hl (funcall
11577 (if (fboundp 'calendar-check-holidays)
11578 'calendar-check-holidays 'check-calendar-holidays) date)))
11579 (if hl (mapconcat 'identity hl "; "))))
11581 (defun org-diary-sexp-entry (sexp entry date)
11582 "Process a SEXP diary ENTRY for DATE."
11583 (require 'diary-lib)
11584 (let ((result (if calendar-debug-sexp
11585 (let ((stack-trace-on-error t))
11586 (eval (car (read-from-string sexp))))
11587 (condition-case nil
11588 (eval (car (read-from-string sexp)))
11589 (error
11590 (beep)
11591 (message "Bad sexp at line %d in %s: %s"
11592 (org-current-line)
11593 (buffer-file-name) sexp)
11594 (sleep-for 2))))))
11595 (cond ((stringp result) result)
11596 ((and (consp result)
11597 (stringp (cdr result))) (cdr result))
11598 (result entry)
11599 (t nil))))
11601 (defun org-diary-to-ical-string (frombuf)
11602 "Get iCalendar entries from diary entries in buffer FROMBUF.
11603 This uses the icalendar.el library."
11604 (let* ((tmpdir (if (featurep 'xemacs)
11605 (temp-directory)
11606 temporary-file-directory))
11607 (tmpfile (make-temp-name
11608 (expand-file-name "orgics" tmpdir)))
11609 buf rtn b e)
11610 (save-excursion
11611 (set-buffer frombuf)
11612 (icalendar-export-region (point-min) (point-max) tmpfile)
11613 (setq buf (find-buffer-visiting tmpfile))
11614 (set-buffer buf)
11615 (goto-char (point-min))
11616 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11617 (setq b (match-beginning 0)))
11618 (goto-char (point-max))
11619 (if (re-search-backward "^END:VEVENT" nil t)
11620 (setq e (match-end 0)))
11621 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11622 (kill-buffer buf)
11623 (delete-file tmpfile)
11624 rtn))
11626 (defun org-closest-date (start current change prefer show-all)
11627 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11628 When PREFER is `past' return a date that is either CURRENT or past.
11629 When PREFER is `future', return a date that is either CURRENT or future.
11630 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11631 ;; Make the proper lists from the dates
11632 (catch 'exit
11633 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11634 dn dw sday cday n1 n2
11635 d m y y1 y2 date1 date2 nmonths nm ny m2)
11637 (setq start (org-date-to-gregorian start)
11638 current (org-date-to-gregorian
11639 (if show-all
11640 current
11641 (time-to-days (current-time))))
11642 sday (calendar-absolute-from-gregorian start)
11643 cday (calendar-absolute-from-gregorian current))
11645 (if (<= cday sday) (throw 'exit sday))
11647 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11648 (setq dn (string-to-number (match-string 1 change))
11649 dw (cdr (assoc (match-string 2 change) a1)))
11650 (error "Invalid change specifyer: %s" change))
11651 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11652 (cond
11653 ((eq dw 'day)
11654 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11655 n2 (+ n1 dn)))
11656 ((eq dw 'year)
11657 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11658 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11659 (setq date1 (list m d y1)
11660 n1 (calendar-absolute-from-gregorian date1)
11661 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11662 n2 (calendar-absolute-from-gregorian date2)))
11663 ((eq dw 'month)
11664 ;; approx number of month between the two dates
11665 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11666 ;; How often does dn fit in there?
11667 (setq d (nth 1 start) m (car start) y (nth 2 start)
11668 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11669 m (+ m nm)
11670 ny (floor (/ m 12))
11671 y (+ y ny)
11672 m (- m (* ny 12)))
11673 (while (> m 12) (setq m (- m 12) y (1+ y)))
11674 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11675 (setq m2 (+ m dn) y2 y)
11676 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11677 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11678 (while (<= n2 cday)
11679 (setq n1 n2 m m2 y y2)
11680 (setq m2 (+ m dn) y2 y)
11681 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11682 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11683 (if show-all
11684 (cond
11685 ((eq prefer 'past) n1)
11686 ((eq prefer 'future) (if (= cday n1) n1 n2))
11687 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11688 (cond
11689 ((eq prefer 'past) n1)
11690 ((eq prefer 'future) (if (= cday n1) n1 n2))
11691 (t (if (= cday n1) n1 n2)))))))
11693 (defun org-date-to-gregorian (date)
11694 "Turn any specification of DATE into a gregorian date for the calendar."
11695 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11696 ((and (listp date) (= (length date) 3)) date)
11697 ((stringp date)
11698 (setq date (org-parse-time-string date))
11699 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11700 ((listp date)
11701 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11703 (defun org-parse-time-string (s &optional nodefault)
11704 "Parse the standard Org-mode time string.
11705 This should be a lot faster than the normal `parse-time-string'.
11706 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11707 hour and minute fields will be nil if not given."
11708 (if (string-match org-ts-regexp0 s)
11709 (list 0
11710 (if (or (match-beginning 8) (not nodefault))
11711 (string-to-number (or (match-string 8 s) "0")))
11712 (if (or (match-beginning 7) (not nodefault))
11713 (string-to-number (or (match-string 7 s) "0")))
11714 (string-to-number (match-string 4 s))
11715 (string-to-number (match-string 3 s))
11716 (string-to-number (match-string 2 s))
11717 nil nil nil)
11718 (make-list 9 0)))
11720 (defun org-timestamp-up (&optional arg)
11721 "Increase the date item at the cursor by one.
11722 If the cursor is on the year, change the year. If it is on the month or
11723 the day, change that.
11724 With prefix ARG, change by that many units."
11725 (interactive "p")
11726 (org-timestamp-change (prefix-numeric-value arg)))
11728 (defun org-timestamp-down (&optional arg)
11729 "Decrease the date item at the cursor by one.
11730 If the cursor is on the year, change the year. If it is on the month or
11731 the day, change that.
11732 With prefix ARG, change by that many units."
11733 (interactive "p")
11734 (org-timestamp-change (- (prefix-numeric-value arg))))
11736 (defun org-timestamp-up-day (&optional arg)
11737 "Increase the date in the time stamp by one day.
11738 With prefix ARG, change that many days."
11739 (interactive "p")
11740 (if (and (not (org-at-timestamp-p t))
11741 (org-on-heading-p))
11742 (org-todo 'up)
11743 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11745 (defun org-timestamp-down-day (&optional arg)
11746 "Decrease the date in the time stamp by one day.
11747 With prefix ARG, change that many days."
11748 (interactive "p")
11749 (if (and (not (org-at-timestamp-p t))
11750 (org-on-heading-p))
11751 (org-todo 'down)
11752 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11754 (defun org-at-timestamp-p (&optional inactive-ok)
11755 "Determine if the cursor is in or at a timestamp."
11756 (interactive)
11757 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11758 (pos (point))
11759 (ans (or (looking-at tsr)
11760 (save-excursion
11761 (skip-chars-backward "^[<\n\r\t")
11762 (if (> (point) (point-min)) (backward-char 1))
11763 (and (looking-at tsr)
11764 (> (- (match-end 0) pos) -1))))))
11765 (and ans
11766 (boundp 'org-ts-what)
11767 (setq org-ts-what
11768 (cond
11769 ((= pos (match-beginning 0)) 'bracket)
11770 ((= pos (1- (match-end 0))) 'bracket)
11771 ((org-pos-in-match-range pos 2) 'year)
11772 ((org-pos-in-match-range pos 3) 'month)
11773 ((org-pos-in-match-range pos 7) 'hour)
11774 ((org-pos-in-match-range pos 8) 'minute)
11775 ((or (org-pos-in-match-range pos 4)
11776 (org-pos-in-match-range pos 5)) 'day)
11777 ((and (> pos (or (match-end 8) (match-end 5)))
11778 (< pos (match-end 0)))
11779 (- pos (or (match-end 8) (match-end 5))))
11780 (t 'day))))
11781 ans))
11783 (defun org-toggle-timestamp-type ()
11784 "Toggle the type (<active> or [inactive]) of a time stamp."
11785 (interactive)
11786 (when (org-at-timestamp-p t)
11787 (let ((beg (match-beginning 0)) (end (match-end 0))
11788 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11789 (save-excursion
11790 (goto-char beg)
11791 (while (re-search-forward "[][<>]" end t)
11792 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11793 t t)))
11794 (message "Timestamp is now %sactive"
11795 (if (equal (char-after beg) ?<) "" "in")))))
11797 (defun org-timestamp-change (n &optional what)
11798 "Change the date in the time stamp at point.
11799 The date will be changed by N times WHAT. WHAT can be `day', `month',
11800 `year', `minute', `second'. If WHAT is not given, the cursor position
11801 in the timestamp determines what will be changed."
11802 (let ((pos (point))
11803 with-hm inactive
11804 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11805 org-ts-what
11806 extra rem
11807 ts time time0)
11808 (if (not (org-at-timestamp-p t))
11809 (error "Not at a timestamp"))
11810 (if (and (not what) (eq org-ts-what 'bracket))
11811 (org-toggle-timestamp-type)
11812 (if (and (not what) (not (eq org-ts-what 'day))
11813 org-display-custom-times
11814 (get-text-property (point) 'display)
11815 (not (get-text-property (1- (point)) 'display)))
11816 (setq org-ts-what 'day))
11817 (setq org-ts-what (or what org-ts-what)
11818 inactive (= (char-after (match-beginning 0)) ?\[)
11819 ts (match-string 0))
11820 (replace-match "")
11821 (if (string-match
11822 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11824 (setq extra (match-string 1 ts)))
11825 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11826 (setq with-hm t))
11827 (setq time0 (org-parse-time-string ts))
11828 (when (and (eq org-ts-what 'minute)
11829 (eq current-prefix-arg nil))
11830 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11831 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11832 (setcar (cdr time0) (+ (nth 1 time0)
11833 (if (> n 0) (- rem) (- dm rem))))))
11834 (setq time
11835 (encode-time (or (car time0) 0)
11836 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11837 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11838 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11839 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11840 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11841 (nthcdr 6 time0)))
11842 (when (integerp org-ts-what)
11843 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11844 (if (eq what 'calendar)
11845 (let ((cal-date (org-get-date-from-calendar)))
11846 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11847 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11848 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11849 (setcar time0 (or (car time0) 0))
11850 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11851 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11852 (setq time (apply 'encode-time time0))))
11853 (setq org-last-changed-timestamp
11854 (org-insert-time-stamp time with-hm inactive nil nil extra))
11855 (org-clock-update-time-maybe)
11856 (goto-char pos)
11857 ;; Try to recenter the calendar window, if any
11858 (if (and org-calendar-follow-timestamp-change
11859 (get-buffer-window "*Calendar*" t)
11860 (memq org-ts-what '(day month year)))
11861 (org-recenter-calendar (time-to-days time))))))
11863 (defun org-modify-ts-extra (s pos n dm)
11864 "Change the different parts of the lead-time and repeat fields in timestamp."
11865 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11866 ng h m new rem)
11867 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11868 (cond
11869 ((or (org-pos-in-match-range pos 2)
11870 (org-pos-in-match-range pos 3))
11871 (setq m (string-to-number (match-string 3 s))
11872 h (string-to-number (match-string 2 s)))
11873 (if (org-pos-in-match-range pos 2)
11874 (setq h (+ h n))
11875 (setq n (* dm (org-no-warnings (signum n))))
11876 (when (not (= 0 (setq rem (% m dm))))
11877 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11878 (setq m (+ m n)))
11879 (if (< m 0) (setq m (+ m 60) h (1- h)))
11880 (if (> m 59) (setq m (- m 60) h (1+ h)))
11881 (setq h (min 24 (max 0 h)))
11882 (setq ng 1 new (format "-%02d:%02d" h m)))
11883 ((org-pos-in-match-range pos 6)
11884 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11885 ((org-pos-in-match-range pos 5)
11886 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11888 ((org-pos-in-match-range pos 9)
11889 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11890 ((org-pos-in-match-range pos 8)
11891 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11893 (when ng
11894 (setq s (concat
11895 (substring s 0 (match-beginning ng))
11897 (substring s (match-end ng))))))
11900 (defun org-recenter-calendar (date)
11901 "If the calendar is visible, recenter it to DATE."
11902 (let* ((win (selected-window))
11903 (cwin (get-buffer-window "*Calendar*" t))
11904 (calendar-move-hook nil))
11905 (when cwin
11906 (select-window cwin)
11907 (calendar-goto-date (if (listp date) date
11908 (calendar-gregorian-from-absolute date)))
11909 (select-window win))))
11911 (defun org-goto-calendar (&optional arg)
11912 "Go to the Emacs calendar at the current date.
11913 If there is a time stamp in the current line, go to that date.
11914 A prefix ARG can be used to force the current date."
11915 (interactive "P")
11916 (let ((tsr org-ts-regexp) diff
11917 (calendar-move-hook nil)
11918 (calendar-view-holidays-initially-flag nil)
11919 (view-calendar-holidays-initially nil)
11920 (calendar-view-diary-initially-flag nil)
11921 (view-diary-entries-initially nil))
11922 (if (or (org-at-timestamp-p)
11923 (save-excursion
11924 (beginning-of-line 1)
11925 (looking-at (concat ".*" tsr))))
11926 (let ((d1 (time-to-days (current-time)))
11927 (d2 (time-to-days
11928 (org-time-string-to-time (match-string 1)))))
11929 (setq diff (- d2 d1))))
11930 (calendar)
11931 (calendar-goto-today)
11932 (if (and diff (not arg)) (calendar-forward-day diff))))
11934 (defun org-get-date-from-calendar ()
11935 "Return a list (month day year) of date at point in calendar."
11936 (with-current-buffer "*Calendar*"
11937 (save-match-data
11938 (calendar-cursor-to-date))))
11940 (defun org-date-from-calendar ()
11941 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11942 If there is already a time stamp at the cursor position, update it."
11943 (interactive)
11944 (if (org-at-timestamp-p t)
11945 (org-timestamp-change 0 'calendar)
11946 (let ((cal-date (org-get-date-from-calendar)))
11947 (org-insert-time-stamp
11948 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11950 (defun org-minutes-to-hh:mm-string (m)
11951 "Compute H:MM from a number of minutes."
11952 (let ((h (/ m 60)))
11953 (setq m (- m (* 60 h)))
11954 (format org-time-clocksum-format h m)))
11956 (defun org-hh:mm-string-to-minutes (s)
11957 "Convert a string H:MM to a number of minutes."
11958 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11959 (+ (* (string-to-number (match-string 1 s)) 60)
11960 (string-to-number (match-string 2 s)))
11963 ;;;; Agenda files
11965 ;;;###autoload
11966 (defun org-iswitchb (&optional arg)
11967 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11968 With a prefix argument, restrict available to files.
11969 With two prefix arguments, restrict available buffers to agenda files.
11971 Due to some yet unresolved reason, the global function
11972 `iswitchb-mode' needs to be active for this function to work."
11973 (interactive "P")
11974 (require 'iswitchb)
11975 (let ((enabled iswitchb-mode) blist)
11976 (or enabled (iswitchb-mode 1))
11977 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11978 ((equal arg '(16)) (org-buffer-list 'agenda))
11979 (t (org-buffer-list))))
11980 (unwind-protect
11981 (let ((iswitchb-make-buflist-hook
11982 (lambda ()
11983 (setq iswitchb-temp-buflist
11984 (mapcar 'buffer-name blist)))))
11985 (switch-to-buffer
11986 (iswitchb-read-buffer
11987 "Switch-to: " nil t))
11988 (or enabled (iswitchb-mode -1))))))
11990 ;;;###autoload
11991 (defun org-ido-switchb (&optional arg)
11992 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
11993 With a prefix argument, restrict available to files.
11994 With two prefix arguments, restrict available buffers to agenda files."
11995 (interactive "P")
11996 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11997 ((equal arg '(16)) (org-buffer-list 'agenda))
11998 (t (org-buffer-list)))))
11999 (switch-to-buffer
12000 (org-ido-completing-read "Org buffer: "
12001 (mapcar 'buffer-name blist)
12002 nil t))))
12004 (defun org-buffer-list (&optional predicate exclude-tmp)
12005 "Return a list of Org buffers.
12006 PREDICATE can be `export', `files' or `agenda'.
12008 export restrict the list to Export buffers.
12009 files restrict the list to buffers visiting Org files.
12010 agenda restrict the list to buffers visiting agenda files.
12012 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12013 (let* ((bfn nil)
12014 (agenda-files (and (eq predicate 'agenda)
12015 (mapcar 'file-truename (org-agenda-files t))))
12016 (filter
12017 (cond
12018 ((eq predicate 'files)
12019 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12020 ((eq predicate 'export)
12021 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12022 ((eq predicate 'agenda)
12023 (lambda (b)
12024 (with-current-buffer b
12025 (and (eq major-mode 'org-mode)
12026 (setq bfn (buffer-file-name b))
12027 (member (file-truename bfn) agenda-files)))))
12028 (t (lambda (b) (with-current-buffer b
12029 (or (eq major-mode 'org-mode)
12030 (string-match "\*Org .*Export"
12031 (buffer-name b)))))))))
12032 (delq nil
12033 (mapcar
12034 (lambda(b)
12035 (if (and (funcall filter b)
12036 (or (not exclude-tmp)
12037 (not (string-match "tmp" (buffer-name b)))))
12039 nil))
12040 (buffer-list)))))
12042 (defun org-agenda-files (&optional unrestricted archives)
12043 "Get the list of agenda files.
12044 Optional UNRESTRICTED means return the full list even if a restriction
12045 is currently in place.
12046 When ARCHIVES is t, include all archive files hat are really being
12047 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12048 `org-agenda-archives-mode' is t."
12049 (let ((files
12050 (cond
12051 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12052 ((stringp org-agenda-files) (org-read-agenda-file-list))
12053 ((listp org-agenda-files) org-agenda-files)
12054 (t (error "Invalid value of `org-agenda-files'")))))
12055 (setq files (apply 'append
12056 (mapcar (lambda (f)
12057 (if (file-directory-p f)
12058 (directory-files
12059 f t org-agenda-file-regexp)
12060 (list f)))
12061 files)))
12062 (when org-agenda-skip-unavailable-files
12063 (setq files (delq nil
12064 (mapcar (function
12065 (lambda (file)
12066 (and (file-readable-p file) file)))
12067 files))))
12068 (when (or (eq archives t)
12069 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12070 (setq files (org-add-archive-files files)))
12071 files))
12073 (defun org-edit-agenda-file-list ()
12074 "Edit the list of agenda files.
12075 Depending on setup, this either uses customize to edit the variable
12076 `org-agenda-files', or it visits the file that is holding the list. In the
12077 latter case, the buffer is set up in a way that saving it automatically kills
12078 the buffer and restores the previous window configuration."
12079 (interactive)
12080 (if (stringp org-agenda-files)
12081 (let ((cw (current-window-configuration)))
12082 (find-file org-agenda-files)
12083 (org-set-local 'org-window-configuration cw)
12084 (org-add-hook 'after-save-hook
12085 (lambda ()
12086 (set-window-configuration
12087 (prog1 org-window-configuration
12088 (kill-buffer (current-buffer))))
12089 (org-install-agenda-files-menu)
12090 (message "New agenda file list installed"))
12091 nil 'local)
12092 (message "%s" (substitute-command-keys
12093 "Edit list and finish with \\[save-buffer]")))
12094 (customize-variable 'org-agenda-files)))
12096 (defun org-store-new-agenda-file-list (list)
12097 "Set new value for the agenda file list and save it correctly."
12098 (if (stringp org-agenda-files)
12099 (let ((f org-agenda-files) b)
12100 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12101 (with-temp-file f
12102 (insert (mapconcat 'identity list "\n") "\n")))
12103 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12104 (setq org-agenda-files list)
12105 (customize-save-variable 'org-agenda-files org-agenda-files))))
12107 (defun org-read-agenda-file-list ()
12108 "Read the list of agenda files from a file."
12109 (when (file-directory-p org-agenda-files)
12110 (error "`org-agenda-files' cannot be a single directory"))
12111 (when (stringp org-agenda-files)
12112 (with-temp-buffer
12113 (insert-file-contents org-agenda-files)
12114 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12117 ;;;###autoload
12118 (defun org-cycle-agenda-files ()
12119 "Cycle through the files in `org-agenda-files'.
12120 If the current buffer visits an agenda file, find the next one in the list.
12121 If the current buffer does not, find the first agenda file."
12122 (interactive)
12123 (let* ((fs (org-agenda-files t))
12124 (files (append fs (list (car fs))))
12125 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12126 file)
12127 (unless files (error "No agenda files"))
12128 (catch 'exit
12129 (while (setq file (pop files))
12130 (if (equal (file-truename file) tcf)
12131 (when (car files)
12132 (find-file (car files))
12133 (throw 'exit t))))
12134 (find-file (car fs)))
12135 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12137 (defun org-agenda-file-to-front (&optional to-end)
12138 "Move/add the current file to the top of the agenda file list.
12139 If the file is not present in the list, it is added to the front. If it is
12140 present, it is moved there. With optional argument TO-END, add/move to the
12141 end of the list."
12142 (interactive "P")
12143 (let ((org-agenda-skip-unavailable-files nil)
12144 (file-alist (mapcar (lambda (x)
12145 (cons (file-truename x) x))
12146 (org-agenda-files t)))
12147 (ctf (file-truename buffer-file-name))
12148 x had)
12149 (setq x (assoc ctf file-alist) had x)
12151 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12152 (if to-end
12153 (setq file-alist (append (delq x file-alist) (list x)))
12154 (setq file-alist (cons x (delq x file-alist))))
12155 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12156 (org-install-agenda-files-menu)
12157 (message "File %s to %s of agenda file list"
12158 (if had "moved" "added") (if to-end "end" "front"))))
12160 (defun org-remove-file (&optional file)
12161 "Remove current file from the list of files in variable `org-agenda-files'.
12162 These are the files which are being checked for agenda entries.
12163 Optional argument FILE means, use this file instead of the current."
12164 (interactive)
12165 (let* ((org-agenda-skip-unavailable-files nil)
12166 (file (or file buffer-file-name))
12167 (true-file (file-truename file))
12168 (afile (abbreviate-file-name file))
12169 (files (delq nil (mapcar
12170 (lambda (x)
12171 (if (equal true-file
12172 (file-truename x))
12173 nil x))
12174 (org-agenda-files t)))))
12175 (if (not (= (length files) (length (org-agenda-files t))))
12176 (progn
12177 (org-store-new-agenda-file-list files)
12178 (org-install-agenda-files-menu)
12179 (message "Removed file: %s" afile))
12180 (message "File was not in list: %s (not removed)" afile))))
12182 (defun org-file-menu-entry (file)
12183 (vector file (list 'find-file file) t))
12185 (defun org-check-agenda-file (file)
12186 "Make sure FILE exists. If not, ask user what to do."
12187 (when (not (file-exists-p file))
12188 (message "non-existent file %s. [R]emove from list or [A]bort?"
12189 (abbreviate-file-name file))
12190 (let ((r (downcase (read-char-exclusive))))
12191 (cond
12192 ((equal r ?r)
12193 (org-remove-file file)
12194 (throw 'nextfile t))
12195 (t (error "Abort"))))))
12197 (defun org-get-agenda-file-buffer (file)
12198 "Get a buffer visiting FILE. If the buffer needs to be created, add
12199 it to the list of buffers which might be released later."
12200 (let ((buf (org-find-base-buffer-visiting file)))
12201 (if buf
12202 buf ; just return it
12203 ;; Make a new buffer and remember it
12204 (setq buf (find-file-noselect file))
12205 (if buf (push buf org-agenda-new-buffers))
12206 buf)))
12208 (defun org-release-buffers (blist)
12209 "Release all buffers in list, asking the user for confirmation when needed.
12210 When a buffer is unmodified, it is just killed. When modified, it is saved
12211 \(if the user agrees) and then killed."
12212 (let (buf file)
12213 (while (setq buf (pop blist))
12214 (setq file (buffer-file-name buf))
12215 (when (and (buffer-modified-p buf)
12216 file
12217 (y-or-n-p (format "Save file %s? " file)))
12218 (with-current-buffer buf (save-buffer)))
12219 (kill-buffer buf))))
12221 (defun org-prepare-agenda-buffers (files)
12222 "Create buffers for all agenda files, protect archived trees and comments."
12223 (interactive)
12224 (let ((pa '(:org-archived t))
12225 (pc '(:org-comment t))
12226 (pall '(:org-archived t :org-comment t))
12227 (inhibit-read-only t)
12228 (rea (concat ":" org-archive-tag ":"))
12229 bmp file re)
12230 (save-excursion
12231 (save-restriction
12232 (while (setq file (pop files))
12233 (if (bufferp file)
12234 (set-buffer file)
12235 (org-check-agenda-file file)
12236 (set-buffer (org-get-agenda-file-buffer file)))
12237 (widen)
12238 (setq bmp (buffer-modified-p))
12239 (org-refresh-category-properties)
12240 (setq org-todo-keywords-for-agenda
12241 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12242 (setq org-done-keywords-for-agenda
12243 (append org-done-keywords-for-agenda org-done-keywords))
12244 (setq org-todo-keyword-alist-for-agenda
12245 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12246 (setq org-tag-alist-for-agenda
12247 (append org-tag-alist-for-agenda org-tag-alist))
12249 (save-excursion
12250 (remove-text-properties (point-min) (point-max) pall)
12251 (when org-agenda-skip-archived-trees
12252 (goto-char (point-min))
12253 (while (re-search-forward rea nil t)
12254 (if (org-on-heading-p t)
12255 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12256 (goto-char (point-min))
12257 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12258 (while (re-search-forward re nil t)
12259 (add-text-properties
12260 (match-beginning 0) (org-end-of-subtree t) pc)))
12261 (set-buffer-modified-p bmp))))
12262 (setq org-todo-keyword-alist-for-agenda
12263 (org-uniquify org-todo-keyword-alist-for-agenda)
12264 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12266 ;;;; Embedded LaTeX
12268 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12269 "Keymap for the minor `org-cdlatex-mode'.")
12271 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12272 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12273 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12274 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12275 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12277 (defvar org-cdlatex-texmathp-advice-is-done nil
12278 "Flag remembering if we have applied the advice to texmathp already.")
12280 (define-minor-mode org-cdlatex-mode
12281 "Toggle the minor `org-cdlatex-mode'.
12282 This mode supports entering LaTeX environment and math in LaTeX fragments
12283 in Org-mode.
12284 \\{org-cdlatex-mode-map}"
12285 nil " OCDL" nil
12286 (when org-cdlatex-mode (require 'cdlatex))
12287 (unless org-cdlatex-texmathp-advice-is-done
12288 (setq org-cdlatex-texmathp-advice-is-done t)
12289 (defadvice texmathp (around org-math-always-on activate)
12290 "Always return t in org-mode buffers.
12291 This is because we want to insert math symbols without dollars even outside
12292 the LaTeX math segments. If Orgmode thinks that point is actually inside
12293 an embedded LaTeX fragment, let texmathp do its job.
12294 \\[org-cdlatex-mode-map]"
12295 (interactive)
12296 (let (p)
12297 (cond
12298 ((not (org-mode-p)) ad-do-it)
12299 ((eq this-command 'cdlatex-math-symbol)
12300 (setq ad-return-value t
12301 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12303 (let ((p (org-inside-LaTeX-fragment-p)))
12304 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12305 (setq ad-return-value t
12306 texmathp-why '("Org-mode embedded math" . 0))
12307 (if p ad-do-it)))))))))
12309 (defun turn-on-org-cdlatex ()
12310 "Unconditionally turn on `org-cdlatex-mode'."
12311 (org-cdlatex-mode 1))
12313 (defun org-inside-LaTeX-fragment-p ()
12314 "Test if point is inside a LaTeX fragment.
12315 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12316 sequence appearing also before point.
12317 Even though the matchers for math are configurable, this function assumes
12318 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12319 delimiters are skipped when they have been removed by customization.
12320 The return value is nil, or a cons cell with the delimiter and
12321 and the position of this delimiter.
12323 This function does a reasonably good job, but can locally be fooled by
12324 for example currency specifications. For example it will assume being in
12325 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12326 fragments that are properly closed, but during editing, we have to live
12327 with the uncertainty caused by missing closing delimiters. This function
12328 looks only before point, not after."
12329 (catch 'exit
12330 (let ((pos (point))
12331 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12332 (lim (progn
12333 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12334 (point)))
12335 dd-on str (start 0) m re)
12336 (goto-char pos)
12337 (when dodollar
12338 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12339 re (nth 1 (assoc "$" org-latex-regexps)))
12340 (while (string-match re str start)
12341 (cond
12342 ((= (match-end 0) (length str))
12343 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12344 ((= (match-end 0) (- (length str) 5))
12345 (throw 'exit nil))
12346 (t (setq start (match-end 0))))))
12347 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12348 (goto-char pos)
12349 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12350 (and (match-beginning 2) (throw 'exit nil))
12351 ;; count $$
12352 (while (re-search-backward "\\$\\$" lim t)
12353 (setq dd-on (not dd-on)))
12354 (goto-char pos)
12355 (if dd-on (cons "$$" m))))))
12358 (defun org-try-cdlatex-tab ()
12359 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12360 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12361 - inside a LaTeX fragment, or
12362 - after the first word in a line, where an abbreviation expansion could
12363 insert a LaTeX environment."
12364 (when org-cdlatex-mode
12365 (cond
12366 ((save-excursion
12367 (skip-chars-backward "a-zA-Z0-9*")
12368 (skip-chars-backward " \t")
12369 (bolp))
12370 (cdlatex-tab) t)
12371 ((org-inside-LaTeX-fragment-p)
12372 (cdlatex-tab) t)
12373 (t nil))))
12375 (defun org-cdlatex-underscore-caret (&optional arg)
12376 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12377 Revert to the normal definition outside of these fragments."
12378 (interactive "P")
12379 (if (org-inside-LaTeX-fragment-p)
12380 (call-interactively 'cdlatex-sub-superscript)
12381 (let (org-cdlatex-mode)
12382 (call-interactively (key-binding (vector last-input-event))))))
12384 (defun org-cdlatex-math-modify (&optional arg)
12385 "Execute `cdlatex-math-modify' in LaTeX fragments.
12386 Revert to the normal definition outside of these fragments."
12387 (interactive "P")
12388 (if (org-inside-LaTeX-fragment-p)
12389 (call-interactively 'cdlatex-math-modify)
12390 (let (org-cdlatex-mode)
12391 (call-interactively (key-binding (vector last-input-event))))))
12393 (defvar org-latex-fragment-image-overlays nil
12394 "List of overlays carrying the images of latex fragments.")
12395 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12397 (defun org-remove-latex-fragment-image-overlays ()
12398 "Remove all overlays with LaTeX fragment images in current buffer."
12399 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12400 (setq org-latex-fragment-image-overlays nil))
12402 (defun org-preview-latex-fragment (&optional subtree)
12403 "Preview the LaTeX fragment at point, or all locally or globally.
12404 If the cursor is in a LaTeX fragment, create the image and overlay
12405 it over the source code. If there is no fragment at point, display
12406 all fragments in the current text, from one headline to the next. With
12407 prefix SUBTREE, display all fragments in the current subtree. With a
12408 double prefix `C-u C-u', or when the cursor is before the first headline,
12409 display all fragments in the buffer.
12410 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12411 (interactive "P")
12412 (org-remove-latex-fragment-image-overlays)
12413 (save-excursion
12414 (save-restriction
12415 (let (beg end at msg)
12416 (cond
12417 ((or (equal subtree '(16))
12418 (not (save-excursion
12419 (re-search-backward (concat "^" outline-regexp) nil t))))
12420 (setq beg (point-min) end (point-max)
12421 msg "Creating images for buffer...%s"))
12422 ((equal subtree '(4))
12423 (org-back-to-heading)
12424 (setq beg (point) end (org-end-of-subtree t)
12425 msg "Creating images for subtree...%s"))
12427 (if (setq at (org-inside-LaTeX-fragment-p))
12428 (goto-char (max (point-min) (- (cdr at) 2)))
12429 (org-back-to-heading))
12430 (setq beg (point) end (progn (outline-next-heading) (point))
12431 msg (if at "Creating image...%s"
12432 "Creating images for entry...%s"))))
12433 (message msg "")
12434 (narrow-to-region beg end)
12435 (goto-char beg)
12436 (org-format-latex
12437 (concat "ltxpng/" (file-name-sans-extension
12438 (file-name-nondirectory
12439 buffer-file-name)))
12440 default-directory 'overlays msg at 'forbuffer)
12441 (message msg "done. Use `C-c C-c' to remove images.")))))
12443 (defvar org-latex-regexps
12444 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12445 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12446 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12447 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12448 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12449 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12450 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12451 "Regular expressions for matching embedded LaTeX.")
12453 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12454 "Replace LaTeX fragments with links to an image, and produce images."
12455 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12456 (let* ((prefixnodir (file-name-nondirectory prefix))
12457 (absprefix (expand-file-name prefix dir))
12458 (todir (file-name-directory absprefix))
12459 (opt org-format-latex-options)
12460 (matchers (plist-get opt :matchers))
12461 (re-list org-latex-regexps)
12462 (cnt 0) txt link beg end re e checkdir
12463 m n block linkfile movefile ov)
12464 ;; Check if there are old images files with this prefix, and remove them
12465 (when (file-directory-p todir)
12466 (mapc 'delete-file
12467 (directory-files
12468 todir 'full
12469 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12470 ;; Check the different regular expressions
12471 (while (setq e (pop re-list))
12472 (setq m (car e) re (nth 1 e) n (nth 2 e)
12473 block (if (nth 3 e) "\n\n" ""))
12474 (when (member m matchers)
12475 (goto-char (point-min))
12476 (while (re-search-forward re nil t)
12477 (when (or (not at) (equal (cdr at) (match-beginning n)))
12478 (setq txt (match-string n)
12479 beg (match-beginning n) end (match-end n)
12480 cnt (1+ cnt)
12481 linkfile (format "%s_%04d.png" prefix cnt)
12482 movefile (format "%s_%04d.png" absprefix cnt)
12483 link (concat block "[[file:" linkfile "]]" block))
12484 (if msg (message msg cnt))
12485 (goto-char beg)
12486 (unless checkdir ; make sure the directory exists
12487 (setq checkdir t)
12488 (or (file-directory-p todir) (make-directory todir)))
12489 (org-create-formula-image
12490 txt movefile opt forbuffer)
12491 (if overlays
12492 (progn
12493 (setq ov (org-make-overlay beg end))
12494 (if (featurep 'xemacs)
12495 (progn
12496 (org-overlay-put ov 'invisible t)
12497 (org-overlay-put
12498 ov 'end-glyph
12499 (make-glyph (vector 'png :file movefile))))
12500 (org-overlay-put
12501 ov 'display
12502 (list 'image :type 'png :file movefile :ascent 'center)))
12503 (push ov org-latex-fragment-image-overlays)
12504 (goto-char end))
12505 (delete-region beg end)
12506 (insert link))))))))
12508 ;; This function borrows from Ganesh Swami's latex2png.el
12509 (defun org-create-formula-image (string tofile options buffer)
12510 (let* ((tmpdir (if (featurep 'xemacs)
12511 (temp-directory)
12512 temporary-file-directory))
12513 (texfilebase (make-temp-name
12514 (expand-file-name "orgtex" tmpdir)))
12515 (texfile (concat texfilebase ".tex"))
12516 (dvifile (concat texfilebase ".dvi"))
12517 (pngfile (concat texfilebase ".png"))
12518 (fnh (if (featurep 'xemacs)
12519 (font-height (get-face-font 'default))
12520 (face-attribute 'default :height nil)))
12521 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12522 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12523 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12524 "Black"))
12525 (bg (or (plist-get options (if buffer :background :html-background))
12526 "Transparent")))
12527 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12528 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12529 (with-temp-file texfile
12530 (insert org-format-latex-header
12531 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12532 (let ((dir default-directory))
12533 (condition-case nil
12534 (progn
12535 (cd tmpdir)
12536 (call-process "latex" nil nil nil texfile))
12537 (error nil))
12538 (cd dir))
12539 (if (not (file-exists-p dvifile))
12540 (progn (message "Failed to create dvi file from %s" texfile) nil)
12541 (condition-case nil
12542 (call-process "dvipng" nil nil nil
12543 "-E" "-fg" fg "-bg" bg
12544 "-D" dpi
12545 ;;"-x" scale "-y" scale
12546 "-T" "tight"
12547 "-o" pngfile
12548 dvifile)
12549 (error nil))
12550 (if (not (file-exists-p pngfile))
12551 (progn (message "Failed to create png file from %s" texfile) nil)
12552 ;; Use the requested file name and clean up
12553 (copy-file pngfile tofile 'replace)
12554 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12555 (delete-file (concat texfilebase e)))
12556 pngfile))))
12558 (defun org-dvipng-color (attr)
12559 "Return an rgb color specification for dvipng."
12560 (apply 'format "rgb %s %s %s"
12561 (mapcar 'org-normalize-color
12562 (color-values (face-attribute 'default attr nil)))))
12564 (defun org-normalize-color (value)
12565 "Return string to be used as color value for an RGB component."
12566 (format "%g" (/ value 65535.0)))
12568 ;;;; Key bindings
12570 ;; Make `C-c C-x' a prefix key
12571 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12573 ;; TAB key with modifiers
12574 (org-defkey org-mode-map "\C-i" 'org-cycle)
12575 (org-defkey org-mode-map [(tab)] 'org-cycle)
12576 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12577 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12578 (org-defkey org-mode-map "\M-\t" 'org-complete)
12579 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12580 ;; The following line is necessary under Suse GNU/Linux
12581 (unless (featurep 'xemacs)
12582 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12583 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12584 (define-key org-mode-map [backtab] 'org-shifttab)
12586 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12587 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12588 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12590 ;; Cursor keys with modifiers
12591 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12592 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12593 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12594 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12596 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12597 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12598 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12599 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12601 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12602 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12603 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12604 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12606 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12607 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12609 ;;; Extra keys for tty access.
12610 ;; We only set them when really needed because otherwise the
12611 ;; menus don't show the simple keys
12613 (when (or org-use-extra-keys
12614 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12615 (not window-system))
12616 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12617 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12618 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12619 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12620 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12621 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12622 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12623 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12624 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12625 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12626 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12627 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12628 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12629 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12630 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12631 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12632 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12633 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12634 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12635 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12636 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12637 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12639 ;; All the other keys
12641 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12642 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12643 (if (boundp 'narrow-map)
12644 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12645 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12646 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12647 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12648 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12649 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12650 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12651 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12652 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12653 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12654 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12655 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12656 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12657 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12658 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12659 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12660 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12661 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12662 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12663 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12664 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12665 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12666 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12667 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12668 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12669 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12670 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12671 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12672 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12673 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12674 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12675 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12676 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12677 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12678 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12679 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12680 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12681 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12682 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12683 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12684 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12685 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12686 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12687 (org-defkey org-mode-map "\C-c^" 'org-sort)
12688 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12689 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12690 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12691 (org-defkey org-mode-map "\C-m" 'org-return)
12692 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12693 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12694 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12695 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12696 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12697 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12698 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12699 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12700 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12701 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12702 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12703 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12704 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12705 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12706 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12707 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12708 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12710 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12711 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12712 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12713 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12715 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12716 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12717 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12718 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12719 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12720 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12721 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12722 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12723 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12724 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12725 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12726 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12728 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12729 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12730 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12732 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12734 (when (featurep 'xemacs)
12735 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12737 (defvar org-table-auto-blank-field) ; defined in org-table.el
12738 (defun org-self-insert-command (N)
12739 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12740 If the cursor is in a table looking at whitespace, the whitespace is
12741 overwritten, and the table is not marked as requiring realignment."
12742 (interactive "p")
12743 (if (and (org-table-p)
12744 (progn
12745 ;; check if we blank the field, and if that triggers align
12746 (and (featurep 'org-table) org-table-auto-blank-field
12747 (member last-command
12748 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12749 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12750 ;; got extra space, this field does not determine column width
12751 (let (org-table-may-need-update) (org-table-blank-field))
12752 ;; no extra space, this field may determine column width
12753 (org-table-blank-field)))
12755 (eq N 1)
12756 (looking-at "[^|\n]* |"))
12757 (let (org-table-may-need-update)
12758 (goto-char (1- (match-end 0)))
12759 (delete-backward-char 1)
12760 (goto-char (match-beginning 0))
12761 (self-insert-command N))
12762 (setq org-table-may-need-update t)
12763 (self-insert-command N)
12764 (org-fix-tags-on-the-fly)))
12766 (defun org-fix-tags-on-the-fly ()
12767 (when (and (equal (char-after (point-at-bol)) ?*)
12768 (org-on-heading-p))
12769 (org-align-tags-here org-tags-column)))
12771 (defun org-delete-backward-char (N)
12772 "Like `delete-backward-char', insert whitespace at field end in tables.
12773 When deleting backwards, in tables this function will insert whitespace in
12774 front of the next \"|\" separator, to keep the table aligned. The table will
12775 still be marked for re-alignment if the field did fill the entire column,
12776 because, in this case the deletion might narrow the column."
12777 (interactive "p")
12778 (if (and (org-table-p)
12779 (eq N 1)
12780 (string-match "|" (buffer-substring (point-at-bol) (point)))
12781 (looking-at ".*?|"))
12782 (let ((pos (point))
12783 (noalign (looking-at "[^|\n\r]* |"))
12784 (c org-table-may-need-update))
12785 (backward-delete-char N)
12786 (skip-chars-forward "^|")
12787 (insert " ")
12788 (goto-char (1- pos))
12789 ;; noalign: if there were two spaces at the end, this field
12790 ;; does not determine the width of the column.
12791 (if noalign (setq org-table-may-need-update c)))
12792 (backward-delete-char N)
12793 (org-fix-tags-on-the-fly)))
12795 (defun org-delete-char (N)
12796 "Like `delete-char', but insert whitespace at field end in tables.
12797 When deleting characters, in tables this function will insert whitespace in
12798 front of the next \"|\" separator, to keep the table aligned. The table will
12799 still be marked for re-alignment if the field did fill the entire column,
12800 because, in this case the deletion might narrow the column."
12801 (interactive "p")
12802 (if (and (org-table-p)
12803 (not (bolp))
12804 (not (= (char-after) ?|))
12805 (eq N 1))
12806 (if (looking-at ".*?|")
12807 (let ((pos (point))
12808 (noalign (looking-at "[^|\n\r]* |"))
12809 (c org-table-may-need-update))
12810 (replace-match (concat
12811 (substring (match-string 0) 1 -1)
12812 " |"))
12813 (goto-char pos)
12814 ;; noalign: if there were two spaces at the end, this field
12815 ;; does not determine the width of the column.
12816 (if noalign (setq org-table-may-need-update c)))
12817 (delete-char N))
12818 (delete-char N)
12819 (org-fix-tags-on-the-fly)))
12821 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12822 (put 'org-self-insert-command 'delete-selection t)
12823 (put 'orgtbl-self-insert-command 'delete-selection t)
12824 (put 'org-delete-char 'delete-selection 'supersede)
12825 (put 'org-delete-backward-char 'delete-selection 'supersede)
12827 ;; Make `flyspell-mode' delay after some commands
12828 (put 'org-self-insert-command 'flyspell-delayed t)
12829 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12830 (put 'org-delete-char 'flyspell-delayed t)
12831 (put 'org-delete-backward-char 'flyspell-delayed t)
12833 ;; Make pabbrev-mode expand after org-mode commands
12834 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12835 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12837 ;; How to do this: Measure non-white length of current string
12838 ;; If equal to column width, we should realign.
12840 (defun org-remap (map &rest commands)
12841 "In MAP, remap the functions given in COMMANDS.
12842 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12843 (let (new old)
12844 (while commands
12845 (setq old (pop commands) new (pop commands))
12846 (if (fboundp 'command-remapping)
12847 (org-defkey map (vector 'remap old) new)
12848 (substitute-key-definition old new map global-map)))))
12850 (when (eq org-enable-table-editor 'optimized)
12851 ;; If the user wants maximum table support, we need to hijack
12852 ;; some standard editing functions
12853 (org-remap org-mode-map
12854 'self-insert-command 'org-self-insert-command
12855 'delete-char 'org-delete-char
12856 'delete-backward-char 'org-delete-backward-char)
12857 (org-defkey org-mode-map "|" 'org-force-self-insert))
12859 (defun org-shiftcursor-error ()
12860 "Throw an error because Shift-Cursor command was applied in wrong context."
12861 (error "This command is active in special context like tables, headlines or timestamps"))
12863 (defun org-shifttab (&optional arg)
12864 "Global visibility cycling or move to previous table field.
12865 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12866 on context.
12867 See the individual commands for more information."
12868 (interactive "P")
12869 (cond
12870 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12871 ((integerp arg)
12872 (message "Content view to level: %d" arg)
12873 (org-content (prefix-numeric-value arg))
12874 (setq org-cycle-global-status 'overview))
12875 (t (call-interactively 'org-global-cycle))))
12877 (defun org-shiftmetaleft ()
12878 "Promote subtree or delete table column.
12879 Calls `org-promote-subtree', `org-outdent-item',
12880 or `org-table-delete-column', depending on context.
12881 See the individual commands for more information."
12882 (interactive)
12883 (cond
12884 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12885 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12886 ((org-at-item-p) (call-interactively 'org-outdent-item))
12887 (t (org-shiftcursor-error))))
12889 (defun org-shiftmetaright ()
12890 "Demote subtree or insert table column.
12891 Calls `org-demote-subtree', `org-indent-item',
12892 or `org-table-insert-column', depending on context.
12893 See the individual commands for more information."
12894 (interactive)
12895 (cond
12896 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12897 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12898 ((org-at-item-p) (call-interactively 'org-indent-item))
12899 (t (org-shiftcursor-error))))
12901 (defun org-shiftmetaup (&optional arg)
12902 "Move subtree up or kill table row.
12903 Calls `org-move-subtree-up' or `org-table-kill-row' or
12904 `org-move-item-up' depending on context. See the individual commands
12905 for more information."
12906 (interactive "P")
12907 (cond
12908 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12909 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12910 ((org-at-item-p) (call-interactively 'org-move-item-up))
12911 (t (org-shiftcursor-error))))
12912 (defun org-shiftmetadown (&optional arg)
12913 "Move subtree down or insert table row.
12914 Calls `org-move-subtree-down' or `org-table-insert-row' or
12915 `org-move-item-down', depending on context. See the individual
12916 commands for more information."
12917 (interactive "P")
12918 (cond
12919 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12920 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12921 ((org-at-item-p) (call-interactively 'org-move-item-down))
12922 (t (org-shiftcursor-error))))
12924 (defun org-metaleft (&optional arg)
12925 "Promote heading or move table column to left.
12926 Calls `org-do-promote' or `org-table-move-column', depending on context.
12927 With no specific context, calls the Emacs default `backward-word'.
12928 See the individual commands for more information."
12929 (interactive "P")
12930 (cond
12931 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12932 ((or (org-on-heading-p) (org-region-active-p))
12933 (call-interactively 'org-do-promote))
12934 ((org-at-item-p) (call-interactively 'org-outdent-item))
12935 (t (call-interactively 'backward-word))))
12937 (defun org-metaright (&optional arg)
12938 "Demote subtree or move table column to right.
12939 Calls `org-do-demote' or `org-table-move-column', depending on context.
12940 With no specific context, calls the Emacs default `forward-word'.
12941 See the individual commands for more information."
12942 (interactive "P")
12943 (cond
12944 ((org-at-table-p) (call-interactively 'org-table-move-column))
12945 ((or (org-on-heading-p) (org-region-active-p))
12946 (call-interactively 'org-do-demote))
12947 ((org-at-item-p) (call-interactively 'org-indent-item))
12948 (t (call-interactively 'forward-word))))
12950 (defun org-metaup (&optional arg)
12951 "Move subtree up or move table row up.
12952 Calls `org-move-subtree-up' or `org-table-move-row' or
12953 `org-move-item-up', depending on context. See the individual commands
12954 for more information."
12955 (interactive "P")
12956 (cond
12957 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12958 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12959 ((org-at-item-p) (call-interactively 'org-move-item-up))
12960 (t (transpose-lines 1) (beginning-of-line -1))))
12962 (defun org-metadown (&optional arg)
12963 "Move subtree down or move table row down.
12964 Calls `org-move-subtree-down' or `org-table-move-row' or
12965 `org-move-item-down', depending on context. See the individual
12966 commands for more information."
12967 (interactive "P")
12968 (cond
12969 ((org-at-table-p) (call-interactively 'org-table-move-row))
12970 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12971 ((org-at-item-p) (call-interactively 'org-move-item-down))
12972 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12974 (defun org-shiftup (&optional arg)
12975 "Increase item in timestamp or increase priority of current headline.
12976 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12977 depending on context. See the individual commands for more information."
12978 (interactive "P")
12979 (cond
12980 ((org-at-timestamp-p t)
12981 (call-interactively (if org-edit-timestamp-down-means-later
12982 'org-timestamp-down 'org-timestamp-up)))
12983 ((org-on-heading-p) (call-interactively 'org-priority-up))
12984 ((org-at-item-p) (call-interactively 'org-previous-item))
12985 ((org-clocktable-try-shift 'up arg))
12986 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12988 (defun org-shiftdown (&optional arg)
12989 "Decrease item in timestamp or decrease priority of current headline.
12990 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12991 depending on context. See the individual commands for more information."
12992 (interactive "P")
12993 (cond
12994 ((org-at-timestamp-p t)
12995 (call-interactively (if org-edit-timestamp-down-means-later
12996 'org-timestamp-up 'org-timestamp-down)))
12997 ((org-on-heading-p) (call-interactively 'org-priority-down))
12998 ((org-clocktable-try-shift 'down arg))
12999 (t (call-interactively 'org-next-item))))
13001 (defun org-shiftright (&optional arg)
13002 "Cycle the thing at point or in the current line, depending on context.
13003 Depending on context, this does one of the following:
13005 - switch a timestamp at point one day into the future
13006 - on a headline, switch to the next TODO keyword.
13007 - on an item, switch entire list to the next bullet type
13008 - on a property line, switch to the next allowed value
13009 - on a clocktable definition line, move time block into the future"
13010 (interactive "P")
13011 (cond
13012 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13013 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13014 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13015 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13016 ((org-clocktable-try-shift 'right arg))
13017 (t (org-shiftcursor-error))))
13019 (defun org-shiftleft (&optional arg)
13020 "Cycle the thing at point or in the current line, depending on context.
13021 Depending on context, this does one of the following:
13023 - switch a timestamp at point one day into the past
13024 - on a headline, switch to the previous TODO keyword.
13025 - on an item, switch entire list to the previous bullet type
13026 - on a property line, switch to the previous allowed value
13027 - on a clocktable definition line, move time block into the past"
13028 (interactive "P")
13029 (cond
13030 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13031 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13032 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13033 ((org-at-property-p)
13034 (call-interactively 'org-property-previous-allowed-value))
13035 ((org-clocktable-try-shift 'left arg))
13036 (t (org-shiftcursor-error))))
13038 (defun org-shiftcontrolright ()
13039 "Switch to next TODO set."
13040 (interactive)
13041 (cond
13042 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13043 (t (org-shiftcursor-error))))
13045 (defun org-shiftcontrolleft ()
13046 "Switch to previous TODO set."
13047 (interactive)
13048 (cond
13049 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13050 (t (org-shiftcursor-error))))
13052 (defun org-ctrl-c-ret ()
13053 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13054 (interactive)
13055 (cond
13056 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13057 (t (call-interactively 'org-insert-heading))))
13059 (defun org-copy-special ()
13060 "Copy region in table or copy current subtree.
13061 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13062 See the individual commands for more information."
13063 (interactive)
13064 (call-interactively
13065 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13067 (defun org-cut-special ()
13068 "Cut region in table or cut current subtree.
13069 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13070 See the individual commands for more information."
13071 (interactive)
13072 (call-interactively
13073 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13075 (defun org-paste-special (arg)
13076 "Paste rectangular region into table, or past subtree relative to level.
13077 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13078 See the individual commands for more information."
13079 (interactive "P")
13080 (if (org-at-table-p)
13081 (org-table-paste-rectangle)
13082 (org-paste-subtree arg)))
13084 (defun org-edit-special ()
13085 "Call a special editor for the stuff at point.
13086 When at a table, call the formula editor with `org-table-edit-formulas'.
13087 When at the first line of an src example, call `org-edit-src-code'.
13088 When in an #+include line, visit the include file. Otherwise call
13089 `ffap' to visit the file at point."
13090 (interactive)
13091 (cond
13092 ((org-at-table-p)
13093 (call-interactively 'org-table-edit-formulas))
13094 ((save-excursion
13095 (beginning-of-line 1)
13096 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13097 (find-file (org-trim (match-string 1))))
13098 ((org-edit-src-code))
13099 ((org-edit-fixed-width-region))
13100 (t (call-interactively 'ffap))))
13102 (defun org-ctrl-c-ctrl-c (&optional arg)
13103 "Set tags in headline, or update according to changed information at point.
13105 This command does many different things, depending on context:
13107 - If the cursor is in a headline, prompt for tags and insert them
13108 into the current line, aligned to `org-tags-column'. When called
13109 with prefix arg, realign all tags in the current buffer.
13111 - If the cursor is in one of the special #+KEYWORD lines, this
13112 triggers scanning the buffer for these lines and updating the
13113 information.
13115 - If the cursor is inside a table, realign the table. This command
13116 works even if the automatic table editor has been turned off.
13118 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13119 the entire table.
13121 - If the cursor is at a footnote reference or definition, jump to
13122 the corresponding definition or references, respectively.
13124 - If the cursor is a the beginning of a dynamic block, update it.
13126 - If the cursor is inside a table created by the table.el package,
13127 activate that table.
13129 - If the current buffer is a remember buffer, close note and file
13130 it. A prefix argument of 1 files to the default location
13131 without further interaction. A prefix argument of 2 files to
13132 the currently clocking task.
13134 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13135 links in this buffer.
13137 - If the cursor is on a numbered item in a plain list, renumber the
13138 ordered list.
13140 - If the cursor is on a checkbox, toggle it."
13141 (interactive "P")
13142 (let ((org-enable-table-editor t))
13143 (cond
13144 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13145 org-occur-highlights
13146 org-latex-fragment-image-overlays)
13147 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13148 (org-remove-occur-highlights)
13149 (org-remove-latex-fragment-image-overlays)
13150 (message "Temporary highlights/overlays removed from current buffer"))
13151 ((and (local-variable-p 'org-finish-function (current-buffer))
13152 (fboundp org-finish-function))
13153 (funcall org-finish-function))
13154 ((org-at-property-p)
13155 (call-interactively 'org-property-action))
13156 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13157 ((org-on-heading-p) (call-interactively 'org-set-tags))
13158 ((org-at-table.el-p)
13159 (require 'table)
13160 (beginning-of-line 1)
13161 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13162 (call-interactively 'table-recognize-table))
13163 ((org-at-table-p)
13164 (org-table-maybe-eval-formula)
13165 (if arg
13166 (call-interactively 'org-table-recalculate)
13167 (org-table-maybe-recalculate-line))
13168 (call-interactively 'org-table-align))
13169 ((or (org-footnote-at-reference-p)
13170 (org-footnote-at-definition-p))
13171 (call-interactively 'org-footnote-action))
13172 ((org-at-item-checkbox-p)
13173 (call-interactively 'org-toggle-checkbox))
13174 ((org-at-item-p)
13175 (call-interactively 'org-maybe-renumber-ordered-list))
13176 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13177 ;; Dynamic block
13178 (beginning-of-line 1)
13179 (save-excursion (org-update-dblock)))
13180 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13181 (cond
13182 ((equal (match-string 1) "TBLFM")
13183 ;; Recalculate the table before this line
13184 (save-excursion
13185 (beginning-of-line 1)
13186 (skip-chars-backward " \r\n\t")
13187 (if (org-at-table-p)
13188 (org-call-with-arg 'org-table-recalculate t))))
13190 ; (org-set-regexps-and-options)
13191 ; (org-restart-font-lock)
13192 (let ((org-inhibit-startup t)) (org-mode-restart))
13193 (message "Local setup has been refreshed"))))
13194 (t (error "C-c C-c can do nothing useful at this location.")))))
13196 (defun org-mode-restart ()
13197 "Restart Org-mode, to scan again for special lines.
13198 Also updates the keyword regular expressions."
13199 (interactive)
13200 (org-mode)
13201 (message "Org-mode restarted"))
13203 (defun org-kill-note-or-show-branches ()
13204 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13205 (interactive)
13206 (if (not org-finish-function)
13207 (call-interactively 'show-branches)
13208 (let ((org-note-abort t))
13209 (funcall org-finish-function))))
13211 (defun org-return (&optional indent)
13212 "Goto next table row or insert a newline.
13213 Calls `org-table-next-row' or `newline', depending on context.
13214 See the individual commands for more information."
13215 (interactive)
13216 (cond
13217 ((bobp) (if indent (newline-and-indent) (newline)))
13218 ((and (org-at-heading-p)
13219 (looking-at
13220 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13221 (org-show-entry)
13222 (end-of-line 1)
13223 (newline))
13224 ((org-at-table-p)
13225 (org-table-justify-field-maybe)
13226 (call-interactively 'org-table-next-row))
13227 (t (if indent (newline-and-indent) (newline)))))
13229 (defun org-return-indent ()
13230 "Goto next table row or insert a newline and indent.
13231 Calls `org-table-next-row' or `newline-and-indent', depending on
13232 context. See the individual commands for more information."
13233 (interactive)
13234 (org-return t))
13236 (defun org-ctrl-c-star ()
13237 "Compute table, or change heading status of lines.
13238 Calls `org-table-recalculate' or `org-toggle-region-headings',
13239 depending on context. This will also turn a plain list item or a normal
13240 line into a subheading."
13241 (interactive)
13242 (cond
13243 ((org-at-table-p)
13244 (call-interactively 'org-table-recalculate))
13245 ((org-region-active-p)
13246 ;; Convert all lines in region to list items
13247 (call-interactively 'org-toggle-region-headings))
13248 ((org-on-heading-p)
13249 (org-toggle-region-headings (point-at-bol)
13250 (min (1+ (point-at-eol)) (point-max))))
13251 ((org-at-item-p)
13252 ;; Convert to heading
13253 (let ((level (save-match-data
13254 (save-excursion
13255 (condition-case nil
13256 (progn
13257 (org-back-to-heading t)
13258 (funcall outline-level))
13259 (error 0))))))
13260 (replace-match
13261 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13262 (t (org-toggle-region-headings (point-at-bol)
13263 (min (1+ (point-at-eol)) (point-max))))))
13265 (defun org-ctrl-c-minus ()
13266 "Insert separator line in table or modify bullet status of line.
13267 Also turns a plain line or a region of lines into list items.
13268 Calls `org-table-insert-hline', `org-toggle-region-items', or
13269 `org-cycle-list-bullet', depending on context."
13270 (interactive)
13271 (cond
13272 ((org-at-table-p)
13273 (call-interactively 'org-table-insert-hline))
13274 ((org-on-heading-p)
13275 ;; Convert to item
13276 (save-excursion
13277 (beginning-of-line 1)
13278 (if (looking-at "\\*+ ")
13279 (replace-match
13280 (concat (make-string
13281 (- (match-end 0) (point) (if org-odd-levels-only 2 1)) ?\ )
13282 "- ")))))
13283 ((org-region-active-p)
13284 ;; Convert all lines in region to list items
13285 (call-interactively 'org-toggle-region-items))
13286 ((org-in-item-p)
13287 (call-interactively 'org-cycle-list-bullet))
13288 (t (org-toggle-region-items (point-at-bol)
13289 (min (1+ (point-at-eol)) (point-max))))))
13291 (defun org-toggle-region-items (beg end)
13292 "Convert all lines in region to list items.
13293 If the first line is already an item, convert all list items in the region
13294 to normal lines."
13295 (interactive "r")
13296 (let (l2 l)
13297 (save-excursion
13298 (goto-char end)
13299 (setq l2 (org-current-line))
13300 (goto-char beg)
13301 (beginning-of-line 1)
13302 (setq l (1- (org-current-line)))
13303 (if (org-at-item-p)
13304 ;; We already have items, de-itemize
13305 (while (< (setq l (1+ l)) l2)
13306 (when (org-at-item-p)
13307 (goto-char (match-beginning 2))
13308 (delete-region (match-beginning 2) (match-end 2))
13309 (and (looking-at "[ \t]+") (replace-match "")))
13310 (beginning-of-line 2))
13311 (while (< (setq l (1+ l)) l2)
13312 (unless (org-at-item-p)
13313 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13314 (replace-match "\\1- \\2")))
13315 (beginning-of-line 2))))))
13317 (defun org-toggle-region-headings (beg end)
13318 "Convert all lines in region to list items.
13319 If the first line is already an item, convert all list items in the region
13320 to normal lines."
13321 (interactive "r")
13322 (let (l2 l)
13323 (save-excursion
13324 (goto-char end)
13325 (setq l2 (org-current-line))
13326 (goto-char beg)
13327 (beginning-of-line 1)
13328 (setq l (1- (org-current-line)))
13329 (if (org-on-heading-p)
13330 ;; We already have headlines, de-star them
13331 (while (< (setq l (1+ l)) l2)
13332 (when (org-on-heading-p t)
13333 (and (looking-at outline-regexp) (replace-match "")))
13334 (beginning-of-line 2))
13335 (let* ((stars (save-excursion
13336 (re-search-backward org-complex-heading-regexp nil t)
13337 (or (match-string 1) "*")))
13338 (add-stars (if org-odd-levels-only "**" "*"))
13339 (rpl (concat stars add-stars " \\2")))
13340 (while (< (setq l (1+ l)) l2)
13341 (unless (org-on-heading-p)
13342 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13343 (replace-match rpl)))
13344 (beginning-of-line 2)))))))
13346 (defun org-meta-return (&optional arg)
13347 "Insert a new heading or wrap a region in a table.
13348 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13349 See the individual commands for more information."
13350 (interactive "P")
13351 (cond
13352 ((org-at-table-p)
13353 (call-interactively 'org-table-wrap-region))
13354 (t (call-interactively 'org-insert-heading))))
13356 ;;; Menu entries
13358 ;; Define the Org-mode menus
13359 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13360 '("Tbl"
13361 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13362 ["Next Field" org-cycle (org-at-table-p)]
13363 ["Previous Field" org-shifttab (org-at-table-p)]
13364 ["Next Row" org-return (org-at-table-p)]
13365 "--"
13366 ["Blank Field" org-table-blank-field (org-at-table-p)]
13367 ["Edit Field" org-table-edit-field (org-at-table-p)]
13368 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13369 "--"
13370 ("Column"
13371 ["Move Column Left" org-metaleft (org-at-table-p)]
13372 ["Move Column Right" org-metaright (org-at-table-p)]
13373 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13374 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13375 ("Row"
13376 ["Move Row Up" org-metaup (org-at-table-p)]
13377 ["Move Row Down" org-metadown (org-at-table-p)]
13378 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13379 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13380 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13381 "--"
13382 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13383 ("Rectangle"
13384 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13385 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13386 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13387 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13388 "--"
13389 ("Calculate"
13390 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13391 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13392 ["Edit Formulas" org-edit-special (org-at-table-p)]
13393 "--"
13394 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13395 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13396 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13397 "--"
13398 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13399 "--"
13400 ["Sum Column/Rectangle" org-table-sum
13401 (or (org-at-table-p) (org-region-active-p))]
13402 ["Which Column?" org-table-current-column (org-at-table-p)])
13403 ["Debug Formulas"
13404 org-table-toggle-formula-debugger
13405 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13406 ["Show Col/Row Numbers"
13407 org-table-toggle-coordinate-overlays
13408 :style toggle
13409 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13410 "--"
13411 ["Create" org-table-create (and (not (org-at-table-p))
13412 org-enable-table-editor)]
13413 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13414 ["Import from File" org-table-import (not (org-at-table-p))]
13415 ["Export to File" org-table-export (org-at-table-p)]
13416 "--"
13417 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13419 (easy-menu-define org-org-menu org-mode-map "Org menu"
13420 '("Org"
13421 ("Show/Hide"
13422 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13423 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13424 ["Sparse Tree..." org-sparse-tree t]
13425 ["Reveal Context" org-reveal t]
13426 ["Show All" show-all t]
13427 "--"
13428 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13429 "--"
13430 ["New Heading" org-insert-heading t]
13431 ("Navigate Headings"
13432 ["Up" outline-up-heading t]
13433 ["Next" outline-next-visible-heading t]
13434 ["Previous" outline-previous-visible-heading t]
13435 ["Next Same Level" outline-forward-same-level t]
13436 ["Previous Same Level" outline-backward-same-level t]
13437 "--"
13438 ["Jump" org-goto t])
13439 ("Edit Structure"
13440 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13441 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13442 "--"
13443 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13444 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13445 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13446 "--"
13447 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13448 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13449 ["Demote Heading" org-metaright (not (org-at-table-p))]
13450 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13451 "--"
13452 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13453 "--"
13454 ["Convert to odd levels" org-convert-to-odd-levels t]
13455 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13456 ("Editing"
13457 ["Emphasis..." org-emphasize t]
13458 ["Edit Source Example" org-edit-special t]
13459 "--"
13460 ["Footnote new/jump" org-footnote-action t]
13461 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13462 ("Archive"
13463 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13464 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13465 ; :active t :keys "C-u C-c C-x C-a"]
13466 ["Sparse trees open ARCHIVE trees"
13467 (setq org-sparse-tree-open-archived-trees
13468 (not org-sparse-tree-open-archived-trees))
13469 :style toggle :selected org-sparse-tree-open-archived-trees]
13470 ["Cycling opens ARCHIVE trees"
13471 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13472 :style toggle :selected org-cycle-open-archived-trees]
13473 "--"
13474 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13475 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13476 ; ["Check and Move Children" (org-archive-subtree '(4))
13477 ; :active t :keys "C-u C-c C-x C-s"]
13479 "--"
13480 ("TODO Lists"
13481 ["TODO/DONE/-" org-todo t]
13482 ("Select keyword"
13483 ["Next keyword" org-shiftright (org-on-heading-p)]
13484 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13485 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13486 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13487 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13488 ["Show TODO Tree" org-show-todo-tree t]
13489 ["Global TODO list" org-todo-list t]
13490 "--"
13491 ["Set Priority" org-priority t]
13492 ["Priority Up" org-shiftup t]
13493 ["Priority Down" org-shiftdown t])
13494 ("TAGS and Properties"
13495 ["Set Tags" org-set-tags-command t]
13496 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13497 "--"
13498 ["Set property" org-set-property t]
13499 ["Column view of properties" org-columns t]
13500 ["Insert Column View DBlock" org-insert-columns-dblock t])
13501 ("Dates and Scheduling"
13502 ["Timestamp" org-time-stamp t]
13503 ["Timestamp (inactive)" org-time-stamp-inactive t]
13504 ("Change Date"
13505 ["1 Day Later" org-shiftright t]
13506 ["1 Day Earlier" org-shiftleft t]
13507 ["1 ... Later" org-shiftup t]
13508 ["1 ... Earlier" org-shiftdown t])
13509 ["Compute Time Range" org-evaluate-time-range t]
13510 ["Schedule Item" org-schedule t]
13511 ["Deadline" org-deadline t]
13512 "--"
13513 ["Custom time format" org-toggle-time-stamp-overlays
13514 :style radio :selected org-display-custom-times]
13515 "--"
13516 ["Goto Calendar" org-goto-calendar t]
13517 ["Date from Calendar" org-date-from-calendar t]
13518 "--"
13519 ["Start/restart timer" org-timer-start t]
13520 ["Insert timer string" org-timer t]
13521 ["Insert timer item" org-timer-item t])
13522 ("Logging work"
13523 ["Clock in" org-clock-in t]
13524 ["Clock out" org-clock-out t]
13525 ["Clock cancel" org-clock-cancel t]
13526 ["Goto running clock" org-clock-goto t]
13527 ["Display times" org-clock-display t]
13528 ["Create clock table" org-clock-report t]
13529 "--"
13530 ["Record DONE time"
13531 (progn (setq org-log-done (not org-log-done))
13532 (message "Switching to %s will %s record a timestamp"
13533 (car org-done-keywords)
13534 (if org-log-done "automatically" "not")))
13535 :style toggle :selected org-log-done])
13536 "--"
13537 ["Agenda Command..." org-agenda t]
13538 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13539 ("File List for Agenda")
13540 ("Special views current file"
13541 ["TODO Tree" org-show-todo-tree t]
13542 ["Check Deadlines" org-check-deadlines t]
13543 ["Timeline" org-timeline t]
13544 ["Tags Tree" org-tags-sparse-tree t])
13545 "--"
13546 ("Hyperlinks"
13547 ["Store Link (Global)" org-store-link t]
13548 ["Insert Link" org-insert-link t]
13549 ["Follow Link" org-open-at-point t]
13550 "--"
13551 ["Next link" org-next-link t]
13552 ["Previous link" org-previous-link t]
13553 "--"
13554 ["Descriptive Links"
13555 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13556 :style radio
13557 :selected (member '(org-link) buffer-invisibility-spec)]
13558 ["Literal Links"
13559 (progn
13560 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13561 :style radio
13562 :selected (not (member '(org-link) buffer-invisibility-spec))])
13563 "--"
13564 ["Export/Publish..." org-export t]
13565 ("LaTeX"
13566 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13567 :selected org-cdlatex-mode]
13568 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13569 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13570 ["Modify math symbol" org-cdlatex-math-modify
13571 (org-inside-LaTeX-fragment-p)]
13572 ["Export LaTeX fragments as images"
13573 (if (featurep 'org-exp)
13574 (setq org-export-with-LaTeX-fragments
13575 (not org-export-with-LaTeX-fragments))
13576 (require 'org-exp))
13577 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13578 org-export-with-LaTeX-fragments)])
13579 "--"
13580 ("Documentation"
13581 ["Show Version" org-version t]
13582 ["Info Documentation" org-info t])
13583 ("Customize"
13584 ["Browse Org Group" org-customize t]
13585 "--"
13586 ["Expand This Menu" org-create-customize-menu
13587 (fboundp 'customize-menu-create)])
13588 "--"
13589 ["Refresh setup" org-mode-restart t]
13592 (defun org-info (&optional node)
13593 "Read documentation for Org-mode in the info system.
13594 With optional NODE, go directly to that node."
13595 (interactive)
13596 (info (format "(org)%s" (or node ""))))
13598 (defun org-install-agenda-files-menu ()
13599 (let ((bl (buffer-list)))
13600 (save-excursion
13601 (while bl
13602 (set-buffer (pop bl))
13603 (if (org-mode-p) (setq bl nil)))
13604 (when (org-mode-p)
13605 (easy-menu-change
13606 '("Org") "File List for Agenda"
13607 (append
13608 (list
13609 ["Edit File List" (org-edit-agenda-file-list) t]
13610 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13611 ["Remove Current File from List" org-remove-file t]
13612 ["Cycle through agenda files" org-cycle-agenda-files t]
13613 ["Occur in all agenda files" org-occur-in-agenda-files t]
13614 "--")
13615 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13617 ;;;; Documentation
13619 ;;;###autoload
13620 (defun org-require-autoloaded-modules ()
13621 (interactive)
13622 (mapc 'require
13623 '(org-agenda org-archive org-clock org-colview
13624 org-exp org-id org-export-latex org-publish
13625 org-remember org-table)))
13627 ;;;###autoload
13628 (defun org-customize ()
13629 "Call the customize function with org as argument."
13630 (interactive)
13631 (org-load-modules-maybe)
13632 (org-require-autoloaded-modules)
13633 (customize-browse 'org))
13635 (defun org-create-customize-menu ()
13636 "Create a full customization menu for Org-mode, insert it into the menu."
13637 (interactive)
13638 (org-load-modules-maybe)
13639 (org-require-autoloaded-modules)
13640 (if (fboundp 'customize-menu-create)
13641 (progn
13642 (easy-menu-change
13643 '("Org") "Customize"
13644 `(["Browse Org group" org-customize t]
13645 "--"
13646 ,(customize-menu-create 'org)
13647 ["Set" Custom-set t]
13648 ["Save" Custom-save t]
13649 ["Reset to Current" Custom-reset-current t]
13650 ["Reset to Saved" Custom-reset-saved t]
13651 ["Reset to Standard Settings" Custom-reset-standard t]))
13652 (message "\"Org\"-menu now contains full customization menu"))
13653 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13655 ;;;; Miscellaneous stuff
13657 ;;; Generally useful functions
13659 (defun org-find-text-property-in-string (prop s)
13660 "Return the first non-nil value of property PROP in string S."
13661 (or (get-text-property 0 prop s)
13662 (get-text-property (or (next-single-property-change 0 prop s) 0)
13663 prop s)))
13665 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13666 "Display the given MESSAGE as a warning."
13667 (if (fboundp 'display-warning)
13668 (display-warning 'org message
13669 (if (featurep 'xemacs)
13670 'warning
13671 :warning))
13672 (let ((buf (get-buffer-create "*Org warnings*")))
13673 (with-current-buffer buf
13674 (goto-char (point-max))
13675 (insert "Warning (Org): " message)
13676 (unless (bolp)
13677 (newline)))
13678 (display-buffer buf)
13679 (sit-for 0))))
13681 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13682 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13683 (if (and marker (marker-buffer marker)
13684 (buffer-live-p (marker-buffer marker)))
13685 (progn
13686 (switch-to-buffer (marker-buffer marker))
13687 (if (or (> marker (point-max)) (< marker (point-min)))
13688 (widen))
13689 (goto-char marker)
13690 (org-show-context 'org-goto))
13691 (if bookmark
13692 (bookmark-jump bookmark)
13693 (error "Cannot find location"))))
13695 (defun org-quote-csv-field (s)
13696 "Quote field for inclusion in CSV material."
13697 (if (string-match "[\",]" s)
13698 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13701 (defun org-plist-delete (plist property)
13702 "Delete PROPERTY from PLIST.
13703 This is in contrast to merely setting it to 0."
13704 (let (p)
13705 (while plist
13706 (if (not (eq property (car plist)))
13707 (setq p (plist-put p (car plist) (nth 1 plist))))
13708 (setq plist (cddr plist)))
13711 (defun org-force-self-insert (N)
13712 "Needed to enforce self-insert under remapping."
13713 (interactive "p")
13714 (self-insert-command N))
13716 (defun org-string-width (s)
13717 "Compute width of string, ignoring invisible characters.
13718 This ignores character with invisibility property `org-link', and also
13719 characters with property `org-cwidth', because these will become invisible
13720 upon the next fontification round."
13721 (let (b l)
13722 (when (or (eq t buffer-invisibility-spec)
13723 (assq 'org-link buffer-invisibility-spec))
13724 (while (setq b (text-property-any 0 (length s)
13725 'invisible 'org-link s))
13726 (setq s (concat (substring s 0 b)
13727 (substring s (or (next-single-property-change
13728 b 'invisible s) (length s)))))))
13729 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13730 (setq s (concat (substring s 0 b)
13731 (substring s (or (next-single-property-change
13732 b 'org-cwidth s) (length s))))))
13733 (setq l (string-width s) b -1)
13734 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13735 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13738 (defun org-get-indentation (&optional line)
13739 "Get the indentation of the current line, interpreting tabs.
13740 When LINE is given, assume it represents a line and compute its indentation."
13741 (if line
13742 (if (string-match "^ *" (org-remove-tabs line))
13743 (match-end 0))
13744 (save-excursion
13745 (beginning-of-line 1)
13746 (skip-chars-forward " \t")
13747 (current-column))))
13749 (defun org-remove-tabs (s &optional width)
13750 "Replace tabulators in S with spaces.
13751 Assumes that s is a single line, starting in column 0."
13752 (setq width (or width tab-width))
13753 (while (string-match "\t" s)
13754 (setq s (replace-match
13755 (make-string
13756 (- (* width (/ (+ (match-beginning 0) width) width))
13757 (match-beginning 0)) ?\ )
13758 t t s)))
13761 (defun org-fix-indentation (line ind)
13762 "Fix indentation in LINE.
13763 IND is a cons cell with target and minimum indentation.
13764 If the current indentation in LINE is smaller than the minimum,
13765 leave it alone. If it is larger than ind, set it to the target."
13766 (let* ((l (org-remove-tabs line))
13767 (i (org-get-indentation l))
13768 (i1 (car ind)) (i2 (cdr ind)))
13769 (if (>= i i2) (setq l (substring line i2)))
13770 (if (> i1 0)
13771 (concat (make-string i1 ?\ ) l)
13772 l)))
13774 (defun org-base-buffer (buffer)
13775 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13776 (if (not buffer)
13777 buffer
13778 (or (buffer-base-buffer buffer)
13779 buffer)))
13781 (defun org-trim (s)
13782 "Remove whitespace at beginning and end of string."
13783 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13784 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13787 (defun org-wrap (string &optional width lines)
13788 "Wrap string to either a number of lines, or a width in characters.
13789 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13790 that costs. If there is a word longer than WIDTH, the text is actually
13791 wrapped to the length of that word.
13792 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13793 many lines, whatever width that takes.
13794 The return value is a list of lines, without newlines at the end."
13795 (let* ((words (org-split-string string "[ \t\n]+"))
13796 (maxword (apply 'max (mapcar 'org-string-width words)))
13797 w ll)
13798 (cond (width
13799 (org-do-wrap words (max maxword width)))
13800 (lines
13801 (setq w maxword)
13802 (setq ll (org-do-wrap words maxword))
13803 (if (<= (length ll) lines)
13805 (setq ll words)
13806 (while (> (length ll) lines)
13807 (setq w (1+ w))
13808 (setq ll (org-do-wrap words w)))
13809 ll))
13810 (t (error "Cannot wrap this")))))
13812 (defun org-do-wrap (words width)
13813 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13814 (let (lines line)
13815 (while words
13816 (setq line (pop words))
13817 (while (and words (< (+ (length line) (length (car words))) width))
13818 (setq line (concat line " " (pop words))))
13819 (setq lines (push line lines)))
13820 (nreverse lines)))
13822 (defun org-split-string (string &optional separators)
13823 "Splits STRING into substrings at SEPARATORS.
13824 No empty strings are returned if there are matches at the beginning
13825 and end of string."
13826 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13827 (start 0)
13828 notfirst
13829 (list nil))
13830 (while (and (string-match rexp string
13831 (if (and notfirst
13832 (= start (match-beginning 0))
13833 (< start (length string)))
13834 (1+ start) start))
13835 (< (match-beginning 0) (length string)))
13836 (setq notfirst t)
13837 (or (eq (match-beginning 0) 0)
13838 (and (eq (match-beginning 0) (match-end 0))
13839 (eq (match-beginning 0) start))
13840 (setq list
13841 (cons (substring string start (match-beginning 0))
13842 list)))
13843 (setq start (match-end 0)))
13844 (or (eq start (length string))
13845 (setq list
13846 (cons (substring string start)
13847 list)))
13848 (nreverse list)))
13850 (defun org-context ()
13851 "Return a list of contexts of the current cursor position.
13852 If several contexts apply, all are returned.
13853 Each context entry is a list with a symbol naming the context, and
13854 two positions indicating start and end of the context. Possible
13855 contexts are:
13857 :headline anywhere in a headline
13858 :headline-stars on the leading stars in a headline
13859 :todo-keyword on a TODO keyword (including DONE) in a headline
13860 :tags on the TAGS in a headline
13861 :priority on the priority cookie in a headline
13862 :item on the first line of a plain list item
13863 :item-bullet on the bullet/number of a plain list item
13864 :checkbox on the checkbox in a plain list item
13865 :table in an org-mode table
13866 :table-special on a special filed in a table
13867 :table-table in a table.el table
13868 :link on a hyperlink
13869 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13870 :target on a <<target>>
13871 :radio-target on a <<<radio-target>>>
13872 :latex-fragment on a LaTeX fragment
13873 :latex-preview on a LaTeX fragment with overlayed preview image
13875 This function expects the position to be visible because it uses font-lock
13876 faces as a help to recognize the following contexts: :table-special, :link,
13877 and :keyword."
13878 (let* ((f (get-text-property (point) 'face))
13879 (faces (if (listp f) f (list f)))
13880 (p (point)) clist o)
13881 ;; First the large context
13882 (cond
13883 ((org-on-heading-p t)
13884 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13885 (when (progn
13886 (beginning-of-line 1)
13887 (looking-at org-todo-line-tags-regexp))
13888 (push (org-point-in-group p 1 :headline-stars) clist)
13889 (push (org-point-in-group p 2 :todo-keyword) clist)
13890 (push (org-point-in-group p 4 :tags) clist))
13891 (goto-char p)
13892 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13893 (if (looking-at "\\[#[A-Z0-9]\\]")
13894 (push (org-point-in-group p 0 :priority) clist)))
13896 ((org-at-item-p)
13897 (push (org-point-in-group p 2 :item-bullet) clist)
13898 (push (list :item (point-at-bol)
13899 (save-excursion (org-end-of-item) (point)))
13900 clist)
13901 (and (org-at-item-checkbox-p)
13902 (push (org-point-in-group p 0 :checkbox) clist)))
13904 ((org-at-table-p)
13905 (push (list :table (org-table-begin) (org-table-end)) clist)
13906 (if (memq 'org-formula faces)
13907 (push (list :table-special
13908 (previous-single-property-change p 'face)
13909 (next-single-property-change p 'face)) clist)))
13910 ((org-at-table-p 'any)
13911 (push (list :table-table) clist)))
13912 (goto-char p)
13914 ;; Now the small context
13915 (cond
13916 ((org-at-timestamp-p)
13917 (push (org-point-in-group p 0 :timestamp) clist))
13918 ((memq 'org-link faces)
13919 (push (list :link
13920 (previous-single-property-change p 'face)
13921 (next-single-property-change p 'face)) clist))
13922 ((memq 'org-special-keyword faces)
13923 (push (list :keyword
13924 (previous-single-property-change p 'face)
13925 (next-single-property-change p 'face)) clist))
13926 ((org-on-target-p)
13927 (push (org-point-in-group p 0 :target) clist)
13928 (goto-char (1- (match-beginning 0)))
13929 (if (looking-at org-radio-target-regexp)
13930 (push (org-point-in-group p 0 :radio-target) clist))
13931 (goto-char p))
13932 ((setq o (car (delq nil
13933 (mapcar
13934 (lambda (x)
13935 (if (memq x org-latex-fragment-image-overlays) x))
13936 (org-overlays-at (point))))))
13937 (push (list :latex-fragment
13938 (org-overlay-start o) (org-overlay-end o)) clist)
13939 (push (list :latex-preview
13940 (org-overlay-start o) (org-overlay-end o)) clist))
13941 ((org-inside-LaTeX-fragment-p)
13942 ;; FIXME: positions wrong.
13943 (push (list :latex-fragment (point) (point)) clist)))
13945 (setq clist (nreverse (delq nil clist)))
13946 clist))
13948 ;; FIXME: Compare with at-regexp-p Do we need both?
13949 (defun org-in-regexp (re &optional nlines visually)
13950 "Check if point is inside a match of regexp.
13951 Normally only the current line is checked, but you can include NLINES extra
13952 lines both before and after point into the search.
13953 If VISUALLY is set, require that the cursor is not after the match but
13954 really on, so that the block visually is on the match."
13955 (catch 'exit
13956 (let ((pos (point))
13957 (eol (point-at-eol (+ 1 (or nlines 0))))
13958 (inc (if visually 1 0)))
13959 (save-excursion
13960 (beginning-of-line (- 1 (or nlines 0)))
13961 (while (re-search-forward re eol t)
13962 (if (and (<= (match-beginning 0) pos)
13963 (>= (+ inc (match-end 0)) pos))
13964 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13966 (defun org-at-regexp-p (regexp)
13967 "Is point inside a match of REGEXP in the current line?"
13968 (catch 'exit
13969 (save-excursion
13970 (let ((pos (point)) (end (point-at-eol)))
13971 (beginning-of-line 1)
13972 (while (re-search-forward regexp end t)
13973 (if (and (<= (match-beginning 0) pos)
13974 (>= (match-end 0) pos))
13975 (throw 'exit t)))
13976 nil))))
13978 (defun org-occur-in-agenda-files (regexp &optional nlines)
13979 "Call `multi-occur' with buffers for all agenda files."
13980 (interactive "sOrg-files matching: \np")
13981 (let* ((files (org-agenda-files))
13982 (tnames (mapcar 'file-truename files))
13983 (extra org-agenda-text-search-extra-files)
13985 (when (eq (car extra) 'agenda-archives)
13986 (setq extra (cdr extra))
13987 (setq files (org-add-archive-files files)))
13988 (while (setq f (pop extra))
13989 (unless (member (file-truename f) tnames)
13990 (add-to-list 'files f 'append)
13991 (add-to-list 'tnames (file-truename f) 'append)))
13992 (multi-occur
13993 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13994 regexp)))
13996 (if (boundp 'occur-mode-find-occurrence-hook)
13997 ;; Emacs 23
13998 (add-hook 'occur-mode-find-occurrence-hook
13999 (lambda ()
14000 (when (org-mode-p)
14001 (org-reveal))))
14002 ;; Emacs 22
14003 (defadvice occur-mode-goto-occurrence
14004 (after org-occur-reveal activate)
14005 (and (org-mode-p) (org-reveal)))
14006 (defadvice occur-mode-goto-occurrence-other-window
14007 (after org-occur-reveal activate)
14008 (and (org-mode-p) (org-reveal)))
14009 (defadvice occur-mode-display-occurrence
14010 (after org-occur-reveal activate)
14011 (when (org-mode-p)
14012 (let ((pos (occur-mode-find-occurrence)))
14013 (with-current-buffer (marker-buffer pos)
14014 (save-excursion
14015 (goto-char pos)
14016 (org-reveal)))))))
14018 (defun org-uniquify (list)
14019 "Remove duplicate elements from LIST."
14020 (let (res)
14021 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14022 res))
14024 (defun org-delete-all (elts list)
14025 "Remove all elements in ELTS from LIST."
14026 (while elts
14027 (setq list (delete (pop elts) list)))
14028 list)
14030 (defun org-back-over-empty-lines ()
14031 "Move backwards over whitespace, to the beginning of the first empty line.
14032 Returns the number of empty lines passed."
14033 (let ((pos (point)))
14034 (skip-chars-backward " \t\n\r")
14035 (beginning-of-line 2)
14036 (goto-char (min (point) pos))
14037 (count-lines (point) pos)))
14039 (defun org-skip-whitespace ()
14040 (skip-chars-forward " \t\n\r"))
14042 (defun org-point-in-group (point group &optional context)
14043 "Check if POINT is in match-group GROUP.
14044 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14045 match. If the match group does ot exist or point is not inside it,
14046 return nil."
14047 (and (match-beginning group)
14048 (>= point (match-beginning group))
14049 (<= point (match-end group))
14050 (if context
14051 (list context (match-beginning group) (match-end group))
14052 t)))
14054 (defun org-switch-to-buffer-other-window (&rest args)
14055 "Switch to buffer in a second window on the current frame.
14056 In particular, do not allow pop-up frames."
14057 (let (pop-up-frames special-display-buffer-names special-display-regexps
14058 special-display-function)
14059 (apply 'switch-to-buffer-other-window args)))
14061 (defun org-combine-plists (&rest plists)
14062 "Create a single property list from all plists in PLISTS.
14063 The process starts by copying the first list, and then setting properties
14064 from the other lists. Settings in the last list are the most significant
14065 ones and overrule settings in the other lists."
14066 (let ((rtn (copy-sequence (pop plists)))
14067 p v ls)
14068 (while plists
14069 (setq ls (pop plists))
14070 (while ls
14071 (setq p (pop ls) v (pop ls))
14072 (setq rtn (plist-put rtn p v))))
14073 rtn))
14075 (defun org-move-line-down (arg)
14076 "Move the current line down. With prefix argument, move it past ARG lines."
14077 (interactive "p")
14078 (let ((col (current-column))
14079 beg end pos)
14080 (beginning-of-line 1) (setq beg (point))
14081 (beginning-of-line 2) (setq end (point))
14082 (beginning-of-line (+ 1 arg))
14083 (setq pos (move-marker (make-marker) (point)))
14084 (insert (delete-and-extract-region beg end))
14085 (goto-char pos)
14086 (org-move-to-column col)))
14088 (defun org-move-line-up (arg)
14089 "Move the current line up. With prefix argument, move it past ARG lines."
14090 (interactive "p")
14091 (let ((col (current-column))
14092 beg end pos)
14093 (beginning-of-line 1) (setq beg (point))
14094 (beginning-of-line 2) (setq end (point))
14095 (beginning-of-line (- arg))
14096 (setq pos (move-marker (make-marker) (point)))
14097 (insert (delete-and-extract-region beg end))
14098 (goto-char pos)
14099 (org-move-to-column col)))
14101 (defun org-replace-escapes (string table)
14102 "Replace %-escapes in STRING with values in TABLE.
14103 TABLE is an association list with keys like \"%a\" and string values.
14104 The sequences in STRING may contain normal field width and padding information,
14105 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14106 so values can contain further %-escapes if they are define later in TABLE."
14107 (let ((case-fold-search nil)
14108 e re rpl)
14109 (while (setq e (pop table))
14110 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14111 (while (string-match re string)
14112 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14113 (cdr e)))
14114 (setq string (replace-match rpl t t string))))
14115 string))
14118 (defun org-sublist (list start end)
14119 "Return a section of LIST, from START to END.
14120 Counting starts at 1."
14121 (let (rtn (c start))
14122 (setq list (nthcdr (1- start) list))
14123 (while (and list (<= c end))
14124 (push (pop list) rtn)
14125 (setq c (1+ c)))
14126 (nreverse rtn)))
14128 (defun org-find-base-buffer-visiting (file)
14129 "Like `find-buffer-visiting' but alway return the base buffer and
14130 not an indirect buffer."
14131 (let ((buf (find-buffer-visiting file)))
14132 (if buf
14133 (or (buffer-base-buffer buf) buf)
14134 nil)))
14136 (defun org-image-file-name-regexp ()
14137 "Return regexp matching the file names of images."
14138 (if (fboundp 'image-file-name-regexp)
14139 (image-file-name-regexp)
14140 (let ((image-file-name-extensions
14141 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14142 "xbm" "xpm" "pbm" "pgm" "ppm")))
14143 (concat "\\."
14144 (regexp-opt (nconc (mapcar 'upcase
14145 image-file-name-extensions)
14146 image-file-name-extensions)
14148 "\\'"))))
14150 (defun org-file-image-p (file)
14151 "Return non-nil if FILE is an image."
14152 (save-match-data
14153 (string-match (org-image-file-name-regexp) file)))
14155 (defun org-get-cursor-date ()
14156 "Return the date at cursor in as a time.
14157 This works in the calendar and in the agenda, anywhere else it just
14158 returns the current time."
14159 (let (date day defd)
14160 (cond
14161 ((eq major-mode 'calendar-mode)
14162 (setq date (calendar-cursor-to-date)
14163 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14164 ((eq major-mode 'org-agenda-mode)
14165 (setq day (get-text-property (point) 'day))
14166 (if day
14167 (setq date (calendar-gregorian-from-absolute day)
14168 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14169 (nth 2 date))))))
14170 (or defd (current-time))))
14172 (defvar org-agenda-action-marker (make-marker)
14173 "Marker pointing to the entry for the next agenda action.")
14175 (defun org-mark-entry-for-agenda-action ()
14176 "Mark the current entry as target of an agenda action.
14177 Agenda actions are actions executed from the agenda with the key `k',
14178 which make use of the date at the cursor."
14179 (interactive)
14180 (move-marker org-agenda-action-marker
14181 (save-excursion (org-back-to-heading t) (point))
14182 (current-buffer))
14183 (message
14184 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14186 ;;; Paragraph filling stuff.
14187 ;; We want this to be just right, so use the full arsenal.
14189 (defun org-indent-line-function ()
14190 "Indent line like previous, but further if previous was headline or item."
14191 (interactive)
14192 (let* ((pos (point))
14193 (itemp (org-at-item-p))
14194 column bpos bcol tpos tcol bullet btype bullet-type)
14195 ;; Find the previous relevant line
14196 (beginning-of-line 1)
14197 (cond
14198 ((looking-at "#") (setq column 0))
14199 ((looking-at "\\*+ ") (setq column 0))
14201 (beginning-of-line 0)
14202 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14203 (beginning-of-line 0))
14204 (cond
14205 ((looking-at "\\*+[ \t]+")
14206 (if (not org-adapt-indentation)
14207 (setq column 0)
14208 (goto-char (match-end 0))
14209 (setq column (current-column))))
14210 ((org-in-item-p)
14211 (org-beginning-of-item)
14212 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14213 (setq bpos (match-beginning 1) tpos (match-end 0)
14214 bcol (progn (goto-char bpos) (current-column))
14215 tcol (progn (goto-char tpos) (current-column))
14216 bullet (match-string 1)
14217 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14218 (if (> tcol (+ bcol org-description-max-indent))
14219 (setq tcol (+ bcol 5)))
14220 (if (not itemp)
14221 (setq column tcol)
14222 (goto-char pos)
14223 (beginning-of-line 1)
14224 (if (looking-at "\\S-")
14225 (progn
14226 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14227 (setq bullet (match-string 1)
14228 btype (if (string-match "[0-9]" bullet) "n" bullet))
14229 (setq column (if (equal btype bullet-type) bcol tcol)))
14230 (setq column (org-get-indentation)))))
14231 (t (setq column (org-get-indentation))))))
14232 (goto-char pos)
14233 (if (<= (current-column) (current-indentation))
14234 (org-indent-line-to column)
14235 (save-excursion (org-indent-line-to column)))
14236 (setq column (current-column))
14237 (beginning-of-line 1)
14238 (if (looking-at
14239 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14240 (replace-match (concat "\\1" (format org-property-format
14241 (match-string 2) (match-string 3)))
14242 t nil))
14243 (org-move-to-column column)))
14245 (defun org-set-autofill-regexps ()
14246 (interactive)
14247 ;; In the paragraph separator we include headlines, because filling
14248 ;; text in a line directly attached to a headline would otherwise
14249 ;; fill the headline as well.
14250 (org-set-local 'comment-start-skip "^#+[ \t]*")
14251 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14252 ;; The paragraph starter includes hand-formatted lists.
14253 (org-set-local 'paragraph-start
14254 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14255 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14256 ;; But only if the user has not turned off tables or fixed-width regions
14257 (org-set-local
14258 'auto-fill-inhibit-regexp
14259 (concat "\\*+ \\|#\\+"
14260 "\\|[ \t]*" org-keyword-time-regexp
14261 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14262 (concat
14263 "\\|[ \t]*["
14264 (if org-enable-table-editor "|" "")
14265 (if org-enable-fixed-width-editor ":" "")
14266 "]"))))
14267 ;; We use our own fill-paragraph function, to make sure that tables
14268 ;; and fixed-width regions are not wrapped. That function will pass
14269 ;; through to `fill-paragraph' when appropriate.
14270 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14271 ; Adaptive filling: To get full control, first make sure that
14272 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14273 (org-set-local 'adaptive-fill-regexp "\000")
14274 (org-set-local 'adaptive-fill-function
14275 'org-adaptive-fill-function)
14276 (org-set-local
14277 'align-mode-rules-list
14278 '((org-in-buffer-settings
14279 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14280 (modes . '(org-mode))))))
14282 (defun org-fill-paragraph (&optional justify)
14283 "Re-align a table, pass through to fill-paragraph if no table."
14284 (let ((table-p (org-at-table-p))
14285 (table.el-p (org-at-table.el-p)))
14286 (cond ((and (equal (char-after (point-at-bol)) ?*)
14287 (save-excursion (goto-char (point-at-bol))
14288 (looking-at outline-regexp)))
14289 t) ; skip headlines
14290 (table.el-p t) ; skip table.el tables
14291 (table-p (org-table-align) t) ; align org-mode tables
14292 (t nil)))) ; call paragraph-fill
14294 ;; For reference, this is the default value of adaptive-fill-regexp
14295 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14297 (defun org-adaptive-fill-function ()
14298 "Return a fill prefix for org-mode files.
14299 In particular, this makes sure hanging paragraphs for hand-formatted lists
14300 work correctly."
14301 (cond ((looking-at "#[ \t]+")
14302 (match-string 0))
14303 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14304 (save-excursion
14305 (if (> (match-end 1) (+ (match-beginning 1)
14306 org-description-max-indent))
14307 (goto-char (+ (match-beginning 1) 5))
14308 (goto-char (match-end 0)))
14309 (make-string (current-column) ?\ )))
14310 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14311 (save-excursion
14312 (goto-char (match-end 0))
14313 (make-string (current-column) ?\ )))
14314 (t nil)))
14316 ;;; Other stuff.
14318 (defun org-toggle-fixed-width-section (arg)
14319 "Toggle the fixed-width export.
14320 If there is no active region, the QUOTE keyword at the current headline is
14321 inserted or removed. When present, it causes the text between this headline
14322 and the next to be exported as fixed-width text, and unmodified.
14323 If there is an active region, this command adds or removes a colon as the
14324 first character of this line. If the first character of a line is a colon,
14325 this line is also exported in fixed-width font."
14326 (interactive "P")
14327 (let* ((cc 0)
14328 (regionp (org-region-active-p))
14329 (beg (if regionp (region-beginning) (point)))
14330 (end (if regionp (region-end)))
14331 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14332 (case-fold-search nil)
14333 (re "[ \t]*\\(:\\)")
14334 off)
14335 (if regionp
14336 (save-excursion
14337 (goto-char beg)
14338 (setq cc (current-column))
14339 (beginning-of-line 1)
14340 (setq off (looking-at re))
14341 (while (> nlines 0)
14342 (setq nlines (1- nlines))
14343 (beginning-of-line 1)
14344 (cond
14345 (arg
14346 (org-move-to-column cc t)
14347 (insert ":\n")
14348 (forward-line -1))
14349 ((and off (looking-at re))
14350 (replace-match "" t t nil 1))
14351 ((not off) (org-move-to-column cc t) (insert ":")))
14352 (forward-line 1)))
14353 (save-excursion
14354 (org-back-to-heading)
14355 (if (looking-at (concat outline-regexp
14356 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14357 (replace-match "" t t nil 1)
14358 (if (looking-at outline-regexp)
14359 (progn
14360 (goto-char (match-end 0))
14361 (insert org-quote-string " "))))))))
14363 ;;;; Functions extending outline functionality
14365 (defun org-beginning-of-line (&optional arg)
14366 "Go to the beginning of the current line. If that is invisible, continue
14367 to a visible line beginning. This makes the function of C-a more intuitive.
14368 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14369 first attempt, and only move to after the tags when the cursor is already
14370 beyond the end of the headline."
14371 (interactive "P")
14372 (let ((pos (point)) refpos)
14373 (beginning-of-line 1)
14374 (if (bobp)
14376 (backward-char 1)
14377 (if (org-invisible-p)
14378 (while (and (not (bobp)) (org-invisible-p))
14379 (backward-char 1)
14380 (beginning-of-line 1))
14381 (forward-char 1)))
14382 (when org-special-ctrl-a/e
14383 (cond
14384 ((and (looking-at org-complex-heading-regexp)
14385 (= (char-after (match-end 1)) ?\ ))
14386 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14387 (point-at-eol)))
14388 (goto-char
14389 (if (eq org-special-ctrl-a/e t)
14390 (cond ((> pos refpos) refpos)
14391 ((= pos (point)) refpos)
14392 (t (point)))
14393 (cond ((> pos (point)) (point))
14394 ((not (eq last-command this-command)) (point))
14395 (t refpos)))))
14396 ((org-at-item-p)
14397 (goto-char
14398 (if (eq org-special-ctrl-a/e t)
14399 (cond ((> pos (match-end 4)) (match-end 4))
14400 ((= pos (point)) (match-end 4))
14401 (t (point)))
14402 (cond ((> pos (point)) (point))
14403 ((not (eq last-command this-command)) (point))
14404 (t (match-end 4))))))))
14405 (org-no-warnings
14406 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14408 (defun org-end-of-line (&optional arg)
14409 "Go to the end of the line.
14410 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14411 first attempt, and only move to after the tags when the cursor is already
14412 beyond the end of the headline."
14413 (interactive "P")
14414 (if (or (not org-special-ctrl-a/e)
14415 (not (org-on-heading-p)))
14416 (end-of-line arg)
14417 (let ((pos (point)))
14418 (beginning-of-line 1)
14419 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14420 (if (eq org-special-ctrl-a/e t)
14421 (if (or (< pos (match-beginning 1))
14422 (= pos (match-end 0)))
14423 (goto-char (match-beginning 1))
14424 (goto-char (match-end 0)))
14425 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14426 (goto-char (match-end 0))
14427 (goto-char (match-beginning 1))))
14428 (end-of-line arg))))
14429 (org-no-warnings
14430 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14433 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14434 (define-key org-mode-map "\C-e" 'org-end-of-line)
14436 (defun org-kill-line (&optional arg)
14437 "Kill line, to tags or end of line."
14438 (interactive "P")
14439 (cond
14440 ((or (not org-special-ctrl-k)
14441 (bolp)
14442 (not (org-on-heading-p)))
14443 (call-interactively 'kill-line))
14444 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14445 (kill-region (point) (match-beginning 1))
14446 (org-set-tags nil t))
14447 (t (kill-region (point) (point-at-eol)))))
14449 (define-key org-mode-map "\C-k" 'org-kill-line)
14451 (defun org-yank (&optional arg)
14452 "Yank. If the kill is a subtree, treat it specially.
14453 This command will look at the current kill and check if is a single
14454 subtree, or a series of subtrees[1]. If it passes the test, and if the
14455 cursor is at the beginning of a line or after the stars of a currently
14456 empty headline, then the yank is handled specially. How exactly depends
14457 on the value of the following variables, both set by default.
14459 org-yank-folded-subtrees
14460 When set, the subtree(s) will be folded after insertion, but only
14461 if doing so would now swallow text after the yanked text.
14463 org-yank-adjusted-subtrees
14464 When set, the subtree will be promoted or demoted in order to
14465 fit into the local outline tree structure, which means that the level
14466 will be adjusted so that it becomes the smaller one of the two
14467 *visible* surrounding headings.
14469 Any prefix to this command will cause `yank' to be called directly with
14470 no special treatment. In particular, a simple `C-u' prefix will just
14471 plainly yank the text as it is.
14473 \[1] Basically, the test checks if the first non-white line is a heading
14474 and if there are no other headings with fewer stars."
14475 (interactive "P")
14476 (setq this-command 'yank)
14477 (if arg
14478 (call-interactively 'yank)
14479 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14480 (and (org-kill-is-subtree-p)
14481 (or (bolp)
14482 (and (looking-at "[ \t]*$")
14483 (string-match
14484 "\\`\\*+\\'"
14485 (buffer-substring (point-at-bol) (point)))))))
14486 swallowp)
14487 (cond
14488 ((and subtreep org-yank-folded-subtrees)
14489 (let ((beg (point))
14490 end)
14491 (if (and subtreep org-yank-adjusted-subtrees)
14492 (org-paste-subtree nil nil 'for-yank)
14493 (call-interactively 'yank))
14494 (setq end (point))
14495 (goto-char beg)
14496 (when (and (bolp) subtreep
14497 (not (setq swallowp
14498 (org-yank-folding-would-swallow-text beg end))))
14499 (or (looking-at outline-regexp)
14500 (re-search-forward (concat "^" outline-regexp) end t))
14501 (while (and (< (point) end) (looking-at outline-regexp))
14502 (hide-subtree)
14503 (org-cycle-show-empty-lines 'folded)
14504 (condition-case nil
14505 (outline-forward-same-level 1)
14506 (error (goto-char end)))))
14507 (when swallowp
14508 (message
14509 "Yanked text not folded because that would swallow text"))
14510 (goto-char end)
14511 (skip-chars-forward " \t\n\r")
14512 (beginning-of-line 1)
14513 (push-mark beg 'nomsg)))
14514 ((and subtreep org-yank-adjusted-subtrees)
14515 (let ((beg (point-at-bol)))
14516 (org-paste-subtree nil nil 'for-yank)
14517 (push-mark beg 'nomsg)))
14519 (call-interactively 'yank))))))
14521 (defun org-yank-folding-would-swallow-text (beg end)
14522 "Would hide-subtree at BEG swallow any text after END?"
14523 (let (level)
14524 (save-excursion
14525 (goto-char beg)
14526 (when (or (looking-at outline-regexp)
14527 (re-search-forward (concat "^" outline-regexp) end t))
14528 (setq level (org-outline-level)))
14529 (goto-char end)
14530 (skip-chars-forward " \t\r\n\v\f")
14531 (if (or (eobp)
14532 (and (bolp) (looking-at org-outline-regexp)
14533 (<= (org-outline-level) level)))
14534 nil ; Nothing would be swallowed
14535 t)))) ; something would swallow
14537 (define-key org-mode-map "\C-y" 'org-yank)
14539 (defun org-invisible-p ()
14540 "Check if point is at a character currently not visible."
14541 ;; Early versions of noutline don't have `outline-invisible-p'.
14542 (if (fboundp 'outline-invisible-p)
14543 (outline-invisible-p)
14544 (get-char-property (point) 'invisible)))
14546 (defun org-invisible-p2 ()
14547 "Check if point is at a character currently not visible."
14548 (save-excursion
14549 (if (and (eolp) (not (bobp))) (backward-char 1))
14550 ;; Early versions of noutline don't have `outline-invisible-p'.
14551 (if (fboundp 'outline-invisible-p)
14552 (outline-invisible-p)
14553 (get-char-property (point) 'invisible))))
14555 (defun org-back-to-heading (&optional invisible-ok)
14556 "Call `outline-back-to-heading', but provide a better error message."
14557 (condition-case nil
14558 (outline-back-to-heading invisible-ok)
14559 (error (error "Before first headline at position %d in buffer %s"
14560 (point) (current-buffer)))))
14562 (defun org-before-first-heading-p ()
14563 "Before first heading?"
14564 (save-excursion
14565 (null (re-search-backward "^\\*+ " nil t))))
14567 (defalias 'org-on-heading-p 'outline-on-heading-p)
14568 (defalias 'org-at-heading-p 'outline-on-heading-p)
14569 (defun org-at-heading-or-item-p ()
14570 (or (org-on-heading-p) (org-at-item-p)))
14572 (defun org-on-target-p ()
14573 (or (org-in-regexp org-radio-target-regexp)
14574 (org-in-regexp org-target-regexp)))
14576 (defun org-up-heading-all (arg)
14577 "Move to the heading line of which the present line is a subheading.
14578 This function considers both visible and invisible heading lines.
14579 With argument, move up ARG levels."
14580 (if (fboundp 'outline-up-heading-all)
14581 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14582 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14584 (defun org-up-heading-safe ()
14585 "Move to the heading line of which the present line is a subheading.
14586 This version will not throw an error. It will return the level of the
14587 headline found, or nil if no higher level is found."
14588 (let (start-level re)
14589 (org-back-to-heading t)
14590 (setq start-level (funcall outline-level))
14591 (if (equal start-level 1)
14593 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14594 (if (re-search-backward re nil t)
14595 (funcall outline-level)))))
14597 (defun org-first-sibling-p ()
14598 "Is this heading the first child of its parents?"
14599 (interactive)
14600 (let ((re (concat "^" outline-regexp))
14601 level l)
14602 (unless (org-at-heading-p t)
14603 (error "Not at a heading"))
14604 (setq level (funcall outline-level))
14605 (save-excursion
14606 (if (not (re-search-backward re nil t))
14608 (setq l (funcall outline-level))
14609 (< l level)))))
14611 (defun org-goto-sibling (&optional previous)
14612 "Goto the next sibling, even if it is invisible.
14613 When PREVIOUS is set, go to the previous sibling instead. Returns t
14614 when a sibling was found. When none is found, return nil and don't
14615 move point."
14616 (let ((fun (if previous 're-search-backward 're-search-forward))
14617 (pos (point))
14618 (re (concat "^" outline-regexp))
14619 level l)
14620 (when (condition-case nil (org-back-to-heading t) (error nil))
14621 (setq level (funcall outline-level))
14622 (catch 'exit
14623 (or previous (forward-char 1))
14624 (while (funcall fun re nil t)
14625 (setq l (funcall outline-level))
14626 (when (< l level) (goto-char pos) (throw 'exit nil))
14627 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14628 (goto-char pos)
14629 nil))))
14631 (defun org-show-siblings ()
14632 "Show all siblings of the current headline."
14633 (save-excursion
14634 (while (org-goto-sibling) (org-flag-heading nil)))
14635 (save-excursion
14636 (while (org-goto-sibling 'previous)
14637 (org-flag-heading nil))))
14639 (defun org-show-hidden-entry ()
14640 "Show an entry where even the heading is hidden."
14641 (save-excursion
14642 (org-show-entry)))
14644 (defun org-flag-heading (flag &optional entry)
14645 "Flag the current heading. FLAG non-nil means make invisible.
14646 When ENTRY is non-nil, show the entire entry."
14647 (save-excursion
14648 (org-back-to-heading t)
14649 ;; Check if we should show the entire entry
14650 (if entry
14651 (progn
14652 (org-show-entry)
14653 (save-excursion
14654 (and (outline-next-heading)
14655 (org-flag-heading nil))))
14656 (outline-flag-region (max (point-min) (1- (point)))
14657 (save-excursion (outline-end-of-heading) (point))
14658 flag))))
14660 (defun org-forward-same-level (arg)
14661 "Move forward to the ARG'th subheading at same level as this one.
14662 Stop at the first and last subheadings of a superior heading.
14663 This is like outline-forward-same-level, but invisible headings are ok."
14664 (interactive "p")
14665 (org-back-to-heading t)
14666 (while (> arg 0)
14667 (let ((point-to-move-to (save-excursion
14668 (org-get-next-sibling))))
14669 (if point-to-move-to
14670 (progn
14671 (goto-char point-to-move-to)
14672 (setq arg (1- arg)))
14673 (progn
14674 (setq arg 0)
14675 (error "No following same-level heading"))))))
14677 (defun org-get-next-sibling ()
14678 "Move to next heading of the same level, and return point.
14679 If there is no such heading, return nil.
14680 This is like outline-next-sibling, but invisible headings are ok."
14681 (let ((level (funcall outline-level)))
14682 (outline-next-heading)
14683 (while (and (not (eobp)) (> (funcall outline-level) level))
14684 (outline-next-heading))
14685 (if (or (eobp) (< (funcall outline-level) level))
14687 (point))))
14689 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14690 ;; This is an exact copy of the original function, but it uses
14691 ;; `org-back-to-heading', to make it work also in invisible
14692 ;; trees. And is uses an invisible-OK argument.
14693 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14694 (org-back-to-heading invisible-OK)
14695 (let ((first t)
14696 (level (funcall outline-level)))
14697 (while (and (not (eobp))
14698 (or first (> (funcall outline-level) level)))
14699 (setq first nil)
14700 (outline-next-heading))
14701 (unless to-heading
14702 (if (memq (preceding-char) '(?\n ?\^M))
14703 (progn
14704 ;; Go to end of line before heading
14705 (forward-char -1)
14706 (if (memq (preceding-char) '(?\n ?\^M))
14707 ;; leave blank line before heading
14708 (forward-char -1))))))
14709 (point))
14711 (defun org-show-subtree ()
14712 "Show everything after this heading at deeper levels."
14713 (outline-flag-region
14714 (point)
14715 (save-excursion
14716 (outline-end-of-subtree) (outline-next-heading) (point))
14717 nil))
14719 (defun org-show-entry ()
14720 "Show the body directly following this heading.
14721 Show the heading too, if it is currently invisible."
14722 (interactive)
14723 (save-excursion
14724 (condition-case nil
14725 (progn
14726 (org-back-to-heading t)
14727 (outline-flag-region
14728 (max (point-min) (1- (point)))
14729 (save-excursion
14730 (re-search-forward
14731 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14732 (or (match-beginning 1) (point-max)))
14733 nil))
14734 (error nil))))
14736 (defun org-make-options-regexp (kwds)
14737 "Make a regular expression for keyword lines."
14738 (concat
14740 "#?[ \t]*\\+\\("
14741 (mapconcat 'regexp-quote kwds "\\|")
14742 "\\):[ \t]*"
14743 "\\(.+\\)"))
14745 ;; Make isearch reveal the necessary context
14746 (defun org-isearch-end ()
14747 "Reveal context after isearch exits."
14748 (when isearch-success ; only if search was successful
14749 (if (featurep 'xemacs)
14750 ;; Under XEmacs, the hook is run in the correct place,
14751 ;; we directly show the context.
14752 (org-show-context 'isearch)
14753 ;; In Emacs the hook runs *before* restoring the overlays.
14754 ;; So we have to use a one-time post-command-hook to do this.
14755 ;; (Emacs 22 has a special variable, see function `org-mode')
14756 (unless (and (boundp 'isearch-mode-end-hook-quit)
14757 isearch-mode-end-hook-quit)
14758 ;; Only when the isearch was not quitted.
14759 (org-add-hook 'post-command-hook 'org-isearch-post-command
14760 'append 'local)))))
14762 (defun org-isearch-post-command ()
14763 "Remove self from hook, and show context."
14764 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14765 (org-show-context 'isearch))
14768 ;;;; Integration with and fixes for other packages
14770 ;;; Imenu support
14772 (defvar org-imenu-markers nil
14773 "All markers currently used by Imenu.")
14774 (make-variable-buffer-local 'org-imenu-markers)
14776 (defun org-imenu-new-marker (&optional pos)
14777 "Return a new marker for use by Imenu, and remember the marker."
14778 (let ((m (make-marker)))
14779 (move-marker m (or pos (point)))
14780 (push m org-imenu-markers)
14783 (defun org-imenu-get-tree ()
14784 "Produce the index for Imenu."
14785 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14786 (setq org-imenu-markers nil)
14787 (let* ((n org-imenu-depth)
14788 (re (concat "^" outline-regexp))
14789 (subs (make-vector (1+ n) nil))
14790 (last-level 0)
14791 m tree level head)
14792 (save-excursion
14793 (save-restriction
14794 (widen)
14795 (goto-char (point-max))
14796 (while (re-search-backward re nil t)
14797 (setq level (org-reduced-level (funcall outline-level)))
14798 (when (<= level n)
14799 (looking-at org-complex-heading-regexp)
14800 (setq head (org-link-display-format
14801 (org-match-string-no-properties 4))
14802 m (org-imenu-new-marker))
14803 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14804 (if (>= level last-level)
14805 (push (cons head m) (aref subs level))
14806 (push (cons head (aref subs (1+ level))) (aref subs level))
14807 (loop for i from (1+ level) to n do (aset subs i nil)))
14808 (setq last-level level)))))
14809 (aref subs 1)))
14811 (eval-after-load "imenu"
14812 '(progn
14813 (add-hook 'imenu-after-jump-hook
14814 (lambda ()
14815 (if (eq major-mode 'org-mode)
14816 (org-show-context 'org-goto))))))
14818 (defun org-link-display-format (link)
14819 "Replace a link with either the description, or the link target
14820 if no description is present"
14821 (save-match-data
14822 (if (string-match org-bracket-link-analytic-regexp link)
14823 (replace-match (or (match-string 5 link)
14824 (concat (match-string 1 link)
14825 (match-string 3 link)))
14826 nil nil link)
14827 link)))
14829 ;; Speedbar support
14831 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14832 "Overlay marking the agenda restriction line in speedbar.")
14833 (org-overlay-put org-speedbar-restriction-lock-overlay
14834 'face 'org-agenda-restriction-lock)
14835 (org-overlay-put org-speedbar-restriction-lock-overlay
14836 'help-echo "Agendas are currently limited to this item.")
14837 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14839 (defun org-speedbar-set-agenda-restriction ()
14840 "Restrict future agenda commands to the location at point in speedbar.
14841 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14842 (interactive)
14843 (require 'org-agenda)
14844 (let (p m tp np dir txt w)
14845 (cond
14846 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14847 'org-imenu t))
14848 (setq m (get-text-property p 'org-imenu-marker))
14849 (save-excursion
14850 (save-restriction
14851 (set-buffer (marker-buffer m))
14852 (goto-char m)
14853 (org-agenda-set-restriction-lock 'subtree))))
14854 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14855 'speedbar-function 'speedbar-find-file))
14856 (setq tp (previous-single-property-change
14857 (1+ p) 'speedbar-function)
14858 np (next-single-property-change
14859 tp 'speedbar-function)
14860 dir (speedbar-line-directory)
14861 txt (buffer-substring-no-properties (or tp (point-min))
14862 (or np (point-max))))
14863 (save-excursion
14864 (save-restriction
14865 (set-buffer (find-file-noselect
14866 (let ((default-directory dir))
14867 (expand-file-name txt))))
14868 (unless (org-mode-p)
14869 (error "Cannot restrict to non-Org-mode file"))
14870 (org-agenda-set-restriction-lock 'file))))
14871 (t (error "Don't know how to restrict Org-mode's agenda")))
14872 (org-move-overlay org-speedbar-restriction-lock-overlay
14873 (point-at-bol) (point-at-eol))
14874 (setq current-prefix-arg nil)
14875 (org-agenda-maybe-redo)))
14877 (eval-after-load "speedbar"
14878 '(progn
14879 (speedbar-add-supported-extension ".org")
14880 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14881 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14882 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14883 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14884 (add-hook 'speedbar-visiting-tag-hook
14885 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14888 ;;; Fixes and Hacks for problems with other packages
14890 ;; Make flyspell not check words in links, to not mess up our keymap
14891 (defun org-mode-flyspell-verify ()
14892 "Don't let flyspell put overlays at active buttons."
14893 (not (get-text-property (point) 'keymap)))
14895 ;; Make `bookmark-jump' show the jump location if it was hidden.
14896 (eval-after-load "bookmark"
14897 '(if (boundp 'bookmark-after-jump-hook)
14898 ;; We can use the hook
14899 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14900 ;; Hook not available, use advice
14901 (defadvice bookmark-jump (after org-make-visible activate)
14902 "Make the position visible."
14903 (org-bookmark-jump-unhide))))
14905 ;; Make sure saveplace show the location if it was hidden
14906 (eval-after-load "saveplace"
14907 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14908 "Make the position visible."
14909 (org-bookmark-jump-unhide)))
14911 (defun org-bookmark-jump-unhide ()
14912 "Unhide the current position, to show the bookmark location."
14913 (and (org-mode-p)
14914 (or (org-invisible-p)
14915 (save-excursion (goto-char (max (point-min) (1- (point))))
14916 (org-invisible-p)))
14917 (org-show-context 'bookmark-jump)))
14919 ;; Make session.el ignore our circular variable
14920 (eval-after-load "session"
14921 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14923 ;;;; Experimental code
14925 (defun org-closed-in-range ()
14926 "Sparse tree of items closed in a certain time range.
14927 Still experimental, may disappear in the future."
14928 (interactive)
14929 ;; Get the time interval from the user.
14930 (let* ((time1 (time-to-seconds
14931 (org-read-date nil 'to-time nil "Starting date: ")))
14932 (time2 (time-to-seconds
14933 (org-read-date nil 'to-time nil "End date:")))
14934 ;; callback function
14935 (callback (lambda ()
14936 (let ((time
14937 (time-to-seconds
14938 (apply 'encode-time
14939 (org-parse-time-string
14940 (match-string 1))))))
14941 ;; check if time in interval
14942 (and (>= time time1) (<= time time2))))))
14943 ;; make tree, check each match with the callback
14944 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14947 ;;;; Finish up
14949 (provide 'org)
14951 (run-hooks 'org-load-hook)
14953 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14955 ;;; org.el ends here