Bugfix: Make sure property time comparison works correctly.
[org-mode.git] / lisp / org.el
blobf9db5162bf079bda678d74106bb2ae617c88715b
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, 2009 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.17trans
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.17trans"
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 . auto)
693 (plain-list-item . auto))
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)
700 (choice (const :tag "Never" nil)
701 (const :tag "Always" t)
702 (const :tag "Auto" auto)))
703 (cons (const plain-list-item)
704 (choice (const :tag "Never" nil)
705 (const :tag "Always" t)
706 (const :tag "Auto" auto)))))
708 (defcustom org-insert-heading-hook nil
709 "Hook being run after inserting a new heading."
710 :group 'org-edit-structure
711 :type 'hook)
713 (defcustom org-enable-fixed-width-editor t
714 "Non-nil means, lines starting with \":\" are treated as fixed-width.
715 This currently only means, they are never auto-wrapped.
716 When nil, such lines will be treated like ordinary lines.
717 See also the QUOTE keyword."
718 :group 'org-edit-structure
719 :type 'boolean)
721 (defcustom org-edit-src-region-extra nil
722 "Additional regexps to identify regions for editing with `org-edit-src-code'.
723 For examples see the function `org-edit-src-find-region-and-lang'.
724 The regular expression identifying the begin marker should end with a newline,
725 and the regexp marking the end line should start with a newline, to make sure
726 there are kept outside the narrowed region."
727 :group 'org-edit-structure
728 :type '(repeat
729 (list
730 (regexp :tag "begin regexp")
731 (regexp :tag "end regexp")
732 (choice :tag "language"
733 (string :tag "specify")
734 (integer :tag "from match group")
735 (const :tag "from `lang' element")
736 (const :tag "from `style' element")))))
738 (defcustom org-coderef-label-format "(ref:%s)"
739 "The default coderef format.
740 This format string will be used to search for coderef labels in literal
741 examples (EXAMPLE and SRC blocks). The format can be overwritten
742 an individual literal example with the -f option, like
744 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
746 #+END_SRC
748 If you want to use this for HTML export, make sure that the format does
749 not introduce special font-locking, and avoid the HTML special
750 characters `<', `>', and `&'. The reason for this restriction is that
751 the labels are searched for only after htmlize has done its job."
752 :group 'org-edit-structure ; FIXME this is not in the right group
753 :type 'string)
755 (defcustom org-edit-fixed-width-region-mode 'artist-mode
756 "The mode that should be used to edit fixed-width regions.
757 These are the regions where each line starts with a colon."
758 :group 'org-edit-structure
759 :type '(choice
760 (const artist-mode)
761 (const picture-mode)
762 (const fundamental-mode)
763 (function :tag "Other (specify)")))
765 (defcustom org-goto-auto-isearch t
766 "Non-nil means, typing characters in org-goto starts incremental search."
767 :group 'org-edit-structure
768 :type 'boolean)
770 (defgroup org-sparse-trees nil
771 "Options concerning sparse trees in Org-mode."
772 :tag "Org Sparse Trees"
773 :group 'org-structure)
775 (defcustom org-highlight-sparse-tree-matches t
776 "Non-nil means, highlight all matches that define a sparse tree.
777 The highlights will automatically disappear the next time the buffer is
778 changed by an edit command."
779 :group 'org-sparse-trees
780 :type 'boolean)
782 (defcustom org-remove-highlights-with-change t
783 "Non-nil means, any change to the buffer will remove temporary highlights.
784 Such highlights are created by `org-occur' and `org-clock-display'.
785 When nil, `C-c C-c needs to be used to get rid of the highlights.
786 The highlights created by `org-preview-latex-fragment' always need
787 `C-c C-c' to be removed."
788 :group 'org-sparse-trees
789 :group 'org-time
790 :type 'boolean)
793 (defcustom org-occur-hook '(org-first-headline-recenter)
794 "Hook that is run after `org-occur' has constructed a sparse tree.
795 This can be used to recenter the window to show as much of the structure
796 as possible."
797 :group 'org-sparse-trees
798 :type 'hook)
800 (defgroup org-imenu-and-speedbar nil
801 "Options concerning imenu and speedbar in Org-mode."
802 :tag "Org Imenu and Speedbar"
803 :group 'org-structure)
805 (defcustom org-imenu-depth 2
806 "The maximum level for Imenu access to Org-mode headlines.
807 This also applied for speedbar access."
808 :group 'org-imenu-and-speedbar
809 :type 'number)
811 (defgroup org-table nil
812 "Options concerning tables in Org-mode."
813 :tag "Org Table"
814 :group 'org)
816 (defcustom org-enable-table-editor 'optimized
817 "Non-nil means, lines starting with \"|\" are handled by the table editor.
818 When nil, such lines will be treated like ordinary lines.
820 When equal to the symbol `optimized', the table editor will be optimized to
821 do the following:
822 - Automatic overwrite mode in front of whitespace in table fields.
823 This makes the structure of the table stay in tact as long as the edited
824 field does not exceed the column width.
825 - Minimize the number of realigns. Normally, the table is aligned each time
826 TAB or RET are pressed to move to another field. With optimization this
827 happens only if changes to a field might have changed the column width.
828 Optimization requires replacing the functions `self-insert-command',
829 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
830 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
831 very good at guessing when a re-align will be necessary, but you can always
832 force one with \\[org-ctrl-c-ctrl-c].
834 If you would like to use the optimized version in Org-mode, but the
835 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
837 This variable can be used to turn on and off the table editor during a session,
838 but in order to toggle optimization, a restart is required.
840 See also the variable `org-table-auto-blank-field'."
841 :group 'org-table
842 :type '(choice
843 (const :tag "off" nil)
844 (const :tag "on" t)
845 (const :tag "on, optimized" optimized)))
847 (defcustom org-table-tab-recognizes-table.el t
848 "Non-nil means, TAB will automatically notice a table.el table.
849 When it sees such a table, it moves point into it and - if necessary -
850 calls `table-recognize-table'."
851 :group 'org-table-editing
852 :type 'boolean)
854 (defgroup org-link nil
855 "Options concerning links in Org-mode."
856 :tag "Org Link"
857 :group 'org)
859 (defvar org-link-abbrev-alist-local nil
860 "Buffer-local version of `org-link-abbrev-alist', which see.
861 The value of this is taken from the #+LINK lines.")
862 (make-variable-buffer-local 'org-link-abbrev-alist-local)
864 (defcustom org-link-abbrev-alist nil
865 "Alist of link abbreviations.
866 The car of each element is a string, to be replaced at the start of a link.
867 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
868 links in Org-mode buffers can have an optional tag after a double colon, e.g.
870 [[linkkey:tag][description]]
872 If REPLACE is a string, the tag will simply be appended to create the link.
873 If the string contains \"%s\", the tag will be inserted there. Alternatively,
874 the placeholder \"%h\" will cause a url-encoded version of the tag to
875 be inserted at that point (see the function `url-hexify-string').
877 REPLACE may also be a function that will be called with the tag as the
878 only argument to create the link, which should be returned as a string.
880 See the manual for examples."
881 :group 'org-link
882 :type '(repeat
883 (cons
884 (string :tag "Protocol")
885 (choice
886 (string :tag "Format")
887 (function)))))
889 (defcustom org-descriptive-links t
890 "Non-nil means, hide link part and only show description of bracket links.
891 Bracket links are like [[link][description]]. This variable sets the initial
892 state in new org-mode buffers. The setting can then be toggled on a
893 per-buffer basis from the Org->Hyperlinks menu."
894 :group 'org-link
895 :type 'boolean)
897 (defcustom org-link-file-path-type 'adaptive
898 "How the path name in file links should be stored.
899 Valid values are:
901 relative Relative to the current directory, i.e. the directory of the file
902 into which the link is being inserted.
903 absolute Absolute path, if possible with ~ for home directory.
904 noabbrev Absolute path, no abbreviation of home directory.
905 adaptive Use relative path for files in the current directory and sub-
906 directories of it. For other files, use an absolute path."
907 :group 'org-link
908 :type '(choice
909 (const relative)
910 (const absolute)
911 (const noabbrev)
912 (const adaptive)))
914 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
915 "Types of links that should be activated in Org-mode files.
916 This is a list of symbols, each leading to the activation of a certain link
917 type. In principle, it does not hurt to turn on most link types - there may
918 be a small gain when turning off unused link types. The types are:
920 bracket The recommended [[link][description]] or [[link]] links with hiding.
921 angular Links in angular brackets that may contain whitespace like
922 <bbdb:Carsten Dominik>.
923 plain Plain links in normal text, no whitespace, like http://google.com.
924 radio Text that is matched by a radio target, see manual for details.
925 tag Tag settings in a headline (link to tag search).
926 date Time stamps (link to calendar).
927 footnote Footnote labels.
929 Changing this variable requires a restart of Emacs to become effective."
930 :group 'org-link
931 :type '(set :greedy t
932 (const :tag "Double bracket links (new style)" bracket)
933 (const :tag "Angular bracket links (old style)" angular)
934 (const :tag "Plain text links" plain)
935 (const :tag "Radio target matches" radio)
936 (const :tag "Tags" tag)
937 (const :tag "Timestamps" date)
938 (const :tag "Footnotes" footnote)))
940 (defcustom org-make-link-description-function nil
941 "Function to use to generate link descriptions from links. If
942 nil the link location will be used. This function must take two
943 parameters; the first is the link and the second the description
944 org-insert-link has generated, and should return the description
945 to use."
946 :group 'org-link
947 :type 'function)
949 (defgroup org-link-store nil
950 "Options concerning storing links in Org-mode."
951 :tag "Org Store Link"
952 :group 'org-link)
954 (defcustom org-email-link-description-format "Email %c: %.30s"
955 "Format of the description part of a link to an email or usenet message.
956 The following %-escapes will be replaced by corresponding information:
958 %F full \"From\" field
959 %f name, taken from \"From\" field, address if no name
960 %T full \"To\" field
961 %t first name in \"To\" field, address if no name
962 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
963 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
964 %s subject
965 %m message-id.
967 You may use normal field width specification between the % and the letter.
968 This is for example useful to limit the length of the subject.
970 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
971 :group 'org-link-store
972 :type 'string)
974 (defcustom org-from-is-user-regexp
975 (let (r1 r2)
976 (when (and user-mail-address (not (string= user-mail-address "")))
977 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
978 (when (and user-full-name (not (string= user-full-name "")))
979 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
980 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
981 "Regexp matched against the \"From:\" header of an email or usenet message.
982 It should match if the message is from the user him/herself."
983 :group 'org-link-store
984 :type 'regexp)
986 (defcustom org-link-to-org-use-id 'create-if-interactive
987 "Non-nil means, storing a link to an Org file will use entry IDs.
989 Note that before this variable is even considered, org-id must be loaded,
990 to please customize `org-modules' and turn it on.
992 The variable can have the following values:
994 t Create an ID if needed to make a link to the current entry.
996 create-if-interactive
997 If `org-store-link' is called directly (interactively, as a user
998 command), do create an ID to support the link. But when doing the
999 job for remember, only use the ID if it already exists. The
1000 purpose of this setting is to avoid proliferation of unwanted
1001 IDs, just because you happen to be in an Org file when you
1002 call `org-remember' that automatically and preemptively
1003 creates a link. If you do want to get an ID link in a remember
1004 template to an entry not having an ID, create it first by
1005 explicitly creating a link to it, using `C-c C-l' first.
1007 use-existing
1008 Use existing ID, do not create one.
1010 nil Never use an ID to make a link, instead link using a text search for
1011 the headline text."
1012 :group 'org-link-store
1013 :type '(choice
1014 (const :tag "Create ID to make link" t)
1015 (const :tag "Create if string link interactively"
1016 'create-if-interactive)
1017 (const :tag "Only use existing" 'use-existing)
1018 (const :tag "Do not use ID to create link" nil)))
1020 (defcustom org-context-in-file-links t
1021 "Non-nil means, file links from `org-store-link' contain context.
1022 A search string will be added to the file name with :: as separator and
1023 used to find the context when the link is activated by the command
1024 `org-open-at-point'.
1025 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1026 negates this setting for the duration of the command."
1027 :group 'org-link-store
1028 :type 'boolean)
1030 (defcustom org-keep-stored-link-after-insertion nil
1031 "Non-nil means, keep link in list for entire session.
1033 The command `org-store-link' adds a link pointing to the current
1034 location to an internal list. These links accumulate during a session.
1035 The command `org-insert-link' can be used to insert links into any
1036 Org-mode file (offering completion for all stored links). When this
1037 option is nil, every link which has been inserted once using \\[org-insert-link]
1038 will be removed from the list, to make completing the unused links
1039 more efficient."
1040 :group 'org-link-store
1041 :type 'boolean)
1043 (defgroup org-link-follow nil
1044 "Options concerning following links in Org-mode."
1045 :tag "Org Follow Link"
1046 :group 'org-link)
1048 (defcustom org-link-translation-function nil
1049 "Function to translate links with different syntax to Org syntax.
1050 This can be used to translate links created for example by the Planner
1051 or emacs-wiki packages to Org syntax.
1052 The function must accept two parameters, a TYPE containing the link
1053 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1054 which is everything after the link protocol. It should return a cons
1055 with possibly modified values of type and path.
1056 Org contains a function for this, so if you set this variable to
1057 `org-translate-link-from-planner', you should be able follow many
1058 links created by planner."
1059 :group 'org-link-follow
1060 :type 'function)
1062 (defcustom org-follow-link-hook nil
1063 "Hook that is run after a link has been followed."
1064 :group 'org-link-follow
1065 :type 'hook)
1067 (defcustom org-tab-follows-link nil
1068 "Non-nil means, on links TAB 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-return-follows-link nil
1074 "Non-nil means, on links RET will follow the link.
1075 Needs to be set before org.el is loaded."
1076 :group 'org-link-follow
1077 :type 'boolean)
1079 (defcustom org-mouse-1-follows-link
1080 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1081 "Non-nil means, mouse-1 on a link will follow the link.
1082 A longer mouse click will still set point. Does not work on XEmacs.
1083 Needs to be set before org.el is loaded."
1084 :group 'org-link-follow
1085 :type 'boolean)
1087 (defcustom org-mark-ring-length 4
1088 "Number of different positions to be recorded in the ring
1089 Changing this requires a restart of Emacs to work correctly."
1090 :group 'org-link-follow
1091 :type 'integer)
1093 (defcustom org-link-frame-setup
1094 '((vm . vm-visit-folder-other-frame)
1095 (gnus . gnus-other-frame)
1096 (file . find-file-other-window))
1097 "Setup the frame configuration for following links.
1098 When following a link with Emacs, it may often be useful to display
1099 this link in another window or frame. This variable can be used to
1100 set this up for the different types of links.
1101 For VM, use any of
1102 `vm-visit-folder'
1103 `vm-visit-folder-other-frame'
1104 For Gnus, use any of
1105 `gnus'
1106 `gnus-other-frame'
1107 `org-gnus-no-new-news'
1108 For FILE, use any of
1109 `find-file'
1110 `find-file-other-window'
1111 `find-file-other-frame'
1112 For the calendar, use the variable `calendar-setup'.
1113 For BBDB, it is currently only possible to display the matches in
1114 another window."
1115 :group 'org-link-follow
1116 :type '(list
1117 (cons (const vm)
1118 (choice
1119 (const vm-visit-folder)
1120 (const vm-visit-folder-other-window)
1121 (const vm-visit-folder-other-frame)))
1122 (cons (const gnus)
1123 (choice
1124 (const gnus)
1125 (const gnus-other-frame)
1126 (const org-gnus-no-new-news)))
1127 (cons (const file)
1128 (choice
1129 (const find-file)
1130 (const find-file-other-window)
1131 (const find-file-other-frame)))))
1133 (defcustom org-display-internal-link-with-indirect-buffer nil
1134 "Non-nil means, use indirect buffer to display infile links.
1135 Activating internal links (from one location in a file to another location
1136 in the same file) normally just jumps to the location. When the link is
1137 activated with a C-u prefix (or with mouse-3), the link is displayed in
1138 another window. When this option is set, the other window actually displays
1139 an indirect buffer clone of the current buffer, to avoid any visibility
1140 changes to the current buffer."
1141 :group 'org-link-follow
1142 :type 'boolean)
1144 (defcustom org-open-non-existing-files nil
1145 "Non-nil means, `org-open-file' will open non-existing files.
1146 When nil, an error will be generated."
1147 :group 'org-link-follow
1148 :type 'boolean)
1150 (defcustom org-open-directory-means-index-dot-org nil
1151 "Non-nil means, a link to a directory really means to index.org.
1152 When nil, following a directory link will run dired or open a finder/explorer
1153 window on that directory."
1154 :group 'org-link-follow
1155 :type 'boolean)
1157 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1158 "Function and arguments to call for following mailto links.
1159 This is a list with the first element being a lisp function, and the
1160 remaining elements being arguments to the function. In string arguments,
1161 %a will be replaced by the address, and %s will be replaced by the subject
1162 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1163 :group 'org-link-follow
1164 :type '(choice
1165 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1166 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1167 (const :tag "message-mail" (message-mail "%a" "%s"))
1168 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1170 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1171 "Non-nil means, ask for confirmation before executing shell links.
1172 Shell links can be dangerous: just think about a link
1174 [[shell:rm -rf ~/*][Google Search]]
1176 This link would show up in your Org-mode document as \"Google Search\",
1177 but really it would remove your entire home directory.
1178 Therefore we advise against setting this variable to nil.
1179 Just change it to `y-or-n-p' of you want to confirm with a
1180 single keystroke rather than having to type \"yes\"."
1181 :group 'org-link-follow
1182 :type '(choice
1183 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1184 (const :tag "with y-or-n (faster)" y-or-n-p)
1185 (const :tag "no confirmation (dangerous)" nil)))
1187 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1188 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1189 Elisp links can be dangerous: just think about a link
1191 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1193 This link would show up in your Org-mode document as \"Google Search\",
1194 but really it would remove your entire home directory.
1195 Therefore we advise against setting this variable to nil.
1196 Just change it to `y-or-n-p' of you want to confirm with a
1197 single keystroke rather than having to type \"yes\"."
1198 :group 'org-link-follow
1199 :type '(choice
1200 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1201 (const :tag "with y-or-n (faster)" y-or-n-p)
1202 (const :tag "no confirmation (dangerous)" nil)))
1204 (defconst org-file-apps-defaults-gnu
1205 '((remote . emacs)
1206 (system . mailcap)
1207 (t . mailcap))
1208 "Default file applications on a UNIX or GNU/Linux system.
1209 See `org-file-apps'.")
1211 (defconst org-file-apps-defaults-macosx
1212 '((remote . emacs)
1213 (t . "open %s")
1214 (system . "open %s")
1215 ("ps.gz" . "gv %s")
1216 ("eps.gz" . "gv %s")
1217 ("dvi" . "xdvi %s")
1218 ("fig" . "xfig %s"))
1219 "Default file applications on a MacOS X system.
1220 The system \"open\" is known as a default, but we use X11 applications
1221 for some files for which the OS does not have a good default.
1222 See `org-file-apps'.")
1224 (defconst org-file-apps-defaults-windowsnt
1225 (list
1226 '(remote . emacs)
1227 (cons t
1228 (list (if (featurep 'xemacs)
1229 'mswindows-shell-execute
1230 'w32-shell-execute)
1231 "open" 'file))
1232 (cons 'system
1233 (list (if (featurep 'xemacs)
1234 'mswindows-shell-execute
1235 'w32-shell-execute)
1236 "open" 'file)))
1237 "Default file applications on a Windows NT system.
1238 The system \"open\" is used for most files.
1239 See `org-file-apps'.")
1241 (defcustom org-file-apps
1243 (auto-mode . emacs)
1244 ("\\.x?html?\\'" . default)
1245 ("\\.pdf\\'" . default)
1247 "External applications for opening `file:path' items in a document.
1248 Org-mode uses system defaults for different file types, but
1249 you can use this variable to set the application for a given file
1250 extension. The entries in this list are cons cells where the car identifies
1251 files and the cdr the corresponding command. Possible values for the
1252 file identifier are
1253 \"regex\" Regular expression matched against the file name. For backward
1254 compatibility, this can also be a string with only alphanumeric
1255 characters, which is then interpreted as an extension.
1256 `directory' Matches a directory
1257 `remote' Matches a remote file, accessible through tramp or efs.
1258 Remote files most likely should be visited through Emacs
1259 because external applications cannot handle such paths.
1260 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1261 so all files Emacs knows how to handle. Using this with
1262 command `emacs' will open most files in Emacs. Beware that this
1263 will also open html files inside Emacs, unless you add
1264 (\"html\" . default) to the list as well.
1265 t Default for files not matched by any of the other options.
1266 `system' The system command to open files, like `open' on Windows
1267 and Mac OS X, and mailcap under GNU/Linux. This is the command
1268 that will be selected if you call `C-c C-o' with a double
1269 `C-u C-u' prefix.
1271 Possible values for the command are:
1272 `emacs' The file will be visited by the current Emacs process.
1273 `default' Use the default application for this file type, which is the
1274 association for t in the list, most likely in the system-specific
1275 part.
1276 This can be used to overrule an unwanted setting in the
1277 system-specific variable.
1278 `system' Use the system command for opening files, like \"open\".
1279 This command is specified by the entry whose car is `system'.
1280 Most likely, the system-specific version of this variable
1281 does define this command, but you can overrule/replace it
1282 here.
1283 string A command to be executed by a shell; %s will be replaced
1284 by the path to the file.
1285 sexp A Lisp form which will be evaluated. The file path will
1286 be available in the Lisp variable `file'.
1287 For more examples, see the system specific constants
1288 `org-file-apps-defaults-macosx'
1289 `org-file-apps-defaults-windowsnt'
1290 `org-file-apps-defaults-gnu'."
1291 :group 'org-link-follow
1292 :type '(repeat
1293 (cons (choice :value ""
1294 (string :tag "Extension")
1295 (const :tag "System command to open files" system)
1296 (const :tag "Default for unrecognized files" t)
1297 (const :tag "Remote file" remote)
1298 (const :tag "Links to a directory" directory)
1299 (const :tag "Any files that have Emacs modes"
1300 auto-mode))
1301 (choice :value ""
1302 (const :tag "Visit with Emacs" emacs)
1303 (const :tag "Use default" default)
1304 (const :tag "Use the system command" system)
1305 (string :tag "Command")
1306 (sexp :tag "Lisp form")))))
1308 (defgroup org-refile nil
1309 "Options concerning refiling entries in Org-mode."
1310 :tag "Org Refile"
1311 :group 'org)
1313 (defcustom org-directory "~/org"
1314 "Directory with org files.
1315 This directory will be used as default to prompt for org files.
1316 Used by the hooks for remember.el."
1317 :group 'org-refile
1318 :group 'org-remember
1319 :type 'directory)
1321 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1322 "Default target for storing notes.
1323 Used by the hooks for remember.el. This can be a string, or nil to mean
1324 the value of `remember-data-file'.
1325 You can set this on a per-template basis with the variable
1326 `org-remember-templates'."
1327 :group 'org-refile
1328 :group 'org-remember
1329 :type '(choice
1330 (const :tag "Default from remember-data-file" nil)
1331 file))
1333 (defcustom org-goto-interface 'outline
1334 "The default interface to be used for `org-goto'.
1335 Allowed values are:
1336 outline The interface shows an outline of the relevant file
1337 and the correct heading is found by moving through
1338 the outline or by searching with incremental search.
1339 outline-path-completion Headlines in the current buffer are offered via
1340 completion. This is the interface also used by
1341 the refile command."
1342 :group 'org-refile
1343 :type '(choice
1344 (const :tag "Outline" outline)
1345 (const :tag "Outline-path-completion" outline-path-completion)))
1347 (defcustom org-goto-max-level 5
1348 "Maximum level to be considered when running org-goto with refile interface."
1349 :group 'org-refile
1350 :type 'number)
1352 (defcustom org-reverse-note-order nil
1353 "Non-nil means, store new notes at the beginning of a file or entry.
1354 When nil, new notes will be filed to the end of a file or entry.
1355 This can also be a list with cons cells of regular expressions that
1356 are matched against file names, and values."
1357 :group 'org-remember
1358 :group 'org-refile
1359 :type '(choice
1360 (const :tag "Reverse always" t)
1361 (const :tag "Reverse never" nil)
1362 (repeat :tag "By file name regexp"
1363 (cons regexp boolean))))
1365 (defcustom org-refile-targets nil
1366 "Targets for refiling entries with \\[org-refile].
1367 This is list of cons cells. Each cell contains:
1368 - a specification of the files to be considered, either a list of files,
1369 or a symbol whose function or variable value will be used to retrieve
1370 a file name or a list of file names. If you use `org-agenda-files' for
1371 that, all agenda files will be scanned for targets. Nil means, consider
1372 headings in the current buffer.
1373 - A specification of how to select find candidate refile targets. This
1374 may be any of
1375 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1376 This tag has to be present in all target headlines, inheritance will
1377 not be considered.
1378 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1379 todo keyword.
1380 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1381 headlines that are refiling targets.
1382 - a cons cell (:level . N). Any headline of level N is considered a target.
1383 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1385 When this variable is nil, all top-level headlines in the current buffer
1386 are used, equivalent to the value `((nil . (:level . 1))'."
1387 :group 'org-refile
1388 :type '(repeat
1389 (cons
1390 (choice :value org-agenda-files
1391 (const :tag "All agenda files" org-agenda-files)
1392 (const :tag "Current buffer" nil)
1393 (function) (variable) (file))
1394 (choice :tag "Identify target headline by"
1395 (cons :tag "Specific tag" (const :value :tag) (string))
1396 (cons :tag "TODO keyword" (const :value :todo) (string))
1397 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1398 (cons :tag "Level number" (const :value :level) (integer))
1399 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1401 (defcustom org-refile-use-outline-path nil
1402 "Non-nil means, provide refile targets as paths.
1403 So a level 3 headline will be available as level1/level2/level3.
1404 When the value is `file', also include the file name (without directory)
1405 into the path. When `full-file-path', include the full file path."
1406 :group 'org-refile
1407 :type '(choice
1408 (const :tag "Not" nil)
1409 (const :tag "Yes" t)
1410 (const :tag "Start with file name" file)
1411 (const :tag "Start with full file path" full-file-path)))
1413 (defcustom org-outline-path-complete-in-steps t
1414 "Non-nil means, complete the outline path in hierarchical steps.
1415 When Org-mode uses the refile interface to select an outline path
1416 \(see variable `org-refile-use-outline-path'), the completion of
1417 the path can be done is a single go, or if can be done in steps down
1418 the headline hierarchy. Going in steps is probably the best if you
1419 do not use a special completion package like `ido' or `icicles'.
1420 However, when using these packages, going in one step can be very
1421 fast, while still showing the whole path to the entry."
1422 :group 'org-refile
1423 :type 'boolean)
1425 (defgroup org-todo nil
1426 "Options concerning TODO items in Org-mode."
1427 :tag "Org TODO"
1428 :group 'org)
1430 (defgroup org-progress nil
1431 "Options concerning Progress logging in Org-mode."
1432 :tag "Org Progress"
1433 :group 'org-time)
1435 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1436 "List of TODO entry keyword sequences and their interpretation.
1437 \\<org-mode-map>This is a list of sequences.
1439 Each sequence starts with a symbol, either `sequence' or `type',
1440 indicating if the keywords should be interpreted as a sequence of
1441 action steps, or as different types of TODO items. The first
1442 keywords are states requiring action - these states will select a headline
1443 for inclusion into the global TODO list Org-mode produces. If one of
1444 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1445 signify that no further action is necessary. If \"|\" is not found,
1446 the last keyword is treated as the only DONE state of the sequence.
1448 The command \\[org-todo] cycles an entry through these states, and one
1449 additional state where no keyword is present. For details about this
1450 cycling, see the manual.
1452 TODO keywords and interpretation can also be set on a per-file basis with
1453 the special #+SEQ_TODO and #+TYP_TODO lines.
1455 Each keyword can optionally specify a character for fast state selection
1456 \(in combination with the variable `org-use-fast-todo-selection')
1457 and specifiers for state change logging, using the same syntax
1458 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1459 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1460 indicates to record a time stamp each time this state is selected.
1462 Each keyword may also specify if a timestamp or a note should be
1463 recorded when entering or leaving the state, by adding additional
1464 characters in the parenthesis after the keyword. This looks like this:
1465 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1466 record only the time of the state change. With X and Y being either
1467 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1468 Y when leaving the state if and only if the *target* state does not
1469 define X. You may omit any of the fast-selection key or X or /Y,
1470 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1472 For backward compatibility, this variable may also be just a list
1473 of keywords - in this case the interpretation (sequence or type) will be
1474 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1475 :group 'org-todo
1476 :group 'org-keywords
1477 :type '(choice
1478 (repeat :tag "Old syntax, just keywords"
1479 (string :tag "Keyword"))
1480 (repeat :tag "New syntax"
1481 (cons
1482 (choice
1483 :tag "Interpretation"
1484 (const :tag "Sequence (cycling hits every state)" sequence)
1485 (const :tag "Type (cycling directly to DONE)" type))
1486 (repeat
1487 (string :tag "Keyword"))))))
1489 (defvar org-todo-keywords-1 nil
1490 "All TODO and DONE keywords active in a buffer.")
1491 (make-variable-buffer-local 'org-todo-keywords-1)
1492 (defvar org-todo-keywords-for-agenda nil)
1493 (defvar org-done-keywords-for-agenda nil)
1494 (defvar org-todo-keyword-alist-for-agenda nil)
1495 (defvar org-tag-alist-for-agenda nil)
1496 (defvar org-agenda-contributing-files nil)
1497 (defvar org-not-done-keywords nil)
1498 (make-variable-buffer-local 'org-not-done-keywords)
1499 (defvar org-done-keywords nil)
1500 (make-variable-buffer-local 'org-done-keywords)
1501 (defvar org-todo-heads nil)
1502 (make-variable-buffer-local 'org-todo-heads)
1503 (defvar org-todo-sets nil)
1504 (make-variable-buffer-local 'org-todo-sets)
1505 (defvar org-todo-log-states nil)
1506 (make-variable-buffer-local 'org-todo-log-states)
1507 (defvar org-todo-kwd-alist nil)
1508 (make-variable-buffer-local 'org-todo-kwd-alist)
1509 (defvar org-todo-key-alist nil)
1510 (make-variable-buffer-local 'org-todo-key-alist)
1511 (defvar org-todo-key-trigger nil)
1512 (make-variable-buffer-local 'org-todo-key-trigger)
1514 (defcustom org-todo-interpretation 'sequence
1515 "Controls how TODO keywords are interpreted.
1516 This variable is in principle obsolete and is only used for
1517 backward compatibility, if the interpretation of todo keywords is
1518 not given already in `org-todo-keywords'. See that variable for
1519 more information."
1520 :group 'org-todo
1521 :group 'org-keywords
1522 :type '(choice (const sequence)
1523 (const type)))
1525 (defcustom org-use-fast-todo-selection 'prefix
1526 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1527 This variable describes if and under what circumstances the cycling
1528 mechanism for TODO keywords will be replaced by a single-key, direct
1529 selection scheme.
1531 When nil, fast selection is never used.
1533 When the symbol `prefix', it will be used when `org-todo' is called with
1534 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1535 in an agenda buffer.
1537 When t, fast selection is used by default. In this case, the prefix
1538 argument forces cycling instead.
1540 In all cases, the special interface is only used if access keys have actually
1541 been assigned by the user, i.e. if keywords in the configuration are followed
1542 by a letter in parenthesis, like TODO(t)."
1543 :group 'org-todo
1544 :type '(choice
1545 (const :tag "Never" nil)
1546 (const :tag "By default" t)
1547 (const :tag "Only with C-u C-c C-t" prefix)))
1549 (defcustom org-provide-todo-statistics t
1550 "Non-nil means, update todo statistics after insert and toggle.
1551 When this is set, todo statistics is updated in the parent of the current
1552 entry each time a todo state is changed."
1553 :group 'org-todo
1554 :type 'boolean)
1556 (defcustom org-after-todo-state-change-hook nil
1557 "Hook which is run after the state of a TODO item was changed.
1558 The new state (a string with a TODO keyword, or nil) is available in the
1559 Lisp variable `state'."
1560 :group 'org-todo
1561 :type 'hook)
1563 (defcustom org-todo-state-tags-triggers nil
1564 "Tag changes that should be triggered by TODO state changes.
1565 This is a list. Each entry is
1567 (state-change (tag . flag) .......)
1569 State-change can be a string with a state, and empty string to indicate the
1570 state that has no TODO keyword, or it can be one of the symbols `todo'
1571 or `done', meaning any not-done or done state, respectively."
1572 :group 'org-todo
1573 :group 'org-tags
1574 :type '(repeat
1575 (cons (choice :tag "When changing to"
1576 (const :tag "Not-done state" todo)
1577 (const :tag "Done state" done)
1578 (string :tag "State"))
1579 (repeat
1580 (cons :tag "Tag action"
1581 (string :tag "Tag")
1582 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1584 (defcustom org-log-done nil
1585 "Information to record when a task moves to the DONE state.
1587 Possible values are:
1589 nil Don't add anything, just change the keyword
1590 time Add a time stamp to the task
1591 note Prompt a closing note and add it with template `org-log-note-headings'
1593 This option can also be set with on a per-file-basis with
1595 #+STARTUP: nologdone
1596 #+STARTUP: logdone
1597 #+STARTUP: lognotedone
1599 You can have local logging settings for a subtree by setting the LOGGING
1600 property to one or more of these keywords."
1601 :group 'org-todo
1602 :group 'org-progress
1603 :type '(choice
1604 (const :tag "No logging" nil)
1605 (const :tag "Record CLOSED timestamp" time)
1606 (const :tag "Record CLOSED timestamp with closing note." note)))
1608 ;; Normalize old uses of org-log-done.
1609 (cond
1610 ((eq org-log-done t) (setq org-log-done 'time))
1611 ((and (listp org-log-done) (memq 'done org-log-done))
1612 (setq org-log-done 'note)))
1614 (defcustom org-log-note-clock-out nil
1615 "Non-nil means, record a note when clocking out of an item.
1616 This can also be configured on a per-file basis by adding one of
1617 the following lines anywhere in the buffer:
1619 #+STARTUP: lognoteclock-out
1620 #+STARTUP: nolognoteclock-out"
1621 :group 'org-todo
1622 :group 'org-progress
1623 :type 'boolean)
1625 (defcustom org-log-done-with-time t
1626 "Non-nil means, the CLOSED time stamp will contain date and time.
1627 When nil, only the date will be recorded."
1628 :group 'org-progress
1629 :type 'boolean)
1631 (defcustom org-log-note-headings
1632 '((done . "CLOSING NOTE %t")
1633 (state . "State %-12s %t")
1634 (note . "Note taken on %t")
1635 (clock-out . ""))
1636 "Headings for notes added to entries.
1637 The value is an alist, with the car being a symbol indicating the note
1638 context, and the cdr is the heading to be used. The heading may also be the
1639 empty string.
1640 %t in the heading will be replaced by a time stamp.
1641 %s will be replaced by the new TODO state, in double quotes.
1642 %u will be replaced by the user name.
1643 %U will be replaced by the full user name."
1644 :group 'org-todo
1645 :group 'org-progress
1646 :type '(list :greedy t
1647 (cons (const :tag "Heading when closing an item" done) string)
1648 (cons (const :tag
1649 "Heading when changing todo state (todo sequence only)"
1650 state) string)
1651 (cons (const :tag "Heading when just taking a note" note) string)
1652 (cons (const :tag "Heading when clocking out" clock-out) string)))
1654 (unless (assq 'note org-log-note-headings)
1655 (push '(note . "%t") org-log-note-headings))
1657 (defcustom org-log-state-notes-insert-after-drawers nil
1658 "Non-nil means, insert state change notes after any drawers in entry.
1659 Only the drawers that *immediately* follow the headline and the
1660 deadline/scheduled line are skipped.
1661 When nil, insert notes right after the heading and perhaps the line
1662 with deadline/scheduling if present."
1663 :group 'org-todo
1664 :group 'org-progress
1665 :type 'boolean)
1667 (defcustom org-log-states-order-reversed t
1668 "Non-nil means, the latest state change note will be directly after heading.
1669 When nil, the notes will be orderer according to time."
1670 :group 'org-todo
1671 :group 'org-progress
1672 :type 'boolean)
1674 (defcustom org-log-repeat 'time
1675 "Non-nil means, record moving through the DONE state when triggering repeat.
1676 An auto-repeating tasks is immediately switched back to TODO when marked
1677 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1678 the TODO keyword definition, or recording a closing note by setting
1679 `org-log-done', there will be no record of the task moving through DONE.
1680 This variable forces taking a note anyway. Possible values are:
1682 nil Don't force a record
1683 time Record a time stamp
1684 note Record a note
1686 This option can also be set with on a per-file-basis with
1688 #+STARTUP: logrepeat
1689 #+STARTUP: lognoterepeat
1690 #+STARTUP: nologrepeat
1692 You can have local logging settings for a subtree by setting the LOGGING
1693 property to one or more of these keywords."
1694 :group 'org-todo
1695 :group 'org-progress
1696 :type '(choice
1697 (const :tag "Don't force a record" nil)
1698 (const :tag "Force recording the DONE state" time)
1699 (const :tag "Force recording a note with the DONE state" note)))
1702 (defgroup org-priorities nil
1703 "Priorities in Org-mode."
1704 :tag "Org Priorities"
1705 :group 'org-todo)
1707 (defcustom org-highest-priority ?A
1708 "The highest priority of TODO items. A character like ?A, ?B etc.
1709 Must have a smaller ASCII number than `org-lowest-priority'."
1710 :group 'org-priorities
1711 :type 'character)
1713 (defcustom org-lowest-priority ?C
1714 "The lowest priority of TODO items. A character like ?A, ?B etc.
1715 Must have a larger ASCII number than `org-highest-priority'."
1716 :group 'org-priorities
1717 :type 'character)
1719 (defcustom org-default-priority ?B
1720 "The default priority of TODO items.
1721 This is the priority an item get if no explicit priority is given."
1722 :group 'org-priorities
1723 :type 'character)
1725 (defcustom org-priority-start-cycle-with-default t
1726 "Non-nil means, start with default priority when starting to cycle.
1727 When this is nil, the first step in the cycle will be (depending on the
1728 command used) one higher or lower that the default priority."
1729 :group 'org-priorities
1730 :type 'boolean)
1732 (defgroup org-time nil
1733 "Options concerning time stamps and deadlines in Org-mode."
1734 :tag "Org Time"
1735 :group 'org)
1737 (defcustom org-insert-labeled-timestamps-at-point nil
1738 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1739 When nil, these labeled time stamps are forces into the second line of an
1740 entry, just after the headline. When scheduling from the global TODO list,
1741 the time stamp will always be forced into the second line."
1742 :group 'org-time
1743 :type 'boolean)
1745 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1746 "Formats for `format-time-string' which are used for time stamps.
1747 It is not recommended to change this constant.")
1749 (defcustom org-time-stamp-rounding-minutes '(0 5)
1750 "Number of minutes to round time stamps to.
1751 These are two values, the first applies when first creating a time stamp.
1752 The second applies when changing it with the commands `S-up' and `S-down'.
1753 When changing the time stamp, this means that it will change in steps
1754 of N minutes, as given by the second value.
1756 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1757 numbers should be factors of 60, so for example 5, 10, 15.
1759 When this is larger than 1, you can still force an exact time-stamp by using
1760 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1761 and by using a prefix arg to `S-up/down' to specify the exact number
1762 of minutes to shift."
1763 :group 'org-time
1764 :get '(lambda (var) ; Make sure all entries have 5 elements
1765 (if (integerp (default-value var))
1766 (list (default-value var) 5)
1767 (default-value var)))
1768 :type '(list
1769 (integer :tag "when inserting times")
1770 (integer :tag "when modifying times")))
1772 ;; Normalize old customizations of this variable.
1773 (when (integerp org-time-stamp-rounding-minutes)
1774 (setq org-time-stamp-rounding-minutes
1775 (list org-time-stamp-rounding-minutes
1776 org-time-stamp-rounding-minutes)))
1778 (defcustom org-display-custom-times nil
1779 "Non-nil means, overlay custom formats over all time stamps.
1780 The formats are defined through the variable `org-time-stamp-custom-formats'.
1781 To turn this on on a per-file basis, insert anywhere in the file:
1782 #+STARTUP: customtime"
1783 :group 'org-time
1784 :set 'set-default
1785 :type 'sexp)
1786 (make-variable-buffer-local 'org-display-custom-times)
1788 (defcustom org-time-stamp-custom-formats
1789 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1790 "Custom formats for time stamps. See `format-time-string' for the syntax.
1791 These are overlayed over the default ISO format if the variable
1792 `org-display-custom-times' is set. Time like %H:%M should be at the
1793 end of the second format."
1794 :group 'org-time
1795 :type 'sexp)
1797 (defun org-time-stamp-format (&optional long inactive)
1798 "Get the right format for a time string."
1799 (let ((f (if long (cdr org-time-stamp-formats)
1800 (car org-time-stamp-formats))))
1801 (if inactive
1802 (concat "[" (substring f 1 -1) "]")
1803 f)))
1805 (defcustom org-time-clocksum-format "%d:%02d"
1806 "The format string used when creating CLOCKSUM lines, or when
1807 org-mode generates a time duration."
1808 :group 'org-time
1809 :type 'string)
1811 (defcustom org-deadline-warning-days 14
1812 "No. of days before expiration during which a deadline becomes active.
1813 This variable governs the display in sparse trees and in the agenda.
1814 When 0 or negative, it means use this number (the absolute value of it)
1815 even if a deadline has a different individual lead time specified."
1816 :group 'org-time
1817 :group 'org-agenda-daily/weekly
1818 :type 'number)
1820 (defcustom org-read-date-prefer-future t
1821 "Non-nil means, assume future for incomplete date input from user.
1822 This affects the following situations:
1823 1. The user gives a day, but no month.
1824 For example, if today is the 15th, and you enter \"3\", Org-mode will
1825 read this as the third of *next* month. However, if you enter \"17\",
1826 it will be considered as *this* month.
1827 2. The user gives a month but not a year.
1828 For example, if it is april and you enter \"feb 2\", this will be read
1829 as feb 2, *next* year. \"May 5\", however, will be this year.
1831 Currently this does not work for ISO week specifications.
1833 When this option is nil, the current month and year will always be used
1834 as defaults."
1835 :group 'org-time
1836 :type 'boolean)
1838 (defcustom org-read-date-display-live t
1839 "Non-nil means, display current interpretation of date prompt live.
1840 This display will be in an overlay, in the minibuffer."
1841 :group 'org-time
1842 :type 'boolean)
1844 (defcustom org-read-date-popup-calendar t
1845 "Non-nil means, pop up a calendar when prompting for a date.
1846 In the calendar, the date can be selected with mouse-1. However, the
1847 minibuffer will also be active, and you can simply enter the date as well.
1848 When nil, only the minibuffer will be available."
1849 :group 'org-time
1850 :type 'boolean)
1851 (if (fboundp 'defvaralias)
1852 (defvaralias 'org-popup-calendar-for-date-prompt
1853 'org-read-date-popup-calendar))
1855 (defcustom org-extend-today-until 0
1856 "The hour when your day really ends. Must be an integer.
1857 This has influence for the following applications:
1858 - When switching the agenda to \"today\". It it is still earlier than
1859 the time given here, the day recognized as TODAY is actually yesterday.
1860 - When a date is read from the user and it is still before the time given
1861 here, the current date and time will be assumed to be yesterday, 23:59.
1862 Also, timestamps inserted in remember templates follow this rule.
1864 IMPORTANT: This is a feature whose implementation is and likely will
1865 remain incomplete. Really, it is only here because past midnight seems to
1866 be the favorite working time of John Wiegley :-)"
1867 :group 'org-time
1868 :type 'number)
1870 (defcustom org-edit-timestamp-down-means-later nil
1871 "Non-nil means, S-down will increase the time in a time stamp.
1872 When nil, S-up will increase."
1873 :group 'org-time
1874 :type 'boolean)
1876 (defcustom org-calendar-follow-timestamp-change t
1877 "Non-nil means, make the calendar window follow timestamp changes.
1878 When a timestamp is modified and the calendar window is visible, it will be
1879 moved to the new date."
1880 :group 'org-time
1881 :type 'boolean)
1883 (defgroup org-tags nil
1884 "Options concerning tags in Org-mode."
1885 :tag "Org Tags"
1886 :group 'org)
1888 (defcustom org-tag-alist nil
1889 "List of tags allowed in Org-mode files.
1890 When this list is nil, Org-mode will base TAG input on what is already in the
1891 buffer.
1892 The value of this variable is an alist, the car of each entry must be a
1893 keyword as a string, the cdr may be a character that is used to select
1894 that tag through the fast-tag-selection interface.
1895 See the manual for details."
1896 :group 'org-tags
1897 :type '(repeat
1898 (choice
1899 (cons (string :tag "Tag name")
1900 (character :tag "Access char"))
1901 (const :tag "Start radio group" (:startgroup))
1902 (const :tag "End radio group" (:endgroup)))))
1904 (defvar org-file-tags nil
1905 "List of tags that can be inherited by all entries in the file.
1906 The tags will be inherited if the variable `org-use-tag-inheritance'
1907 says they should be.
1908 This variable is populated from #+TAG lines.")
1910 (defcustom org-use-fast-tag-selection 'auto
1911 "Non-nil means, use fast tag selection scheme.
1912 This is a special interface to select and deselect tags with single keys.
1913 When nil, fast selection is never used.
1914 When the symbol `auto', fast selection is used if and only if selection
1915 characters for tags have been configured, either through the variable
1916 `org-tag-alist' or through a #+TAGS line in the buffer.
1917 When t, fast selection is always used and selection keys are assigned
1918 automatically if necessary."
1919 :group 'org-tags
1920 :type '(choice
1921 (const :tag "Always" t)
1922 (const :tag "Never" nil)
1923 (const :tag "When selection characters are configured" 'auto)))
1925 (defcustom org-fast-tag-selection-single-key nil
1926 "Non-nil means, fast tag selection exits after first change.
1927 When nil, you have to press RET to exit it.
1928 During fast tag selection, you can toggle this flag with `C-c'.
1929 This variable can also have the value `expert'. In this case, the window
1930 displaying the tags menu is not even shown, until you press C-c again."
1931 :group 'org-tags
1932 :type '(choice
1933 (const :tag "No" nil)
1934 (const :tag "Yes" t)
1935 (const :tag "Expert" expert)))
1937 (defvar org-fast-tag-selection-include-todo nil
1938 "Non-nil means, fast tags selection interface will also offer TODO states.
1939 This is an undocumented feature, you should not rely on it.")
1941 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1942 "The column to which tags should be indented in a headline.
1943 If this number is positive, it specifies the column. If it is negative,
1944 it means that the tags should be flushright to that column. For example,
1945 -80 works well for a normal 80 character screen."
1946 :group 'org-tags
1947 :type 'integer)
1949 (defcustom org-auto-align-tags t
1950 "Non-nil means, realign tags after pro/demotion of TODO state change.
1951 These operations change the length of a headline and therefore shift
1952 the tags around. With this options turned on, after each such operation
1953 the tags are again aligned to `org-tags-column'."
1954 :group 'org-tags
1955 :type 'boolean)
1957 (defcustom org-use-tag-inheritance t
1958 "Non-nil means, tags in levels apply also for sublevels.
1959 When nil, only the tags directly given in a specific line apply there.
1960 This may also be a list of tags that should be inherited, or a regexp that
1961 matches tags that should be inherited. Additional control is possible
1962 with the variable `org-tags-exclude-from-inheritance' which gives an
1963 explicit list of tags to be excluded from inheritance., even if the value of
1964 `org-use-tag-inheritance' would select it for inheritance.
1966 If this option is t, a match early-on in a tree can lead to a large
1967 number of matches in the subtree when constructing the agenda or creating
1968 a sparse tree. If you only want to see the first match in a tree during
1969 a search, check out the variable `org-tags-match-list-sublevels'."
1970 :group 'org-tags
1971 :type '(choice
1972 (const :tag "Not" nil)
1973 (const :tag "Always" t)
1974 (repeat :tag "Specific tags" (string :tag "Tag"))
1975 (regexp :tag "Tags matched by regexp")))
1977 (defcustom org-tags-exclude-from-inheritance nil
1978 "List of tags that should never be inherited.
1979 This is a way to exclude a few tags from inheritance. For way to do
1980 the opposite, to actively allow inheritance for selected tags,
1981 see the variable `org-use-tag-inheritance'."
1982 :group 'org-tags
1983 :type '(repeat (string :tag "Tag")))
1985 (defun org-tag-inherit-p (tag)
1986 "Check if TAG is one that should be inherited."
1987 (cond
1988 ((member tag org-tags-exclude-from-inheritance) nil)
1989 ((eq org-use-tag-inheritance t) t)
1990 ((not org-use-tag-inheritance) nil)
1991 ((stringp org-use-tag-inheritance)
1992 (string-match org-use-tag-inheritance tag))
1993 ((listp org-use-tag-inheritance)
1994 (member tag org-use-tag-inheritance))
1995 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1997 (defcustom org-tags-match-list-sublevels t
1998 "Non-nil means list also sublevels of headlines matching tag search.
1999 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2000 the sublevels of a headline matching a tag search often also match
2001 the same search. Listing all of them can create very long lists.
2002 Setting this variable to nil causes subtrees of a match to be skipped.
2003 This option is off by default, because inheritance in on. If you turn
2004 inheritance off, you very likely want to turn this option on.
2006 As a special case, if the tag search is restricted to TODO items, the
2007 value of this variable is ignored and sublevels are always checked, to
2008 make sure all corresponding TODO items find their way into the list.
2010 This variable is semi-obsolete and probably should always be true. It
2011 is better to limit inheritance to certain tags using the variables
2012 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2013 :group 'org-tags
2014 :type 'boolean)
2016 (defvar org-tags-history nil
2017 "History of minibuffer reads for tags.")
2018 (defvar org-last-tags-completion-table nil
2019 "The last used completion table for tags.")
2020 (defvar org-after-tags-change-hook nil
2021 "Hook that is run after the tags in a line have changed.")
2023 (defgroup org-properties nil
2024 "Options concerning properties in Org-mode."
2025 :tag "Org Properties"
2026 :group 'org)
2028 (defcustom org-property-format "%-10s %s"
2029 "How property key/value pairs should be formatted by `indent-line'.
2030 When `indent-line' hits a property definition, it will format the line
2031 according to this format, mainly to make sure that the values are
2032 lined-up with respect to each other."
2033 :group 'org-properties
2034 :type 'string)
2036 (defcustom org-use-property-inheritance nil
2037 "Non-nil means, properties apply also for sublevels.
2039 This setting is chiefly used during property searches. Turning it on can
2040 cause significant overhead when doing a search, which is why it is not
2041 on by default.
2043 When nil, only the properties directly given in the current entry count.
2044 When t, every property is inherited. The value may also be a list of
2045 properties that should have inheritance, or a regular expression matching
2046 properties that should be inherited.
2048 However, note that some special properties use inheritance under special
2049 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2050 and the properties ending in \"_ALL\" when they are used as descriptor
2051 for valid values of a property.
2053 Note for programmers:
2054 When querying an entry with `org-entry-get', you can control if inheritance
2055 should be used. By default, `org-entry-get' looks only at the local
2056 properties. You can request inheritance by setting the inherit argument
2057 to t (to force inheritance) or to `selective' (to respect the setting
2058 in this variable)."
2059 :group 'org-properties
2060 :type '(choice
2061 (const :tag "Not" nil)
2062 (const :tag "Always" t)
2063 (repeat :tag "Specific properties" (string :tag "Property"))
2064 (regexp :tag "Properties matched by regexp")))
2066 (defun org-property-inherit-p (property)
2067 "Check if PROPERTY is one that should be inherited."
2068 (cond
2069 ((eq org-use-property-inheritance t) t)
2070 ((not org-use-property-inheritance) nil)
2071 ((stringp org-use-property-inheritance)
2072 (string-match org-use-property-inheritance property))
2073 ((listp org-use-property-inheritance)
2074 (member property org-use-property-inheritance))
2075 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2077 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2078 "The default column format, if no other format has been defined.
2079 This variable can be set on the per-file basis by inserting a line
2081 #+COLUMNS: %25ITEM ....."
2082 :group 'org-properties
2083 :type 'string)
2085 (defcustom org-columns-ellipses ".."
2086 "The ellipses to be used when a field in column view is truncated.
2087 When this is the empty string, as many characters as possible are shown,
2088 but then there will be no visual indication that the field has been truncated.
2089 When this is a string of length N, the last N characters of a truncated
2090 field are replaced by this string. If the column is narrower than the
2091 ellipses string, only part of the ellipses string will be shown."
2092 :group 'org-properties
2093 :type 'string)
2095 (defcustom org-columns-modify-value-for-display-function nil
2096 "Function that modifies values for display in column view.
2097 For example, it can be used to cut out a certain part from a time stamp.
2098 The function must take 2 arguments:
2100 column-title The title of the column (*not* the property name)
2101 value The value that should be modified.
2103 The function should return the value that should be displayed,
2104 or nil if the normal value should be used."
2105 :group 'org-properties
2106 :type 'function)
2108 (defcustom org-effort-property "Effort"
2109 "The property that is being used to keep track of effort estimates.
2110 Effort estimates given in this property need to have the format H:MM."
2111 :group 'org-properties
2112 :group 'org-progress
2113 :type '(string :tag "Property"))
2115 (defconst org-global-properties-fixed
2116 '(("VISIBILITY_ALL" . "folded children content all"))
2117 "List of property/value pairs that can be inherited by any entry.
2118 These are fixed values, for the preset properties.")
2121 (defcustom org-global-properties nil
2122 "List of property/value pairs that can be inherited by any entry.
2123 You can set buffer-local values for the same purpose in the variable
2124 `org-file-properties' this by adding lines like
2126 #+PROPERTY: NAME VALUE"
2127 :group 'org-properties
2128 :type '(repeat
2129 (cons (string :tag "Property")
2130 (string :tag "Value"))))
2132 (defvar org-file-properties nil
2133 "List of property/value pairs that can be inherited by any entry.
2134 Valid for the current buffer.
2135 This variable is populated from #+PROPERTY lines.")
2136 (make-variable-buffer-local 'org-file-properties)
2138 (defgroup org-agenda nil
2139 "Options concerning agenda views in Org-mode."
2140 :tag "Org Agenda"
2141 :group 'org)
2143 (defvar org-category nil
2144 "Variable used by org files to set a category for agenda display.
2145 Such files should use a file variable to set it, for example
2147 # -*- mode: org; org-category: \"ELisp\"
2149 or contain a special line
2151 #+CATEGORY: ELisp
2153 If the file does not specify a category, then file's base name
2154 is used instead.")
2155 (make-variable-buffer-local 'org-category)
2156 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2158 (defcustom org-agenda-files nil
2159 "The files to be used for agenda display.
2160 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2161 \\[org-remove-file]. You can also use customize to edit the list.
2163 If an entry is a directory, all files in that directory that are matched by
2164 `org-agenda-file-regexp' will be part of the file list.
2166 If the value of the variable is not a list but a single file name, then
2167 the list of agenda files is actually stored and maintained in that file, one
2168 agenda file per line."
2169 :group 'org-agenda
2170 :type '(choice
2171 (repeat :tag "List of files and directories" file)
2172 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2174 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2175 "Regular expression to match files for `org-agenda-files'.
2176 If any element in the list in that variable contains a directory instead
2177 of a normal file, all files in that directory that are matched by this
2178 regular expression will be included."
2179 :group 'org-agenda
2180 :type 'regexp)
2182 (defcustom org-agenda-text-search-extra-files nil
2183 "List of extra files to be searched by text search commands.
2184 These files will be search in addition to the agenda files by the
2185 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2186 Note that these files will only be searched for text search commands,
2187 not for the other agenda views like todo lists, tag searches or the weekly
2188 agenda. This variable is intended to list notes and possibly archive files
2189 that should also be searched by these two commands.
2190 In fact, if the first element in the list is the symbol `agenda-archives',
2191 than all archive files of all agenda files will be added to the search
2192 scope."
2193 :group 'org-agenda
2194 :type '(set :greedy t
2195 (const :tag "Agenda Archives" agenda-archives)
2196 (repeat :inline t (file))))
2198 (if (fboundp 'defvaralias)
2199 (defvaralias 'org-agenda-multi-occur-extra-files
2200 'org-agenda-text-search-extra-files))
2202 (defcustom org-agenda-skip-unavailable-files nil
2203 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2204 A nil value means to remove them, after a query, from the list."
2205 :group 'org-agenda
2206 :type 'boolean)
2208 (defcustom org-calendar-to-agenda-key [?c]
2209 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2210 The command `org-calendar-goto-agenda' will be bound to this key. The
2211 default is the character `c' because then `c' can be used to switch back and
2212 forth between agenda and calendar."
2213 :group 'org-agenda
2214 :type 'sexp)
2216 (defcustom org-calendar-agenda-action-key [?k]
2217 "The key to be installed in `calendar-mode-map' for agenda-action.
2218 The command `org-agenda-action' will be bound to this key. The
2219 default is the character `k' because we use the same key in the agenda."
2220 :group 'org-agenda
2221 :type 'sexp)
2223 (eval-after-load "calendar"
2224 '(progn
2225 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2226 'org-calendar-goto-agenda)
2227 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2228 'org-agenda-action)))
2230 (defgroup org-latex nil
2231 "Options for embedding LaTeX code into Org-mode."
2232 :tag "Org LaTeX"
2233 :group 'org)
2235 (defcustom org-format-latex-options
2236 '(:foreground default :background default :scale 1.0
2237 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2238 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2239 "Options for creating images from LaTeX fragments.
2240 This is a property list with the following properties:
2241 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2242 `default' means use the foreground of the default face.
2243 :background the background color, or \"Transparent\".
2244 `default' means use the background of the default face.
2245 :scale a scaling factor for the size of the images.
2246 :html-foreground, :html-background, :html-scale
2247 the same numbers for HTML export.
2248 :matchers a list indicating which matchers should be used to
2249 find LaTeX fragments. Valid members of this list are:
2250 \"begin\" find environments
2251 \"$1\" find single characters surrounded by $.$
2252 \"$\" find math expressions surrounded by $...$
2253 \"$$\" find math expressions surrounded by $$....$$
2254 \"\\(\" find math expressions surrounded by \\(...\\)
2255 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2256 :group 'org-latex
2257 :type 'plist)
2259 (defcustom org-format-latex-header "\\documentclass{article}
2260 \\usepackage{fullpage} % do not remove
2261 \\usepackage{amssymb}
2262 \\usepackage[usenames]{color}
2263 \\usepackage{amsmath}
2264 \\usepackage{latexsym}
2265 \\usepackage[mathscr]{eucal}
2266 \\pagestyle{empty} % do not remove"
2267 "The document header used for processing LaTeX fragments."
2268 :group 'org-latex
2269 :type 'string)
2272 (defgroup org-font-lock nil
2273 "Font-lock settings for highlighting in Org-mode."
2274 :tag "Org Font Lock"
2275 :group 'org)
2277 (defcustom org-level-color-stars-only nil
2278 "Non-nil means fontify only the stars in each headline.
2279 When nil, the entire headline is fontified.
2280 Changing it requires restart of `font-lock-mode' to become effective
2281 also in regions already fontified."
2282 :group 'org-font-lock
2283 :type 'boolean)
2285 (defcustom org-hide-leading-stars nil
2286 "Non-nil means, hide the first N-1 stars in a headline.
2287 This works by using the face `org-hide' for these stars. This
2288 face is white for a light background, and black for a dark
2289 background. You may have to customize the face `org-hide' to
2290 make this work.
2291 Changing it requires restart of `font-lock-mode' to become effective
2292 also in regions already fontified.
2293 You may also set this on a per-file basis by adding one of the following
2294 lines to the buffer:
2296 #+STARTUP: hidestars
2297 #+STARTUP: showstars"
2298 :group 'org-font-lock
2299 :type 'boolean)
2301 (defcustom org-fontify-done-headline nil
2302 "Non-nil means, change the face of a headline if it is marked DONE.
2303 Normally, only the TODO/DONE keyword indicates the state of a headline.
2304 When this is non-nil, the headline after the keyword is set to the
2305 `org-headline-done' as an additional indication."
2306 :group 'org-font-lock
2307 :type 'boolean)
2309 (defcustom org-fontify-emphasized-text t
2310 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2311 Changing this variable requires a restart of Emacs to take effect."
2312 :group 'org-font-lock
2313 :type 'boolean)
2315 (defcustom org-highlight-latex-fragments-and-specials nil
2316 "Non-nil means, fontify what is treated specially by the exporters."
2317 :group 'org-font-lock
2318 :type 'boolean)
2320 (defcustom org-hide-emphasis-markers nil
2321 "Non-nil mean font-lock should hide the emphasis marker characters."
2322 :group 'org-font-lock
2323 :type 'boolean)
2325 (defvar org-emph-re nil
2326 "Regular expression for matching emphasis.")
2327 (defvar org-verbatim-re nil
2328 "Regular expression for matching verbatim text.")
2329 (defvar org-emphasis-regexp-components) ; defined just below
2330 (defvar org-emphasis-alist) ; defined just below
2331 (defun org-set-emph-re (var val)
2332 "Set variable and compute the emphasis regular expression."
2333 (set var val)
2334 (when (and (boundp 'org-emphasis-alist)
2335 (boundp 'org-emphasis-regexp-components)
2336 org-emphasis-alist org-emphasis-regexp-components)
2337 (let* ((e org-emphasis-regexp-components)
2338 (pre (car e))
2339 (post (nth 1 e))
2340 (border (nth 2 e))
2341 (body (nth 3 e))
2342 (nl (nth 4 e))
2343 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2344 (body1 (concat body "*?"))
2345 (markers (mapconcat 'car org-emphasis-alist ""))
2346 (vmarkers (mapconcat
2347 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2348 org-emphasis-alist "")))
2349 ;; make sure special characters appear at the right position in the class
2350 (if (string-match "\\^" markers)
2351 (setq markers (concat (replace-match "" t t markers) "^")))
2352 (if (string-match "-" markers)
2353 (setq markers (concat (replace-match "" t t markers) "-")))
2354 (if (string-match "\\^" vmarkers)
2355 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2356 (if (string-match "-" vmarkers)
2357 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2358 (if (> nl 0)
2359 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2360 (int-to-string nl) "\\}")))
2361 ;; Make the regexp
2362 (setq org-emph-re
2363 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2364 "\\("
2365 "\\([" markers "]\\)"
2366 "\\("
2367 "[^" border "]\\|"
2368 "[^" border (if (and nil stacked) markers) "]"
2369 body1
2370 "[^" border (if (and nil stacked) markers) "]"
2371 "\\)"
2372 "\\3\\)"
2373 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2374 (setq org-verbatim-re
2375 (concat "\\([" pre "]\\|^\\)"
2376 "\\("
2377 "\\([" vmarkers "]\\)"
2378 "\\("
2379 "[^" border "]\\|"
2380 "[^" border "]"
2381 body1
2382 "[^" border "]"
2383 "\\)"
2384 "\\3\\)"
2385 "\\([" post "]\\|$\\)")))))
2387 (defcustom org-emphasis-regexp-components
2388 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2389 "Components used to build the regular expression for emphasis.
2390 This is a list with 6 entries. Terminology: In an emphasis string
2391 like \" *strong word* \", we call the initial space PREMATCH, the final
2392 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2393 and \"trong wor\" is the body. The different components in this variable
2394 specify what is allowed/forbidden in each part:
2396 pre Chars allowed as prematch. Beginning of line will be allowed too.
2397 post Chars allowed as postmatch. End of line will be allowed too.
2398 border The chars *forbidden* as border characters.
2399 body-regexp A regexp like \".\" to match a body character. Don't use
2400 non-shy groups here, and don't allow newline here.
2401 newline The maximum number of newlines allowed in an emphasis exp.
2403 Use customize to modify this, or restart Emacs after changing it."
2404 :group 'org-font-lock
2405 :set 'org-set-emph-re
2406 :type '(list
2407 (sexp :tag "Allowed chars in pre ")
2408 (sexp :tag "Allowed chars in post ")
2409 (sexp :tag "Forbidden chars in border ")
2410 (sexp :tag "Regexp for body ")
2411 (integer :tag "number of newlines allowed")
2412 (option (boolean :tag "Please ignore this button"))))
2414 (defcustom org-emphasis-alist
2415 `(("*" bold "<b>" "</b>")
2416 ("/" italic "<i>" "</i>")
2417 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2418 ("=" org-code "<code>" "</code>" verbatim)
2419 ("~" org-verbatim "<code>" "</code>" verbatim)
2420 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2421 "<del>" "</del>")
2423 "Special syntax for emphasized text.
2424 Text starting and ending with a special character will be emphasized, for
2425 example *bold*, _underlined_ and /italic/. This variable sets the marker
2426 characters, the face to be used by font-lock for highlighting in Org-mode
2427 Emacs buffers, and the HTML tags to be used for this.
2428 Use customize to modify this, or restart Emacs after changing it."
2429 :group 'org-font-lock
2430 :set 'org-set-emph-re
2431 :type '(repeat
2432 (list
2433 (string :tag "Marker character")
2434 (choice
2435 (face :tag "Font-lock-face")
2436 (plist :tag "Face property list"))
2437 (string :tag "HTML start tag")
2438 (string :tag "HTML end tag")
2439 (option (const verbatim)))))
2441 ;;; Miscellaneous options
2443 (defgroup org-completion nil
2444 "Completion in Org-mode."
2445 :tag "Org Completion"
2446 :group 'org)
2448 (defcustom org-completion-use-ido nil
2449 "Non-nil means, use ido completion wherever possible.
2450 Note that `ido-mode' must be active for this variable to be relevant.
2451 If you decide to turn this variable on, you might well want to turn off
2452 `org-outline-path-complete-in-steps'."
2453 :group 'org-completion
2454 :type 'boolean)
2456 (defcustom org-completion-fallback-command 'hippie-expand
2457 "The expansion command called by \\[org-complete] in normal context.
2458 Normal means, no org-mode-specific context."
2459 :group 'org-completion
2460 :type 'function)
2462 ;;; Functions and variables from ther packages
2463 ;; Declared here to avoid compiler warnings
2465 ;; XEmacs only
2466 (defvar outline-mode-menu-heading)
2467 (defvar outline-mode-menu-show)
2468 (defvar outline-mode-menu-hide)
2469 (defvar zmacs-regions) ; XEmacs regions
2471 ;; Emacs only
2472 (defvar mark-active)
2474 ;; Various packages
2475 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2476 (declare-function calendar-forward-day "cal-move" (arg))
2477 (declare-function calendar-goto-date "cal-move" (date))
2478 (declare-function calendar-goto-today "cal-move" ())
2479 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2480 (defvar calc-embedded-close-formula)
2481 (defvar calc-embedded-open-formula)
2482 (declare-function cdlatex-tab "ext:cdlatex" ())
2483 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2484 (defvar font-lock-unfontify-region-function)
2485 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2486 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2487 (defvar iswitchb-temp-buflist)
2488 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2489 (declare-function org-agenda-skip "org-agenda" ())
2490 (declare-function org-format-agenda-item "org-agenda"
2491 (extra txt &optional category tags dotime noprefix remove-re))
2492 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2493 (declare-function org-agenda-change-all-lines "org-agenda"
2494 (newhead hdmarker &optional fixface just-this))
2495 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2496 (declare-function org-agenda-maybe-redo "org-agenda" ())
2497 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2498 (beg end))
2499 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2500 (declare-function parse-time-string "parse-time" (string))
2501 (declare-function remember "remember" (&optional initial))
2502 (declare-function remember-buffer-desc "remember" ())
2503 (declare-function remember-finalize "remember" ())
2504 (defvar remember-save-after-remembering)
2505 (defvar remember-data-file)
2506 (defvar remember-register)
2507 (defvar remember-buffer)
2508 (defvar remember-handler-functions)
2509 (defvar remember-annotation-functions)
2510 (defvar texmathp-why)
2511 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2512 (declare-function table--at-cell-p "table" (position &optional object at-column))
2514 (defvar w3m-current-url)
2515 (defvar w3m-current-title)
2517 (defvar org-latex-regexps)
2519 ;;; Autoload and prepare some org modules
2521 ;; Some table stuff that needs to be defined here, because it is used
2522 ;; by the functions setting up org-mode or checking for table context.
2524 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2525 "Detects an org-type or table-type table.")
2526 (defconst org-table-line-regexp "^[ \t]*|"
2527 "Detects an org-type table line.")
2528 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2529 "Detects an org-type table line.")
2530 (defconst org-table-hline-regexp "^[ \t]*|-"
2531 "Detects an org-type table hline.")
2532 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2533 "Detects a table-type table hline.")
2534 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2535 "Searching from within a table (any type) this finds the first line
2536 outside the table.")
2538 ;; Autoload the functions in org-table.el that are needed by functions here.
2540 (eval-and-compile
2541 (org-autoload "org-table"
2542 '(org-table-align org-table-begin org-table-blank-field
2543 org-table-convert org-table-convert-region org-table-copy-down
2544 org-table-copy-region org-table-create
2545 org-table-create-or-convert-from-region
2546 org-table-create-with-table.el org-table-current-dline
2547 org-table-cut-region org-table-delete-column org-table-edit-field
2548 org-table-edit-formulas org-table-end org-table-eval-formula
2549 org-table-export org-table-field-info
2550 org-table-get-stored-formulas org-table-goto-column
2551 org-table-hline-and-move org-table-import org-table-insert-column
2552 org-table-insert-hline org-table-insert-row org-table-iterate
2553 org-table-justify-field-maybe org-table-kill-row
2554 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2555 org-table-move-column org-table-move-column-left
2556 org-table-move-column-right org-table-move-row
2557 org-table-move-row-down org-table-move-row-up
2558 org-table-next-field org-table-next-row org-table-paste-rectangle
2559 org-table-previous-field org-table-recalculate
2560 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2561 org-table-toggle-coordinate-overlays
2562 org-table-toggle-formula-debugger org-table-wrap-region
2563 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2565 (defun org-at-table-p (&optional table-type)
2566 "Return t if the cursor is inside an org-type table.
2567 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2568 (if org-enable-table-editor
2569 (save-excursion
2570 (beginning-of-line 1)
2571 (looking-at (if table-type org-table-any-line-regexp
2572 org-table-line-regexp)))
2573 nil))
2574 (defsubst org-table-p () (org-at-table-p))
2576 (defun org-at-table.el-p ()
2577 "Return t if and only if we are at a table.el table."
2578 (and (org-at-table-p 'any)
2579 (save-excursion
2580 (goto-char (org-table-begin 'any))
2581 (looking-at org-table1-hline-regexp))))
2582 (defun org-table-recognize-table.el ()
2583 "If there is a table.el table nearby, recognize it and move into it."
2584 (if org-table-tab-recognizes-table.el
2585 (if (org-at-table.el-p)
2586 (progn
2587 (beginning-of-line 1)
2588 (if (looking-at org-table-dataline-regexp)
2590 (if (looking-at org-table1-hline-regexp)
2591 (progn
2592 (beginning-of-line 2)
2593 (if (looking-at org-table-any-border-regexp)
2594 (beginning-of-line -1)))))
2595 (if (re-search-forward "|" (org-table-end t) t)
2596 (progn
2597 (require 'table)
2598 (if (table--at-cell-p (point))
2600 (message "recognizing table.el table...")
2601 (table-recognize-table)
2602 (message "recognizing table.el table...done")))
2603 (error "This should not happen..."))
2605 nil)
2606 nil))
2608 (defun org-at-table-hline-p ()
2609 "Return t if the cursor is inside a hline in a table."
2610 (if org-enable-table-editor
2611 (save-excursion
2612 (beginning-of-line 1)
2613 (looking-at org-table-hline-regexp))
2614 nil))
2616 (defvar org-table-clean-did-remove-column nil)
2618 (defun org-table-map-tables (function)
2619 "Apply FUNCTION to the start of all tables in the buffer."
2620 (save-excursion
2621 (save-restriction
2622 (widen)
2623 (goto-char (point-min))
2624 (while (re-search-forward org-table-any-line-regexp nil t)
2625 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2626 (beginning-of-line 1)
2627 (if (looking-at org-table-line-regexp)
2628 (save-excursion (funcall function)))
2629 (re-search-forward org-table-any-border-regexp nil 1))))
2630 (message "Mapping tables: done"))
2632 ;; Declare and autoload functions from org-exp.el
2634 (declare-function org-default-export-plist "org-exp")
2635 (declare-function org-infile-export-plist "org-exp")
2636 (declare-function org-get-current-options "org-exp")
2637 (eval-and-compile
2638 (org-autoload "org-exp"
2639 '(org-export org-export-as-ascii org-export-visible
2640 org-insert-export-options-template org-export-as-html-and-open
2641 org-export-as-html-batch org-export-as-html-to-buffer
2642 org-replace-region-by-html org-export-region-as-html
2643 org-export-as-html org-export-icalendar-this-file
2644 org-export-icalendar-all-agenda-files
2645 org-table-clean-before-export
2646 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2648 ;; Declare and autoload functions from org-agenda.el
2650 (eval-and-compile
2651 (org-autoload "org-agenda"
2652 '(org-agenda org-agenda-list org-search-view
2653 org-todo-list org-tags-view org-agenda-list-stuck-projects
2654 org-diary org-agenda-to-appt)))
2656 ;; Autoload org-remember
2658 (eval-and-compile
2659 (org-autoload "org-remember"
2660 '(org-remember-insinuate org-remember-annotation
2661 org-remember-apply-template org-remember org-remember-handler)))
2663 ;; Autoload org-clock.el
2666 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2667 (beg end))
2668 (declare-function org-update-mode-line "org-clock" ())
2669 (defvar org-clock-start-time)
2670 (defvar org-clock-marker (make-marker)
2671 "Marker recording the last clock-in.")
2673 (eval-and-compile
2674 (org-autoload
2675 "org-clock"
2676 '(org-clock-in org-clock-out org-clock-cancel
2677 org-clock-goto org-clock-sum org-clock-display
2678 org-clock-remove-overlays org-clock-report
2679 org-clocktable-shift org-dblock-write:clocktable
2680 org-get-clocktable)))
2682 (defun org-clock-update-time-maybe ()
2683 "If this is a CLOCK line, update it and return t.
2684 Otherwise, return nil."
2685 (interactive)
2686 (save-excursion
2687 (beginning-of-line 1)
2688 (skip-chars-forward " \t")
2689 (when (looking-at org-clock-string)
2690 (let ((re (concat "[ \t]*" org-clock-string
2691 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2692 "\\([ \t]*=>.*\\)?\\)?"))
2693 ts te h m s neg)
2694 (cond
2695 ((not (looking-at re))
2696 nil)
2697 ((not (match-end 2))
2698 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2699 (> org-clock-marker (point))
2700 (<= org-clock-marker (point-at-eol)))
2701 ;; The clock is running here
2702 (setq org-clock-start-time
2703 (apply 'encode-time
2704 (org-parse-time-string (match-string 1))))
2705 (org-update-mode-line)))
2707 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2708 (end-of-line 1)
2709 (setq ts (match-string 1)
2710 te (match-string 3))
2711 (setq s (- (time-to-seconds
2712 (apply 'encode-time (org-parse-time-string te)))
2713 (time-to-seconds
2714 (apply 'encode-time (org-parse-time-string ts))))
2715 neg (< s 0)
2716 s (abs s)
2717 h (floor (/ s 3600))
2718 s (- s (* 3600 h))
2719 m (floor (/ s 60))
2720 s (- s (* 60 s)))
2721 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2722 t))))))
2724 (defun org-check-running-clock ()
2725 "Check if the current buffer contains the running clock.
2726 If yes, offer to stop it and to save the buffer with the changes."
2727 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2728 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2729 (buffer-name))))
2730 (org-clock-out)
2731 (when (y-or-n-p "Save changed buffer?")
2732 (save-buffer))))
2734 (defun org-clocktable-try-shift (dir n)
2735 "Check if this line starts a clock table, if yes, shift the time block."
2736 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2737 (org-clocktable-shift dir n)))
2739 ;; Autoload org-timer.el
2741 ;(declare-function org-timer "org-timer")
2743 (eval-and-compile
2744 (org-autoload
2745 "org-timer"
2746 '(org-timer-start org-timer org-timer-item
2747 org-timer-change-times-in-region)))
2750 ;; Autoload archiving code
2751 ;; The stuff that is needed for cycling and tags has to be defined here.
2753 (defgroup org-archive nil
2754 "Options concerning archiving in Org-mode."
2755 :tag "Org Archive"
2756 :group 'org-structure)
2758 (defcustom org-archive-location "%s_archive::"
2759 "The location where subtrees should be archived.
2761 The value of this variable is a string, consisting of two parts,
2762 separated by a double-colon. The first part is a filename and
2763 the second part is a headline.
2765 When the filename is omitted, archiving happens in the same file.
2766 %s in the filename will be replaced by the current file
2767 name (without the directory part). Archiving to a different file
2768 is useful to keep archived entries from contributing to the
2769 Org-mode Agenda.
2771 The archived entries will be filed as subtrees of the specified
2772 headline. When the headline is omitted, the subtrees are simply
2773 filed away at the end of the file, as top-level entries. Also in
2774 the heading you can use %s to represent the file name, this can be
2775 useful when using the same archive for a number of different files.
2777 Here are a few examples:
2778 \"%s_archive::\"
2779 If the current file is Projects.org, archive in file
2780 Projects.org_archive, as top-level trees. This is the default.
2782 \"::* Archived Tasks\"
2783 Archive in the current file, under the top-level headline
2784 \"* Archived Tasks\".
2786 \"~/org/archive.org::\"
2787 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2789 \"~/org/archive.org::From %s\"
2790 Archive in file ~/org/archive.org (absolute path), und headlines
2791 \"From FILENAME\" where file name is the current file name.
2793 \"basement::** Finished Tasks\"
2794 Archive in file ./basement (relative path), as level 3 trees
2795 below the level 2 heading \"** Finished Tasks\".
2797 You may set this option on a per-file basis by adding to the buffer a
2798 line like
2800 #+ARCHIVE: basement::** Finished Tasks
2802 You may also define it locally for a subtree by setting an ARCHIVE property
2803 in the entry. If such a property is found in an entry, or anywhere up
2804 the hierarchy, it will be used."
2805 :group 'org-archive
2806 :type 'string)
2808 (defcustom org-archive-tag "ARCHIVE"
2809 "The tag that marks a subtree as archived.
2810 An archived subtree does not open during visibility cycling, and does
2811 not contribute to the agenda listings.
2812 After changing this, font-lock must be restarted in the relevant buffers to
2813 get the proper fontification."
2814 :group 'org-archive
2815 :group 'org-keywords
2816 :type 'string)
2818 (defcustom org-agenda-skip-archived-trees t
2819 "Non-nil means, the agenda will skip any items located in archived trees.
2820 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2821 variable is no longer recommended, you should leave it at the value t.
2822 Instead, use the key `v' to cycle the archives-mode in the agenda."
2823 :group 'org-archive
2824 :group 'org-agenda-skip
2825 :type 'boolean)
2827 (defcustom org-cycle-open-archived-trees nil
2828 "Non-nil means, `org-cycle' will open archived trees.
2829 An archived tree is a tree marked with the tag ARCHIVE.
2830 When nil, archived trees will stay folded. You can still open them with
2831 normal outline commands like `show-all', but not with the cycling commands."
2832 :group 'org-archive
2833 :group 'org-cycle
2834 :type 'boolean)
2836 (defcustom org-sparse-tree-open-archived-trees nil
2837 "Non-nil means sparse tree construction shows matches in archived trees.
2838 When nil, matches in these trees are highlighted, but the trees are kept in
2839 collapsed state."
2840 :group 'org-archive
2841 :group 'org-sparse-trees
2842 :type 'boolean)
2844 (defun org-cycle-hide-archived-subtrees (state)
2845 "Re-hide all archived subtrees after a visibility state change."
2846 (when (and (not org-cycle-open-archived-trees)
2847 (not (memq state '(overview folded))))
2848 (save-excursion
2849 (let* ((globalp (memq state '(contents all)))
2850 (beg (if globalp (point-min) (point)))
2851 (end (if globalp (point-max) (org-end-of-subtree t))))
2852 (org-hide-archived-subtrees beg end)
2853 (goto-char beg)
2854 (if (looking-at (concat ".*:" org-archive-tag ":"))
2855 (message "%s" (substitute-command-keys
2856 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2858 (defun org-force-cycle-archived ()
2859 "Cycle subtree even if it is archived."
2860 (interactive)
2861 (setq this-command 'org-cycle)
2862 (let ((org-cycle-open-archived-trees t))
2863 (call-interactively 'org-cycle)))
2865 (defun org-hide-archived-subtrees (beg end)
2866 "Re-hide all archived subtrees after a visibility state change."
2867 (save-excursion
2868 (let* ((re (concat ":" org-archive-tag ":")))
2869 (goto-char beg)
2870 (while (re-search-forward re end t)
2871 (and (org-on-heading-p) (hide-subtree))
2872 (org-end-of-subtree t)))))
2874 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2876 (eval-and-compile
2877 (org-autoload "org-archive"
2878 '(org-add-archive-files org-archive-subtree
2879 org-archive-to-archive-sibling org-toggle-archive-tag)))
2881 ;; Autoload Column View Code
2883 (declare-function org-columns-number-to-string "org-colview")
2884 (declare-function org-columns-get-format-and-top-level "org-colview")
2885 (declare-function org-columns-compute "org-colview")
2887 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2888 '(org-columns-number-to-string org-columns-get-format-and-top-level
2889 org-columns-compute org-agenda-columns org-columns-remove-overlays
2890 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2892 ;; Autoload ID code
2894 (declare-function org-id-store-link "org-id")
2895 (org-autoload "org-id"
2896 '(org-id-get-create org-id-new org-id-copy org-id-get
2897 org-id-get-with-outline-path-completion
2898 org-id-get-with-outline-drilling
2899 org-id-goto org-id-find org-id-store-link))
2901 ;;; Variables for pre-computed regular expressions, all buffer local
2903 (defvar org-drawer-regexp nil
2904 "Matches first line of a hidden block.")
2905 (make-variable-buffer-local 'org-drawer-regexp)
2906 (defvar org-todo-regexp nil
2907 "Matches any of the TODO state keywords.")
2908 (make-variable-buffer-local 'org-todo-regexp)
2909 (defvar org-not-done-regexp nil
2910 "Matches any of the TODO state keywords except the last one.")
2911 (make-variable-buffer-local 'org-not-done-regexp)
2912 (defvar org-todo-line-regexp nil
2913 "Matches a headline and puts TODO state into group 2 if present.")
2914 (make-variable-buffer-local 'org-todo-line-regexp)
2915 (defvar org-complex-heading-regexp nil
2916 "Matches a headline and puts everything into groups:
2917 group 1: the stars
2918 group 2: The todo keyword, maybe
2919 group 3: Priority cookie
2920 group 4: True headline
2921 group 5: Tags")
2922 (make-variable-buffer-local 'org-complex-heading-regexp)
2923 (defvar org-todo-line-tags-regexp nil
2924 "Matches a headline and puts TODO state into group 2 if present.
2925 Also put tags into group 4 if tags are present.")
2926 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2927 (defvar org-nl-done-regexp nil
2928 "Matches newline followed by a headline with the DONE keyword.")
2929 (make-variable-buffer-local 'org-nl-done-regexp)
2930 (defvar org-looking-at-done-regexp nil
2931 "Matches the DONE keyword a point.")
2932 (make-variable-buffer-local 'org-looking-at-done-regexp)
2933 (defvar org-ds-keyword-length 12
2934 "Maximum length of the Deadline and SCHEDULED keywords.")
2935 (make-variable-buffer-local 'org-ds-keyword-length)
2936 (defvar org-deadline-regexp nil
2937 "Matches the DEADLINE keyword.")
2938 (make-variable-buffer-local 'org-deadline-regexp)
2939 (defvar org-deadline-time-regexp nil
2940 "Matches the DEADLINE keyword together with a time stamp.")
2941 (make-variable-buffer-local 'org-deadline-time-regexp)
2942 (defvar org-deadline-line-regexp nil
2943 "Matches the DEADLINE keyword and the rest of the line.")
2944 (make-variable-buffer-local 'org-deadline-line-regexp)
2945 (defvar org-scheduled-regexp nil
2946 "Matches the SCHEDULED keyword.")
2947 (make-variable-buffer-local 'org-scheduled-regexp)
2948 (defvar org-scheduled-time-regexp nil
2949 "Matches the SCHEDULED keyword together with a time stamp.")
2950 (make-variable-buffer-local 'org-scheduled-time-regexp)
2951 (defvar org-closed-time-regexp nil
2952 "Matches the CLOSED keyword together with a time stamp.")
2953 (make-variable-buffer-local 'org-closed-time-regexp)
2955 (defvar org-keyword-time-regexp nil
2956 "Matches any of the 4 keywords, together with the time stamp.")
2957 (make-variable-buffer-local 'org-keyword-time-regexp)
2958 (defvar org-keyword-time-not-clock-regexp nil
2959 "Matches any of the 3 keywords, together with the time stamp.")
2960 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2961 (defvar org-maybe-keyword-time-regexp nil
2962 "Matches a timestamp, possibly preceeded by a keyword.")
2963 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2964 (defvar org-planning-or-clock-line-re nil
2965 "Matches a line with planning or clock info.")
2966 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2968 (defconst org-plain-time-of-day-regexp
2969 (concat
2970 "\\(\\<[012]?[0-9]"
2971 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2972 "\\(--?"
2973 "\\(\\<[012]?[0-9]"
2974 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2975 "\\)?")
2976 "Regular expression to match a plain time or time range.
2977 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2978 groups carry important information:
2979 0 the full match
2980 1 the first time, range or not
2981 8 the second time, if it is a range.")
2983 (defconst org-plain-time-extension-regexp
2984 (concat
2985 "\\(\\<[012]?[0-9]"
2986 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2987 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2988 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2989 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2990 groups carry important information:
2991 0 the full match
2992 7 hours of duration
2993 9 minutes of duration")
2995 (defconst org-stamp-time-of-day-regexp
2996 (concat
2997 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2998 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2999 "\\(--?"
3000 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3001 "Regular expression to match a timestamp time or time range.
3002 After a match, the following groups carry important information:
3003 0 the full match
3004 1 date plus weekday, for backreferencing to make sure both times on same day
3005 2 the first time, range or not
3006 4 the second time, if it is a range.")
3008 (defconst org-startup-options
3009 '(("fold" org-startup-folded t)
3010 ("overview" org-startup-folded t)
3011 ("nofold" org-startup-folded nil)
3012 ("showall" org-startup-folded nil)
3013 ("content" org-startup-folded content)
3014 ("hidestars" org-hide-leading-stars t)
3015 ("showstars" org-hide-leading-stars nil)
3016 ("odd" org-odd-levels-only t)
3017 ("oddeven" org-odd-levels-only nil)
3018 ("align" org-startup-align-all-tables t)
3019 ("noalign" org-startup-align-all-tables nil)
3020 ("customtime" org-display-custom-times t)
3021 ("logdone" org-log-done time)
3022 ("lognotedone" org-log-done note)
3023 ("nologdone" org-log-done nil)
3024 ("lognoteclock-out" org-log-note-clock-out t)
3025 ("nolognoteclock-out" org-log-note-clock-out nil)
3026 ("logrepeat" org-log-repeat state)
3027 ("lognoterepeat" org-log-repeat note)
3028 ("nologrepeat" org-log-repeat nil)
3029 ("fninline" org-footnote-define-inline t)
3030 ("nofninline" org-footnote-define-inline nil)
3031 ("fnlocal" org-footnote-section nil)
3032 ("fnauto" org-footnote-auto-label t)
3033 ("fnprompt" org-footnote-auto-label nil)
3034 ("fnconfirm" org-footnote-auto-label confirm)
3035 ("fnplain" org-footnote-auto-label plain)
3036 ("constcgs" constants-unit-system cgs)
3037 ("constSI" constants-unit-system SI))
3038 "Variable associated with STARTUP options for org-mode.
3039 Each element is a list of three items: The startup options as written
3040 in the #+STARTUP line, the corresponding variable, and the value to
3041 set this variable to if the option is found. An optional forth element PUSH
3042 means to push this value onto the list in the variable.")
3044 (defun org-set-regexps-and-options ()
3045 "Precompute regular expressions for current buffer."
3046 (when (org-mode-p)
3047 (org-set-local 'org-todo-kwd-alist nil)
3048 (org-set-local 'org-todo-key-alist nil)
3049 (org-set-local 'org-todo-key-trigger nil)
3050 (org-set-local 'org-todo-keywords-1 nil)
3051 (org-set-local 'org-done-keywords nil)
3052 (org-set-local 'org-todo-heads nil)
3053 (org-set-local 'org-todo-sets nil)
3054 (org-set-local 'org-todo-log-states nil)
3055 (org-set-local 'org-file-properties nil)
3056 (org-set-local 'org-file-tags nil)
3057 (let ((re (org-make-options-regexp
3058 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3059 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3060 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3061 (splitre "[ \t]+")
3062 kwds kws0 kwsa key log value cat arch tags const links hw dws
3063 tail sep kws1 prio props ftags drawers
3064 ext-setup-or-nil setup-contents (start 0))
3065 (save-excursion
3066 (save-restriction
3067 (widen)
3068 (goto-char (point-min))
3069 (while (or (and ext-setup-or-nil
3070 (string-match re ext-setup-or-nil start)
3071 (setq start (match-end 0)))
3072 (and (setq ext-setup-or-nil nil start 0)
3073 (re-search-forward re nil t)))
3074 (setq key (upcase (match-string 1 ext-setup-or-nil))
3075 value (org-match-string-no-properties 2 ext-setup-or-nil))
3076 (cond
3077 ((equal key "CATEGORY")
3078 (if (string-match "[ \t]+$" value)
3079 (setq value (replace-match "" t t value)))
3080 (setq cat value))
3081 ((member key '("SEQ_TODO" "TODO"))
3082 (push (cons 'sequence (org-split-string value splitre)) kwds))
3083 ((equal key "TYP_TODO")
3084 (push (cons 'type (org-split-string value splitre)) kwds))
3085 ((equal key "TAGS")
3086 (setq tags (append tags (org-split-string value splitre))))
3087 ((equal key "COLUMNS")
3088 (org-set-local 'org-columns-default-format value))
3089 ((equal key "LINK")
3090 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3091 (push (cons (match-string 1 value)
3092 (org-trim (match-string 2 value)))
3093 links)))
3094 ((equal key "PRIORITIES")
3095 (setq prio (org-split-string value " +")))
3096 ((equal key "PROPERTY")
3097 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3098 (push (cons (match-string 1 value) (match-string 2 value))
3099 props)))
3100 ((equal key "FILETAGS")
3101 (when (string-match "\\S-" value)
3102 (setq ftags
3103 (append
3104 ftags
3105 (apply 'append
3106 (mapcar (lambda (x) (org-split-string x ":"))
3107 (org-split-string value)))))))
3108 ((equal key "DRAWERS")
3109 (setq drawers (org-split-string value splitre)))
3110 ((equal key "CONSTANTS")
3111 (setq const (append const (org-split-string value splitre))))
3112 ((equal key "STARTUP")
3113 (let ((opts (org-split-string value splitre))
3114 l var val)
3115 (while (setq l (pop opts))
3116 (when (setq l (assoc l org-startup-options))
3117 (setq var (nth 1 l) val (nth 2 l))
3118 (if (not (nth 3 l))
3119 (set (make-local-variable var) val)
3120 (if (not (listp (symbol-value var)))
3121 (set (make-local-variable var) nil))
3122 (set (make-local-variable var) (symbol-value var))
3123 (add-to-list var val))))))
3124 ((equal key "ARCHIVE")
3125 (string-match " *$" value)
3126 (setq arch (replace-match "" t t value))
3127 (remove-text-properties 0 (length arch)
3128 '(face t fontified t) arch))
3129 ((equal key "SETUPFILE")
3130 (setq setup-contents (org-file-contents
3131 (expand-file-name
3132 (org-remove-double-quotes value))
3133 'noerror))
3134 (if (not ext-setup-or-nil)
3135 (setq ext-setup-or-nil setup-contents start 0)
3136 (setq ext-setup-or-nil
3137 (concat (substring ext-setup-or-nil 0 start)
3138 "\n" setup-contents "\n"
3139 (substring ext-setup-or-nil start)))))
3140 ))))
3141 (when cat
3142 (org-set-local 'org-category (intern cat))
3143 (push (cons "CATEGORY" cat) props))
3144 (when prio
3145 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3146 (setq prio (mapcar 'string-to-char prio))
3147 (org-set-local 'org-highest-priority (nth 0 prio))
3148 (org-set-local 'org-lowest-priority (nth 1 prio))
3149 (org-set-local 'org-default-priority (nth 2 prio)))
3150 (and props (org-set-local 'org-file-properties (nreverse props)))
3151 (and ftags (org-set-local 'org-file-tags ftags))
3152 (and drawers (org-set-local 'org-drawers drawers))
3153 (and arch (org-set-local 'org-archive-location arch))
3154 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3155 ;; Process the TODO keywords
3156 (unless kwds
3157 ;; Use the global values as if they had been given locally.
3158 (setq kwds (default-value 'org-todo-keywords))
3159 (if (stringp (car kwds))
3160 (setq kwds (list (cons org-todo-interpretation
3161 (default-value 'org-todo-keywords)))))
3162 (setq kwds (reverse kwds)))
3163 (setq kwds (nreverse kwds))
3164 (let (inter kws kw)
3165 (while (setq kws (pop kwds))
3166 (setq inter (pop kws) sep (member "|" kws)
3167 kws0 (delete "|" (copy-sequence kws))
3168 kwsa nil
3169 kws1 (mapcar
3170 (lambda (x)
3171 ;; 1 2
3172 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3173 (progn
3174 (setq kw (match-string 1 x)
3175 key (and (match-end 2) (match-string 2 x))
3176 log (org-extract-log-state-settings x))
3177 (push (cons kw (and key (string-to-char key))) kwsa)
3178 (and log (push log org-todo-log-states))
3180 (error "Invalid TODO keyword %s" x)))
3181 kws0)
3182 kwsa (if kwsa (append '((:startgroup))
3183 (nreverse kwsa)
3184 '((:endgroup))))
3185 hw (car kws1)
3186 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3187 tail (list inter hw (car dws) (org-last dws)))
3188 (add-to-list 'org-todo-heads hw 'append)
3189 (push kws1 org-todo-sets)
3190 (setq org-done-keywords (append org-done-keywords dws nil))
3191 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3192 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3193 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3194 (setq org-todo-sets (nreverse org-todo-sets)
3195 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3196 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3197 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3198 ;; Process the constants
3199 (when const
3200 (let (e cst)
3201 (while (setq e (pop const))
3202 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3203 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3204 (setq org-table-formula-constants-local cst)))
3206 ;; Process the tags.
3207 (when tags
3208 (let (e tgs)
3209 (while (setq e (pop tags))
3210 (cond
3211 ((equal e "{") (push '(:startgroup) tgs))
3212 ((equal e "}") (push '(:endgroup) tgs))
3213 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3214 (push (cons (match-string 1 e)
3215 (string-to-char (match-string 2 e)))
3216 tgs))
3217 (t (push (list e) tgs))))
3218 (org-set-local 'org-tag-alist nil)
3219 (while (setq e (pop tgs))
3220 (or (and (stringp (car e))
3221 (assoc (car e) org-tag-alist))
3222 (push e org-tag-alist)))))
3224 ;; Compute the regular expressions and other local variables
3225 (if (not org-done-keywords)
3226 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3227 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3228 (length org-scheduled-string)
3229 (length org-clock-string)
3230 (length org-closed-string)))
3231 org-drawer-regexp
3232 (concat "^[ \t]*:\\("
3233 (mapconcat 'regexp-quote org-drawers "\\|")
3234 "\\):[ \t]*$")
3235 org-not-done-keywords
3236 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3237 org-todo-regexp
3238 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3239 "\\|") "\\)\\>")
3240 org-not-done-regexp
3241 (concat "\\<\\("
3242 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3243 "\\)\\>")
3244 org-todo-line-regexp
3245 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3246 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3247 "\\)\\>\\)?[ \t]*\\(.*\\)")
3248 org-complex-heading-regexp
3249 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3250 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3251 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3252 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3253 org-nl-done-regexp
3254 (concat "\n\\*+[ \t]+"
3255 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3256 "\\)" "\\>")
3257 org-todo-line-tags-regexp
3258 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3259 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3260 (org-re
3261 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3262 org-looking-at-done-regexp
3263 (concat "^" "\\(?:"
3264 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3265 "\\>")
3266 org-deadline-regexp (concat "\\<" org-deadline-string)
3267 org-deadline-time-regexp
3268 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3269 org-deadline-line-regexp
3270 (concat "\\<\\(" org-deadline-string "\\).*")
3271 org-scheduled-regexp
3272 (concat "\\<" org-scheduled-string)
3273 org-scheduled-time-regexp
3274 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3275 org-closed-time-regexp
3276 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3277 org-keyword-time-regexp
3278 (concat "\\<\\(" org-scheduled-string
3279 "\\|" org-deadline-string
3280 "\\|" org-closed-string
3281 "\\|" org-clock-string "\\)"
3282 " *[[<]\\([^]>]+\\)[]>]")
3283 org-keyword-time-not-clock-regexp
3284 (concat "\\<\\(" org-scheduled-string
3285 "\\|" org-deadline-string
3286 "\\|" org-closed-string
3287 "\\)"
3288 " *[[<]\\([^]>]+\\)[]>]")
3289 org-maybe-keyword-time-regexp
3290 (concat "\\(\\<\\(" org-scheduled-string
3291 "\\|" org-deadline-string
3292 "\\|" org-closed-string
3293 "\\|" org-clock-string "\\)\\)?"
3294 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3295 org-planning-or-clock-line-re
3296 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3297 "\\|" org-deadline-string
3298 "\\|" org-closed-string "\\|" org-clock-string
3299 "\\)\\>\\)")
3301 (org-compute-latex-and-specials-regexp)
3302 (org-set-font-lock-defaults))))
3304 (defun org-file-contents (file &optional noerror)
3305 "Return the contents of FILE, as a string."
3306 (if (or (not file)
3307 (not (file-readable-p file)))
3308 (if noerror
3309 (progn
3310 (message "Cannot read file %s" file)
3311 (ding) (sit-for 2)
3313 (error "Cannot read file %s" file))
3314 (with-temp-buffer
3315 (insert-file-contents file)
3316 (buffer-string))))
3318 (defun org-extract-log-state-settings (x)
3319 "Extract the log state setting from a TODO keyword string.
3320 This will extract info from a string like \"WAIT(w@/!)\"."
3321 (let (kw key log1 log2)
3322 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3323 (setq kw (match-string 1 x)
3324 key (and (match-end 2) (match-string 2 x))
3325 log1 (and (match-end 3) (match-string 3 x))
3326 log2 (and (match-end 4) (match-string 4 x)))
3327 (and (or log1 log2)
3328 (list kw
3329 (and log1 (if (equal log1 "!") 'time 'note))
3330 (and log2 (if (equal log2 "!") 'time 'note)))))))
3332 (defun org-remove-keyword-keys (list)
3333 "Remove a pair of parenthesis at the end of each string in LIST."
3334 (mapcar (lambda (x)
3335 (if (string-match "(.*)$" x)
3336 (substring x 0 (match-beginning 0))
3338 list))
3340 ;; FIXME: this could be done much better, using second characters etc.
3341 (defun org-assign-fast-keys (alist)
3342 "Assign fast keys to a keyword-key alist.
3343 Respect keys that are already there."
3344 (let (new e k c c1 c2 (char ?a))
3345 (while (setq e (pop alist))
3346 (cond
3347 ((equal e '(:startgroup)) (push e new))
3348 ((equal e '(:endgroup)) (push e new))
3350 (setq k (car e) c2 nil)
3351 (if (cdr e)
3352 (setq c (cdr e))
3353 ;; automatically assign a character.
3354 (setq c1 (string-to-char
3355 (downcase (substring
3356 k (if (= (string-to-char k) ?@) 1 0)))))
3357 (if (or (rassoc c1 new) (rassoc c1 alist))
3358 (while (or (rassoc char new) (rassoc char alist))
3359 (setq char (1+ char)))
3360 (setq c2 c1))
3361 (setq c (or c2 char)))
3362 (push (cons k c) new))))
3363 (nreverse new)))
3365 ;;; Some variables used in various places
3367 (defvar org-window-configuration nil
3368 "Used in various places to store a window configuration.")
3369 (defvar org-finish-function nil
3370 "Function to be called when `C-c C-c' is used.
3371 This is for getting out of special buffers like remember.")
3374 ;; FIXME: Occasionally check by commenting these, to make sure
3375 ;; no other functions uses these, forgetting to let-bind them.
3376 (defvar entry)
3377 (defvar state)
3378 (defvar last-state)
3379 (defvar date)
3380 (defvar description)
3382 ;; Defined somewhere in this file, but used before definition.
3383 (defvar org-html-entities)
3384 (defvar org-struct-menu)
3385 (defvar org-org-menu)
3386 (defvar org-tbl-menu)
3387 (defvar org-agenda-keymap)
3389 ;;;; Define the Org-mode
3391 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3392 (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."))
3395 ;; We use a before-change function to check if a table might need
3396 ;; an update.
3397 (defvar org-table-may-need-update t
3398 "Indicates that a table might need an update.
3399 This variable is set by `org-before-change-function'.
3400 `org-table-align' sets it back to nil.")
3401 (defun org-before-change-function (beg end)
3402 "Every change indicates that a table might need an update."
3403 (setq org-table-may-need-update t))
3404 (defvar org-mode-map)
3405 (defvar org-mode-hook nil
3406 "Mode hook for Org-mode, run after the mode was turned on.")
3407 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3408 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3409 (defvar org-table-buffer-is-an nil)
3410 (defconst org-outline-regexp "\\*+ ")
3412 ;;;###autoload
3413 (define-derived-mode org-mode outline-mode "Org"
3414 "Outline-based notes management and organizer, alias
3415 \"Carsten's outline-mode for keeping track of everything.\"
3417 Org-mode develops organizational tasks around a NOTES file which
3418 contains information about projects as plain text. Org-mode is
3419 implemented on top of outline-mode, which is ideal to keep the content
3420 of large files well structured. It supports ToDo items, deadlines and
3421 time stamps, which magically appear in the diary listing of the Emacs
3422 calendar. Tables are easily created with a built-in table editor.
3423 Plain text URL-like links connect to websites, emails (VM), Usenet
3424 messages (Gnus), BBDB entries, and any files related to the project.
3425 For printing and sharing of notes, an Org-mode file (or a part of it)
3426 can be exported as a structured ASCII or HTML file.
3428 The following commands are available:
3430 \\{org-mode-map}"
3432 ;; Get rid of Outline menus, they are not needed
3433 ;; Need to do this here because define-derived-mode sets up
3434 ;; the keymap so late. Still, it is a waste to call this each time
3435 ;; we switch another buffer into org-mode.
3436 (if (featurep 'xemacs)
3437 (when (boundp 'outline-mode-menu-heading)
3438 ;; Assume this is Greg's port, it used easymenu
3439 (easy-menu-remove outline-mode-menu-heading)
3440 (easy-menu-remove outline-mode-menu-show)
3441 (easy-menu-remove outline-mode-menu-hide))
3442 (define-key org-mode-map [menu-bar headings] 'undefined)
3443 (define-key org-mode-map [menu-bar hide] 'undefined)
3444 (define-key org-mode-map [menu-bar show] 'undefined))
3446 (org-load-modules-maybe)
3447 (easy-menu-add org-org-menu)
3448 (easy-menu-add org-tbl-menu)
3449 (org-install-agenda-files-menu)
3450 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3451 (org-add-to-invisibility-spec '(org-cwidth))
3452 (when (featurep 'xemacs)
3453 (org-set-local 'line-move-ignore-invisible t))
3454 (org-set-local 'outline-regexp org-outline-regexp)
3455 (org-set-local 'outline-level 'org-outline-level)
3456 (when (and org-ellipsis
3457 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3458 (fboundp 'make-glyph-code))
3459 (unless org-display-table
3460 (setq org-display-table (make-display-table)))
3461 (set-display-table-slot
3462 org-display-table 4
3463 (vconcat (mapcar
3464 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3465 org-ellipsis)))
3466 (if (stringp org-ellipsis) org-ellipsis "..."))))
3467 (setq buffer-display-table org-display-table))
3468 (org-set-regexps-and-options)
3469 (when (and org-tag-faces (not org-tags-special-faces-re))
3470 ;; tag faces set outside customize.... force initialization.
3471 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3472 ;; Calc embedded
3473 (org-set-local 'calc-embedded-open-mode "# ")
3474 (modify-syntax-entry ?# "<")
3475 (modify-syntax-entry ?@ "w")
3476 (if org-startup-truncated (setq truncate-lines t))
3477 (org-set-local 'font-lock-unfontify-region-function
3478 'org-unfontify-region)
3479 ;; Activate before-change-function
3480 (org-set-local 'org-table-may-need-update t)
3481 (org-add-hook 'before-change-functions 'org-before-change-function nil
3482 'local)
3483 ;; Check for running clock before killing a buffer
3484 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3485 ;; Paragraphs and auto-filling
3486 (org-set-autofill-regexps)
3487 (setq indent-line-function 'org-indent-line-function)
3488 (org-update-radio-target-regexp)
3490 ;; Comment characters
3491 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3492 (org-set-local 'comment-padding " ")
3494 ;; Align options lines
3495 (org-set-local
3496 'align-mode-rules-list
3497 '((org-in-buffer-settings
3498 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3499 (modes . '(org-mode)))))
3501 ;; Imenu
3502 (org-set-local 'imenu-create-index-function
3503 'org-imenu-get-tree)
3505 ;; Make isearch reveal context
3506 (if (or (featurep 'xemacs)
3507 (not (boundp 'outline-isearch-open-invisible-function)))
3508 ;; Emacs 21 and XEmacs make use of the hook
3509 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3510 ;; Emacs 22 deals with this through a special variable
3511 (org-set-local 'outline-isearch-open-invisible-function
3512 (lambda (&rest ignore) (org-show-context 'isearch))))
3514 ;; If empty file that did not turn on org-mode automatically, make it to.
3515 (if (and org-insert-mode-line-in-empty-file
3516 (interactive-p)
3517 (= (point-min) (point-max)))
3518 (insert "# -*- mode: org -*-\n\n"))
3520 (unless org-inhibit-startup
3521 (when org-startup-align-all-tables
3522 (let ((bmp (buffer-modified-p)))
3523 (org-table-map-tables 'org-table-align)
3524 (set-buffer-modified-p bmp)))
3525 (org-set-startup-visibility)))
3527 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3529 (defun org-current-time ()
3530 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3531 (if (> (car org-time-stamp-rounding-minutes) 1)
3532 (let ((r (car org-time-stamp-rounding-minutes))
3533 (time (decode-time)))
3534 (apply 'encode-time
3535 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3536 (nthcdr 2 time))))
3537 (current-time)))
3539 ;;;; Font-Lock stuff, including the activators
3541 (defvar org-mouse-map (make-sparse-keymap))
3542 (org-defkey org-mouse-map
3543 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3544 (org-defkey org-mouse-map
3545 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3546 (when org-mouse-1-follows-link
3547 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3548 (when org-tab-follows-link
3549 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3550 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3551 (when org-return-follows-link
3552 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3553 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3555 (require 'font-lock)
3557 (defconst org-non-link-chars "]\t\n\r<>")
3558 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3559 "shell" "elisp"))
3560 (defvar org-link-types-re nil
3561 "Matches a link that has a url-like prefix like \"http:\"")
3562 (defvar org-link-re-with-space nil
3563 "Matches a link with spaces, optional angular brackets around it.")
3564 (defvar org-link-re-with-space2 nil
3565 "Matches a link with spaces, optional angular brackets around it.")
3566 (defvar org-link-re-with-space3 nil
3567 "Matches a link with spaces, only for internal part in bracket links.")
3568 (defvar org-angle-link-re nil
3569 "Matches link with angular brackets, spaces are allowed.")
3570 (defvar org-plain-link-re nil
3571 "Matches plain link, without spaces.")
3572 (defvar org-bracket-link-regexp nil
3573 "Matches a link in double brackets.")
3574 (defvar org-bracket-link-analytic-regexp nil
3575 "Regular expression used to analyze links.
3576 Here is what the match groups contain after a match:
3577 1: http:
3578 2: http
3579 3: path
3580 4: [desc]
3581 5: desc")
3582 (defvar org-bracket-link-analytic-regexp++ nil
3583 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3584 (defvar org-any-link-re nil
3585 "Regular expression matching any link.")
3587 (defun org-make-link-regexps ()
3588 "Update the link regular expressions.
3589 This should be called after the variable `org-link-types' has changed."
3590 (setq org-link-types-re
3591 (concat
3592 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3593 org-link-re-with-space
3594 (concat
3595 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3596 "\\([^" org-non-link-chars " ]"
3597 "[^" org-non-link-chars "]*"
3598 "[^" org-non-link-chars " ]\\)>?")
3599 org-link-re-with-space2
3600 (concat
3601 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3602 "\\([^" org-non-link-chars " ]"
3603 "[^\t\n\r]*"
3604 "[^" org-non-link-chars " ]\\)>?")
3605 org-link-re-with-space3
3606 (concat
3607 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3608 "\\([^" org-non-link-chars " ]"
3609 "[^\t\n\r]*\\)")
3610 org-angle-link-re
3611 (concat
3612 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3613 "\\([^" org-non-link-chars " ]"
3614 "[^" org-non-link-chars "]*"
3615 "\\)>")
3616 org-plain-link-re
3617 (concat
3618 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3619 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3620 org-bracket-link-regexp
3621 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3622 org-bracket-link-analytic-regexp
3623 (concat
3624 "\\[\\["
3625 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3626 "\\([^]]+\\)"
3627 "\\]"
3628 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3629 "\\]")
3630 org-bracket-link-analytic-regexp++
3631 (concat
3632 "\\[\\["
3633 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3634 "\\([^]]+\\)"
3635 "\\]"
3636 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3637 "\\]")
3638 org-any-link-re
3639 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3640 org-angle-link-re "\\)\\|\\("
3641 org-plain-link-re "\\)")))
3643 (org-make-link-regexps)
3645 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3646 "Regular expression for fast time stamp matching.")
3647 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3648 "Regular expression for fast time stamp matching.")
3649 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3650 "Regular expression matching time strings for analysis.
3651 This one does not require the space after the date, so it can be used
3652 on a string that terminates immediately after the date.")
3653 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3654 "Regular expression matching time strings for analysis.")
3655 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3656 "Regular expression matching time stamps, with groups.")
3657 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3658 "Regular expression matching time stamps (also [..]), with groups.")
3659 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3660 "Regular expression matching a time stamp range.")
3661 (defconst org-tr-regexp-both
3662 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3663 "Regular expression matching a time stamp range.")
3664 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3665 org-ts-regexp "\\)?")
3666 "Regular expression matching a time stamp or time stamp range.")
3667 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3668 org-ts-regexp-both "\\)?")
3669 "Regular expression matching a time stamp or time stamp range.
3670 The time stamps may be either active or inactive.")
3672 (defvar org-emph-face nil)
3674 (defun org-do-emphasis-faces (limit)
3675 "Run through the buffer and add overlays to links."
3676 (let (rtn)
3677 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3678 (if (not (= (char-after (match-beginning 3))
3679 (char-after (match-beginning 4))))
3680 (progn
3681 (setq rtn t)
3682 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3683 'face
3684 (nth 1 (assoc (match-string 3)
3685 org-emphasis-alist)))
3686 (add-text-properties (match-beginning 2) (match-end 2)
3687 '(font-lock-multiline t))
3688 (when org-hide-emphasis-markers
3689 (add-text-properties (match-end 4) (match-beginning 5)
3690 '(invisible org-link))
3691 (add-text-properties (match-beginning 3) (match-end 3)
3692 '(invisible org-link)))))
3693 (backward-char 1))
3694 rtn))
3696 (defun org-emphasize (&optional char)
3697 "Insert or change an emphasis, i.e. a font like bold or italic.
3698 If there is an active region, change that region to a new emphasis.
3699 If there is no region, just insert the marker characters and position
3700 the cursor between them.
3701 CHAR should be either the marker character, or the first character of the
3702 HTML tag associated with that emphasis. If CHAR is a space, the means
3703 to remove the emphasis of the selected region.
3704 If char is not given (for example in an interactive call) it
3705 will be prompted for."
3706 (interactive)
3707 (let ((eal org-emphasis-alist) e det
3708 (erc org-emphasis-regexp-components)
3709 (prompt "")
3710 (string "") beg end move tag c s)
3711 (if (org-region-active-p)
3712 (setq beg (region-beginning) end (region-end)
3713 string (buffer-substring beg end))
3714 (setq move t))
3716 (while (setq e (pop eal))
3717 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3718 c (aref tag 0))
3719 (push (cons c (string-to-char (car e))) det)
3720 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3721 (substring tag 1)))))
3722 (setq det (nreverse det))
3723 (unless char
3724 (message "%s" (concat "Emphasis marker or tag:" prompt))
3725 (setq char (read-char-exclusive)))
3726 (setq char (or (cdr (assoc char det)) char))
3727 (if (equal char ?\ )
3728 (setq s "" move nil)
3729 (unless (assoc (char-to-string char) org-emphasis-alist)
3730 (error "No such emphasis marker: \"%c\"" char))
3731 (setq s (char-to-string char)))
3732 (while (and (> (length string) 1)
3733 (equal (substring string 0 1) (substring string -1))
3734 (assoc (substring string 0 1) org-emphasis-alist))
3735 (setq string (substring string 1 -1)))
3736 (setq string (concat s string s))
3737 (if beg (delete-region beg end))
3738 (unless (or (bolp)
3739 (string-match (concat "[" (nth 0 erc) "\n]")
3740 (char-to-string (char-before (point)))))
3741 (insert " "))
3742 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3743 (char-to-string (char-after (point))))
3744 (insert " ") (backward-char 1))
3745 (insert string)
3746 (and move (backward-char 1))))
3748 (defconst org-nonsticky-props
3749 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3752 (defun org-activate-plain-links (limit)
3753 "Run through the buffer and add overlays to links."
3754 (catch 'exit
3755 (let (f)
3756 (while (re-search-forward org-plain-link-re limit t)
3757 (setq f (get-text-property (match-beginning 0) 'face))
3758 (if (or (eq f 'org-tag)
3759 (and (listp f) (memq 'org-tag f)))
3761 (add-text-properties (match-beginning 0) (match-end 0)
3762 (list 'mouse-face 'highlight
3763 'rear-nonsticky org-nonsticky-props
3764 'keymap org-mouse-map
3766 (throw 'exit t))))))
3768 (defun org-activate-code (limit)
3769 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3770 (progn
3771 (remove-text-properties (match-beginning 0) (match-end 0)
3772 '(display t invisible t intangible t))
3773 t)))
3775 (defun org-activate-angle-links (limit)
3776 "Run through the buffer and add overlays to links."
3777 (if (re-search-forward org-angle-link-re limit t)
3778 (progn
3779 (add-text-properties (match-beginning 0) (match-end 0)
3780 (list 'mouse-face 'highlight
3781 'rear-nonsticky org-nonsticky-props
3782 'keymap org-mouse-map
3784 t)))
3786 (defun org-activate-footnote-links (limit)
3787 "Run through the buffer and add overlays to links."
3788 (if (re-search-forward "\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)"
3789 limit t)
3790 (progn
3791 (add-text-properties (match-beginning 0) (match-end 0)
3792 (list 'mouse-face 'highlight
3793 'rear-nonsticky org-nonsticky-props
3794 'keymap org-mouse-map
3795 'help-echo
3796 (if (= (point-at-bol) (match-beginning 0))
3797 "Footnote definition"
3798 "Footnote reference")
3800 t)))
3802 (defun org-activate-bracket-links (limit)
3803 "Run through the buffer and add overlays to bracketed links."
3804 (if (re-search-forward org-bracket-link-regexp limit t)
3805 (let* ((help (concat "LINK: "
3806 (org-match-string-no-properties 1)))
3807 ;; FIXME: above we should remove the escapes.
3808 ;; but that requires another match, protecting match data,
3809 ;; a lot of overhead for font-lock.
3810 (ip (org-maybe-intangible
3811 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3812 'keymap org-mouse-map 'mouse-face 'highlight
3813 'font-lock-multiline t 'help-echo help)))
3814 (vp (list 'rear-nonsticky org-nonsticky-props
3815 'keymap org-mouse-map 'mouse-face 'highlight
3816 ' font-lock-multiline t 'help-echo help)))
3817 ;; We need to remove the invisible property here. Table narrowing
3818 ;; may have made some of this invisible.
3819 (remove-text-properties (match-beginning 0) (match-end 0)
3820 '(invisible nil))
3821 (if (match-end 3)
3822 (progn
3823 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3824 (add-text-properties (match-beginning 3) (match-end 3) vp)
3825 (add-text-properties (match-end 3) (match-end 0) ip))
3826 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3827 (add-text-properties (match-beginning 1) (match-end 1) vp)
3828 (add-text-properties (match-end 1) (match-end 0) ip))
3829 t)))
3831 (defun org-activate-dates (limit)
3832 "Run through the buffer and add overlays to dates."
3833 (if (re-search-forward org-tsr-regexp-both limit t)
3834 (progn
3835 (add-text-properties (match-beginning 0) (match-end 0)
3836 (list 'mouse-face 'highlight
3837 'rear-nonsticky org-nonsticky-props
3838 'keymap org-mouse-map))
3839 (when org-display-custom-times
3840 (if (match-end 3)
3841 (org-display-custom-time (match-beginning 3) (match-end 3)))
3842 (org-display-custom-time (match-beginning 1) (match-end 1)))
3843 t)))
3845 (defvar org-target-link-regexp nil
3846 "Regular expression matching radio targets in plain text.")
3847 (make-variable-buffer-local 'org-target-link-regexp)
3848 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3849 "Regular expression matching a link target.")
3850 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3851 "Regular expression matching a radio target.")
3852 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3853 "Regular expression matching any target.")
3855 (defun org-activate-target-links (limit)
3856 "Run through the buffer and add overlays to target matches."
3857 (when org-target-link-regexp
3858 (let ((case-fold-search t))
3859 (if (re-search-forward org-target-link-regexp limit t)
3860 (progn
3861 (add-text-properties (match-beginning 0) (match-end 0)
3862 (list 'mouse-face 'highlight
3863 'rear-nonsticky org-nonsticky-props
3864 'keymap org-mouse-map
3865 'help-echo "Radio target link"
3866 'org-linked-text t))
3867 t)))))
3869 (defun org-update-radio-target-regexp ()
3870 "Find all radio targets in this file and update the regular expression."
3871 (interactive)
3872 (when (memq 'radio org-activate-links)
3873 (setq org-target-link-regexp
3874 (org-make-target-link-regexp (org-all-targets 'radio)))
3875 (org-restart-font-lock)))
3877 (defun org-hide-wide-columns (limit)
3878 (let (s e)
3879 (setq s (text-property-any (point) (or limit (point-max))
3880 'org-cwidth t))
3881 (when s
3882 (setq e (next-single-property-change s 'org-cwidth))
3883 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3884 (goto-char e)
3885 t)))
3887 (defvar org-latex-and-specials-regexp nil
3888 "Regular expression for highlighting export special stuff.")
3889 (defvar org-match-substring-regexp)
3890 (defvar org-match-substring-with-braces-regexp)
3891 (defvar org-export-html-special-string-regexps)
3893 (defun org-compute-latex-and-specials-regexp ()
3894 "Compute regular expression for stuff treated specially by exporters."
3895 (if (not org-highlight-latex-fragments-and-specials)
3896 (org-set-local 'org-latex-and-specials-regexp nil)
3897 (require 'org-exp)
3898 (let*
3899 ((matchers (plist-get org-format-latex-options :matchers))
3900 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3901 org-latex-regexps)))
3902 (options (org-combine-plists (org-default-export-plist)
3903 (org-infile-export-plist)))
3904 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3905 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3906 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3907 (org-export-html-expand (plist-get options :expand-quoted-html))
3908 (org-export-with-special-strings (plist-get options :special-strings))
3909 (re-sub
3910 (cond
3911 ((equal org-export-with-sub-superscripts '{})
3912 (list org-match-substring-with-braces-regexp))
3913 (org-export-with-sub-superscripts
3914 (list org-match-substring-regexp))
3915 (t nil)))
3916 (re-latex
3917 (if org-export-with-LaTeX-fragments
3918 (mapcar (lambda (x) (nth 1 x)) latexs)))
3919 (re-macros
3920 (if org-export-with-TeX-macros
3921 (list (concat "\\\\"
3922 (regexp-opt
3923 (append (mapcar 'car org-html-entities)
3924 (if (boundp 'org-latex-entities)
3925 org-latex-entities nil))
3926 'words))) ; FIXME
3928 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3929 (re-special (if org-export-with-special-strings
3930 (mapcar (lambda (x) (car x))
3931 org-export-html-special-string-regexps)))
3932 (re-rest
3933 (delq nil
3934 (list
3935 (if org-export-html-expand "@<[^>\n]+>")
3936 ))))
3937 (org-set-local
3938 'org-latex-and-specials-regexp
3939 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3940 re-rest) "\\|")))))
3942 (defun org-do-latex-and-special-faces (limit)
3943 "Run through the buffer and add overlays to links."
3944 (when org-latex-and-specials-regexp
3945 (let (rtn d)
3946 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3947 limit t))
3948 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3949 'face))
3950 '(org-code org-verbatim underline)))
3951 (progn
3952 (setq rtn t
3953 d (cond ((member (char-after (1+ (match-beginning 0)))
3954 '(?_ ?^)) 1)
3955 (t 0)))
3956 (font-lock-prepend-text-property
3957 (+ d (match-beginning 0)) (match-end 0)
3958 'face 'org-latex-and-export-specials)
3959 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3960 '(font-lock-multiline t)))))
3961 rtn)))
3963 (defun org-restart-font-lock ()
3964 "Restart font-lock-mode, to force refontification."
3965 (when (and (boundp 'font-lock-mode) font-lock-mode)
3966 (font-lock-mode -1)
3967 (font-lock-mode 1)))
3969 (defun org-all-targets (&optional radio)
3970 "Return a list of all targets in this file.
3971 With optional argument RADIO, only find radio targets."
3972 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3973 rtn)
3974 (save-excursion
3975 (goto-char (point-min))
3976 (while (re-search-forward re nil t)
3977 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3978 rtn)))
3980 (defun org-make-target-link-regexp (targets)
3981 "Make regular expression matching all strings in TARGETS.
3982 The regular expression finds the targets also if there is a line break
3983 between words."
3984 (and targets
3985 (concat
3986 "\\<\\("
3987 (mapconcat
3988 (lambda (x)
3989 (while (string-match " +" x)
3990 (setq x (replace-match "\\s-+" t t x)))
3992 targets
3993 "\\|")
3994 "\\)\\>")))
3996 (defun org-activate-tags (limit)
3997 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3998 (progn
3999 (add-text-properties (match-beginning 1) (match-end 1)
4000 (list 'mouse-face 'highlight
4001 'rear-nonsticky org-nonsticky-props
4002 'keymap org-mouse-map))
4003 t)))
4005 (defun org-outline-level ()
4006 (save-excursion
4007 (looking-at outline-regexp)
4008 (if (match-beginning 1)
4009 (+ (org-get-string-indentation (match-string 1)) 1000)
4010 (1- (- (match-end 0) (match-beginning 0))))))
4012 (defvar org-font-lock-keywords nil)
4014 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4015 "Regular expression matching a property line.")
4017 (defvar org-font-lock-hook nil
4018 "Functions to be called for special font lock stuff.")
4020 (defun org-font-lock-hook (limit)
4021 (run-hook-with-args 'org-font-lock-hook limit))
4023 (defun org-set-font-lock-defaults ()
4024 (let* ((em org-fontify-emphasized-text)
4025 (lk org-activate-links)
4026 (org-font-lock-extra-keywords
4027 (list
4028 ;; Call the hook
4029 '(org-font-lock-hook)
4030 ;; Headlines
4031 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4032 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4033 ;; Table lines
4034 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4035 (1 'org-table t))
4036 ;; Table internals
4037 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4038 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4039 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4040 ;; Drawers
4041 (list org-drawer-regexp '(0 'org-special-keyword t))
4042 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4043 ;; Properties
4044 (list org-property-re
4045 '(1 'org-special-keyword t)
4046 '(3 'org-property-value t))
4047 (if org-format-transports-properties-p
4048 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4049 ;; Links
4050 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4051 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4052 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4053 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4054 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4055 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4056 (if (memq 'footnote lk) '(org-activate-footnote-links
4057 (0 'org-footnote t)))
4058 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4059 '(org-hide-wide-columns (0 nil append))
4060 ;; TODO lines
4061 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4062 '(1 (org-get-todo-face 1) t))
4063 ;; DONE
4064 (if org-fontify-done-headline
4065 (list (concat "^[*]+ +\\<\\("
4066 (mapconcat 'regexp-quote org-done-keywords "\\|")
4067 "\\)\\(.*\\)")
4068 '(2 'org-headline-done t))
4069 nil)
4070 ;; Priorities
4071 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4072 ;; Tags
4073 '(org-font-lock-add-tag-faces)
4074 ;; Special keywords
4075 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4076 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4077 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4078 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4079 ;; Emphasis
4080 (if em
4081 (if (featurep 'xemacs)
4082 '(org-do-emphasis-faces (0 nil append))
4083 '(org-do-emphasis-faces)))
4084 ;; Checkboxes
4085 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4086 2 'bold prepend)
4087 (if org-provide-checkbox-statistics
4088 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4089 (0 (org-get-checkbox-statistics-face) t)))
4090 ;; Description list items
4091 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4092 2 'bold prepend)
4093 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4094 '(1 'org-archived prepend))
4095 ;; Specials
4096 '(org-do-latex-and-special-faces)
4097 ;; Code
4098 '(org-activate-code (1 'org-code t))
4099 ;; COMMENT
4100 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4101 "\\|" org-quote-string "\\)\\>")
4102 '(1 'org-special-keyword t))
4103 '("^#.*" (0 'font-lock-comment-face t))
4105 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4106 ;; Now set the full font-lock-keywords
4107 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4108 (org-set-local 'font-lock-defaults
4109 '(org-font-lock-keywords t nil nil backward-paragraph))
4110 (kill-local-variable 'font-lock-keywords) nil))
4112 (defvar org-m nil)
4113 (defvar org-l nil)
4114 (defvar org-f nil)
4115 (defun org-get-level-face (n)
4116 "Get the right face for match N in font-lock matching of headlines."
4117 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4118 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4119 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4120 (cond
4121 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4122 ((eq n 2) org-f)
4123 (t (if org-level-color-stars-only nil org-f))))
4125 (defun org-get-todo-face (kwd)
4126 "Get the right face for a TODO keyword KWD.
4127 If KWD is a number, get the corresponding match group."
4128 (if (numberp kwd) (setq kwd (match-string kwd)))
4129 (or (cdr (assoc kwd org-todo-keyword-faces))
4130 (and (member kwd org-done-keywords) 'org-done)
4131 'org-todo))
4133 (defun org-font-lock-add-tag-faces (limit)
4134 "Add the special tag faces."
4135 (when (and org-tag-faces org-tags-special-faces-re)
4136 (while (re-search-forward org-tags-special-faces-re limit t)
4137 (add-text-properties (match-beginning 1) (match-end 1)
4138 (list 'face (org-get-tag-face 1)
4139 'font-lock-fontified t))
4140 (backward-char 1))))
4142 (defun org-get-tag-face (kwd)
4143 "Get the right face for a TODO keyword KWD.
4144 If KWD is a number, get the corresponding match group."
4145 (if (numberp kwd) (setq kwd (match-string kwd)))
4146 (or (cdr (assoc kwd org-tag-faces))
4147 'org-tag))
4149 (defun org-unfontify-region (beg end &optional maybe_loudly)
4150 "Remove fontification and activation overlays from links."
4151 (font-lock-default-unfontify-region beg end)
4152 (let* ((buffer-undo-list t)
4153 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4154 (inhibit-modification-hooks t)
4155 deactivate-mark buffer-file-name buffer-file-truename)
4156 (remove-text-properties beg end
4157 '(mouse-face t keymap t org-linked-text t
4158 invisible t intangible t))))
4160 ;;;; Visibility cycling, including org-goto and indirect buffer
4162 ;;; Cycling
4164 (defvar org-cycle-global-status nil)
4165 (make-variable-buffer-local 'org-cycle-global-status)
4166 (defvar org-cycle-subtree-status nil)
4167 (make-variable-buffer-local 'org-cycle-subtree-status)
4169 ;;;###autoload
4170 (defun org-cycle (&optional arg)
4171 "Visibility cycling for Org-mode.
4173 - When this function is called with a prefix argument, rotate the entire
4174 buffer through 3 states (global cycling)
4175 1. OVERVIEW: Show only top-level headlines.
4176 2. CONTENTS: Show all headlines of all levels, but no body text.
4177 3. SHOW ALL: Show everything.
4178 When called with two C-u C-u prefixes, switch to the startup visibility,
4179 determined by the variable `org-startup-folded', and by any VISIBILITY
4180 properties in the buffer.
4181 When called with three C-u C-u C-u prefixed, show the entire buffer,
4182 including drawers.
4184 - When point is at the beginning of a headline, rotate the subtree started
4185 by this line through 3 different states (local cycling)
4186 1. FOLDED: Only the main headline is shown.
4187 2. CHILDREN: The main headline and the direct children are shown.
4188 From this state, you can move to one of the children
4189 and zoom in further.
4190 3. SUBTREE: Show the entire subtree, including body text.
4192 - When there is a numeric prefix, go up to a heading with level ARG, do
4193 a `show-subtree' and return to the previous cursor position. If ARG
4194 is negative, go up that many levels.
4196 - When point is not at the beginning of a headline, execute the global
4197 binding for TAB, which is re-indenting the line. See the option
4198 `org-cycle-emulate-tab' for details.
4200 - Special case: if point is at the beginning of the buffer and there is
4201 no headline in line 1, this function will act as if called with prefix arg.
4202 But only if also the variable `org-cycle-global-at-bob' is t."
4203 (interactive "P")
4204 (org-load-modules-maybe)
4205 (let* ((outline-regexp
4206 (if (and (org-mode-p) org-cycle-include-plain-lists)
4207 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4208 outline-regexp))
4209 (bob-special (and org-cycle-global-at-bob (bobp)
4210 (not (looking-at outline-regexp))))
4211 (org-cycle-hook
4212 (if bob-special
4213 (delq 'org-optimize-window-after-visibility-change
4214 (copy-sequence org-cycle-hook))
4215 org-cycle-hook))
4216 (pos (point)))
4218 (if (or bob-special (equal arg '(4)))
4219 ;; special case: use global cycling
4220 (setq arg t))
4222 (cond
4224 ((equal arg '(16))
4225 (org-set-startup-visibility)
4226 (message "Startup visibility, plus VISIBILITY properties"))
4228 ((equal arg '(64))
4229 (show-all)
4230 (message "Entire buffer visible, including drawers"))
4232 ((org-at-table-p 'any)
4233 ;; Enter the table or move to the next field in the table
4234 (or (org-table-recognize-table.el)
4235 (progn
4236 (if arg (org-table-edit-field t)
4237 (org-table-justify-field-maybe)
4238 (call-interactively 'org-table-next-field)))))
4240 ((eq arg t) ;; Global cycling
4242 (cond
4243 ((and (eq last-command this-command)
4244 (eq org-cycle-global-status 'overview))
4245 ;; We just created the overview - now do table of contents
4246 ;; This can be slow in very large buffers, so indicate action
4247 (message "CONTENTS...")
4248 (org-content)
4249 (message "CONTENTS...done")
4250 (setq org-cycle-global-status 'contents)
4251 (run-hook-with-args 'org-cycle-hook 'contents))
4253 ((and (eq last-command this-command)
4254 (eq org-cycle-global-status 'contents))
4255 ;; We just showed the table of contents - now show everything
4256 (show-all)
4257 (message "SHOW ALL")
4258 (setq org-cycle-global-status 'all)
4259 (run-hook-with-args 'org-cycle-hook 'all))
4262 ;; Default action: go to overview
4263 (org-overview)
4264 (message "OVERVIEW")
4265 (setq org-cycle-global-status 'overview)
4266 (run-hook-with-args 'org-cycle-hook 'overview))))
4268 ((and org-drawers org-drawer-regexp
4269 (save-excursion
4270 (beginning-of-line 1)
4271 (looking-at org-drawer-regexp)))
4272 ;; Toggle block visibility
4273 (org-flag-drawer
4274 (not (get-char-property (match-end 0) 'invisible))))
4276 ((integerp arg)
4277 ;; Show-subtree, ARG levels up from here.
4278 (save-excursion
4279 (org-back-to-heading)
4280 (outline-up-heading (if (< arg 0) (- arg)
4281 (- (funcall outline-level) arg)))
4282 (org-show-subtree)))
4284 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4285 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4286 ;; At a heading: rotate between three different views
4287 (org-back-to-heading)
4288 (let ((goal-column 0) eoh eol eos)
4289 ;; First, some boundaries
4290 (save-excursion
4291 (org-back-to-heading)
4292 (save-excursion
4293 (beginning-of-line 2)
4294 (while (and (not (eobp)) ;; this is like `next-line'
4295 (get-char-property (1- (point)) 'invisible))
4296 (beginning-of-line 2)) (setq eol (point)))
4297 (outline-end-of-heading) (setq eoh (point))
4298 (org-end-of-subtree t)
4299 (unless (eobp)
4300 (skip-chars-forward " \t\n")
4301 (beginning-of-line 1) ; in case this is an item
4303 (setq eos (1- (point))))
4304 ;; Find out what to do next and set `this-command'
4305 (cond
4306 ((= eos eoh)
4307 ;; Nothing is hidden behind this heading
4308 (message "EMPTY ENTRY")
4309 (setq org-cycle-subtree-status nil)
4310 (save-excursion
4311 (goto-char eos)
4312 (outline-next-heading)
4313 (if (org-invisible-p) (org-flag-heading nil))))
4314 ((or (>= eol eos)
4315 (not (string-match "\\S-" (buffer-substring eol eos))))
4316 ;; Entire subtree is hidden in one line: open it
4317 (org-show-entry)
4318 (show-children)
4319 (message "CHILDREN")
4320 (save-excursion
4321 (goto-char eos)
4322 (outline-next-heading)
4323 (if (org-invisible-p) (org-flag-heading nil)))
4324 (setq org-cycle-subtree-status 'children)
4325 (run-hook-with-args 'org-cycle-hook 'children))
4326 ((and (eq last-command this-command)
4327 (eq org-cycle-subtree-status 'children))
4328 ;; We just showed the children, now show everything.
4329 (org-show-subtree)
4330 (message "SUBTREE")
4331 (setq org-cycle-subtree-status 'subtree)
4332 (run-hook-with-args 'org-cycle-hook 'subtree))
4334 ;; Default action: hide the subtree.
4335 (hide-subtree)
4336 (message "FOLDED")
4337 (setq org-cycle-subtree-status 'folded)
4338 (run-hook-with-args 'org-cycle-hook 'folded)))))
4340 ;; TAB emulation and template completion
4341 (buffer-read-only (org-back-to-heading))
4343 ((org-try-structure-completion))
4345 ((org-try-cdlatex-tab))
4347 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4348 (or (not (bolp))
4349 (not (looking-at outline-regexp))))
4350 (call-interactively (global-key-binding "\t")))
4352 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4353 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4354 (or (and (eq org-cycle-emulate-tab 'white)
4355 (= (match-end 0) (point-at-eol)))
4356 (and (eq org-cycle-emulate-tab 'whitestart)
4357 (>= (match-end 0) pos))))
4359 (eq org-cycle-emulate-tab t))
4360 (call-interactively (global-key-binding "\t")))
4362 (t (save-excursion
4363 (org-back-to-heading)
4364 (org-cycle))))))
4366 ;;;###autoload
4367 (defun org-global-cycle (&optional arg)
4368 "Cycle the global visibility. For details see `org-cycle'.
4369 With C-u prefix arg, switch to startup visibility.
4370 With a numeric prefix, show all headlines up to that level."
4371 (interactive "P")
4372 (let ((org-cycle-include-plain-lists
4373 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4374 (cond
4375 ((integerp arg)
4376 (show-all)
4377 (hide-sublevels arg)
4378 (setq org-cycle-global-status 'contents))
4379 ((equal arg '(4))
4380 (org-set-startup-visibility)
4381 (message "Startup visibility, plus VISIBILITY properties."))
4383 (org-cycle '(4))))))
4385 (defun org-set-startup-visibility ()
4386 "Set the visibility required by startup options and properties."
4387 (cond
4388 ((eq org-startup-folded t)
4389 (org-cycle '(4)))
4390 ((eq org-startup-folded 'content)
4391 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4392 (org-cycle '(4)) (org-cycle '(4)))))
4393 (org-set-visibility-according-to-property 'no-cleanup)
4394 (org-cycle-hide-archived-subtrees 'all)
4395 (org-cycle-hide-drawers 'all)
4396 (org-cycle-show-empty-lines 'all))
4398 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4399 "Switch subtree visibilities according to :VISIBILITY: property."
4400 (interactive)
4401 (let (state)
4402 (save-excursion
4403 (goto-char (point-min))
4404 (while (re-search-forward
4405 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4406 nil t)
4407 (setq state (match-string 1))
4408 (save-excursion
4409 (org-back-to-heading t)
4410 (hide-subtree)
4411 (org-reveal)
4412 (cond
4413 ((equal state '("fold" "folded"))
4414 (hide-subtree))
4415 ((equal state "children")
4416 (org-show-hidden-entry)
4417 (show-children))
4418 ((equal state "content")
4419 (save-excursion
4420 (save-restriction
4421 (org-narrow-to-subtree)
4422 (org-content))))
4423 ((member state '("all" "showall"))
4424 (show-subtree)))))
4425 (unless no-cleanup
4426 (org-cycle-hide-archived-subtrees 'all)
4427 (org-cycle-hide-drawers 'all)
4428 (org-cycle-show-empty-lines 'all)))))
4430 (defun org-overview ()
4431 "Switch to overview mode, showing only top-level headlines.
4432 Really, this shows all headlines with level equal or greater than the level
4433 of the first headline in the buffer. This is important, because if the
4434 first headline is not level one, then (hide-sublevels 1) gives confusing
4435 results."
4436 (interactive)
4437 (let ((level (save-excursion
4438 (goto-char (point-min))
4439 (if (re-search-forward (concat "^" outline-regexp) nil t)
4440 (progn
4441 (goto-char (match-beginning 0))
4442 (funcall outline-level))))))
4443 (and level (hide-sublevels level))))
4445 (defun org-content (&optional arg)
4446 "Show all headlines in the buffer, like a table of contents.
4447 With numerical argument N, show content up to level N."
4448 (interactive "P")
4449 (save-excursion
4450 ;; Visit all headings and show their offspring
4451 (and (integerp arg) (org-overview))
4452 (goto-char (point-max))
4453 (catch 'exit
4454 (while (and (progn (condition-case nil
4455 (outline-previous-visible-heading 1)
4456 (error (goto-char (point-min))))
4458 (looking-at outline-regexp))
4459 (if (integerp arg)
4460 (show-children (1- arg))
4461 (show-branches))
4462 (if (bobp) (throw 'exit nil))))))
4465 (defun org-optimize-window-after-visibility-change (state)
4466 "Adjust the window after a change in outline visibility.
4467 This function is the default value of the hook `org-cycle-hook'."
4468 (when (get-buffer-window (current-buffer))
4469 (cond
4470 ; ((eq state 'overview) (org-first-headline-recenter 1))
4471 ; ((eq state 'overview) (org-beginning-of-line))
4472 ((eq state 'content) nil)
4473 ((eq state 'all) nil)
4474 ((eq state 'folded) nil)
4475 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4476 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4478 (defun org-compact-display-after-subtree-move ()
4479 (let (beg end)
4480 (save-excursion
4481 (if (org-up-heading-safe)
4482 (progn
4483 (hide-subtree)
4484 (show-entry)
4485 (show-children)
4486 (org-cycle-show-empty-lines 'children)
4487 (org-cycle-hide-drawers 'children))
4488 (org-overview)))))
4490 (defun org-cycle-show-empty-lines (state)
4491 "Show empty lines above all visible headlines.
4492 The region to be covered depends on STATE when called through
4493 `org-cycle-hook'. Lisp program can use t for STATE to get the
4494 entire buffer covered. Note that an empty line is only shown if there
4495 are at least `org-cycle-separator-lines' empty lines before the headline."
4496 (when (> org-cycle-separator-lines 0)
4497 (save-excursion
4498 (let* ((n org-cycle-separator-lines)
4499 (re (cond
4500 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4501 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4502 (t (let ((ns (number-to-string (- n 2))))
4503 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4504 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4505 beg end)
4506 (cond
4507 ((memq state '(overview contents t))
4508 (setq beg (point-min) end (point-max)))
4509 ((memq state '(children folded))
4510 (setq beg (point) end (progn (org-end-of-subtree t t)
4511 (beginning-of-line 2)
4512 (point)))))
4513 (when beg
4514 (goto-char beg)
4515 (while (re-search-forward re end t)
4516 (if (not (get-char-property (match-end 1) 'invisible))
4517 (outline-flag-region
4518 (match-beginning 1) (match-end 1) nil)))))))
4519 ;; Never hide empty lines at the end of the file.
4520 (save-excursion
4521 (goto-char (point-max))
4522 (outline-previous-heading)
4523 (outline-end-of-heading)
4524 (if (and (looking-at "[ \t\n]+")
4525 (= (match-end 0) (point-max)))
4526 (outline-flag-region (point) (match-end 0) nil))))
4528 (defun org-show-empty-lines-in-parent ()
4529 "Move to the parent and re-show empty lines before visible headlines."
4530 (save-excursion
4531 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4532 (org-cycle-show-empty-lines context))))
4534 (defun org-cycle-hide-drawers (state)
4535 "Re-hide all drawers after a visibility state change."
4536 (when (and (org-mode-p)
4537 (not (memq state '(overview folded))))
4538 (save-excursion
4539 (let* ((globalp (memq state '(contents all)))
4540 (beg (if globalp (point-min) (point)))
4541 (end (if globalp (point-max) (org-end-of-subtree t))))
4542 (goto-char beg)
4543 (while (re-search-forward org-drawer-regexp end t)
4544 (org-flag-drawer t))))))
4546 (defun org-flag-drawer (flag)
4547 (save-excursion
4548 (beginning-of-line 1)
4549 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4550 (let ((b (match-end 0))
4551 (outline-regexp org-outline-regexp))
4552 (if (re-search-forward
4553 "^[ \t]*:END:"
4554 (save-excursion (outline-next-heading) (point)) t)
4555 (outline-flag-region b (point-at-eol) flag)
4556 (error ":END: line missing"))))))
4558 (defun org-subtree-end-visible-p ()
4559 "Is the end of the current subtree visible?"
4560 (pos-visible-in-window-p
4561 (save-excursion (org-end-of-subtree t) (point))))
4563 (defun org-first-headline-recenter (&optional N)
4564 "Move cursor to the first headline and recenter the headline.
4565 Optional argument N means, put the headline into the Nth line of the window."
4566 (goto-char (point-min))
4567 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4568 (beginning-of-line)
4569 (recenter (prefix-numeric-value N))))
4571 ;;; Org-goto
4573 (defvar org-goto-window-configuration nil)
4574 (defvar org-goto-marker nil)
4575 (defvar org-goto-map
4576 (let ((map (make-sparse-keymap)))
4577 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4578 (while (setq cmd (pop cmds))
4579 (substitute-key-definition cmd cmd map global-map)))
4580 (suppress-keymap map)
4581 (org-defkey map "\C-m" 'org-goto-ret)
4582 (org-defkey map [(return)] 'org-goto-ret)
4583 (org-defkey map [(left)] 'org-goto-left)
4584 (org-defkey map [(right)] 'org-goto-right)
4585 (org-defkey map [(control ?g)] 'org-goto-quit)
4586 (org-defkey map "\C-i" 'org-cycle)
4587 (org-defkey map [(tab)] 'org-cycle)
4588 (org-defkey map [(down)] 'outline-next-visible-heading)
4589 (org-defkey map [(up)] 'outline-previous-visible-heading)
4590 (if org-goto-auto-isearch
4591 (if (fboundp 'define-key-after)
4592 (define-key-after map [t] 'org-goto-local-auto-isearch)
4593 nil)
4594 (org-defkey map "q" 'org-goto-quit)
4595 (org-defkey map "n" 'outline-next-visible-heading)
4596 (org-defkey map "p" 'outline-previous-visible-heading)
4597 (org-defkey map "f" 'outline-forward-same-level)
4598 (org-defkey map "b" 'outline-backward-same-level)
4599 (org-defkey map "u" 'outline-up-heading))
4600 (org-defkey map "/" 'org-occur)
4601 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4602 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4603 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4604 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4605 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4606 map))
4608 (defconst org-goto-help
4609 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4610 RET=jump to location [Q]uit and return to previous location
4611 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4613 (defvar org-goto-start-pos) ; dynamically scoped parameter
4615 ;; FIXME: Docstring doe not mention both interfaces
4616 (defun org-goto (&optional alternative-interface)
4617 "Look up a different location in the current file, keeping current visibility.
4619 When you want look-up or go to a different location in a document, the
4620 fastest way is often to fold the entire buffer and then dive into the tree.
4621 This method has the disadvantage, that the previous location will be folded,
4622 which may not be what you want.
4624 This command works around this by showing a copy of the current buffer
4625 in an indirect buffer, in overview mode. You can dive into the tree in
4626 that copy, use org-occur and incremental search to find a location.
4627 When pressing RET or `Q', the command returns to the original buffer in
4628 which the visibility is still unchanged. After RET is will also jump to
4629 the location selected in the indirect buffer and expose the
4630 the headline hierarchy above."
4631 (interactive "P")
4632 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4633 (org-refile-use-outline-path t)
4634 (interface
4635 (if (not alternative-interface)
4636 org-goto-interface
4637 (if (eq org-goto-interface 'outline)
4638 'outline-path-completion
4639 'outline)))
4640 (org-goto-start-pos (point))
4641 (selected-point
4642 (if (eq interface 'outline)
4643 (car (org-get-location (current-buffer) org-goto-help))
4644 (nth 3 (org-refile-get-location "Goto: ")))))
4645 (if selected-point
4646 (progn
4647 (org-mark-ring-push org-goto-start-pos)
4648 (goto-char selected-point)
4649 (if (or (org-invisible-p) (org-invisible-p2))
4650 (org-show-context 'org-goto)))
4651 (message "Quit"))))
4653 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4654 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4655 (defvar org-goto-local-auto-isearch-map) ; defined below
4657 (defun org-get-location (buf help)
4658 "Let the user select a location in the Org-mode buffer BUF.
4659 This function uses a recursive edit. It returns the selected position
4660 or nil."
4661 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4662 (isearch-hide-immediately nil)
4663 (isearch-search-fun-function
4664 (lambda () 'org-goto-local-search-headings))
4665 (org-goto-selected-point org-goto-exit-command))
4666 (save-excursion
4667 (save-window-excursion
4668 (delete-other-windows)
4669 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4670 (switch-to-buffer
4671 (condition-case nil
4672 (make-indirect-buffer (current-buffer) "*org-goto*")
4673 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4674 (with-output-to-temp-buffer "*Help*"
4675 (princ help))
4676 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4677 (setq buffer-read-only nil)
4678 (let ((org-startup-truncated t)
4679 (org-startup-folded nil)
4680 (org-startup-align-all-tables nil))
4681 (org-mode)
4682 (org-overview))
4683 (setq buffer-read-only t)
4684 (if (and (boundp 'org-goto-start-pos)
4685 (integer-or-marker-p org-goto-start-pos))
4686 (let ((org-show-hierarchy-above t)
4687 (org-show-siblings t)
4688 (org-show-following-heading t))
4689 (goto-char org-goto-start-pos)
4690 (and (org-invisible-p) (org-show-context)))
4691 (goto-char (point-min)))
4692 (org-beginning-of-line)
4693 (message "Select location and press RET")
4694 (use-local-map org-goto-map)
4695 (recursive-edit)
4697 (kill-buffer "*org-goto*")
4698 (cons org-goto-selected-point org-goto-exit-command)))
4700 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4701 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4702 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4703 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4705 (defun org-goto-local-search-headings (string bound noerror)
4706 "Search and make sure that any matches are in headlines."
4707 (catch 'return
4708 (while (if isearch-forward
4709 (search-forward string bound noerror)
4710 (search-backward string bound noerror))
4711 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4712 (and (member :headline context)
4713 (not (member :tags context))))
4714 (throw 'return (point))))))
4716 (defun org-goto-local-auto-isearch ()
4717 "Start isearch."
4718 (interactive)
4719 (goto-char (point-min))
4720 (let ((keys (this-command-keys)))
4721 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4722 (isearch-mode t)
4723 (isearch-process-search-char (string-to-char keys)))))
4725 (defun org-goto-ret (&optional arg)
4726 "Finish `org-goto' by going to the new location."
4727 (interactive "P")
4728 (setq org-goto-selected-point (point)
4729 org-goto-exit-command 'return)
4730 (throw 'exit nil))
4732 (defun org-goto-left ()
4733 "Finish `org-goto' by going to the new location."
4734 (interactive)
4735 (if (org-on-heading-p)
4736 (progn
4737 (beginning-of-line 1)
4738 (setq org-goto-selected-point (point)
4739 org-goto-exit-command 'left)
4740 (throw 'exit nil))
4741 (error "Not on a heading")))
4743 (defun org-goto-right ()
4744 "Finish `org-goto' by going to the new location."
4745 (interactive)
4746 (if (org-on-heading-p)
4747 (progn
4748 (setq org-goto-selected-point (point)
4749 org-goto-exit-command 'right)
4750 (throw 'exit nil))
4751 (error "Not on a heading")))
4753 (defun org-goto-quit ()
4754 "Finish `org-goto' without cursor motion."
4755 (interactive)
4756 (setq org-goto-selected-point nil)
4757 (setq org-goto-exit-command 'quit)
4758 (throw 'exit nil))
4760 ;;; Indirect buffer display of subtrees
4762 (defvar org-indirect-dedicated-frame nil
4763 "This is the frame being used for indirect tree display.")
4764 (defvar org-last-indirect-buffer nil)
4766 (defun org-tree-to-indirect-buffer (&optional arg)
4767 "Create indirect buffer and narrow it to current subtree.
4768 With numerical prefix ARG, go up to this level and then take that tree.
4769 If ARG is negative, go up that many levels.
4770 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4771 indirect buffer previously made with this command, to avoid proliferation of
4772 indirect buffers. However, when you call the command with a `C-u' prefix, or
4773 when `org-indirect-buffer-display' is `new-frame', the last buffer
4774 is kept so that you can work with several indirect buffers at the same time.
4775 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4776 requests that a new frame be made for the new buffer, so that the dedicated
4777 frame is not changed."
4778 (interactive "P")
4779 (let ((cbuf (current-buffer))
4780 (cwin (selected-window))
4781 (pos (point))
4782 beg end level heading ibuf)
4783 (save-excursion
4784 (org-back-to-heading t)
4785 (when (numberp arg)
4786 (setq level (org-outline-level))
4787 (if (< arg 0) (setq arg (+ level arg)))
4788 (while (> (setq level (org-outline-level)) arg)
4789 (outline-up-heading 1 t)))
4790 (setq beg (point)
4791 heading (org-get-heading))
4792 (org-end-of-subtree t) (setq end (point)))
4793 (if (and (buffer-live-p org-last-indirect-buffer)
4794 (not (eq org-indirect-buffer-display 'new-frame))
4795 (not arg))
4796 (kill-buffer org-last-indirect-buffer))
4797 (setq ibuf (org-get-indirect-buffer cbuf)
4798 org-last-indirect-buffer ibuf)
4799 (cond
4800 ((or (eq org-indirect-buffer-display 'new-frame)
4801 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4802 (select-frame (make-frame))
4803 (delete-other-windows)
4804 (switch-to-buffer ibuf)
4805 (org-set-frame-title heading))
4806 ((eq org-indirect-buffer-display 'dedicated-frame)
4807 (raise-frame
4808 (select-frame (or (and org-indirect-dedicated-frame
4809 (frame-live-p org-indirect-dedicated-frame)
4810 org-indirect-dedicated-frame)
4811 (setq org-indirect-dedicated-frame (make-frame)))))
4812 (delete-other-windows)
4813 (switch-to-buffer ibuf)
4814 (org-set-frame-title (concat "Indirect: " heading)))
4815 ((eq org-indirect-buffer-display 'current-window)
4816 (switch-to-buffer ibuf))
4817 ((eq org-indirect-buffer-display 'other-window)
4818 (pop-to-buffer ibuf))
4819 (t (error "Invalid value.")))
4820 (if (featurep 'xemacs)
4821 (save-excursion (org-mode) (turn-on-font-lock)))
4822 (narrow-to-region beg end)
4823 (show-all)
4824 (goto-char pos)
4825 (and (window-live-p cwin) (select-window cwin))))
4827 (defun org-get-indirect-buffer (&optional buffer)
4828 (setq buffer (or buffer (current-buffer)))
4829 (let ((n 1) (base (buffer-name buffer)) bname)
4830 (while (buffer-live-p
4831 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4832 (setq n (1+ n)))
4833 (condition-case nil
4834 (make-indirect-buffer buffer bname 'clone)
4835 (error (make-indirect-buffer buffer bname)))))
4837 (defun org-set-frame-title (title)
4838 "Set the title of the current frame to the string TITLE."
4839 ;; FIXME: how to name a single frame in XEmacs???
4840 (unless (featurep 'xemacs)
4841 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4843 ;;;; Structure editing
4845 ;;; Inserting headlines
4847 (defun org-previous-line-empty-p ()
4848 (save-excursion
4849 (and (not (bobp))
4850 (or (beginning-of-line 0) t)
4851 (save-match-data
4852 (looking-at "[ \t]*$")))))
4854 (defun org-insert-heading (&optional force-heading)
4855 "Insert a new heading or item with same depth at point.
4856 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4857 If point is at the beginning of a headline, insert a sibling before the
4858 current headline. If point is not at the beginning, do not split the line,
4859 but create the new headline after the current line."
4860 (interactive "P")
4861 (if (= (buffer-size) 0)
4862 (insert "\n* ")
4863 (when (or force-heading (not (org-insert-item)))
4864 (let* ((empty-line-p nil)
4865 (head (save-excursion
4866 (condition-case nil
4867 (progn
4868 (org-back-to-heading)
4869 (setq empty-line-p (org-previous-line-empty-p))
4870 (match-string 0))
4871 (error "*"))))
4872 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4873 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4874 pos hide-previous previous-pos)
4875 (cond
4876 ((and (org-on-heading-p) (bolp)
4877 (or (bobp)
4878 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4879 ;; insert before the current line
4880 (open-line (if blank 2 1)))
4881 ((and (bolp)
4882 (or (bobp)
4883 (save-excursion
4884 (backward-char 1) (not (org-invisible-p)))))
4885 ;; insert right here
4886 nil)
4888 ;; somewhere in the line
4889 (save-excursion
4890 (setq previous-pos (point-at-bol))
4891 (end-of-line)
4892 (setq hide-previous (org-invisible-p)))
4893 (and org-insert-heading-respect-content (org-show-subtree))
4894 (let ((split
4895 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4896 (save-excursion
4897 (let ((p (point)))
4898 (goto-char (point-at-bol))
4899 (and (looking-at org-complex-heading-regexp)
4900 (> p (match-beginning 4)))))))
4901 tags pos)
4902 (cond
4903 (org-insert-heading-respect-content
4904 (org-end-of-subtree nil t)
4905 (or (bolp) (newline))
4906 (or (org-previous-line-empty-p)
4907 (and blank (newline)))
4908 (open-line 1))
4909 ((org-on-heading-p)
4910 (when hide-previous
4911 (show-children)
4912 (org-show-entry))
4913 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4914 (setq tags (and (match-end 2) (match-string 2)))
4915 (and (match-end 1)
4916 (delete-region (match-beginning 1) (match-end 1)))
4917 (setq pos (point-at-bol))
4918 (or split (end-of-line 1))
4919 (delete-horizontal-space)
4920 (newline (if blank 2 1))
4921 (when tags
4922 (save-excursion
4923 (goto-char pos)
4924 (end-of-line 1)
4925 (insert " " tags)
4926 (org-set-tags nil 'align))))
4928 (or split (end-of-line 1))
4929 (newline (if blank 2 1)))))))
4930 (insert head) (just-one-space)
4931 (setq pos (point))
4932 (end-of-line 1)
4933 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4934 (when (and org-insert-heading-respect-content hide-previous)
4935 (save-excursion
4936 (goto-char previous-pos)
4937 (hide-subtree)))
4938 (run-hooks 'org-insert-heading-hook)))))
4940 (defun org-get-heading (&optional no-tags)
4941 "Return the heading of the current entry, without the stars."
4942 (save-excursion
4943 (org-back-to-heading t)
4944 (if (looking-at
4945 (if no-tags
4946 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4947 "\\*+[ \t]+\\([^\r\n]*\\)"))
4948 (match-string 1) "")))
4950 (defun org-heading-components ()
4951 "Return the components of the current heading.
4952 This is a list with the following elements:
4953 - the level as an integer
4954 - the reduced level, different if `org-odd-levels-only' is set.
4955 - the TODO keyword, or nil
4956 - the priority character, like ?A, or nil if no priority is given
4957 - the headline text itself, or the tags string if no headline text
4958 - the tags string, or nil."
4959 (save-excursion
4960 (org-back-to-heading t)
4961 (if (looking-at org-complex-heading-regexp)
4962 (list (length (match-string 1))
4963 (org-reduced-level (length (match-string 1)))
4964 (org-match-string-no-properties 2)
4965 (and (match-end 3) (aref (match-string 3) 2))
4966 (org-match-string-no-properties 4)
4967 (org-match-string-no-properties 5)))))
4969 (defun org-insert-heading-after-current ()
4970 "Insert a new heading with same level as current, after current subtree."
4971 (interactive)
4972 (org-back-to-heading)
4973 (org-insert-heading)
4974 (org-move-subtree-down)
4975 (end-of-line 1))
4977 (defun org-insert-heading-respect-content ()
4978 (interactive)
4979 (let ((org-insert-heading-respect-content t))
4980 (org-insert-heading t)))
4982 (defun org-insert-todo-heading-respect-content (&optional force-state)
4983 (interactive "P")
4984 (let ((org-insert-heading-respect-content t))
4985 (org-insert-todo-heading force-state t)))
4987 (defun org-insert-todo-heading (arg &optional force-heading)
4988 "Insert a new heading with the same level and TODO state as current heading.
4989 If the heading has no TODO state, or if the state is DONE, use the first
4990 state (TODO by default). Also with prefix arg, force first state."
4991 (interactive "P")
4992 (when (or force-heading (not (org-insert-item 'checkbox)))
4993 (org-insert-heading force-heading)
4994 (save-excursion
4995 (org-back-to-heading)
4996 (outline-previous-heading)
4997 (looking-at org-todo-line-regexp))
4998 (if (or arg
4999 (not (match-beginning 2))
5000 (member (match-string 2) org-done-keywords))
5001 (insert (car org-todo-keywords-1) " ")
5002 (insert (match-string 2) " "))
5003 (when org-provide-todo-statistics
5004 (org-update-parent-todo-statistics))))
5006 (defun org-insert-subheading (arg)
5007 "Insert a new subheading and demote it.
5008 Works for outline headings and for plain lists alike."
5009 (interactive "P")
5010 (org-insert-heading arg)
5011 (cond
5012 ((org-on-heading-p) (org-do-demote))
5013 ((org-at-item-p) (org-indent-item 1))))
5015 (defun org-insert-todo-subheading (arg)
5016 "Insert a new subheading with TODO keyword or checkbox and demote it.
5017 Works for outline headings and for plain lists alike."
5018 (interactive "P")
5019 (org-insert-todo-heading arg)
5020 (cond
5021 ((org-on-heading-p) (org-do-demote))
5022 ((org-at-item-p) (org-indent-item 1))))
5024 ;;; Promotion and Demotion
5026 (defun org-promote-subtree ()
5027 "Promote the entire subtree.
5028 See also `org-promote'."
5029 (interactive)
5030 (save-excursion
5031 (org-map-tree 'org-promote))
5032 (org-fix-position-after-promote))
5034 (defun org-demote-subtree ()
5035 "Demote the entire subtree. See `org-demote'.
5036 See also `org-promote'."
5037 (interactive)
5038 (save-excursion
5039 (org-map-tree 'org-demote))
5040 (org-fix-position-after-promote))
5043 (defun org-do-promote ()
5044 "Promote the current heading higher up the tree.
5045 If the region is active in `transient-mark-mode', promote all headings
5046 in the region."
5047 (interactive)
5048 (save-excursion
5049 (if (org-region-active-p)
5050 (org-map-region 'org-promote (region-beginning) (region-end))
5051 (org-promote)))
5052 (org-fix-position-after-promote))
5054 (defun org-do-demote ()
5055 "Demote the current heading lower down the tree.
5056 If the region is active in `transient-mark-mode', demote all headings
5057 in the region."
5058 (interactive)
5059 (save-excursion
5060 (if (org-region-active-p)
5061 (org-map-region 'org-demote (region-beginning) (region-end))
5062 (org-demote)))
5063 (org-fix-position-after-promote))
5065 (defun org-fix-position-after-promote ()
5066 "Make sure that after pro/demotion cursor position is right."
5067 (let ((pos (point)))
5068 (when (save-excursion
5069 (beginning-of-line 1)
5070 (looking-at org-todo-line-regexp)
5071 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5072 (cond ((eobp) (insert " "))
5073 ((eolp) (insert " "))
5074 ((equal (char-after) ?\ ) (forward-char 1))))))
5076 (defun org-reduced-level (l)
5077 "Compute the effective level of a heading.
5078 This takes into account the setting of `org-odd-levels-only'."
5079 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5081 (defun org-get-valid-level (level &optional change)
5082 "Rectify a level change under the influence of `org-odd-levels-only'
5083 LEVEL is a current level, CHANGE is by how much the level should be
5084 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5085 even level numbers will become the next higher odd number."
5086 (if org-odd-levels-only
5087 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5088 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5089 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5090 (max 1 (+ level change))))
5092 (if (boundp 'define-obsolete-function-alias)
5093 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5094 (define-obsolete-function-alias 'org-get-legal-level
5095 'org-get-valid-level)
5096 (define-obsolete-function-alias 'org-get-legal-level
5097 'org-get-valid-level "23.1")))
5099 (defun org-promote ()
5100 "Promote the current heading higher up the tree.
5101 If the region is active in `transient-mark-mode', promote all headings
5102 in the region."
5103 (org-back-to-heading t)
5104 (let* ((level (save-match-data (funcall outline-level)))
5105 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5106 (diff (abs (- level (length up-head) -1))))
5107 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5108 (replace-match up-head nil t)
5109 ;; Fixup tag positioning
5110 (and org-auto-align-tags (org-set-tags nil t))
5111 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5113 (defun org-demote ()
5114 "Demote the current heading lower down the tree.
5115 If the region is active in `transient-mark-mode', demote all headings
5116 in the region."
5117 (org-back-to-heading t)
5118 (let* ((level (save-match-data (funcall outline-level)))
5119 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5120 (diff (abs (- level (length down-head) -1))))
5121 (replace-match down-head nil t)
5122 ;; Fixup tag positioning
5123 (and org-auto-align-tags (org-set-tags nil t))
5124 (if org-adapt-indentation (org-fixup-indentation diff))))
5126 (defun org-map-tree (fun)
5127 "Call FUN for every heading underneath the current one."
5128 (org-back-to-heading)
5129 (let ((level (funcall outline-level)))
5130 (save-excursion
5131 (funcall fun)
5132 (while (and (progn
5133 (outline-next-heading)
5134 (> (funcall outline-level) level))
5135 (not (eobp)))
5136 (funcall fun)))))
5138 (defun org-map-region (fun beg end)
5139 "Call FUN for every heading between BEG and END."
5140 (let ((org-ignore-region t))
5141 (save-excursion
5142 (setq end (copy-marker end))
5143 (goto-char beg)
5144 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5145 (< (point) end))
5146 (funcall fun))
5147 (while (and (progn
5148 (outline-next-heading)
5149 (< (point) end))
5150 (not (eobp)))
5151 (funcall fun)))))
5153 (defun org-fixup-indentation (diff)
5154 "Change the indentation in the current entry by DIFF
5155 However, if any line in the current entry has no indentation, or if it
5156 would end up with no indentation after the change, nothing at all is done."
5157 (save-excursion
5158 (let ((end (save-excursion (outline-next-heading)
5159 (point-marker)))
5160 (prohibit (if (> diff 0)
5161 "^\\S-"
5162 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5163 col)
5164 (unless (save-excursion (end-of-line 1)
5165 (re-search-forward prohibit end t))
5166 (while (and (< (point) end)
5167 (re-search-forward "^[ \t]+" end t))
5168 (goto-char (match-end 0))
5169 (setq col (current-column))
5170 (if (< diff 0) (replace-match ""))
5171 (org-indent-to-column (+ diff col))))
5172 (move-marker end nil))))
5174 (defun org-convert-to-odd-levels ()
5175 "Convert an org-mode file with all levels allowed to one with odd levels.
5176 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5177 level 5 etc."
5178 (interactive)
5179 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5180 (let ((org-odd-levels-only nil) n)
5181 (save-excursion
5182 (goto-char (point-min))
5183 (while (re-search-forward "^\\*\\*+ " nil t)
5184 (setq n (- (length (match-string 0)) 2))
5185 (while (>= (setq n (1- n)) 0)
5186 (org-demote))
5187 (end-of-line 1))))))
5190 (defun org-convert-to-oddeven-levels ()
5191 "Convert an org-mode file with only odd levels to one with odd and even levels.
5192 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5193 section with an even level, conversion would destroy the structure of the file. An error
5194 is signaled in this case."
5195 (interactive)
5196 (goto-char (point-min))
5197 ;; First check if there are no even levels
5198 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5199 (org-show-context t)
5200 (error "Not all levels are odd in this file. Conversion not possible."))
5201 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5202 (let ((org-odd-levels-only nil) n)
5203 (save-excursion
5204 (goto-char (point-min))
5205 (while (re-search-forward "^\\*\\*+ " nil t)
5206 (setq n (/ (1- (length (match-string 0))) 2))
5207 (while (>= (setq n (1- n)) 0)
5208 (org-promote))
5209 (end-of-line 1))))))
5211 (defun org-tr-level (n)
5212 "Make N odd if required."
5213 (if org-odd-levels-only (1+ (/ n 2)) n))
5215 ;;; Vertical tree motion, cutting and pasting of subtrees
5217 (defun org-move-subtree-up (&optional arg)
5218 "Move the current subtree up past ARG headlines of the same level."
5219 (interactive "p")
5220 (org-move-subtree-down (- (prefix-numeric-value arg))))
5222 (defun org-move-subtree-down (&optional arg)
5223 "Move the current subtree down past ARG headlines of the same level."
5224 (interactive "p")
5225 (setq arg (prefix-numeric-value arg))
5226 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5227 'outline-get-last-sibling))
5228 (ins-point (make-marker))
5229 (cnt (abs arg))
5230 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5231 ;; Select the tree
5232 (org-back-to-heading)
5233 (setq beg0 (point))
5234 (save-excursion
5235 (setq ne-beg (org-back-over-empty-lines))
5236 (setq beg (point)))
5237 (save-match-data
5238 (save-excursion (outline-end-of-heading)
5239 (setq folded (org-invisible-p)))
5240 (outline-end-of-subtree))
5241 (outline-next-heading)
5242 (setq ne-end (org-back-over-empty-lines))
5243 (setq end (point))
5244 (goto-char beg0)
5245 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5246 ;; include less whitespace
5247 (save-excursion
5248 (goto-char beg)
5249 (forward-line (- ne-beg ne-end))
5250 (setq beg (point))))
5251 ;; Find insertion point, with error handling
5252 (while (> cnt 0)
5253 (or (and (funcall movfunc) (looking-at outline-regexp))
5254 (progn (goto-char beg0)
5255 (error "Cannot move past superior level or buffer limit")))
5256 (setq cnt (1- cnt)))
5257 (if (> arg 0)
5258 ;; Moving forward - still need to move over subtree
5259 (progn (org-end-of-subtree t t)
5260 (save-excursion
5261 (org-back-over-empty-lines)
5262 (or (bolp) (newline)))))
5263 (setq ne-ins (org-back-over-empty-lines))
5264 (move-marker ins-point (point))
5265 (setq txt (buffer-substring beg end))
5266 (org-save-markers-in-region beg end)
5267 (delete-region beg end)
5268 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5269 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5270 (let ((bbb (point)))
5271 (insert-before-markers txt)
5272 (org-reinstall-markers-in-region bbb)
5273 (move-marker ins-point bbb))
5274 (or (bolp) (insert "\n"))
5275 (setq ins-end (point))
5276 (goto-char ins-point)
5277 (org-skip-whitespace)
5278 (when (and (< arg 0)
5279 (org-first-sibling-p)
5280 (> ne-ins ne-beg))
5281 ;; Move whitespace back to beginning
5282 (save-excursion
5283 (goto-char ins-end)
5284 (let ((kill-whole-line t))
5285 (kill-line (- ne-ins ne-beg)) (point)))
5286 (insert (make-string (- ne-ins ne-beg) ?\n)))
5287 (move-marker ins-point nil)
5288 (org-compact-display-after-subtree-move)
5289 (org-show-empty-lines-in-parent)
5290 (unless folded
5291 (org-show-entry)
5292 (show-children)
5293 (org-cycle-hide-drawers 'children))))
5295 (defvar org-subtree-clip ""
5296 "Clipboard for cut and paste of subtrees.
5297 This is actually only a copy of the kill, because we use the normal kill
5298 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5300 (defvar org-subtree-clip-folded nil
5301 "Was the last copied subtree folded?
5302 This is used to fold the tree back after pasting.")
5304 (defun org-cut-subtree (&optional n)
5305 "Cut the current subtree into the clipboard.
5306 With prefix arg N, cut this many sequential subtrees.
5307 This is a short-hand for marking the subtree and then cutting it."
5308 (interactive "p")
5309 (org-copy-subtree n 'cut))
5311 (defun org-copy-subtree (&optional n cut force-store-markers)
5312 "Cut the current subtree into the clipboard.
5313 With prefix arg N, cut this many sequential subtrees.
5314 This is a short-hand for marking the subtree and then copying it.
5315 If CUT is non-nil, actually cut the subtree.
5316 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5317 of some markers in the region, even if CUT is non-nil. This is
5318 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5319 (interactive "p")
5320 (let (beg end folded (beg0 (point)))
5321 (if (interactive-p)
5322 (org-back-to-heading nil) ; take what looks like a subtree
5323 (org-back-to-heading t)) ; take what is really there
5324 (org-back-over-empty-lines)
5325 (setq beg (point))
5326 (skip-chars-forward " \t\r\n")
5327 (save-match-data
5328 (save-excursion (outline-end-of-heading)
5329 (setq folded (org-invisible-p)))
5330 (condition-case nil
5331 (outline-forward-same-level (1- n))
5332 (error nil))
5333 (org-end-of-subtree t t))
5334 (org-back-over-empty-lines)
5335 (setq end (point))
5336 (goto-char beg0)
5337 (when (> end beg)
5338 (setq org-subtree-clip-folded folded)
5339 (when (or cut force-store-markers)
5340 (org-save-markers-in-region beg end))
5341 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5342 (setq org-subtree-clip (current-kill 0))
5343 (message "%s: Subtree(s) with %d characters"
5344 (if cut "Cut" "Copied")
5345 (length org-subtree-clip)))))
5347 (defun org-paste-subtree (&optional level tree for-yank)
5348 "Paste the clipboard as a subtree, with modification of headline level.
5349 The entire subtree is promoted or demoted in order to match a new headline
5350 level.
5352 If the cursor is at the beginning of a headline, the same level as
5353 that headline is used to paste the tree
5355 If not, the new level is derived from the *visible* headings
5356 before and after the insertion point, and taken to be the inferior headline
5357 level of the two. So if the previous visible heading is level 3 and the
5358 next is level 4 (or vice versa), level 4 will be used for insertion.
5359 This makes sure that the subtree remains an independent subtree and does
5360 not swallow low level entries.
5362 You can also force a different level, either by using a numeric prefix
5363 argument, or by inserting the heading marker by hand. For example, if the
5364 cursor is after \"*****\", then the tree will be shifted to level 5.
5366 If optional TREE is given, use this text instead of the kill ring.
5368 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5369 move back over whitespace before inserting, and move point to the end of
5370 the inserted text when done."
5371 (interactive "P")
5372 (unless (org-kill-is-subtree-p tree)
5373 (error "%s"
5374 (substitute-command-keys
5375 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5376 (let* ((visp (not (org-invisible-p)))
5377 (txt (or tree (and kill-ring (current-kill 0))))
5378 (^re (concat "^\\(" outline-regexp "\\)"))
5379 (re (concat "\\(" outline-regexp "\\)"))
5380 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5382 (old-level (if (string-match ^re txt)
5383 (- (match-end 0) (match-beginning 0) 1)
5384 -1))
5385 (force-level (cond (level (prefix-numeric-value level))
5386 ((and (looking-at "[ \t]*$")
5387 (string-match
5388 ^re_ (buffer-substring
5389 (point-at-bol) (point))))
5390 (- (match-end 1) (match-beginning 1)))
5391 ((and (bolp)
5392 (looking-at org-outline-regexp))
5393 (- (match-end 0) (point) 1))
5394 (t nil)))
5395 (previous-level (save-excursion
5396 (condition-case nil
5397 (progn
5398 (outline-previous-visible-heading 1)
5399 (if (looking-at re)
5400 (- (match-end 0) (match-beginning 0) 1)
5402 (error 1))))
5403 (next-level (save-excursion
5404 (condition-case nil
5405 (progn
5406 (or (looking-at outline-regexp)
5407 (outline-next-visible-heading 1))
5408 (if (looking-at re)
5409 (- (match-end 0) (match-beginning 0) 1)
5411 (error 1))))
5412 (new-level (or force-level (max previous-level next-level)))
5413 (shift (if (or (= old-level -1)
5414 (= new-level -1)
5415 (= old-level new-level))
5417 (- new-level old-level)))
5418 (delta (if (> shift 0) -1 1))
5419 (func (if (> shift 0) 'org-demote 'org-promote))
5420 (org-odd-levels-only nil)
5421 beg end newend)
5422 ;; Remove the forced level indicator
5423 (if force-level
5424 (delete-region (point-at-bol) (point)))
5425 ;; Paste
5426 (beginning-of-line 1)
5427 (unless for-yank (org-back-over-empty-lines))
5428 (setq beg (point))
5429 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5430 (insert-before-markers txt)
5431 (unless (string-match "\n\\'" txt) (insert "\n"))
5432 (setq newend (point))
5433 (org-reinstall-markers-in-region beg)
5434 (setq end (point))
5435 (goto-char beg)
5436 (skip-chars-forward " \t\n\r")
5437 (setq beg (point))
5438 (if (and (org-invisible-p) visp)
5439 (save-excursion (outline-show-heading)))
5440 ;; Shift if necessary
5441 (unless (= shift 0)
5442 (save-restriction
5443 (narrow-to-region beg end)
5444 (while (not (= shift 0))
5445 (org-map-region func (point-min) (point-max))
5446 (setq shift (+ delta shift)))
5447 (goto-char (point-min))
5448 (setq newend (point-max))))
5449 (when (or (interactive-p) for-yank)
5450 (message "Clipboard pasted as level %d subtree" new-level))
5451 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5452 kill-ring
5453 (eq org-subtree-clip (current-kill 0))
5454 org-subtree-clip-folded)
5455 ;; The tree was folded before it was killed/copied
5456 (hide-subtree))
5457 (and for-yank (goto-char newend))))
5459 (defun org-kill-is-subtree-p (&optional txt)
5460 "Check if the current kill is an outline subtree, or a set of trees.
5461 Returns nil if kill does not start with a headline, or if the first
5462 headline level is not the largest headline level in the tree.
5463 So this will actually accept several entries of equal levels as well,
5464 which is OK for `org-paste-subtree'.
5465 If optional TXT is given, check this string instead of the current kill."
5466 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5467 (start-level (and kill
5468 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5469 org-outline-regexp "\\)")
5470 kill)
5471 (- (match-end 2) (match-beginning 2) 1)))
5472 (re (concat "^" org-outline-regexp))
5473 (start (1+ (or (match-beginning 2) -1))))
5474 (if (not start-level)
5475 (progn
5476 nil) ;; does not even start with a heading
5477 (catch 'exit
5478 (while (setq start (string-match re kill (1+ start)))
5479 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5480 (throw 'exit nil)))
5481 t))))
5483 (defvar org-markers-to-move nil
5484 "Markers that should be moved with a cut-and-paste operation.
5485 Those markers are stored together with their positions relative to
5486 the start of the region.")
5488 (defun org-save-markers-in-region (beg end)
5489 "Check markers in region.
5490 If these markers are between BEG and END, record their position relative
5491 to BEG, so that after moving the block of text, we can put the markers back
5492 into place.
5493 This function gets called just before an entry or tree gets cut from the
5494 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5495 called immediately, to move the markers with the entries."
5496 (setq org-markers-to-move nil)
5497 (when (featurep 'org-clock)
5498 (org-clock-save-markers-for-cut-and-paste beg end))
5499 (when (featurep 'org-agenda)
5500 (org-agenda-save-markers-for-cut-and-paste beg end)))
5502 (defun org-check-and-save-marker (marker beg end)
5503 "Check if MARKER is between BEG and END.
5504 If yes, remember the marker and the distance to BEG."
5505 (when (and (marker-buffer marker)
5506 (equal (marker-buffer marker) (current-buffer)))
5507 (if (and (>= marker beg) (< marker end))
5508 (push (cons marker (- marker beg)) org-markers-to-move))))
5510 (defun org-reinstall-markers-in-region (beg)
5511 "Move all remembered markers to their position relative to BEG."
5512 (mapc (lambda (x)
5513 (move-marker (car x) (+ beg (cdr x))))
5514 org-markers-to-move)
5515 (setq org-markers-to-move nil))
5517 (defun org-narrow-to-subtree ()
5518 "Narrow buffer to the current subtree."
5519 (interactive)
5520 (save-excursion
5521 (save-match-data
5522 (narrow-to-region
5523 (progn (org-back-to-heading) (point))
5524 (progn (org-end-of-subtree t) (point))))))
5527 ;;; Outline Sorting
5529 (defun org-sort (with-case)
5530 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5531 Optional argument WITH-CASE means sort case-sensitively."
5532 (interactive "P")
5533 (if (org-at-table-p)
5534 (org-call-with-arg 'org-table-sort-lines with-case)
5535 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5537 (defun org-sort-remove-invisible (s)
5538 (remove-text-properties 0 (length s) org-rm-props s)
5539 (while (string-match org-bracket-link-regexp s)
5540 (setq s (replace-match (if (match-end 2)
5541 (match-string 3 s)
5542 (match-string 1 s)) t t s)))
5545 (defvar org-priority-regexp) ; defined later in the file
5547 (defun org-sort-entries-or-items
5548 (&optional with-case sorting-type getkey-func compare-func property)
5549 "Sort entries on a certain level of an outline tree.
5550 If there is an active region, the entries in the region are sorted.
5551 Else, if the cursor is before the first entry, sort the top-level items.
5552 Else, the children of the entry at point are sorted.
5554 Sorting can be alphabetically, numerically, and by date/time as given by
5555 the first time stamp in the entry. The command prompts for the sorting
5556 type unless it has been given to the function through the SORTING-TYPE
5557 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5558 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5559 called with point at the beginning of the record. It must return either
5560 a string or a number that should serve as the sorting key for that record.
5562 Comparing entries ignores case by default. However, with an optional argument
5563 WITH-CASE, the sorting considers case as well."
5564 (interactive "P")
5565 (let ((case-func (if with-case 'identity 'downcase))
5566 start beg end stars re re2
5567 txt what tmp plain-list-p)
5568 ;; Find beginning and end of region to sort
5569 (cond
5570 ((org-region-active-p)
5571 ;; we will sort the region
5572 (setq end (region-end)
5573 what "region")
5574 (goto-char (region-beginning))
5575 (if (not (org-on-heading-p)) (outline-next-heading))
5576 (setq start (point)))
5577 ((org-at-item-p)
5578 ;; we will sort this plain list
5579 (org-beginning-of-item-list) (setq start (point))
5580 (org-end-of-item-list) (setq end (point))
5581 (goto-char start)
5582 (setq plain-list-p t
5583 what "plain list"))
5584 ((or (org-on-heading-p)
5585 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5586 ;; we will sort the children of the current headline
5587 (org-back-to-heading)
5588 (setq start (point)
5589 end (progn (org-end-of-subtree t t)
5590 (org-back-over-empty-lines)
5591 (point))
5592 what "children")
5593 (goto-char start)
5594 (show-subtree)
5595 (outline-next-heading))
5597 ;; we will sort the top-level entries in this file
5598 (goto-char (point-min))
5599 (or (org-on-heading-p) (outline-next-heading))
5600 (setq start (point) end (point-max) what "top-level")
5601 (goto-char start)
5602 (show-all)))
5604 (setq beg (point))
5605 (if (>= beg end) (error "Nothing to sort"))
5607 (unless plain-list-p
5608 (looking-at "\\(\\*+\\)")
5609 (setq stars (match-string 1)
5610 re (concat "^" (regexp-quote stars) " +")
5611 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5612 txt (buffer-substring beg end))
5613 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5614 (if (and (not (equal stars "*")) (string-match re2 txt))
5615 (error "Region to sort contains a level above the first entry")))
5617 (unless sorting-type
5618 (message
5619 (if plain-list-p
5620 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5621 "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:")
5622 what)
5623 (setq sorting-type (read-char-exclusive))
5625 (and (= (downcase sorting-type) ?f)
5626 (setq getkey-func
5627 (org-ido-completing-read "Sort using function: "
5628 obarray 'fboundp t nil nil))
5629 (setq getkey-func (intern getkey-func)))
5631 (and (= (downcase sorting-type) ?r)
5632 (setq property
5633 (org-ido-completing-read "Property: "
5634 (mapcar 'list (org-buffer-property-keys t))
5635 nil t))))
5637 (message "Sorting entries...")
5639 (save-restriction
5640 (narrow-to-region start end)
5642 (let ((dcst (downcase sorting-type))
5643 (now (current-time)))
5644 (sort-subr
5645 (/= dcst sorting-type)
5646 ;; This function moves to the beginning character of the "record" to
5647 ;; be sorted.
5648 (if plain-list-p
5649 (lambda nil
5650 (if (org-at-item-p) t (goto-char (point-max))))
5651 (lambda nil
5652 (if (re-search-forward re nil t)
5653 (goto-char (match-beginning 0))
5654 (goto-char (point-max)))))
5655 ;; This function moves to the last character of the "record" being
5656 ;; sorted.
5657 (if plain-list-p
5658 'org-end-of-item
5659 (lambda nil
5660 (save-match-data
5661 (condition-case nil
5662 (outline-forward-same-level 1)
5663 (error
5664 (goto-char (point-max)))))))
5666 ;; This function returns the value that gets sorted against.
5667 (if plain-list-p
5668 (lambda nil
5669 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5670 (cond
5671 ((= dcst ?n)
5672 (string-to-number (buffer-substring (match-end 0)
5673 (point-at-eol))))
5674 ((= dcst ?a)
5675 (buffer-substring (match-end 0) (point-at-eol)))
5676 ((= dcst ?t)
5677 (if (re-search-forward org-ts-regexp
5678 (point-at-eol) t)
5679 (org-time-string-to-time (match-string 0))
5680 now))
5681 ((= dcst ?f)
5682 (if getkey-func
5683 (progn
5684 (setq tmp (funcall getkey-func))
5685 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5686 tmp)
5687 (error "Invalid key function `%s'" getkey-func)))
5688 (t (error "Invalid sorting type `%c'" sorting-type)))))
5689 (lambda nil
5690 (cond
5691 ((= dcst ?n)
5692 (if (looking-at org-complex-heading-regexp)
5693 (string-to-number (match-string 4))
5694 nil))
5695 ((= dcst ?a)
5696 (if (looking-at org-complex-heading-regexp)
5697 (funcall case-func (match-string 4))
5698 nil))
5699 ((= dcst ?t)
5700 (if (re-search-forward org-ts-regexp
5701 (save-excursion
5702 (forward-line 2)
5703 (point)) t)
5704 (org-time-string-to-time (match-string 0))
5705 now))
5706 ((= dcst ?p)
5707 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5708 (string-to-char (match-string 2))
5709 org-default-priority))
5710 ((= dcst ?r)
5711 (or (org-entry-get nil property) ""))
5712 ((= dcst ?o)
5713 (if (looking-at org-complex-heading-regexp)
5714 (- 9999 (length (member (match-string 2)
5715 org-todo-keywords-1)))))
5716 ((= dcst ?f)
5717 (if getkey-func
5718 (progn
5719 (setq tmp (funcall getkey-func))
5720 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5721 tmp)
5722 (error "Invalid key function `%s'" getkey-func)))
5723 (t (error "Invalid sorting type `%c'" sorting-type)))))
5725 (cond
5726 ((= dcst ?a) 'string<)
5727 ((= dcst ?t) 'time-less-p)
5728 ((= dcst ?f) compare-func)
5729 (t nil)))))
5730 (message "Sorting entries...done")))
5732 (defun org-do-sort (table what &optional with-case sorting-type)
5733 "Sort TABLE of WHAT according to SORTING-TYPE.
5734 The user will be prompted for the SORTING-TYPE if the call to this
5735 function does not specify it. WHAT is only for the prompt, to indicate
5736 what is being sorted. The sorting key will be extracted from
5737 the car of the elements of the table.
5738 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5739 (unless sorting-type
5740 (message
5741 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5742 what)
5743 (setq sorting-type (read-char-exclusive)))
5744 (let ((dcst (downcase sorting-type))
5745 extractfun comparefun)
5746 ;; Define the appropriate functions
5747 (cond
5748 ((= dcst ?n)
5749 (setq extractfun 'string-to-number
5750 comparefun (if (= dcst sorting-type) '< '>)))
5751 ((= dcst ?a)
5752 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5753 (lambda(x) (downcase (org-sort-remove-invisible x))))
5754 comparefun (if (= dcst sorting-type)
5755 'string<
5756 (lambda (a b) (and (not (string< a b))
5757 (not (string= a b)))))))
5758 ((= dcst ?t)
5759 (setq extractfun
5760 (lambda (x)
5761 (if (string-match org-ts-regexp x)
5762 (time-to-seconds
5763 (org-time-string-to-time (match-string 0 x)))
5765 comparefun (if (= dcst sorting-type) '< '>)))
5766 (t (error "Invalid sorting type `%c'" sorting-type)))
5768 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5769 table)
5770 (lambda (a b) (funcall comparefun (car a) (car b))))))
5772 ;;; Editing source examples
5774 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5775 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5776 (defvar org-edit-src-force-single-line nil)
5777 (defvar org-edit-src-from-org-mode nil)
5778 (defvar org-edit-src-picture nil)
5780 (define-minor-mode org-exit-edit-mode
5781 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5783 (defun org-edit-src-code ()
5784 "Edit the source code example at point.
5785 An indirect buffer is created, and that buffer is then narrowed to the
5786 example at point and switched to the correct language mode. When done,
5787 exit by killing the buffer with \\[org-edit-src-exit]."
5788 (interactive)
5789 (let ((line (org-current-line))
5790 (case-fold-search t)
5791 (msg (substitute-command-keys
5792 "Edit, then exit with C-c ' (C-c and single quote)"))
5793 (info (org-edit-src-find-region-and-lang))
5794 (org-mode-p (eq major-mode 'org-mode))
5795 beg end lang lang-f single lfmt)
5796 (if (not info)
5798 (setq beg (nth 0 info)
5799 end (nth 1 info)
5800 lang (nth 2 info)
5801 single (nth 3 info)
5802 lfmt (nth 4 info)
5803 lang-f (intern (concat lang "-mode")))
5804 (unless (functionp lang-f)
5805 (error "No such language mode: %s" lang-f))
5806 (goto-line line)
5807 (if (get-buffer "*Org Edit Src Example*")
5808 (kill-buffer "*Org Edit Src Example*"))
5809 (switch-to-buffer (make-indirect-buffer (current-buffer)
5810 "*Org Edit Src Example*"))
5811 (narrow-to-region beg end)
5812 (remove-text-properties beg end '(display nil invisible nil
5813 intangible nil))
5814 (let ((org-inhibit-startup t))
5815 (funcall lang-f))
5816 (set (make-local-variable 'org-edit-src-force-single-line) single)
5817 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5818 (when lfmt
5819 (set (make-local-variable 'org-coderef-label-format) lfmt))
5820 (when org-mode-p
5821 (goto-char (point-min))
5822 (while (re-search-forward "^," nil t)
5823 (replace-match "")))
5824 (goto-line line)
5825 (org-exit-edit-mode)
5826 (org-set-local 'header-line-format msg)
5827 (message "%s" msg)
5828 t)))
5830 (defun org-edit-fixed-width-region ()
5831 "Edit the fixed-width ascii drawing at point.
5832 This must be a region where each line starts with a colon followed by
5833 a space character.
5834 An indirect buffer is created, and that buffer is then narrowed to the
5835 example at point and switched to artist-mode. When done,
5836 exit by killing the buffer with \\[org-edit-src-exit]."
5837 (interactive)
5838 (let ((line (org-current-line))
5839 (case-fold-search t)
5840 (msg (substitute-command-keys
5841 "Edit, then exit with C-c ' (C-c and single quote)"))
5842 (org-mode-p (eq major-mode 'org-mode))
5843 beg end lang lang-f)
5844 (beginning-of-line 1)
5845 (if (looking-at "[ \t]*[^:\n \t]")
5847 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5848 (setq beg (point) end beg)
5849 (save-excursion
5850 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5851 (setq beg (point-at-bol 2))
5852 (setq beg (point))))
5853 (save-excursion
5854 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5855 (setq end (1- (match-beginning 0)))
5856 (setq end (point))))
5857 (goto-line line))
5858 (if (get-buffer "*Org Edit Picture*")
5859 (kill-buffer "*Org Edit Picture*"))
5860 (switch-to-buffer (make-indirect-buffer (current-buffer)
5861 "*Org Edit Picture*"))
5862 (narrow-to-region beg end)
5863 (remove-text-properties beg end '(display nil invisible nil
5864 intangible nil))
5865 (when (fboundp 'font-lock-unfontify-region)
5866 (font-lock-unfontify-region (point-min) (point-max)))
5867 (cond
5868 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5869 (fundamental-mode)
5870 (artist-mode 1))
5871 (t (funcall org-edit-fixed-width-region-mode)))
5872 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5873 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5874 (set (make-local-variable 'org-edit-src-picture) t)
5875 (goto-char (point-min))
5876 (while (re-search-forward "^[ \t]*: ?" nil t)
5877 (replace-match ""))
5878 (goto-line line)
5879 (org-exit-edit-mode)
5880 (org-set-local 'header-line-format msg)
5881 (message "%s" msg)
5882 t)))
5885 (defun org-edit-src-find-region-and-lang ()
5886 "Find the region and language for a local edit.
5887 Return a list with beginning and end of the region, a string representing
5888 the language, a switch telling of the content should be in a single line."
5889 (let ((re-list
5890 (append
5891 org-edit-src-region-extra
5893 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5894 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5895 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5896 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5897 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5898 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5899 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5900 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5901 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5902 ("^#\\+html:" "\n" "html" single-line)
5903 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5904 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5905 ("^#\\+latex:" "\n" "latex" single-line)
5906 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5907 ("^#\\+ascii:" "\n" "ascii" single-line)
5909 (pos (point))
5910 re re1 re2 single beg end lang lfmt match-re1)
5911 (catch 'exit
5912 (while (setq entry (pop re-list))
5913 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5914 single (nth 3 entry))
5915 (save-excursion
5916 (if (or (looking-at re1)
5917 (re-search-backward re1 nil t))
5918 (progn
5919 (setq match-re1 (match-string 0))
5920 (setq beg (match-end 0)
5921 lang (org-edit-src-get-lang lang)
5922 lfmt (org-edit-src-get-label-format match-re1))
5923 (if (and (re-search-forward re2 nil t)
5924 (>= (match-end 0) pos))
5925 (throw 'exit (list beg (match-beginning 0)
5926 lang single lfmt))))
5927 (if (or (looking-at re2)
5928 (re-search-forward re2 nil t))
5929 (progn
5930 (setq end (match-beginning 0))
5931 (if (and (re-search-backward re1 nil t)
5932 (<= (match-beginning 0) pos))
5933 (progn
5934 (setq lfmt (org-edit-src-get-label-format
5935 (match-string 0)))
5936 (throw 'exit
5937 (list (match-end 0) end
5938 (org-edit-src-get-lang lang)
5939 single lfmt))))))))))))
5941 (defun org-edit-src-get-lang (lang)
5942 "Extract the src language."
5943 (let ((m (match-string 0)))
5944 (cond
5945 ((stringp lang) lang)
5946 ((integerp lang) (match-string lang))
5947 ((and (eq lang 'lang)
5948 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5949 (match-string 1 m))
5950 ((and (eq lang 'style)
5951 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5952 (match-string 1 m))
5953 (t "fundamental"))))
5955 (defun org-edit-src-get-label-format (s)
5956 "Extract the label format."
5957 (save-match-data
5958 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
5959 (match-string 1 s))))
5961 (defun org-edit-src-exit ()
5962 "Exit special edit and protect problematic lines."
5963 (interactive)
5964 (unless (buffer-base-buffer (current-buffer))
5965 (error "This is not an indirect buffer, something is wrong..."))
5966 (unless (> (point-min) 1)
5967 (error "This buffer is not narrowed, something is wrong..."))
5968 (goto-char (point-min))
5969 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5970 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5971 (when (org-bound-and-true-p org-edit-src-force-single-line)
5972 (goto-char (point-min))
5973 (while (re-search-forward "\n" nil t)
5974 (replace-match " "))
5975 (goto-char (point-min))
5976 (if (looking-at "\\s-*") (replace-match " "))
5977 (if (re-search-forward "\\s-+\\'" nil t)
5978 (replace-match "")))
5979 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5980 (goto-char (point-min))
5981 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5982 (replace-match ",\\1"))
5983 (when font-lock-mode
5984 (font-lock-unfontify-region (point-min) (point-max)))
5985 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5986 (when (org-bound-and-true-p org-edit-src-picture)
5987 (untabify (point-min) (point-max))
5988 (goto-char (point-min))
5989 (while (re-search-forward "^" nil t)
5990 (replace-match ": "))
5991 (when font-lock-mode
5992 (font-lock-unfontify-region (point-min) (point-max)))
5993 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5994 (kill-buffer (current-buffer))
5995 (and (org-mode-p) (org-restart-font-lock)))
5998 ;;; The orgstruct minor mode
6000 ;; Define a minor mode which can be used in other modes in order to
6001 ;; integrate the org-mode structure editing commands.
6003 ;; This is really a hack, because the org-mode structure commands use
6004 ;; keys which normally belong to the major mode. Here is how it
6005 ;; works: The minor mode defines all the keys necessary to operate the
6006 ;; structure commands, but wraps the commands into a function which
6007 ;; tests if the cursor is currently at a headline or a plain list
6008 ;; item. If that is the case, the structure command is used,
6009 ;; temporarily setting many Org-mode variables like regular
6010 ;; expressions for filling etc. However, when any of those keys is
6011 ;; used at a different location, function uses `key-binding' to look
6012 ;; up if the key has an associated command in another currently active
6013 ;; keymap (minor modes, major mode, global), and executes that
6014 ;; command. There might be problems if any of the keys is otherwise
6015 ;; used as a prefix key.
6017 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6018 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6019 ;; addresses this by checking explicitly for both bindings.
6021 (defvar orgstruct-mode-map (make-sparse-keymap)
6022 "Keymap for the minor `orgstruct-mode'.")
6024 (defvar org-local-vars nil
6025 "List of local variables, for use by `orgstruct-mode'")
6027 ;;;###autoload
6028 (define-minor-mode orgstruct-mode
6029 "Toggle the minor more `orgstruct-mode'.
6030 This mode is for using Org-mode structure commands in other modes.
6031 The following key behave as if Org-mode was active, if the cursor
6032 is on a headline, or on a plain list item (both in the definition
6033 of Org-mode).
6035 M-up Move entry/item up
6036 M-down Move entry/item down
6037 M-left Promote
6038 M-right Demote
6039 M-S-up Move entry/item up
6040 M-S-down Move entry/item down
6041 M-S-left Promote subtree
6042 M-S-right Demote subtree
6043 M-q Fill paragraph and items like in Org-mode
6044 C-c ^ Sort entries
6045 C-c - Cycle list bullet
6046 TAB Cycle item visibility
6047 M-RET Insert new heading/item
6048 S-M-RET Insert new TODO heading / Checkbox item
6049 C-c C-c Set tags / toggle checkbox"
6050 nil " OrgStruct" nil
6051 (org-load-modules-maybe)
6052 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6054 ;;;###autoload
6055 (defun turn-on-orgstruct ()
6056 "Unconditionally turn on `orgstruct-mode'."
6057 (orgstruct-mode 1))
6059 ;;;###autoload
6060 (defun turn-on-orgstruct++ ()
6061 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6062 In addition to setting orgstruct-mode, this also exports all indentation and
6063 autofilling variables from org-mode into the buffer. Note that turning
6064 off orgstruct-mode will *not* remove these additional settings."
6065 (orgstruct-mode 1)
6066 (let (var val)
6067 (mapc
6068 (lambda (x)
6069 (when (string-match
6070 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6071 (symbol-name (car x)))
6072 (setq var (car x) val (nth 1 x))
6073 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6074 org-local-vars)))
6076 (defun orgstruct-error ()
6077 "Error when there is no default binding for a structure key."
6078 (interactive)
6079 (error "This key has no function outside structure elements"))
6081 (defun orgstruct-setup ()
6082 "Setup orgstruct keymaps."
6083 (let ((nfunc 0)
6084 (bindings
6085 (list
6086 '([(meta up)] org-metaup)
6087 '([(meta down)] org-metadown)
6088 '([(meta left)] org-metaleft)
6089 '([(meta right)] org-metaright)
6090 '([(meta shift up)] org-shiftmetaup)
6091 '([(meta shift down)] org-shiftmetadown)
6092 '([(meta shift left)] org-shiftmetaleft)
6093 '([(meta shift right)] org-shiftmetaright)
6094 '([(shift up)] org-shiftup)
6095 '([(shift down)] org-shiftdown)
6096 '([(shift left)] org-shiftleft)
6097 '([(shift right)] org-shiftright)
6098 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6099 '("\M-q" fill-paragraph)
6100 '("\C-c^" org-sort)
6101 '("\C-c-" org-cycle-list-bullet)))
6102 elt key fun cmd)
6103 (while (setq elt (pop bindings))
6104 (setq nfunc (1+ nfunc))
6105 (setq key (org-key (car elt))
6106 fun (nth 1 elt)
6107 cmd (orgstruct-make-binding fun nfunc key))
6108 (org-defkey orgstruct-mode-map key cmd))
6110 ;; Special treatment needed for TAB and RET
6111 (org-defkey orgstruct-mode-map [(tab)]
6112 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6113 (org-defkey orgstruct-mode-map "\C-i"
6114 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6116 (org-defkey orgstruct-mode-map "\M-\C-m"
6117 (orgstruct-make-binding 'org-insert-heading 105
6118 "\M-\C-m" [(meta return)]))
6119 (org-defkey orgstruct-mode-map [(meta return)]
6120 (orgstruct-make-binding 'org-insert-heading 106
6121 [(meta return)] "\M-\C-m"))
6123 (org-defkey orgstruct-mode-map [(shift meta return)]
6124 (orgstruct-make-binding 'org-insert-todo-heading 107
6125 [(meta return)] "\M-\C-m"))
6127 (unless org-local-vars
6128 (setq org-local-vars (org-get-local-variables)))
6132 (defun orgstruct-make-binding (fun n &rest keys)
6133 "Create a function for binding in the structure minor mode.
6134 FUN is the command to call inside a table. N is used to create a unique
6135 command name. KEYS are keys that should be checked in for a command
6136 to execute outside of tables."
6137 (eval
6138 (list 'defun
6139 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6140 '(arg)
6141 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6142 "Outside of structure, run the binding of `"
6143 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6144 "'.")
6145 '(interactive "p")
6146 (list 'if
6147 '(org-context-p 'headline 'item)
6148 (list 'org-run-like-in-org-mode (list 'quote fun))
6149 (list 'let '(orgstruct-mode)
6150 (list 'call-interactively
6151 (append '(or)
6152 (mapcar (lambda (k)
6153 (list 'key-binding k))
6154 keys)
6155 '('orgstruct-error))))))))
6157 (defun org-context-p (&rest contexts)
6158 "Check if local context is any of CONTEXTS.
6159 Possible values in the list of contexts are `table', `headline', and `item'."
6160 (let ((pos (point)))
6161 (goto-char (point-at-bol))
6162 (prog1 (or (and (memq 'table contexts)
6163 (looking-at "[ \t]*|"))
6164 (and (memq 'headline contexts)
6165 ;;????????? (looking-at "\\*+"))
6166 (looking-at outline-regexp))
6167 (and (memq 'item contexts)
6168 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6169 (goto-char pos))))
6171 (defun org-get-local-variables ()
6172 "Return a list of all local variables in an org-mode buffer."
6173 (let (varlist)
6174 (with-current-buffer (get-buffer-create "*Org tmp*")
6175 (erase-buffer)
6176 (org-mode)
6177 (setq varlist (buffer-local-variables)))
6178 (kill-buffer "*Org tmp*")
6179 (delq nil
6180 (mapcar
6181 (lambda (x)
6182 (setq x
6183 (if (symbolp x)
6184 (list x)
6185 (list (car x) (list 'quote (cdr x)))))
6186 (if (string-match
6187 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6188 (symbol-name (car x)))
6189 x nil))
6190 varlist))))
6192 ;;;###autoload
6193 (defun org-run-like-in-org-mode (cmd)
6194 (org-load-modules-maybe)
6195 (unless org-local-vars
6196 (setq org-local-vars (org-get-local-variables)))
6197 (eval (list 'let org-local-vars
6198 (list 'call-interactively (list 'quote cmd)))))
6200 ;;;; Archiving
6202 (defun org-get-category (&optional pos)
6203 "Get the category applying to position POS."
6204 (get-text-property (or pos (point)) 'org-category))
6206 (defun org-refresh-category-properties ()
6207 "Refresh category text properties in the buffer."
6208 (let ((def-cat (cond
6209 ((null org-category)
6210 (if buffer-file-name
6211 (file-name-sans-extension
6212 (file-name-nondirectory buffer-file-name))
6213 "???"))
6214 ((symbolp org-category) (symbol-name org-category))
6215 (t org-category)))
6216 beg end cat pos optionp)
6217 (org-unmodified
6218 (save-excursion
6219 (save-restriction
6220 (widen)
6221 (goto-char (point-min))
6222 (put-text-property (point) (point-max) 'org-category def-cat)
6223 (while (re-search-forward
6224 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6225 (setq pos (match-end 0)
6226 optionp (equal (char-after (match-beginning 0)) ?#)
6227 cat (org-trim (match-string 2)))
6228 (if optionp
6229 (setq beg (point-at-bol) end (point-max))
6230 (org-back-to-heading t)
6231 (setq beg (point) end (org-end-of-subtree t t)))
6232 (put-text-property beg end 'org-category cat)
6233 (goto-char pos)))))))
6236 ;;;; Link Stuff
6238 ;;; Link abbreviations
6240 (defun org-link-expand-abbrev (link)
6241 "Apply replacements as defined in `org-link-abbrev-alist."
6242 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6243 (let* ((key (match-string 1 link))
6244 (as (or (assoc key org-link-abbrev-alist-local)
6245 (assoc key org-link-abbrev-alist)))
6246 (tag (and (match-end 2) (match-string 3 link)))
6247 rpl)
6248 (if (not as)
6249 link
6250 (setq rpl (cdr as))
6251 (cond
6252 ((symbolp rpl) (funcall rpl tag))
6253 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6254 ((string-match "%h" rpl)
6255 (replace-match (url-hexify-string (or tag "")) t t rpl))
6256 (t (concat rpl tag)))))
6257 link))
6259 ;;; Storing and inserting links
6261 (defvar org-insert-link-history nil
6262 "Minibuffer history for links inserted with `org-insert-link'.")
6264 (defvar org-stored-links nil
6265 "Contains the links stored with `org-store-link'.")
6267 (defvar org-store-link-plist nil
6268 "Plist with info about the most recently link created with `org-store-link'.")
6270 (defvar org-link-protocols nil
6271 "Link protocols added to Org-mode using `org-add-link-type'.")
6273 (defvar org-store-link-functions nil
6274 "List of functions that are called to create and store a link.
6275 Each function will be called in turn until one returns a non-nil
6276 value. Each function should check if it is responsible for creating
6277 this link (for example by looking at the major mode).
6278 If not, it must exit and return nil.
6279 If yes, it should return a non-nil value after a calling
6280 `org-store-link-props' with a list of properties and values.
6281 Special properties are:
6283 :type The link prefix. like \"http\". This must be given.
6284 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6285 This is obligatory as well.
6286 :description Optional default description for the second pair
6287 of brackets in an Org-mode link. The user can still change
6288 this when inserting this link into an Org-mode buffer.
6290 In addition to these, any additional properties can be specified
6291 and then used in remember templates.")
6293 (defun org-add-link-type (type &optional follow export)
6294 "Add TYPE to the list of `org-link-types'.
6295 Re-compute all regular expressions depending on `org-link-types'
6297 FOLLOW and EXPORT are two functions.
6299 FOLLOW should take the link path as the single argument and do whatever
6300 is necessary to follow the link, for example find a file or display
6301 a mail message.
6303 EXPORT should format the link path for export to one of the export formats.
6304 It should be a function accepting three arguments:
6306 path the path of the link, the text after the prefix (like \"http:\")
6307 desc the description of the link, if any, nil if there was no description
6308 format the export format, a symbol like `html' or `latex'.
6310 The function may use the FORMAT information to return different values
6311 depending on the format. The return value will be put literally into
6312 the exported file.
6313 Org-mode has a built-in default for exporting links. If you are happy with
6314 this default, there is no need to define an export function for the link
6315 type. For a simple example of an export function, see `org-bbdb.el'."
6316 (add-to-list 'org-link-types type t)
6317 (org-make-link-regexps)
6318 (if (assoc type org-link-protocols)
6319 (setcdr (assoc type org-link-protocols) (list follow export))
6320 (push (list type follow export) org-link-protocols)))
6322 ;;;###autoload
6323 (defun org-store-link (arg)
6324 "\\<org-mode-map>Store an org-link to the current location.
6325 This link is added to `org-stored-links' and can later be inserted
6326 into an org-buffer with \\[org-insert-link].
6328 For some link types, a prefix arg is interpreted:
6329 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6330 For file links, arg negates `org-context-in-file-links'."
6331 (interactive "P")
6332 (org-load-modules-maybe)
6333 (setq org-store-link-plist nil) ; reset
6334 (let (link cpltxt desc description search txt)
6335 (cond
6337 ((run-hook-with-args-until-success 'org-store-link-functions)
6338 (setq link (plist-get org-store-link-plist :link)
6339 desc (or (plist-get org-store-link-plist :description) link)))
6341 ((equal (buffer-name) "*Org Edit Src Example*")
6342 (let (label gc)
6343 (while (or (not label)
6344 (save-excursion
6345 (save-restriction
6346 (widen)
6347 (goto-char (point-min))
6348 (re-search-forward
6349 (regexp-quote (format org-coderef-label-format label))
6350 nil t))))
6351 (when label (message "Label exists already") (sit-for 2))
6352 (setq label (read-string "Code line label: " label)))
6353 (end-of-line 1)
6354 (setq link (format org-coderef-label-format label))
6355 (setq gc (- 79 (length link)))
6356 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6357 (insert link)
6358 (setq link (concat "(" label ")") desc nil)))
6360 ((eq major-mode 'calendar-mode)
6361 (let ((cd (calendar-cursor-to-date)))
6362 (setq link
6363 (format-time-string
6364 (car org-time-stamp-formats)
6365 (apply 'encode-time
6366 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6367 nil nil nil))))
6368 (org-store-link-props :type "calendar" :date cd)))
6370 ((eq major-mode 'w3-mode)
6371 (setq cpltxt (url-view-url t)
6372 link (org-make-link cpltxt))
6373 (org-store-link-props :type "w3" :url (url-view-url t)))
6375 ((eq major-mode 'w3m-mode)
6376 (setq cpltxt (or w3m-current-title w3m-current-url)
6377 link (org-make-link w3m-current-url))
6378 (org-store-link-props :type "w3m" :url (url-view-url t)))
6380 ((setq search (run-hook-with-args-until-success
6381 'org-create-file-search-functions))
6382 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6383 "::" search))
6384 (setq cpltxt (or description link)))
6386 ((eq major-mode 'image-mode)
6387 (setq cpltxt (concat "file:"
6388 (abbreviate-file-name buffer-file-name))
6389 link (org-make-link cpltxt))
6390 (org-store-link-props :type "image" :file buffer-file-name))
6392 ((eq major-mode 'dired-mode)
6393 ;; link to the file in the current line
6394 (setq cpltxt (concat "file:"
6395 (abbreviate-file-name
6396 (expand-file-name
6397 (dired-get-filename nil t))))
6398 link (org-make-link cpltxt)))
6400 ((and buffer-file-name (org-mode-p))
6401 (cond
6402 ((org-in-regexp "<<\\(.*?\\)>>")
6403 (setq cpltxt
6404 (concat "file:"
6405 (abbreviate-file-name buffer-file-name)
6406 "::" (match-string 1))
6407 link (org-make-link cpltxt)))
6408 ((and (featurep 'org-id)
6409 (or (eq org-link-to-org-use-id t)
6410 (and (eq org-link-to-org-use-id 'create-if-interactive)
6411 (interactive-p))
6412 (and org-link-to-org-use-id
6413 (condition-case nil
6414 (org-entry-get nil "ID")
6415 (error nil)))))
6416 ;; We can make a link using the ID.
6417 (setq link (condition-case nil
6418 (prog1 (org-id-store-link)
6419 (setq desc (plist-get org-store-link-plist
6420 :description)))
6421 (error
6422 ;; probably before first headline, link to file only
6423 (concat "file:"
6424 (abbreviate-file-name buffer-file-name))))))
6426 ;; Just link to current headline
6427 (setq cpltxt (concat "file:"
6428 (abbreviate-file-name buffer-file-name)))
6429 ;; Add a context search string
6430 (when (org-xor org-context-in-file-links arg)
6431 (setq txt (cond
6432 ((org-on-heading-p) nil)
6433 ((org-region-active-p)
6434 (buffer-substring (region-beginning) (region-end)))
6435 (t nil)))
6436 (when (or (null txt) (string-match "\\S-" txt))
6437 (setq cpltxt
6438 (concat cpltxt "::"
6439 (condition-case nil
6440 (org-make-org-heading-search-string txt)
6441 (error "")))
6442 desc "NONE")))
6443 (if (string-match "::\\'" cpltxt)
6444 (setq cpltxt (substring cpltxt 0 -2)))
6445 (setq link (org-make-link cpltxt)))))
6447 ((buffer-file-name (buffer-base-buffer))
6448 ;; Just link to this file here.
6449 (setq cpltxt (concat "file:"
6450 (abbreviate-file-name
6451 (buffer-file-name (buffer-base-buffer)))))
6452 ;; Add a context string
6453 (when (org-xor org-context-in-file-links arg)
6454 (setq txt (if (org-region-active-p)
6455 (buffer-substring (region-beginning) (region-end))
6456 (buffer-substring (point-at-bol) (point-at-eol))))
6457 ;; Only use search option if there is some text.
6458 (when (string-match "\\S-" txt)
6459 (setq cpltxt
6460 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6461 desc "NONE")))
6462 (setq link (org-make-link cpltxt)))
6464 ((interactive-p)
6465 (error "Cannot link to a buffer which is not visiting a file"))
6467 (t (setq link nil)))
6469 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6470 (setq link (or link cpltxt)
6471 desc (or desc cpltxt))
6472 (if (equal desc "NONE") (setq desc nil))
6474 (if (and (interactive-p) link)
6475 (progn
6476 (setq org-stored-links
6477 (cons (list link desc) org-stored-links))
6478 (message "Stored: %s" (or desc link)))
6479 (and link (org-make-link-string link desc)))))
6481 (defun org-store-link-props (&rest plist)
6482 "Store link properties, extract names and addresses."
6483 (let (x adr)
6484 (when (setq x (plist-get plist :from))
6485 (setq adr (mail-extract-address-components x))
6486 (setq plist (plist-put plist :fromname (car adr)))
6487 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6488 (when (setq x (plist-get plist :to))
6489 (setq adr (mail-extract-address-components x))
6490 (setq plist (plist-put plist :toname (car adr)))
6491 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6492 (let ((from (plist-get plist :from))
6493 (to (plist-get plist :to)))
6494 (when (and from to org-from-is-user-regexp)
6495 (setq plist
6496 (plist-put plist :fromto
6497 (if (string-match org-from-is-user-regexp from)
6498 (concat "to %t")
6499 (concat "from %f"))))))
6500 (setq org-store-link-plist plist))
6502 (defun org-add-link-props (&rest plist)
6503 "Add these properties to the link property list."
6504 (let (key value)
6505 (while plist
6506 (setq key (pop plist) value (pop plist))
6507 (setq org-store-link-plist
6508 (plist-put org-store-link-plist key value)))))
6510 (defun org-email-link-description (&optional fmt)
6511 "Return the description part of an email link.
6512 This takes information from `org-store-link-plist' and formats it
6513 according to FMT (default from `org-email-link-description-format')."
6514 (setq fmt (or fmt org-email-link-description-format))
6515 (let* ((p org-store-link-plist)
6516 (to (plist-get p :toaddress))
6517 (from (plist-get p :fromaddress))
6518 (table
6519 (list
6520 (cons "%c" (plist-get p :fromto))
6521 (cons "%F" (plist-get p :from))
6522 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6523 (cons "%T" (plist-get p :to))
6524 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6525 (cons "%s" (plist-get p :subject))
6526 (cons "%m" (plist-get p :message-id)))))
6527 (when (string-match "%c" fmt)
6528 ;; Check if the user wrote this message
6529 (if (and org-from-is-user-regexp from to
6530 (save-match-data (string-match org-from-is-user-regexp from)))
6531 (setq fmt (replace-match "to %t" t t fmt))
6532 (setq fmt (replace-match "from %f" t t fmt))))
6533 (org-replace-escapes fmt table)))
6535 (defun org-make-org-heading-search-string (&optional string heading)
6536 "Make search string for STRING or current headline."
6537 (interactive)
6538 (let ((s (or string (org-get-heading))))
6539 (unless (and string (not heading))
6540 ;; We are using a headline, clean up garbage in there.
6541 (if (string-match org-todo-regexp s)
6542 (setq s (replace-match "" t t s)))
6543 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6544 (setq s (replace-match "" t t s)))
6545 (setq s (org-trim s))
6546 (if (string-match (concat "^\\(" org-quote-string "\\|"
6547 org-comment-string "\\)") s)
6548 (setq s (replace-match "" t t s)))
6549 (while (string-match org-ts-regexp s)
6550 (setq s (replace-match "" t t s))))
6551 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6552 (setq s (replace-match " " t t s)))
6553 (or string (setq s (concat "*" s))) ; Add * for headlines
6554 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6556 (defun org-make-link (&rest strings)
6557 "Concatenate STRINGS."
6558 (apply 'concat strings))
6560 (defun org-make-link-string (link &optional description)
6561 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6562 (unless (string-match "\\S-" link)
6563 (error "Empty link"))
6564 (when (stringp description)
6565 ;; Remove brackets from the description, they are fatal.
6566 (while (string-match "\\[" description)
6567 (setq description (replace-match "{" t t description)))
6568 (while (string-match "\\]" description)
6569 (setq description (replace-match "}" t t description))))
6570 (when (equal (org-link-escape link) description)
6571 ;; No description needed, it is identical
6572 (setq description nil))
6573 (when (and (not description)
6574 (not (equal link (org-link-escape link))))
6575 (setq description (org-extract-attributes link)))
6576 (concat "[[" (org-link-escape link) "]"
6577 (if description (concat "[" description "]") "")
6578 "]"))
6580 (defconst org-link-escape-chars
6581 '((?\ . "%20")
6582 (?\[ . "%5B")
6583 (?\] . "%5D")
6584 (?\340 . "%E0") ; `a
6585 (?\342 . "%E2") ; ^a
6586 (?\347 . "%E7") ; ,c
6587 (?\350 . "%E8") ; `e
6588 (?\351 . "%E9") ; 'e
6589 (?\352 . "%EA") ; ^e
6590 (?\356 . "%EE") ; ^i
6591 (?\364 . "%F4") ; ^o
6592 (?\371 . "%F9") ; `u
6593 (?\373 . "%FB") ; ^u
6594 (?\; . "%3B")
6595 (?? . "%3F")
6596 (?= . "%3D")
6597 (?+ . "%2B")
6599 "Association list of escapes for some characters problematic in links.
6600 This is the list that is used for internal purposes.")
6602 (defconst org-link-escape-chars-browser
6603 '((?\ . "%20")) ; 32 for the SPC char
6604 "Association list of escapes for some characters problematic in links.
6605 This is the list that is used before handing over to the browser.")
6607 (defun org-link-escape (text &optional table)
6608 "Escape characters in TEXT that are problematic for links."
6609 (setq table (or table org-link-escape-chars))
6610 (when text
6611 (let ((re (mapconcat (lambda (x) (regexp-quote
6612 (char-to-string (car x))))
6613 table "\\|")))
6614 (while (string-match re text)
6615 (setq text
6616 (replace-match
6617 (cdr (assoc (string-to-char (match-string 0 text))
6618 table))
6619 t t text)))
6620 text)))
6622 (defun org-link-unescape (text &optional table)
6623 "Reverse the action of `org-link-escape'."
6624 (setq table (or table org-link-escape-chars))
6625 (when text
6626 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6627 table "\\|")))
6628 (while (string-match re text)
6629 (setq text
6630 (replace-match
6631 (char-to-string (car (rassoc (match-string 0 text) table)))
6632 t t text)))
6633 text)))
6635 (defun org-xor (a b)
6636 "Exclusive or."
6637 (if a (not b) b))
6639 (defun org-fixup-message-id-for-http (s)
6640 "Replace special characters in a message id, so it can be used in an http query."
6641 (while (string-match "<" s)
6642 (setq s (replace-match "%3C" t t s)))
6643 (while (string-match ">" s)
6644 (setq s (replace-match "%3E" t t s)))
6645 (while (string-match "@" s)
6646 (setq s (replace-match "%40" t t s)))
6649 ;;;###autoload
6650 (defun org-insert-link-global ()
6651 "Insert a link like Org-mode does.
6652 This command can be called in any mode to insert a link in Org-mode syntax."
6653 (interactive)
6654 (org-load-modules-maybe)
6655 (org-run-like-in-org-mode 'org-insert-link))
6657 (defun org-insert-link (&optional complete-file link-location)
6658 "Insert a link. At the prompt, enter the link.
6660 Completion can be used to insert any of the link protocol prefixes like
6661 http or ftp in use.
6663 The history can be used to select a link previously stored with
6664 `org-store-link'. When the empty string is entered (i.e. if you just
6665 press RET at the prompt), the link defaults to the most recently
6666 stored link. As SPC triggers completion in the minibuffer, you need to
6667 use M-SPC or C-q SPC to force the insertion of a space character.
6669 You will also be prompted for a description, and if one is given, it will
6670 be displayed in the buffer instead of the link.
6672 If there is already a link at point, this command will allow you to edit link
6673 and description parts.
6675 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6676 be selected using completion. The path to the file will be relative to the
6677 current directory if the file is in the current directory or a subdirectory.
6678 Otherwise, the link will be the absolute path as completed in the minibuffer
6679 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6680 option `org-link-file-path-type'.
6682 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6683 the current directory or below.
6685 With three \\[universal-argument] prefixes, negate the meaning of
6686 `org-keep-stored-link-after-insertion'.
6688 If `org-make-link-description-function' is non-nil, this function will be
6689 called with the link target, and the result will be the default
6690 link description.
6692 If the LINK-LOCATION parameter is non-nil, this value will be
6693 used as the link location instead of reading one interactively."
6694 (interactive "P")
6695 (let* ((wcf (current-window-configuration))
6696 (region (if (org-region-active-p)
6697 (buffer-substring (region-beginning) (region-end))))
6698 (remove (and region (list (region-beginning) (region-end))))
6699 (desc region)
6700 tmphist ; byte-compile incorrectly complains about this
6701 (link link-location)
6702 entry file)
6703 (cond
6704 (link-location) ; specified by arg, just use it.
6705 ((org-in-regexp org-bracket-link-regexp 1)
6706 ;; We do have a link at point, and we are going to edit it.
6707 (setq remove (list (match-beginning 0) (match-end 0)))
6708 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6709 (setq link (read-string "Link: "
6710 (org-link-unescape
6711 (org-match-string-no-properties 1)))))
6712 ((or (org-in-regexp org-angle-link-re)
6713 (org-in-regexp org-plain-link-re))
6714 ;; Convert to bracket link
6715 (setq remove (list (match-beginning 0) (match-end 0))
6716 link (read-string "Link: "
6717 (org-remove-angle-brackets (match-string 0)))))
6718 ((member complete-file '((4) (16)))
6719 ;; Completing read for file names.
6720 (setq file (read-file-name "File: "))
6721 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6722 (pwd1 (file-name-as-directory (abbreviate-file-name
6723 (expand-file-name ".")))))
6724 (cond
6725 ((equal complete-file '(16))
6726 (setq link (org-make-link
6727 "file:"
6728 (abbreviate-file-name (expand-file-name file)))))
6729 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6730 (setq link (org-make-link "file:" (match-string 1 file))))
6731 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6732 (expand-file-name file))
6733 (setq link (org-make-link
6734 "file:" (match-string 1 (expand-file-name file)))))
6735 (t (setq link (org-make-link "file:" file))))))
6737 ;; Read link, with completion for stored links.
6738 (with-output-to-temp-buffer "*Org Links*"
6739 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6740 (when org-stored-links
6741 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6742 (princ (mapconcat
6743 (lambda (x)
6744 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6745 (reverse org-stored-links) "\n"))))
6746 (let ((cw (selected-window)))
6747 (select-window (get-buffer-window "*Org Links*"))
6748 (setq truncate-lines t)
6749 (org-fit-window-to-buffer)
6750 (select-window cw))
6751 ;; Fake a link history, containing the stored links.
6752 (setq tmphist (append (mapcar 'car org-stored-links)
6753 org-insert-link-history))
6754 (unwind-protect
6755 (setq link
6756 (let ((org-completion-use-ido nil))
6757 (org-completing-read
6758 "Link: "
6759 (append
6760 (mapcar (lambda (x) (list (concat (car x) ":")))
6761 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6762 (mapcar (lambda (x) (list (concat x ":")))
6763 org-link-types))
6764 nil nil nil
6765 'tmphist
6766 (or (car (car org-stored-links))))))
6767 (set-window-configuration wcf)
6768 (kill-buffer "*Org Links*"))
6769 (setq entry (assoc link org-stored-links))
6770 (or entry (push link org-insert-link-history))
6771 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6772 (not org-keep-stored-link-after-insertion))
6773 (setq org-stored-links (delq (assoc link org-stored-links)
6774 org-stored-links)))
6775 (setq desc (or desc (nth 1 entry)))))
6777 (if (string-match org-plain-link-re link)
6778 ;; URL-like link, normalize the use of angular brackets.
6779 (setq link (org-make-link (org-remove-angle-brackets link))))
6781 ;; Check if we are linking to the current file with a search option
6782 ;; If yes, simplify the link by using only the search option.
6783 (when (and buffer-file-name
6784 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6785 (let* ((path (match-string 1 link))
6786 (case-fold-search nil)
6787 (search (match-string 2 link)))
6788 (save-match-data
6789 (if (equal (file-truename buffer-file-name) (file-truename path))
6790 ;; We are linking to this same file, with a search option
6791 (setq link search)))))
6793 ;; Check if we can/should use a relative path. If yes, simplify the link
6794 (when (string-match "^file:\\(.*\\)" link)
6795 (let* ((path (match-string 1 link))
6796 (origpath path)
6797 (case-fold-search nil))
6798 (cond
6799 ((or (eq org-link-file-path-type 'absolute)
6800 (equal complete-file '(16)))
6801 (setq path (abbreviate-file-name (expand-file-name path))))
6802 ((eq org-link-file-path-type 'noabbrev)
6803 (setq path (expand-file-name path)))
6804 ((eq org-link-file-path-type 'relative)
6805 (setq path (file-relative-name path)))
6807 (save-match-data
6808 (if (string-match (concat "^" (regexp-quote
6809 (file-name-as-directory
6810 (expand-file-name "."))))
6811 (expand-file-name path))
6812 ;; We are linking a file with relative path name.
6813 (setq path (substring (expand-file-name path)
6814 (match-end 0)))
6815 (setq path (abbreviate-file-name (expand-file-name path)))))))
6816 (setq link (concat "file:" path))
6817 (if (equal desc origpath)
6818 (setq desc path))))
6820 (if org-make-link-description-function
6821 (setq desc (funcall org-make-link-description-function link desc)))
6823 (setq desc (read-string "Description: " desc))
6824 (unless (string-match "\\S-" desc) (setq desc nil))
6825 (if remove (apply 'delete-region remove))
6826 (insert (org-make-link-string link desc))))
6828 (defun org-completing-read (&rest args)
6829 "Completing-read with SPACE being a normal character."
6830 (let ((minibuffer-local-completion-map
6831 (copy-keymap minibuffer-local-completion-map)))
6832 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6833 (apply 'org-ido-completing-read args)))
6835 (defun org-ido-completing-read (&rest args)
6836 "Completing-read using `ido-mode' speedups if available"
6837 (if (and org-completion-use-ido
6838 (fboundp 'ido-completing-read)
6839 (boundp 'ido-mode) ido-mode
6840 (listp (second args)))
6841 (apply 'ido-completing-read (concat (car args)) (cdr args))
6842 (apply 'completing-read args)))
6844 (defun org-extract-attributes (s)
6845 "Extract the attributes cookie from a string and set as text property."
6846 (let (a attr (start 0) key value)
6847 (save-match-data
6848 (when (string-match "{{\\([^}]+\\)}}$" s)
6849 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6850 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6851 (setq key (match-string 1 a) value (match-string 2 a)
6852 start (match-end 0)
6853 attr (plist-put attr (intern key) value))))
6854 (org-add-props s nil 'org-attr attr))
6857 (defun org-attributes-to-string (plist)
6858 "Format a property list into an HTML attribute list."
6859 (let ((s "") key value)
6860 (while plist
6861 (setq key (pop plist) value (pop plist))
6862 (and value
6863 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6866 ;;; Opening/following a link
6868 (defvar org-link-search-failed nil)
6870 (defun org-next-link ()
6871 "Move forward to the next link.
6872 If the link is in hidden text, expose it."
6873 (interactive)
6874 (when (and org-link-search-failed (eq this-command last-command))
6875 (goto-char (point-min))
6876 (message "Link search wrapped back to beginning of buffer"))
6877 (setq org-link-search-failed nil)
6878 (let* ((pos (point))
6879 (ct (org-context))
6880 (a (assoc :link ct)))
6881 (if a (goto-char (nth 2 a)))
6882 (if (re-search-forward org-any-link-re nil t)
6883 (progn
6884 (goto-char (match-beginning 0))
6885 (if (org-invisible-p) (org-show-context)))
6886 (goto-char pos)
6887 (setq org-link-search-failed t)
6888 (error "No further link found"))))
6890 (defun org-previous-link ()
6891 "Move backward to the previous link.
6892 If the link is in hidden text, expose it."
6893 (interactive)
6894 (when (and org-link-search-failed (eq this-command last-command))
6895 (goto-char (point-max))
6896 (message "Link search wrapped back to end of buffer"))
6897 (setq org-link-search-failed nil)
6898 (let* ((pos (point))
6899 (ct (org-context))
6900 (a (assoc :link ct)))
6901 (if a (goto-char (nth 1 a)))
6902 (if (re-search-backward org-any-link-re nil t)
6903 (progn
6904 (goto-char (match-beginning 0))
6905 (if (org-invisible-p) (org-show-context)))
6906 (goto-char pos)
6907 (setq org-link-search-failed t)
6908 (error "No further link found"))))
6910 (defun org-translate-link (s)
6911 "Translate a link string if a translation function has been defined."
6912 (if (and org-link-translation-function
6913 (fboundp org-link-translation-function)
6914 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6915 (progn
6916 (setq s (funcall org-link-translation-function
6917 (match-string 1) (match-string 2)))
6918 (concat (car s) ":" (cdr s)))
6921 (defun org-translate-link-from-planner (type path)
6922 "Translate a link from Emacs Planner syntax so that Org can follow it.
6923 This is still an experimental function, your mileage may vary."
6924 (cond
6925 ((member type '("http" "https" "news" "ftp"))
6926 ;; standard Internet links are the same.
6927 nil)
6928 ((and (equal type "irc") (string-match "^//" path))
6929 ;; Planner has two / at the beginning of an irc link, we have 1.
6930 ;; We should have zero, actually....
6931 (setq path (substring path 1)))
6932 ((and (equal type "lisp") (string-match "^/" path))
6933 ;; Planner has a slash, we do not.
6934 (setq type "elisp" path (substring path 1)))
6935 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6936 ;; A typical message link. Planner has the id after the fina slash,
6937 ;; we separate it with a hash mark
6938 (setq path (concat (match-string 1 path) "#"
6939 (org-remove-angle-brackets (match-string 2 path)))))
6941 (cons type path))
6943 (defun org-find-file-at-mouse (ev)
6944 "Open file link or URL at mouse."
6945 (interactive "e")
6946 (mouse-set-point ev)
6947 (org-open-at-point 'in-emacs))
6949 (defun org-open-at-mouse (ev)
6950 "Open file link or URL at mouse."
6951 (interactive "e")
6952 (mouse-set-point ev)
6953 (if (eq major-mode 'org-agenda-mode)
6954 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6955 (org-open-at-point))
6957 (defvar org-window-config-before-follow-link nil
6958 "The window configuration before following a link.
6959 This is saved in case the need arises to restore it.")
6961 (defvar org-open-link-marker (make-marker)
6962 "Marker pointing to the location where `org-open-at-point; was called.")
6964 ;;;###autoload
6965 (defun org-open-at-point-global ()
6966 "Follow a link like Org-mode does.
6967 This command can be called in any mode to follow a link that has
6968 Org-mode syntax."
6969 (interactive)
6970 (org-run-like-in-org-mode 'org-open-at-point))
6972 ;;;###autoload
6973 (defun org-open-link-from-string (s &optional arg)
6974 "Open a link in the string S, as if it was in Org-mode."
6975 (interactive "sLink: \nP")
6976 (with-temp-buffer
6977 (let ((org-inhibit-startup t))
6978 (org-mode)
6979 (insert s)
6980 (goto-char (point-min))
6981 (org-open-at-point arg))))
6983 (defun org-open-at-point (&optional in-emacs)
6984 "Open link at or after point.
6985 If there is no link at point, this function will search forward up to
6986 the end of the current subtree.
6987 Normally, files will be opened by an appropriate application. If the
6988 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6989 With a double prefix argument, try to open outside of Emacs, in the
6990 application the system uses for this file type."
6991 (interactive "P")
6992 (org-load-modules-maybe)
6993 (move-marker org-open-link-marker (point))
6994 (setq org-window-config-before-follow-link (current-window-configuration))
6995 (org-remove-occur-highlights nil nil t)
6996 (cond
6997 ((org-at-timestamp-p t) (org-follow-timestamp-link))
6998 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
6999 (org-footnote-action))
7001 (let (type path link line search (pos (point)))
7002 (catch 'match
7003 (save-excursion
7004 (skip-chars-forward "^]\n\r")
7005 (when (org-in-regexp org-bracket-link-regexp)
7006 (setq link (org-extract-attributes
7007 (org-link-unescape (org-match-string-no-properties 1))))
7008 (while (string-match " *\n *" link)
7009 (setq link (replace-match " " t t link)))
7010 (setq link (org-link-expand-abbrev link))
7011 (cond
7012 ((or (file-name-absolute-p link)
7013 (string-match "^\\.\\.?/" link))
7014 (setq type "file" path link))
7015 ((string-match org-link-re-with-space3 link)
7016 (setq type (match-string 1 link) path (match-string 2 link)))
7017 (t (setq type "thisfile" path link)))
7018 (throw 'match t)))
7020 (when (get-text-property (point) 'org-linked-text)
7021 (setq type "thisfile"
7022 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7023 (1+ (point)) (point))
7024 path (buffer-substring
7025 (previous-single-property-change pos 'org-linked-text)
7026 (next-single-property-change pos 'org-linked-text)))
7027 (throw 'match t))
7029 (save-excursion
7030 (when (or (org-in-regexp org-angle-link-re)
7031 (org-in-regexp org-plain-link-re))
7032 (setq type (match-string 1) path (match-string 2))
7033 (throw 'match t)))
7034 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7035 (setq type "tree-match"
7036 path (match-string 1))
7037 (throw 'match t))
7038 (save-excursion
7039 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7040 (setq type "tags"
7041 path (match-string 1))
7042 (while (string-match ":" path)
7043 (setq path (replace-match "+" t t path)))
7044 (throw 'match t))))
7045 (unless path
7046 (error "No link found"))
7047 ;; Remove any trailing spaces in path
7048 (if (string-match " +\\'" path)
7049 (setq path (replace-match "" t t path)))
7050 (if (and org-link-translation-function
7051 (fboundp org-link-translation-function))
7052 ;; Check if we need to translate the link
7053 (let ((tmp (funcall org-link-translation-function type path)))
7054 (setq type (car tmp) path (cdr tmp))))
7056 (cond
7058 ((assoc type org-link-protocols)
7059 (funcall (nth 1 (assoc type org-link-protocols)) path))
7061 ((equal type "mailto")
7062 (let ((cmd (car org-link-mailto-program))
7063 (args (cdr org-link-mailto-program)) args1
7064 (address path) (subject "") a)
7065 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7066 (setq address (match-string 1 path)
7067 subject (org-link-escape (match-string 2 path))))
7068 (while args
7069 (cond
7070 ((not (stringp (car args))) (push (pop args) args1))
7071 (t (setq a (pop args))
7072 (if (string-match "%a" a)
7073 (setq a (replace-match address t t a)))
7074 (if (string-match "%s" a)
7075 (setq a (replace-match subject t t a)))
7076 (push a args1))))
7077 (apply cmd (nreverse args1))))
7079 ((member type '("http" "https" "ftp" "news"))
7080 (browse-url (concat type ":" (org-link-escape
7081 path org-link-escape-chars-browser))))
7083 ((member type '("message"))
7084 (browse-url (concat type ":" path)))
7086 ((string= type "tags")
7087 (org-tags-view in-emacs path))
7088 ((string= type "thisfile")
7089 (if in-emacs
7090 (switch-to-buffer-other-window
7091 (org-get-buffer-for-internal-link (current-buffer)))
7092 (org-mark-ring-push))
7093 (let ((cmd `(org-link-search
7094 ,path
7095 ,(cond ((equal in-emacs '(4)) 'occur)
7096 ((equal in-emacs '(16)) 'org-occur)
7097 (t nil))
7098 ,pos)))
7099 (condition-case nil (eval cmd)
7100 (error (progn (widen) (eval cmd))))))
7102 ((string= type "tree-match")
7103 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7105 ((string= type "file")
7106 (if (string-match "::\\([0-9]+\\)\\'" path)
7107 (setq line (string-to-number (match-string 1 path))
7108 path (substring path 0 (match-beginning 0)))
7109 (if (string-match "::\\(.+\\)\\'" path)
7110 (setq search (match-string 1 path)
7111 path (substring path 0 (match-beginning 0)))))
7112 (if (string-match "[*?{]" (file-name-nondirectory path))
7113 (dired path)
7114 (org-open-file path in-emacs line search)))
7116 ((string= type "news")
7117 (require 'org-gnus)
7118 (org-gnus-follow-link path))
7120 ((string= type "shell")
7121 (let ((cmd path))
7122 (if (or (not org-confirm-shell-link-function)
7123 (funcall org-confirm-shell-link-function
7124 (format "Execute \"%s\" in shell? "
7125 (org-add-props cmd nil
7126 'face 'org-warning))))
7127 (progn
7128 (message "Executing %s" cmd)
7129 (shell-command cmd))
7130 (error "Abort"))))
7132 ((string= type "elisp")
7133 (let ((cmd path))
7134 (if (or (not org-confirm-elisp-link-function)
7135 (funcall org-confirm-elisp-link-function
7136 (format "Execute \"%s\" as elisp? "
7137 (org-add-props cmd nil
7138 'face 'org-warning))))
7139 (message "%s => %s" cmd
7140 (if (equal (string-to-char cmd) ?\()
7141 (eval (read cmd))
7142 (call-interactively (read cmd))))
7143 (error "Abort"))))
7146 (browse-url-at-point))))))
7147 (move-marker org-open-link-marker nil)
7148 (run-hook-with-args 'org-follow-link-hook))
7150 ;;;; Time estimates
7152 (defun org-get-effort (&optional pom)
7153 "Get the effort estimate for the current entry."
7154 (org-entry-get pom org-effort-property))
7156 ;;; File search
7158 (defvar org-create-file-search-functions nil
7159 "List of functions to construct the right search string for a file link.
7160 These functions are called in turn with point at the location to
7161 which the link should point.
7163 A function in the hook should first test if it would like to
7164 handle this file type, for example by checking the major-mode or
7165 the file extension. If it decides not to handle this file, it
7166 should just return nil to give other functions a chance. If it
7167 does handle the file, it must return the search string to be used
7168 when following the link. The search string will be part of the
7169 file link, given after a double colon, and `org-open-at-point'
7170 will automatically search for it. If special measures must be
7171 taken to make the search successful, another function should be
7172 added to the companion hook `org-execute-file-search-functions',
7173 which see.
7175 A function in this hook may also use `setq' to set the variable
7176 `description' to provide a suggestion for the descriptive text to
7177 be used for this link when it gets inserted into an Org-mode
7178 buffer with \\[org-insert-link].")
7180 (defvar org-execute-file-search-functions nil
7181 "List of functions to execute a file search triggered by a link.
7183 Functions added to this hook must accept a single argument, the
7184 search string that was part of the file link, the part after the
7185 double colon. The function must first check if it would like to
7186 handle this search, for example by checking the major-mode or the
7187 file extension. If it decides not to handle this search, it
7188 should just return nil to give other functions a chance. If it
7189 does handle the search, it must return a non-nil value to keep
7190 other functions from trying.
7192 Each function can access the current prefix argument through the
7193 variable `current-prefix-argument'. Note that a single prefix is
7194 used to force opening a link in Emacs, so it may be good to only
7195 use a numeric or double prefix to guide the search function.
7197 In case this is needed, a function in this hook can also restore
7198 the window configuration before `org-open-at-point' was called using:
7200 (set-window-configuration org-window-config-before-follow-link)")
7202 (defun org-link-search (s &optional type avoid-pos)
7203 "Search for a link search option.
7204 If S is surrounded by forward slashes, it is interpreted as a
7205 regular expression. In org-mode files, this will create an `org-occur'
7206 sparse tree. In ordinary files, `occur' will be used to list matches.
7207 If the current buffer is in `dired-mode', grep will be used to search
7208 in all files. If AVOID-POS is given, ignore matches near that position."
7209 (let ((case-fold-search t)
7210 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7211 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7212 (append '(("") (" ") ("\t") ("\n"))
7213 org-emphasis-alist)
7214 "\\|") "\\)"))
7215 (pos (point))
7216 (pre nil) (post nil)
7217 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7218 (cond
7219 ;; First check if there are any special
7220 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7221 ;; Now try the builtin stuff
7222 ((save-excursion
7223 (goto-char (point-min))
7224 (and
7225 (re-search-forward
7226 (concat "<<" (regexp-quote s0) ">>") nil t)
7227 (setq type 'dedicated
7228 pos (match-beginning 0))))
7229 ;; There is an exact target for this
7230 (goto-char pos))
7231 ((and (string-match "^(\\(.*\\))$" s0)
7232 (save-excursion
7233 (goto-char (point-min))
7234 (and
7235 (re-search-forward
7236 (concat "[^[]" (regexp-quote
7237 (format org-coderef-label-format
7238 (match-string 1 s0))))
7239 nil t)
7240 (setq type 'dedicated
7241 pos (1+ (match-beginning 0))))))
7242 ;; There is a coderef target for this
7243 (goto-char pos))
7244 ((string-match "^/\\(.*\\)/$" s)
7245 ;; A regular expression
7246 (cond
7247 ((org-mode-p)
7248 (org-occur (match-string 1 s)))
7249 ;;((eq major-mode 'dired-mode)
7250 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7251 (t (org-do-occur (match-string 1 s)))))
7253 ;; A normal search strings
7254 (when (equal (string-to-char s) ?*)
7255 ;; Anchor on headlines, post may include tags.
7256 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7257 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7258 s (substring s 1)))
7259 (remove-text-properties
7260 0 (length s)
7261 '(face nil mouse-face nil keymap nil fontified nil) s)
7262 ;; Make a series of regular expressions to find a match
7263 (setq words (org-split-string s "[ \n\r\t]+")
7265 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7266 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7267 "\\)" markers)
7268 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7269 re2a (concat "[ \t\r\n]" re2a_)
7270 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7271 re4 (concat "[^a-zA-Z_]" re4_)
7273 re1 (concat pre re2 post)
7274 re3 (concat pre (if pre re4_ re4) post)
7275 re5 (concat pre ".*" re4)
7276 re2 (concat pre re2)
7277 re2a (concat pre (if pre re2a_ re2a))
7278 re4 (concat pre (if pre re4_ re4))
7279 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7280 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7281 re5 "\\)"
7283 (cond
7284 ((eq type 'org-occur) (org-occur reall))
7285 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7286 (t (goto-char (point-min))
7287 (setq type 'fuzzy)
7288 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7289 (org-search-not-self 1 re1 nil t)
7290 (org-search-not-self 1 re2 nil t)
7291 (org-search-not-self 1 re2a nil t)
7292 (org-search-not-self 1 re3 nil t)
7293 (org-search-not-self 1 re4 nil t)
7294 (org-search-not-self 1 re5 nil t)
7296 (goto-char (match-beginning 1))
7297 (goto-char pos)
7298 (error "No match")))))
7300 ;; Normal string-search
7301 (goto-char (point-min))
7302 (if (search-forward s nil t)
7303 (goto-char (match-beginning 0))
7304 (error "No match"))))
7305 (and (org-mode-p) (org-show-context 'link-search))
7306 type))
7308 (defun org-search-not-self (group &rest args)
7309 "Execute `re-search-forward', but only accept matches that do not
7310 enclose the position of `org-open-link-marker'."
7311 (let ((m org-open-link-marker))
7312 (catch 'exit
7313 (while (apply 're-search-forward args)
7314 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7315 (goto-char (match-end group))
7316 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7317 (> (match-beginning 0) (marker-position m))
7318 (< (match-end 0) (marker-position m)))
7319 (save-match-data
7320 (or (not (org-in-regexp
7321 org-bracket-link-analytic-regexp 1))
7322 (not (match-end 4)) ; no description
7323 (and (<= (match-beginning 4) (point))
7324 (>= (match-end 4) (point))))))
7325 (throw 'exit (point))))))))
7327 (defun org-get-buffer-for-internal-link (buffer)
7328 "Return a buffer to be used for displaying the link target of internal links."
7329 (cond
7330 ((not org-display-internal-link-with-indirect-buffer)
7331 buffer)
7332 ((string-match "(Clone)$" (buffer-name buffer))
7333 (message "Buffer is already a clone, not making another one")
7334 ;; we also do not modify visibility in this case
7335 buffer)
7336 (t ; make a new indirect buffer for displaying the link
7337 (let* ((bn (buffer-name buffer))
7338 (ibn (concat bn "(Clone)"))
7339 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7340 (with-current-buffer ib (org-overview))
7341 ib))))
7343 (defun org-do-occur (regexp &optional cleanup)
7344 "Call the Emacs command `occur'.
7345 If CLEANUP is non-nil, remove the printout of the regular expression
7346 in the *Occur* buffer. This is useful if the regex is long and not useful
7347 to read."
7348 (occur regexp)
7349 (when cleanup
7350 (let ((cwin (selected-window)) win beg end)
7351 (when (setq win (get-buffer-window "*Occur*"))
7352 (select-window win))
7353 (goto-char (point-min))
7354 (when (re-search-forward "match[a-z]+" nil t)
7355 (setq beg (match-end 0))
7356 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7357 (setq end (1- (match-beginning 0)))))
7358 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7359 (goto-char (point-min))
7360 (select-window cwin))))
7362 ;;; The mark ring for links jumps
7364 (defvar org-mark-ring nil
7365 "Mark ring for positions before jumps in Org-mode.")
7366 (defvar org-mark-ring-last-goto nil
7367 "Last position in the mark ring used to go back.")
7368 ;; Fill and close the ring
7369 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7370 (loop for i from 1 to org-mark-ring-length do
7371 (push (make-marker) org-mark-ring))
7372 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7373 org-mark-ring)
7375 (defun org-mark-ring-push (&optional pos buffer)
7376 "Put the current position or POS into the mark ring and rotate it."
7377 (interactive)
7378 (setq pos (or pos (point)))
7379 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7380 (move-marker (car org-mark-ring)
7381 (or pos (point))
7382 (or buffer (current-buffer)))
7383 (message "%s"
7384 (substitute-command-keys
7385 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7387 (defun org-mark-ring-goto (&optional n)
7388 "Jump to the previous position in the mark ring.
7389 With prefix arg N, jump back that many stored positions. When
7390 called several times in succession, walk through the entire ring.
7391 Org-mode commands jumping to a different position in the current file,
7392 or to another Org-mode file, automatically push the old position
7393 onto the ring."
7394 (interactive "p")
7395 (let (p m)
7396 (if (eq last-command this-command)
7397 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7398 (setq p org-mark-ring))
7399 (setq org-mark-ring-last-goto p)
7400 (setq m (car p))
7401 (switch-to-buffer (marker-buffer m))
7402 (goto-char m)
7403 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7405 (defun org-remove-angle-brackets (s)
7406 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7407 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7409 (defun org-add-angle-brackets (s)
7410 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7411 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7413 (defun org-remove-double-quotes (s)
7414 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7415 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7418 ;;; Following specific links
7420 (defun org-follow-timestamp-link ()
7421 (cond
7422 ((org-at-date-range-p t)
7423 (let ((org-agenda-start-on-weekday)
7424 (t1 (match-string 1))
7425 (t2 (match-string 2)))
7426 (setq t1 (time-to-days (org-time-string-to-time t1))
7427 t2 (time-to-days (org-time-string-to-time t2)))
7428 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7429 ((org-at-timestamp-p t)
7430 (org-agenda-list nil (time-to-days (org-time-string-to-time
7431 (substring (match-string 1) 0 10)))
7433 (t (error "This should not happen"))))
7436 ;;; Following file links
7437 (defvar org-wait nil)
7438 (defun org-open-file (path &optional in-emacs line search)
7439 "Open the file at PATH.
7440 First, this expands any special file name abbreviations. Then the
7441 configuration variable `org-file-apps' is checked if it contains an
7442 entry for this file type, and if yes, the corresponding command is launched.
7444 If no application is found, Emacs simply visits the file.
7446 With optional prefix argument IN-EMACS, Emacs will visit the file.
7447 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7448 and o use an external application to visit the file.
7450 Optional LINE specifies a line to go to, optional SEARCH a string to
7451 search for. If LINE or SEARCH is given, the file will always be
7452 opened in Emacs.
7453 If the file does not exist, an error is thrown."
7454 (setq in-emacs (or in-emacs line search))
7455 (let* ((file (if (equal path "")
7456 buffer-file-name
7457 (substitute-in-file-name (expand-file-name path))))
7458 (apps (append org-file-apps (org-default-apps)))
7459 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7460 (dirp (if remp nil (file-directory-p file)))
7461 (file (if (and dirp org-open-directory-means-index-dot-org)
7462 (concat (file-name-as-directory file) "index.org")
7463 file))
7464 (a-m-a-p (assq 'auto-mode apps))
7465 (dfile (downcase file))
7466 (old-buffer (current-buffer))
7467 (old-pos (point))
7468 (old-mode major-mode)
7469 ext cmd)
7470 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7471 (setq ext (match-string 1 dfile))
7472 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7473 (setq ext (match-string 1 dfile))))
7474 (cond
7475 ((equal in-emacs '(16))
7476 (setq cmd (cdr (assoc 'system apps))))
7477 (in-emacs (setq cmd 'emacs))
7479 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7480 (and dirp (cdr (assoc 'directory apps)))
7481 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7482 'string-match)
7483 (cdr (assoc ext apps))
7484 (cdr (assoc t apps))))))
7485 (when (eq cmd 'system)
7486 (setq cmd (cdr (assoc 'system apps))))
7487 (when (eq cmd 'default)
7488 (setq cmd (cdr (assoc t apps))))
7489 (when (eq cmd 'mailcap)
7490 (require 'mailcap)
7491 (mailcap-parse-mailcaps)
7492 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7493 (command (mailcap-mime-info mime-type)))
7494 (if (stringp command)
7495 (setq cmd command)
7496 (setq cmd 'emacs))))
7497 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7498 (not (file-exists-p file))
7499 (not org-open-non-existing-files))
7500 (error "No such file: %s" file))
7501 (cond
7502 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7503 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7504 (while (string-match "['\"]%s['\"]" cmd)
7505 (setq cmd (replace-match "%s" t t cmd)))
7506 (while (string-match "%s" cmd)
7507 (setq cmd (replace-match
7508 (save-match-data
7509 (shell-quote-argument
7510 (convert-standard-filename file)))
7511 t t cmd)))
7512 (save-window-excursion
7513 (start-process-shell-command cmd nil cmd)
7514 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7516 ((or (stringp cmd)
7517 (eq cmd 'emacs))
7518 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7519 (widen)
7520 (if line (goto-line line)
7521 (if search (org-link-search search))))
7522 ((consp cmd)
7523 (let ((file (convert-standard-filename file)))
7524 (eval cmd)))
7525 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7526 (and (org-mode-p) (eq old-mode 'org-mode)
7527 (or (not (equal old-buffer (current-buffer)))
7528 (not (equal old-pos (point))))
7529 (org-mark-ring-push old-pos old-buffer))))
7531 (defun org-default-apps ()
7532 "Return the default applications for this operating system."
7533 (cond
7534 ((eq system-type 'darwin)
7535 org-file-apps-defaults-macosx)
7536 ((eq system-type 'windows-nt)
7537 org-file-apps-defaults-windowsnt)
7538 (t org-file-apps-defaults-gnu)))
7540 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7541 "Convert extensions to regular expressions in the cars of LIST.
7542 Also, weed out any non-string entries, because the return value is used
7543 only for regexp matching.
7544 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7545 point to the symbol `emacs', indicating that the file should
7546 be opened in Emacs."
7547 (append
7548 (delq nil
7549 (mapcar (lambda (x)
7550 (if (not (stringp (car x)))
7552 (if (string-match "\\W" (car x))
7554 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7555 list))
7556 (if add-auto-mode
7557 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7559 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7560 (defun org-file-remote-p (file)
7561 "Test whether FILE specifies a location on a remote system.
7562 Return non-nil if the location is indeed remote.
7564 For example, the filename \"/user@host:/foo\" specifies a location
7565 on the system \"/user@host:\"."
7566 (cond ((fboundp 'file-remote-p)
7567 (file-remote-p file))
7568 ((fboundp 'tramp-handle-file-remote-p)
7569 (tramp-handle-file-remote-p file))
7570 ((and (boundp 'ange-ftp-name-format)
7571 (string-match (car ange-ftp-name-format) file))
7573 (t nil)))
7576 ;;;; Refiling
7578 (defun org-get-org-file ()
7579 "Read a filename, with default directory `org-directory'."
7580 (let ((default (or org-default-notes-file remember-data-file)))
7581 (read-file-name (format "File name [%s]: " default)
7582 (file-name-as-directory org-directory)
7583 default)))
7585 (defun org-notes-order-reversed-p ()
7586 "Check if the current file should receive notes in reversed order."
7587 (cond
7588 ((not org-reverse-note-order) nil)
7589 ((eq t org-reverse-note-order) t)
7590 ((not (listp org-reverse-note-order)) nil)
7591 (t (catch 'exit
7592 (let ((all org-reverse-note-order)
7593 entry)
7594 (while (setq entry (pop all))
7595 (if (string-match (car entry) buffer-file-name)
7596 (throw 'exit (cdr entry))))
7597 nil)))))
7599 (defvar org-refile-target-table nil
7600 "The list of refile targets, created by `org-refile'.")
7602 (defvar org-agenda-new-buffers nil
7603 "Buffers created to visit agenda files.")
7605 (defun org-get-refile-targets (&optional default-buffer)
7606 "Produce a table with refile targets."
7607 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7608 targets txt re files f desc descre fast-path-p level)
7609 (message "Getting targets...")
7610 (with-current-buffer (or default-buffer (current-buffer))
7611 (while (setq entry (pop entries))
7612 (setq files (car entry) desc (cdr entry))
7613 (setq fast-path-p nil)
7614 (cond
7615 ((null files) (setq files (list (current-buffer))))
7616 ((eq files 'org-agenda-files)
7617 (setq files (org-agenda-files 'unrestricted)))
7618 ((and (symbolp files) (fboundp files))
7619 (setq files (funcall files)))
7620 ((and (symbolp files) (boundp files))
7621 (setq files (symbol-value files))))
7622 (if (stringp files) (setq files (list files)))
7623 (cond
7624 ((eq (car desc) :tag)
7625 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7626 ((eq (car desc) :todo)
7627 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7628 ((eq (car desc) :regexp)
7629 (setq descre (cdr desc)))
7630 ((eq (car desc) :level)
7631 (setq descre (concat "^\\*\\{" (number-to-string
7632 (if org-odd-levels-only
7633 (1- (* 2 (cdr desc)))
7634 (cdr desc)))
7635 "\\}[ \t]")))
7636 ((eq (car desc) :maxlevel)
7637 (setq fast-path-p t)
7638 (setq descre (concat "^\\*\\{1," (number-to-string
7639 (if org-odd-levels-only
7640 (1- (* 2 (cdr desc)))
7641 (cdr desc)))
7642 "\\}[ \t]")))
7643 (t (error "Bad refiling target description %s" desc)))
7644 (while (setq f (pop files))
7645 (save-excursion
7646 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7647 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7648 (setq f (expand-file-name f))
7649 (save-excursion
7650 (save-restriction
7651 (widen)
7652 (goto-char (point-min))
7653 (while (re-search-forward descre nil t)
7654 (goto-char (point-at-bol))
7655 (when (looking-at org-complex-heading-regexp)
7656 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7657 txt (org-link-display-format (match-string 4))
7658 re (concat "^" (regexp-quote
7659 (buffer-substring (match-beginning 1)
7660 (match-end 4)))))
7661 (if (match-end 5) (setq re (concat re "[ \t]+"
7662 (regexp-quote
7663 (match-string 5)))))
7664 (setq re (concat re "[ \t]*$"))
7665 (when org-refile-use-outline-path
7666 (setq txt (mapconcat 'org-protect-slash
7667 (append
7668 (if (eq org-refile-use-outline-path 'file)
7669 (list (file-name-nondirectory
7670 (buffer-file-name (buffer-base-buffer))))
7671 (if (eq org-refile-use-outline-path 'full-file-path)
7672 (list (buffer-file-name (buffer-base-buffer)))))
7673 (org-get-outline-path fast-path-p level txt)
7674 (list txt))
7675 "/")))
7676 (push (list txt f re (point)) targets))
7677 (goto-char (point-at-eol))))))))
7678 (message "Getting targets...done")
7679 (nreverse targets))))
7681 (defun org-protect-slash (s)
7682 (while (string-match "/" s)
7683 (setq s (replace-match "\\" t t s)))
7686 (defvar org-olpa (make-vector 20 nil))
7688 (defun org-get-outline-path (&optional fastp level heading)
7689 "Return the outline path to the current entry, as a list."
7690 (if fastp
7691 (progn
7692 (if (> level 19)
7693 (error "Outline path failure, more than 19 levels."))
7694 (loop for i from level upto 19 do
7695 (aset org-olpa i nil))
7696 (prog1
7697 (delq nil (append org-olpa nil))
7698 (aset org-olpa level heading)))
7699 (let (rtn)
7700 (save-excursion
7701 (while (org-up-heading-safe)
7702 (when (looking-at org-complex-heading-regexp)
7703 (push (org-match-string-no-properties 4) rtn)))
7704 rtn))))
7706 (defvar org-refile-history nil
7707 "History for refiling operations.")
7709 (defun org-refile (&optional goto default-buffer)
7710 "Move the entry at point to another heading.
7711 The list of target headings is compiled using the information in
7712 `org-refile-targets', which see. This list is created before each use
7713 and will therefore always be up-to-date.
7715 At the target location, the entry is filed as a subitem of the target heading.
7716 Depending on `org-reverse-note-order', the new subitem will either be the
7717 first or the last subitem.
7719 If there is an active region, all entries in that region will be moved.
7720 However, the region must fulfil the requirement that the first heading
7721 is the first one sets the top-level of the moved text - at most siblings
7722 below it are allowed.
7724 With prefix arg GOTO, the command will only visit the target location,
7725 not actually move anything.
7726 With a double prefix `C-u C-u', go to the location where the last refiling
7727 operation has put the subtree."
7728 (interactive "P")
7729 (let* ((cbuf (current-buffer))
7730 (regionp (org-region-active-p))
7731 (region-start (and regionp (region-beginning)))
7732 (region-end (and regionp (region-end)))
7733 (region-length (and regionp (- region-end region-start)))
7734 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7735 pos it nbuf file re level reversed)
7736 (when regionp (goto-char region-start)
7737 (unless (org-kill-is-subtree-p
7738 (buffer-substring region-start region-end))
7739 (error "The region is not a (sequence of) subtree(s)")))
7740 (if (equal goto '(16))
7741 (org-refile-goto-last-stored)
7742 (when (setq it (org-refile-get-location
7743 (if goto "Goto: " "Refile to: ") default-buffer))
7744 (setq file (nth 1 it)
7745 re (nth 2 it)
7746 pos (nth 3 it))
7747 (if (and (equal (buffer-file-name) file)
7748 (if regionp
7749 (and (>= pos region-start)
7750 (<= pos region-end))
7751 (and (>= pos (point))
7752 (< pos (save-excursion
7753 (org-end-of-subtree t t))))))
7754 (error "Cannot refile to position inside the tree or region"))
7756 (setq nbuf (or (find-buffer-visiting file)
7757 (find-file-noselect file)))
7758 (if goto
7759 (progn
7760 (switch-to-buffer nbuf)
7761 (goto-char pos)
7762 (org-show-context 'org-goto))
7763 (if regionp
7764 (progn
7765 (kill-new (buffer-substring region-start region-end))
7766 (org-save-markers-in-region region-start region-end))
7767 (org-copy-subtree 1 nil t))
7768 (save-excursion
7769 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7770 (find-file-noselect file))))
7771 (setq reversed (org-notes-order-reversed-p))
7772 (save-excursion
7773 (save-restriction
7774 (widen)
7775 (goto-char pos)
7776 (looking-at outline-regexp)
7777 (setq level (org-get-valid-level (funcall outline-level) 1))
7778 (goto-char
7779 (if reversed
7780 (or (outline-next-heading) (point-max))
7781 (or (save-excursion (outline-get-next-sibling))
7782 (org-end-of-subtree t t)
7783 (point-max))))
7784 (if (not (bolp)) (newline))
7785 (bookmark-set "org-refile-last-stored")
7786 (org-paste-subtree level))))
7787 (if regionp
7788 (delete-region (point) (+ (point) region-length))
7789 (org-cut-subtree))
7790 (setq org-markers-to-move nil)
7791 (message "Refiled to \"%s\"" (car it)))))))
7793 (defun org-refile-goto-last-stored ()
7794 "Go to the location where the last refile was stored."
7795 (interactive)
7796 (bookmark-jump "org-refile-last-stored")
7797 (message "This is the location of the last refile"))
7799 (defun org-refile-get-location (&optional prompt default-buffer)
7800 "Prompt the user for a refile location, using PROMPT."
7801 (let ((org-refile-targets org-refile-targets)
7802 (org-refile-use-outline-path org-refile-use-outline-path))
7803 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7804 (unless org-refile-target-table
7805 (error "No refile targets"))
7806 (let* ((cbuf (current-buffer))
7807 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7808 (cfunc (if (and org-refile-use-outline-path
7809 org-outline-path-complete-in-steps)
7810 'org-olpath-completing-read
7811 'org-ido-completing-read))
7812 (extra (if org-refile-use-outline-path "/" ""))
7813 (filename (and cfn (expand-file-name cfn)))
7814 (tbl (mapcar
7815 (lambda (x)
7816 (if (not (equal filename (nth 1 x)))
7817 (cons (concat (car x) extra " ("
7818 (file-name-nondirectory (nth 1 x)) ")")
7819 (cdr x))
7820 (cons (concat (car x) extra) (cdr x))))
7821 org-refile-target-table))
7822 (completion-ignore-case t))
7823 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7824 tbl)))
7826 (defun org-olpath-completing-read (prompt collection &rest args)
7827 "Read an outline path like a file name."
7828 (let ((thetable collection))
7829 (apply
7830 'org-ido-completing-read prompt
7831 (lambda (string predicate &optional flag)
7832 (let (rtn r s f (l (length string)))
7833 (cond
7834 ((eq flag nil)
7835 ;; try completion
7836 (try-completion string thetable))
7837 ((eq flag t)
7838 ;; all-completions
7839 (setq rtn (all-completions string thetable predicate))
7840 (mapcar
7841 (lambda (x)
7842 (setq r (substring x l))
7843 (if (string-match " ([^)]*)$" x)
7844 (setq f (match-string 0 x))
7845 (setq f ""))
7846 (if (string-match "/" r)
7847 (concat string (substring r 0 (match-end 0)) f)
7849 rtn))
7850 ((eq flag 'lambda)
7851 ;; exact match?
7852 (assoc string thetable)))
7854 args)))
7856 ;;;; Dynamic blocks
7858 (defun org-find-dblock (name)
7859 "Find the first dynamic block with name NAME in the buffer.
7860 If not found, stay at current position and return nil."
7861 (let (pos)
7862 (save-excursion
7863 (goto-char (point-min))
7864 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7865 nil t)
7866 (match-beginning 0))))
7867 (if pos (goto-char pos))
7868 pos))
7870 (defconst org-dblock-start-re
7871 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7872 "Matches the startline of a dynamic block, with parameters.")
7874 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7875 "Matches the end of a dynamic block.")
7877 (defun org-create-dblock (plist)
7878 "Create a dynamic block section, with parameters taken from PLIST.
7879 PLIST must contain a :name entry which is used as name of the block."
7880 (unless (bolp) (newline))
7881 (let ((name (plist-get plist :name)))
7882 (insert "#+BEGIN: " name)
7883 (while plist
7884 (if (eq (car plist) :name)
7885 (setq plist (cddr plist))
7886 (insert " " (prin1-to-string (pop plist)))))
7887 (insert "\n\n#+END:\n")
7888 (beginning-of-line -2)))
7890 (defun org-prepare-dblock ()
7891 "Prepare dynamic block for refresh.
7892 This empties the block, puts the cursor at the insert position and returns
7893 the property list including an extra property :name with the block name."
7894 (unless (looking-at org-dblock-start-re)
7895 (error "Not at a dynamic block"))
7896 (let* ((begdel (1+ (match-end 0)))
7897 (name (org-no-properties (match-string 1)))
7898 (params (append (list :name name)
7899 (read (concat "(" (match-string 3) ")")))))
7900 (unless (re-search-forward org-dblock-end-re nil t)
7901 (error "Dynamic block not terminated"))
7902 (setq params
7903 (append params
7904 (list :content (buffer-substring
7905 begdel (match-beginning 0)))))
7906 (delete-region begdel (match-beginning 0))
7907 (goto-char begdel)
7908 (open-line 1)
7909 params))
7911 (defun org-map-dblocks (&optional command)
7912 "Apply COMMAND to all dynamic blocks in the current buffer.
7913 If COMMAND is not given, use `org-update-dblock'."
7914 (let ((cmd (or command 'org-update-dblock))
7915 pos)
7916 (save-excursion
7917 (goto-char (point-min))
7918 (while (re-search-forward org-dblock-start-re nil t)
7919 (goto-char (setq pos (match-beginning 0)))
7920 (condition-case nil
7921 (funcall cmd)
7922 (error (message "Error during update of dynamic block")))
7923 (goto-char pos)
7924 (unless (re-search-forward org-dblock-end-re nil t)
7925 (error "Dynamic block not terminated"))))))
7927 (defun org-dblock-update (&optional arg)
7928 "User command for updating dynamic blocks.
7929 Update the dynamic block at point. With prefix ARG, update all dynamic
7930 blocks in the buffer."
7931 (interactive "P")
7932 (if arg
7933 (org-update-all-dblocks)
7934 (or (looking-at org-dblock-start-re)
7935 (org-beginning-of-dblock))
7936 (org-update-dblock)))
7938 (defun org-update-dblock ()
7939 "Update the dynamic block at point
7940 This means to empty the block, parse for parameters and then call
7941 the correct writing function."
7942 (save-window-excursion
7943 (let* ((pos (point))
7944 (line (org-current-line))
7945 (params (org-prepare-dblock))
7946 (name (plist-get params :name))
7947 (cmd (intern (concat "org-dblock-write:" name))))
7948 (message "Updating dynamic block `%s' at line %d..." name line)
7949 (funcall cmd params)
7950 (message "Updating dynamic block `%s' at line %d...done" name line)
7951 (goto-char pos))))
7953 (defun org-beginning-of-dblock ()
7954 "Find the beginning of the dynamic block at point.
7955 Error if there is no such block at point."
7956 (let ((pos (point))
7957 beg)
7958 (end-of-line 1)
7959 (if (and (re-search-backward org-dblock-start-re nil t)
7960 (setq beg (match-beginning 0))
7961 (re-search-forward org-dblock-end-re nil t)
7962 (> (match-end 0) pos))
7963 (goto-char beg)
7964 (goto-char pos)
7965 (error "Not in a dynamic block"))))
7967 (defun org-update-all-dblocks ()
7968 "Update all dynamic blocks in the buffer.
7969 This function can be used in a hook."
7970 (when (org-mode-p)
7971 (org-map-dblocks 'org-update-dblock)))
7974 ;;;; Completion
7976 (defconst org-additional-option-like-keywords
7977 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7978 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7979 "BEGIN_EXAMPLE" "END_EXAMPLE"
7980 "BEGIN_QUOTE" "END_QUOTE"
7981 "BEGIN_VERSE" "END_VERSE"
7982 "BEGIN_SRC" "END_SRC"
7983 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7985 (defcustom org-structure-template-alist
7987 ("s" "#+begin_src ?\n\n#+end_src"
7988 "<src lang=\"?\">\n\n</src>")
7989 ("e" "#+begin_example\n?\n#+end_example"
7990 "<example>\n?\n</example>")
7991 ("q" "#+begin_quote\n?\n#+end_quote"
7992 "<quote>\n?\n</quote>")
7993 ("v" "#+begin_verse\n?\n#+end_verse"
7994 "<verse>\n?\n/verse>")
7995 ("l" "#+begin_latex\n?\n#+end_latex"
7996 "<literal style=\"latex\">\n?\n</literal>")
7997 ("L" "#+latex: "
7998 "<literal style=\"latex\">?</literal>")
7999 ("h" "#+begin_html\n?\n#+end_html"
8000 "<literal style=\"html\">\n?\n</literal>")
8001 ("H" "#+html: "
8002 "<literal style=\"html\">?</literal>")
8003 ("a" "#+begin_ascii\n?\n#+end_ascii")
8004 ("A" "#+ascii: ")
8005 ("i" "#+include %file ?"
8006 "<include file=%file markup=\"?\">")
8008 "Structure completion elements.
8009 This is a list of abbreviation keys and values. The value gets inserted
8010 it you type @samp{.} followed by the key and then the completion key,
8011 usually `M-TAB'. %file will be replaced by a file name after prompting
8012 for the file using completion.
8013 There are two templates for each key, the first uses the original Org syntax,
8014 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8015 the default when the /org-mtags.el/ module has been loaded. See also the
8016 variable `org-mtags-prefer-muse-templates'.
8017 This is an experimental feature, it is undecided if it is going to stay in."
8018 :group 'org-completion
8019 :type '(repeat
8020 (string :tag "Key")
8021 (string :tag "Template")
8022 (string :tag "Muse Template")))
8024 (defun org-try-structure-completion ()
8025 "Try to complete a structure template before point.
8026 This looks for strings like \"<e\" on an otherwise empty line and
8027 expands them."
8028 (let ((l (buffer-substring (point-at-bol) (point)))
8030 (when (and (looking-at "[ \t]*$")
8031 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8032 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8033 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8034 (match-beginning 1)) a)
8035 t)))
8037 (defun org-complete-expand-structure-template (start cell)
8038 "Expand a structure template."
8039 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8040 (rpl (nth (if musep 2 1) cell)))
8041 (delete-region start (point))
8042 (when (string-match "\\`#\\+" rpl)
8043 (cond
8044 ((bolp))
8045 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8046 (delete-region (point-at-bol) (point)))
8047 (t (newline))))
8048 (setq start (point))
8049 (if (string-match "%file" rpl)
8050 (setq rpl (replace-match
8051 (concat
8052 "\""
8053 (save-match-data
8054 (abbreviate-file-name (read-file-name "Include file: ")))
8055 "\"")
8056 t t rpl)))
8057 (insert rpl)
8058 (if (re-search-backward "\\?" start t) (delete-char 1))))
8061 (defun org-complete (&optional arg)
8062 "Perform completion on word at point.
8063 At the beginning of a headline, this completes TODO keywords as given in
8064 `org-todo-keywords'.
8065 If the current word is preceded by a backslash, completes the TeX symbols
8066 that are supported for HTML support.
8067 If the current word is preceded by \"#+\", completes special words for
8068 setting file options.
8069 In the line after \"#+STARTUP:, complete valid keywords.\"
8070 At all other locations, this simply calls the value of
8071 `org-completion-fallback-command'."
8072 (interactive "P")
8073 (org-without-partial-completion
8074 (catch 'exit
8075 (let* ((a nil)
8076 (end (point))
8077 (beg1 (save-excursion
8078 (skip-chars-backward (org-re "[:alnum:]_@"))
8079 (point)))
8080 (beg (save-excursion
8081 (skip-chars-backward "a-zA-Z0-9_:$")
8082 (point)))
8083 (confirm (lambda (x) (stringp (car x))))
8084 (searchhead (equal (char-before beg) ?*))
8085 (struct
8086 (when (and (member (char-before beg1) '(?. ?<))
8087 (setq a (assoc (buffer-substring beg1 (point))
8088 org-structure-template-alist)))
8089 (org-complete-expand-structure-template (1- beg1) a)
8090 (throw 'exit t)))
8091 (tag (and (equal (char-before beg1) ?:)
8092 (equal (char-after (point-at-bol)) ?*)))
8093 (prop (and (equal (char-before beg1) ?:)
8094 (not (equal (char-after (point-at-bol)) ?*))))
8095 (texp (equal (char-before beg) ?\\))
8096 (link (equal (char-before beg) ?\[))
8097 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8098 beg)
8099 "#+"))
8100 (startup (string-match "^#\\+STARTUP:.*"
8101 (buffer-substring (point-at-bol) (point))))
8102 (completion-ignore-case opt)
8103 (type nil)
8104 (tbl nil)
8105 (table (cond
8106 (opt
8107 (setq type :opt)
8108 (require 'org-exp)
8109 (append
8110 (mapcar
8111 (lambda (x)
8112 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8113 (cons (match-string 2 x) (match-string 1 x)))
8114 (org-split-string (org-get-current-options) "\n"))
8115 (mapcar 'list org-additional-option-like-keywords)))
8116 (startup
8117 (setq type :startup)
8118 org-startup-options)
8119 (link (append org-link-abbrev-alist-local
8120 org-link-abbrev-alist))
8121 (texp
8122 (setq type :tex)
8123 org-html-entities)
8124 ((string-match "\\`\\*+[ \t]+\\'"
8125 (buffer-substring (point-at-bol) beg))
8126 (setq type :todo)
8127 (mapcar 'list org-todo-keywords-1))
8128 (searchhead
8129 (setq type :searchhead)
8130 (save-excursion
8131 (goto-char (point-min))
8132 (while (re-search-forward org-todo-line-regexp nil t)
8133 (push (list
8134 (org-make-org-heading-search-string
8135 (match-string 3) t))
8136 tbl)))
8137 tbl)
8138 (tag (setq type :tag beg beg1)
8139 (or org-tag-alist (org-get-buffer-tags)))
8140 (prop (setq type :prop beg beg1)
8141 (mapcar 'list (org-buffer-property-keys nil t t)))
8142 (t (progn
8143 (call-interactively org-completion-fallback-command)
8144 (throw 'exit nil)))))
8145 (pattern (buffer-substring-no-properties beg end))
8146 (completion (try-completion pattern table confirm)))
8147 (cond ((eq completion t)
8148 (if (not (assoc (upcase pattern) table))
8149 (message "Already complete")
8150 (if (and (equal type :opt)
8151 (not (member (car (assoc (upcase pattern) table))
8152 org-additional-option-like-keywords)))
8153 (insert (substring (cdr (assoc (upcase pattern) table))
8154 (length pattern)))
8155 (if (memq type '(:tag :prop)) (insert ":")))))
8156 ((null completion)
8157 (message "Can't find completion for \"%s\"" pattern)
8158 (ding))
8159 ((not (string= pattern completion))
8160 (delete-region beg end)
8161 (if (string-match " +$" completion)
8162 (setq completion (replace-match "" t t completion)))
8163 (insert completion)
8164 (if (get-buffer-window "*Completions*")
8165 (delete-window (get-buffer-window "*Completions*")))
8166 (if (assoc completion table)
8167 (if (eq type :todo) (insert " ")
8168 (if (memq type '(:tag :prop)) (insert ":"))))
8169 (if (and (equal type :opt) (assoc completion table))
8170 (message "%s" (substitute-command-keys
8171 "Press \\[org-complete] again to insert example settings"))))
8173 (message "Making completion list...")
8174 (let ((list (sort (all-completions pattern table confirm)
8175 'string<)))
8176 (with-output-to-temp-buffer "*Completions*"
8177 (condition-case nil
8178 ;; Protection needed for XEmacs and emacs 21
8179 (display-completion-list list pattern)
8180 (error (display-completion-list list)))))
8181 (message "Making completion list...%s" "done")))))))
8183 ;;;; TODO, DEADLINE, Comments
8185 (defun org-toggle-comment ()
8186 "Change the COMMENT state of an entry."
8187 (interactive)
8188 (save-excursion
8189 (org-back-to-heading)
8190 (let (case-fold-search)
8191 (if (looking-at (concat outline-regexp
8192 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8193 (replace-match "" t t nil 1)
8194 (if (looking-at outline-regexp)
8195 (progn
8196 (goto-char (match-end 0))
8197 (insert org-comment-string " ")))))))
8199 (defvar org-last-todo-state-is-todo nil
8200 "This is non-nil when the last TODO state change led to a TODO state.
8201 If the last change removed the TODO tag or switched to DONE, then
8202 this is nil.")
8204 (defvar org-setting-tags nil) ; dynamically skipped
8206 (defun org-parse-local-options (string var)
8207 "Parse STRING for startup setting relevant for variable VAR."
8208 (let ((rtn (symbol-value var))
8209 e opts)
8210 (save-match-data
8211 (if (or (not string) (not (string-match "\\S-" string)))
8213 (setq opts (delq nil (mapcar (lambda (x)
8214 (setq e (assoc x org-startup-options))
8215 (if (eq (nth 1 e) var) e nil))
8216 (org-split-string string "[ \t]+"))))
8217 (if (not opts)
8219 (setq rtn nil)
8220 (while (setq e (pop opts))
8221 (if (not (nth 3 e))
8222 (setq rtn (nth 2 e))
8223 (if (not (listp rtn)) (setq rtn nil))
8224 (push (nth 2 e) rtn)))
8225 rtn)))))
8227 (defvar org-blocker-hook nil
8228 "Hook for functions that are allowed to block a state change.
8230 Each function gets as its single argument a property list, see
8231 `org-trigger-hook' for more information about this list.
8233 If any of the functions in this hook returns nil, the state change
8234 is blocked.")
8236 (defvar org-trigger-hook nil
8237 "Hook for functions that are triggered by a state change.
8239 Each function gets as its single argument a property list with at least
8240 the following elements:
8242 (:type type-of-change :position pos-at-entry-start
8243 :from old-state :to new-state)
8245 Depending on the type, more properties may be present.
8247 This mechanism is currently implemented for:
8249 TODO state changes
8250 ------------------
8251 :type todo-state-change
8252 :from previous state (keyword as a string), or nil
8253 :to new state (keyword as a string), or nil")
8255 (defvar org-agenda-headline-snapshot-before-repeat)
8256 (defun org-todo (&optional arg)
8257 "Change the TODO state of an item.
8258 The state of an item is given by a keyword at the start of the heading,
8259 like
8260 *** TODO Write paper
8261 *** DONE Call mom
8263 The different keywords are specified in the variable `org-todo-keywords'.
8264 By default the available states are \"TODO\" and \"DONE\".
8265 So for this example: when the item starts with TODO, it is changed to DONE.
8266 When it starts with DONE, the DONE is removed. And when neither TODO nor
8267 DONE are present, add TODO at the beginning of the heading.
8269 With C-u prefix arg, use completion to determine the new state.
8270 With numeric prefix arg, switch to that state.
8272 For calling through lisp, arg is also interpreted in the following way:
8273 'none -> empty state
8274 \"\"(empty string) -> switch to empty state
8275 'done -> switch to DONE
8276 'nextset -> switch to the next set of keywords
8277 'previousset -> switch to the previous set of keywords
8278 \"WAITING\" -> switch to the specified keyword, but only if it
8279 really is a member of `org-todo-keywords'."
8280 (interactive "P")
8281 (save-excursion
8282 (catch 'exit
8283 (org-back-to-heading)
8284 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8285 (or (looking-at (concat " +" org-todo-regexp " *"))
8286 (looking-at " *"))
8287 (let* ((match-data (match-data))
8288 (startpos (point-at-bol))
8289 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8290 (org-log-done org-log-done)
8291 (org-log-repeat org-log-repeat)
8292 (org-todo-log-states org-todo-log-states)
8293 (this (match-string 1))
8294 (hl-pos (match-beginning 0))
8295 (head (org-get-todo-sequence-head this))
8296 (ass (assoc head org-todo-kwd-alist))
8297 (interpret (nth 1 ass))
8298 (done-word (nth 3 ass))
8299 (final-done-word (nth 4 ass))
8300 (last-state (or this ""))
8301 (completion-ignore-case t)
8302 (member (member this org-todo-keywords-1))
8303 (tail (cdr member))
8304 (state (cond
8305 ((and org-todo-key-trigger
8306 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8307 (and (not arg) org-use-fast-todo-selection
8308 (not (eq org-use-fast-todo-selection 'prefix)))))
8309 ;; Use fast selection
8310 (org-fast-todo-selection))
8311 ((and (equal arg '(4))
8312 (or (not org-use-fast-todo-selection)
8313 (not org-todo-key-trigger)))
8314 ;; Read a state with completion
8315 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8316 org-todo-keywords-1)
8317 nil t))
8318 ((eq arg 'right)
8319 (if this
8320 (if tail (car tail) nil)
8321 (car org-todo-keywords-1)))
8322 ((eq arg 'left)
8323 (if (equal member org-todo-keywords-1)
8325 (if this
8326 (nth (- (length org-todo-keywords-1) (length tail) 2)
8327 org-todo-keywords-1)
8328 (org-last org-todo-keywords-1))))
8329 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8330 (setq arg nil))) ; hack to fall back to cycling
8331 (arg
8332 ;; user or caller requests a specific state
8333 (cond
8334 ((equal arg "") nil)
8335 ((eq arg 'none) nil)
8336 ((eq arg 'done) (or done-word (car org-done-keywords)))
8337 ((eq arg 'nextset)
8338 (or (car (cdr (member head org-todo-heads)))
8339 (car org-todo-heads)))
8340 ((eq arg 'previousset)
8341 (let ((org-todo-heads (reverse org-todo-heads)))
8342 (or (car (cdr (member head org-todo-heads)))
8343 (car org-todo-heads))))
8344 ((car (member arg org-todo-keywords-1)))
8345 ((nth (1- (prefix-numeric-value arg))
8346 org-todo-keywords-1))))
8347 ((null member) (or head (car org-todo-keywords-1)))
8348 ((equal this final-done-word) nil) ;; -> make empty
8349 ((null tail) nil) ;; -> first entry
8350 ((eq interpret 'sequence)
8351 (car tail))
8352 ((memq interpret '(type priority))
8353 (if (eq this-command last-command)
8354 (car tail)
8355 (if (> (length tail) 0)
8356 (or done-word (car org-done-keywords))
8357 nil)))
8358 (t nil)))
8359 (next (if state (concat " " state " ") " "))
8360 (change-plist (list :type 'todo-state-change :from this :to state
8361 :position startpos))
8362 dolog now-done-p)
8363 (when org-blocker-hook
8364 (unless (save-excursion
8365 (save-match-data
8366 (run-hook-with-args-until-failure
8367 'org-blocker-hook change-plist)))
8368 (if (interactive-p)
8369 (error "TODO state change from %s to %s blocked" this state)
8370 ;; fail silently
8371 (message "TODO state change from %s to %s blocked" this state)
8372 (throw 'exit nil))))
8373 (store-match-data match-data)
8374 (replace-match next t t)
8375 (unless (pos-visible-in-window-p hl-pos)
8376 (message "TODO state changed to %s" (org-trim next)))
8377 (unless head
8378 (setq head (org-get-todo-sequence-head state)
8379 ass (assoc head org-todo-kwd-alist)
8380 interpret (nth 1 ass)
8381 done-word (nth 3 ass)
8382 final-done-word (nth 4 ass)))
8383 (when (memq arg '(nextset previousset))
8384 (message "Keyword-Set %d/%d: %s"
8385 (- (length org-todo-sets) -1
8386 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8387 (length org-todo-sets)
8388 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8389 (setq org-last-todo-state-is-todo
8390 (not (member state org-done-keywords)))
8391 (setq now-done-p (and (member state org-done-keywords)
8392 (not (member this org-done-keywords))))
8393 (and logging (org-local-logging logging))
8394 (when (and (or org-todo-log-states org-log-done)
8395 (not (memq arg '(nextset previousset))))
8396 ;; we need to look at recording a time and note
8397 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8398 (nth 2 (assoc this org-todo-log-states))))
8399 (when (and state
8400 (member state org-not-done-keywords)
8401 (not (member this org-not-done-keywords)))
8402 ;; This is now a todo state and was not one before
8403 ;; If there was a CLOSED time stamp, get rid of it.
8404 (org-add-planning-info nil nil 'closed))
8405 (when (and now-done-p org-log-done)
8406 ;; It is now done, and it was not done before
8407 (org-add-planning-info 'closed (org-current-time))
8408 (if (and (not dolog) (eq 'note org-log-done))
8409 (org-add-log-setup 'done state 'findpos 'note)))
8410 (when (and state dolog)
8411 ;; This is a non-nil state, and we need to log it
8412 (org-add-log-setup 'state state 'findpos dolog)))
8413 ;; Fixup tag positioning
8414 (org-todo-trigger-tag-changes state)
8415 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8416 (when org-provide-todo-statistics
8417 (org-update-parent-todo-statistics))
8418 (run-hooks 'org-after-todo-state-change-hook)
8419 (if (and arg (not (member state org-done-keywords)))
8420 (setq head (org-get-todo-sequence-head state)))
8421 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8422 ;; Do we need to trigger a repeat?
8423 (when now-done-p
8424 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8425 ;; This is for the agenda, take a snapshot of the headline.
8426 (save-match-data
8427 (setq org-agenda-headline-snapshot-before-repeat
8428 (org-get-heading))))
8429 (org-auto-repeat-maybe state))
8430 ;; Fixup cursor location if close to the keyword
8431 (if (and (outline-on-heading-p)
8432 (not (bolp))
8433 (save-excursion (beginning-of-line 1)
8434 (looking-at org-todo-line-regexp))
8435 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8436 (progn
8437 (goto-char (or (match-end 2) (match-end 1)))
8438 (just-one-space)))
8439 (when org-trigger-hook
8440 (save-excursion
8441 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8443 (defun org-update-parent-todo-statistics ()
8444 "Update any statistics cookie in the parent of the current headline."
8445 (interactive)
8446 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8447 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8448 (catch 'exit
8449 (save-excursion
8450 (setq level (org-up-heading-safe))
8451 (unless (and level
8452 (re-search-forward box-re (point-at-eol) t))
8453 (throw 'exit nil))
8454 (setq is-percent (match-end 2))
8455 (save-match-data
8456 (unless (outline-next-heading) (throw 'exit nil))
8457 (while (looking-at org-todo-line-regexp)
8458 (setq kwd (match-string 2))
8459 (and kwd (setq cnt-all (1+ cnt-all)))
8460 (and (member kwd org-done-keywords)
8461 (setq cnt-done (1+ cnt-done)))
8462 (condition-case nil
8463 (org-forward-same-level 1)
8464 (error (end-of-line 1)))))
8465 (replace-match
8466 (if is-percent
8467 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8468 (format "[%d/%d]" cnt-done cnt-all)))
8469 (run-hook-with-args 'org-after-todo-statistics-hook
8470 cnt-done (- cnt-all cnt-done))))))
8472 (defvar org-after-todo-statistics-hook nil
8473 "Hook that is called after a TODO statistics cookie has been updated.
8474 Each function is called with two arguments: the number of not-done entries
8475 and the number of done entries.
8477 For example, the following function, when added to this hook, will switch
8478 an entry to DONE when all children are done, and back to TODO when new
8479 entries are set to a TODO status. Note that this hook is only called
8480 when there is a statistics cookie in the headline!
8482 (defun org-summary-todo (n-done n-not-done)
8483 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8484 (let (org-log-done org-log-states) ; turn off logging
8485 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8488 (defun org-todo-trigger-tag-changes (state)
8489 "Apply the changes defined in `org-todo-state-tags-triggers'."
8490 (let ((l org-todo-state-tags-triggers)
8491 changes)
8492 (when (or (not state) (equal state ""))
8493 (setq changes (append changes (cdr (assoc "" l)))))
8494 (when (and (stringp state) (> (length state) 0))
8495 (setq changes (append changes (cdr (assoc state l)))))
8496 (when (member state org-not-done-keywords)
8497 (setq changes (append changes (cdr (assoc 'todo l)))))
8498 (when (member state org-done-keywords)
8499 (setq changes (append changes (cdr (assoc 'done l)))))
8500 (dolist (c changes)
8501 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8503 (defun org-local-logging (value)
8504 "Get logging settings from a property VALUE."
8505 (let* (words w a)
8506 ;; directly set the variables, they are already local.
8507 (setq org-log-done nil
8508 org-log-repeat nil
8509 org-todo-log-states nil)
8510 (setq words (org-split-string value))
8511 (while (setq w (pop words))
8512 (cond
8513 ((setq a (assoc w org-startup-options))
8514 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8515 (set (nth 1 a) (nth 2 a))))
8516 ((setq a (org-extract-log-state-settings w))
8517 (and (member (car a) org-todo-keywords-1)
8518 (push a org-todo-log-states)))))))
8520 (defun org-get-todo-sequence-head (kwd)
8521 "Return the head of the TODO sequence to which KWD belongs.
8522 If KWD is not set, check if there is a text property remembering the
8523 right sequence."
8524 (let (p)
8525 (cond
8526 ((not kwd)
8527 (or (get-text-property (point-at-bol) 'org-todo-head)
8528 (progn
8529 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8530 nil (point-at-eol)))
8531 (get-text-property p 'org-todo-head))))
8532 ((not (member kwd org-todo-keywords-1))
8533 (car org-todo-keywords-1))
8534 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8536 (defun org-fast-todo-selection ()
8537 "Fast TODO keyword selection with single keys.
8538 Returns the new TODO keyword, or nil if no state change should occur."
8539 (let* ((fulltable org-todo-key-alist)
8540 (done-keywords org-done-keywords) ;; needed for the faces.
8541 (maxlen (apply 'max (mapcar
8542 (lambda (x)
8543 (if (stringp (car x)) (string-width (car x)) 0))
8544 fulltable)))
8545 (expert nil)
8546 (fwidth (+ maxlen 3 1 3))
8547 (ncol (/ (- (window-width) 4) fwidth))
8548 tg cnt e c tbl
8549 groups ingroup)
8550 (save-window-excursion
8551 (if expert
8552 (set-buffer (get-buffer-create " *Org todo*"))
8553 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8554 (erase-buffer)
8555 (org-set-local 'org-done-keywords done-keywords)
8556 (setq tbl fulltable cnt 0)
8557 (while (setq e (pop tbl))
8558 (cond
8559 ((equal e '(:startgroup))
8560 (push '() groups) (setq ingroup t)
8561 (when (not (= cnt 0))
8562 (setq cnt 0)
8563 (insert "\n"))
8564 (insert "{ "))
8565 ((equal e '(:endgroup))
8566 (setq ingroup nil cnt 0)
8567 (insert "}\n"))
8569 (setq tg (car e) c (cdr e))
8570 (if ingroup (push tg (car groups)))
8571 (setq tg (org-add-props tg nil 'face
8572 (org-get-todo-face tg)))
8573 (if (and (= cnt 0) (not ingroup)) (insert " "))
8574 (insert "[" c "] " tg (make-string
8575 (- fwidth 4 (length tg)) ?\ ))
8576 (when (= (setq cnt (1+ cnt)) ncol)
8577 (insert "\n")
8578 (if ingroup (insert " "))
8579 (setq cnt 0)))))
8580 (insert "\n")
8581 (goto-char (point-min))
8582 (if (not expert) (org-fit-window-to-buffer))
8583 (message "[a-z..]:Set [SPC]:clear")
8584 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8585 (cond
8586 ((or (= c ?\C-g)
8587 (and (= c ?q) (not (rassoc c fulltable))))
8588 (setq quit-flag t))
8589 ((= c ?\ ) nil)
8590 ((setq e (rassoc c fulltable) tg (car e))
8592 (t (setq quit-flag t))))))
8594 (defun org-entry-is-todo-p ()
8595 (member (org-get-todo-state) org-not-done-keywords))
8597 (defun org-entry-is-done-p ()
8598 (member (org-get-todo-state) org-done-keywords))
8600 (defun org-get-todo-state ()
8601 (save-excursion
8602 (org-back-to-heading t)
8603 (and (looking-at org-todo-line-regexp)
8604 (match-end 2)
8605 (match-string 2))))
8607 (defun org-at-date-range-p (&optional inactive-ok)
8608 "Is the cursor inside a date range?"
8609 (interactive)
8610 (save-excursion
8611 (catch 'exit
8612 (let ((pos (point)))
8613 (skip-chars-backward "^[<\r\n")
8614 (skip-chars-backward "<[")
8615 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8616 (>= (match-end 0) pos)
8617 (throw 'exit t))
8618 (skip-chars-backward "^<[\r\n")
8619 (skip-chars-backward "<[")
8620 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8621 (>= (match-end 0) pos)
8622 (throw 'exit t)))
8623 nil)))
8625 (defun org-get-repeat ()
8626 "Check if there is a deadline/schedule with repeater in this entry."
8627 (save-match-data
8628 (save-excursion
8629 (org-back-to-heading t)
8630 (if (re-search-forward
8631 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8632 (match-string 1)))))
8634 (defvar org-last-changed-timestamp)
8635 (defvar org-last-inserted-timestamp)
8636 (defvar org-log-post-message)
8637 (defvar org-log-note-purpose)
8638 (defvar org-log-note-how)
8639 (defvar org-log-note-extra)
8640 (defun org-auto-repeat-maybe (done-word)
8641 "Check if the current headline contains a repeated deadline/schedule.
8642 If yes, set TODO state back to what it was and change the base date
8643 of repeating deadline/scheduled time stamps to new date.
8644 This function is run automatically after each state change to a DONE state."
8645 ;; last-state is dynamically scoped into this function
8646 (let* ((repeat (org-get-repeat))
8647 (aa (assoc last-state org-todo-kwd-alist))
8648 (interpret (nth 1 aa))
8649 (head (nth 2 aa))
8650 (whata '(("d" . day) ("m" . month) ("y" . year)))
8651 (msg "Entry repeats: ")
8652 (org-log-done nil)
8653 (org-todo-log-states nil)
8654 (nshiftmax 10) (nshift 0)
8655 re type n what ts mb0 time)
8656 (when repeat
8657 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8658 (org-todo (if (eq interpret 'type) last-state head))
8659 (when org-log-repeat
8660 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8661 (memq 'org-add-log-note post-command-hook))
8662 ;; OK, we are already setup for some record
8663 (if (eq org-log-repeat 'note)
8664 ;; make sure we take a note, not only a time stamp
8665 (setq org-log-note-how 'note))
8666 ;; Set up for taking a record
8667 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8668 'findpos org-log-repeat)))
8669 (org-back-to-heading t)
8670 (org-add-planning-info nil nil 'closed)
8671 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8672 org-deadline-time-regexp "\\)\\|\\("
8673 org-ts-regexp "\\)"))
8674 (while (re-search-forward
8675 re (save-excursion (outline-next-heading) (point)) t)
8676 (setq type (if (match-end 1) org-scheduled-string
8677 (if (match-end 3) org-deadline-string "Plain:"))
8678 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8679 mb0 (match-beginning 0))
8680 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8681 (setq n (string-to-number (match-string 2 ts))
8682 what (match-string 3 ts))
8683 (if (equal what "w") (setq n (* n 7) what "d"))
8684 ;; Preparation, see if we need to modify the start date for the change
8685 (when (match-end 1)
8686 (setq time (save-match-data (org-time-string-to-time ts)))
8687 (cond
8688 ((equal (match-string 1 ts) ".")
8689 ;; Shift starting date to today
8690 (org-timestamp-change
8691 (- (time-to-days (current-time)) (time-to-days time))
8692 'day))
8693 ((equal (match-string 1 ts) "+")
8694 (while (or (= nshift 0)
8695 (<= (time-to-days time) (time-to-days (current-time))))
8696 (when (= (incf nshift) nshiftmax)
8697 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8698 (error "Abort")))
8699 (org-timestamp-change n (cdr (assoc what whata)))
8700 (org-at-timestamp-p t)
8701 (setq ts (match-string 1))
8702 (setq time (save-match-data (org-time-string-to-time ts))))
8703 (org-timestamp-change (- n) (cdr (assoc what whata)))
8704 ;; rematch, so that we have everything in place for the real shift
8705 (org-at-timestamp-p t)
8706 (setq ts (match-string 1))
8707 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8708 (org-timestamp-change n (cdr (assoc what whata)))
8709 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8710 (setq org-log-post-message msg)
8711 (message "%s" msg))))
8713 (defun org-show-todo-tree (arg)
8714 "Make a compact tree which shows all headlines marked with TODO.
8715 The tree will show the lines where the regexp matches, and all higher
8716 headlines above the match.
8717 With a \\[universal-argument] prefix, also show the DONE entries.
8718 With a numeric prefix N, construct a sparse tree for the Nth element
8719 of `org-todo-keywords-1'."
8720 (interactive "P")
8721 (let ((case-fold-search nil)
8722 (kwd-re
8723 (cond ((null arg) org-not-done-regexp)
8724 ((equal arg '(4))
8725 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8726 (mapcar 'list org-todo-keywords-1))))
8727 (concat "\\("
8728 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8729 "\\)\\>")))
8730 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8731 (regexp-quote (nth (1- (prefix-numeric-value arg))
8732 org-todo-keywords-1)))
8733 (t (error "Invalid prefix argument: %s" arg)))))
8734 (message "%d TODO entries found"
8735 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8737 (defun org-deadline (&optional remove time)
8738 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8739 With argument REMOVE, remove any deadline from the item.
8740 When TIME is set, it should be an internal time specification, and the
8741 scheduling will use the corresponding date."
8742 (interactive "P")
8743 (if remove
8744 (progn
8745 (org-remove-timestamp-with-keyword org-deadline-string)
8746 (message "Item no longer has a deadline."))
8747 (if (org-get-repeat)
8748 (error "Cannot change deadline on task with repeater, please do that by hand")
8749 (org-add-planning-info 'deadline time 'closed)
8750 (message "Deadline on %s" org-last-inserted-timestamp))))
8752 (defun org-schedule (&optional remove time)
8753 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8754 With argument REMOVE, remove any scheduling date from the item.
8755 When TIME is set, it should be an internal time specification, and the
8756 scheduling will use the corresponding date."
8757 (interactive "P")
8758 (if remove
8759 (progn
8760 (org-remove-timestamp-with-keyword org-scheduled-string)
8761 (message "Item is no longer scheduled."))
8762 (if (org-get-repeat)
8763 (error "Cannot reschedule task with repeater, please do that by hand")
8764 (org-add-planning-info 'scheduled time 'closed)
8765 (message "Scheduled to %s" org-last-inserted-timestamp))))
8767 (defun org-remove-timestamp-with-keyword (keyword)
8768 "Remove all time stamps with KEYWORD in the current entry."
8769 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8770 beg)
8771 (save-excursion
8772 (org-back-to-heading t)
8773 (setq beg (point))
8774 (org-end-of-subtree t t)
8775 (while (re-search-backward re beg t)
8776 (replace-match "")
8777 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8778 (equal (char-before) ?\ ))
8779 (backward-delete-char 1)
8780 (if (string-match "^[ \t]*$" (buffer-substring
8781 (point-at-bol) (point-at-eol)))
8782 (delete-region (point-at-bol)
8783 (min (point-max) (1+ (point-at-eol))))))))))
8785 (defun org-add-planning-info (what &optional time &rest remove)
8786 "Insert new timestamp with keyword in the line directly after the headline.
8787 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8788 If non is given, the user is prompted for a date.
8789 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8790 be removed."
8791 (interactive)
8792 (let (org-time-was-given org-end-time-was-given ts
8793 end default-time default-input)
8795 (when (and (not time) (memq what '(scheduled deadline)))
8796 ;; Try to get a default date/time from existing timestamp
8797 (save-excursion
8798 (org-back-to-heading t)
8799 (setq end (save-excursion (outline-next-heading) (point)))
8800 (when (re-search-forward (if (eq what 'scheduled)
8801 org-scheduled-time-regexp
8802 org-deadline-time-regexp)
8803 end t)
8804 (setq ts (match-string 1)
8805 default-time
8806 (apply 'encode-time (org-parse-time-string ts))
8807 default-input (and ts (org-get-compact-tod ts))))))
8808 (when what
8809 ;; If necessary, get the time from the user
8810 (setq time (or time (org-read-date nil 'to-time nil nil
8811 default-time default-input))))
8813 (when (and org-insert-labeled-timestamps-at-point
8814 (member what '(scheduled deadline)))
8815 (insert
8816 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8817 (org-insert-time-stamp time org-time-was-given
8818 nil nil nil (list org-end-time-was-given))
8819 (setq what nil))
8820 (save-excursion
8821 (save-restriction
8822 (let (col list elt ts buffer-invisibility-spec)
8823 (org-back-to-heading t)
8824 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8825 (goto-char (match-end 1))
8826 (setq col (current-column))
8827 (goto-char (match-end 0))
8828 (if (eobp) (insert "\n") (forward-char 1))
8829 (if (and (not (looking-at outline-regexp))
8830 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8831 "[^\r\n]*"))
8832 (not (equal (match-string 1) org-clock-string)))
8833 (narrow-to-region (match-beginning 0) (match-end 0))
8834 (insert-before-markers "\n")
8835 (backward-char 1)
8836 (narrow-to-region (point) (point))
8837 (and org-adapt-indentation (org-indent-to-column col)))
8838 ;; Check if we have to remove something.
8839 (setq list (cons what remove))
8840 (while list
8841 (setq elt (pop list))
8842 (goto-char (point-min))
8843 (when (or (and (eq elt 'scheduled)
8844 (re-search-forward org-scheduled-time-regexp nil t))
8845 (and (eq elt 'deadline)
8846 (re-search-forward org-deadline-time-regexp nil t))
8847 (and (eq elt 'closed)
8848 (re-search-forward org-closed-time-regexp nil t)))
8849 (replace-match "")
8850 (if (looking-at "--+<[^>]+>") (replace-match ""))
8851 (if (looking-at " +") (replace-match ""))))
8852 (goto-char (point-max))
8853 (when what
8854 (insert
8855 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8856 (cond ((eq what 'scheduled) org-scheduled-string)
8857 ((eq what 'deadline) org-deadline-string)
8858 ((eq what 'closed) org-closed-string))
8859 " ")
8860 (setq ts (org-insert-time-stamp
8861 time
8862 (or org-time-was-given
8863 (and (eq what 'closed) org-log-done-with-time))
8864 (eq what 'closed)
8865 nil nil (list org-end-time-was-given)))
8866 (end-of-line 1))
8867 (goto-char (point-min))
8868 (widen)
8869 (if (and (looking-at "[ \t]+\n")
8870 (equal (char-before) ?\n))
8871 (delete-region (1- (point)) (point-at-eol)))
8872 ts)))))
8874 (defvar org-log-note-marker (make-marker))
8875 (defvar org-log-note-purpose nil)
8876 (defvar org-log-note-state nil)
8877 (defvar org-log-note-how nil)
8878 (defvar org-log-note-extra nil)
8879 (defvar org-log-note-window-configuration nil)
8880 (defvar org-log-note-return-to (make-marker))
8881 (defvar org-log-post-message nil
8882 "Message to be displayed after a log note has been stored.
8883 The auto-repeater uses this.")
8885 (defun org-add-note ()
8886 "Add a note to the current entry.
8887 This is done in the same way as adding a state change note."
8888 (interactive)
8889 (org-add-log-setup 'note nil 'findpos nil))
8891 (defvar org-property-end-re)
8892 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8893 "Set up the post command hook to take a note.
8894 If this is about to TODO state change, the new state is expected in STATE.
8895 When FINDPOS is non-nil, find the correct position for the note in
8896 the current entry. If not, assume that it can be inserted at point.
8897 HOW is an indicator what kind of note should be created.
8898 EXTRA is additional text that will be inserted into the notes buffer."
8899 (save-restriction
8900 (save-excursion
8901 (when findpos
8902 (org-back-to-heading t)
8903 (narrow-to-region (point) (save-excursion
8904 (outline-next-heading) (point)))
8905 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8906 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8907 "[^\r\n]*\\)?"))
8908 (goto-char (match-end 0))
8909 (when (and org-log-state-notes-insert-after-drawers
8910 (save-excursion
8911 (forward-line) (looking-at org-drawer-regexp)))
8912 (progn (forward-line)
8913 (while (looking-at org-drawer-regexp)
8914 (goto-char (match-end 0))
8915 (re-search-forward org-property-end-re (point-max) t)
8916 (forward-line))
8917 (forward-line -1)))
8918 (unless org-log-states-order-reversed
8919 (and (= (char-after) ?\n) (forward-char 1))
8920 (org-skip-over-state-notes)
8921 (skip-chars-backward " \t\n\r")))
8922 (move-marker org-log-note-marker (point))
8923 (setq org-log-note-purpose purpose
8924 org-log-note-state state
8925 org-log-note-how how
8926 org-log-note-extra extra)
8927 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8929 (defun org-skip-over-state-notes ()
8930 "Skip past the list of State notes in an entry."
8931 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8932 (while (looking-at "[ \t]*- State")
8933 (condition-case nil
8934 (org-next-item)
8935 (error (org-end-of-item)))))
8937 (defun org-add-log-note (&optional purpose)
8938 "Pop up a window for taking a note, and add this note later at point."
8939 (remove-hook 'post-command-hook 'org-add-log-note)
8940 (setq org-log-note-window-configuration (current-window-configuration))
8941 (delete-other-windows)
8942 (move-marker org-log-note-return-to (point))
8943 (switch-to-buffer (marker-buffer org-log-note-marker))
8944 (goto-char org-log-note-marker)
8945 (org-switch-to-buffer-other-window "*Org Note*")
8946 (erase-buffer)
8947 (if (memq org-log-note-how '(time state))
8948 (let (current-prefix-arg) (org-store-log-note))
8949 (let ((org-inhibit-startup t)) (org-mode))
8950 (insert (format "# Insert note for %s.
8951 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8952 (cond
8953 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8954 ((eq org-log-note-purpose 'done) "closed todo item")
8955 ((eq org-log-note-purpose 'state)
8956 (format "state change to \"%s\"" org-log-note-state))
8957 ((eq org-log-note-purpose 'note)
8958 "this entry")
8959 (t (error "This should not happen")))))
8960 (if org-log-note-extra (insert org-log-note-extra))
8961 (org-set-local 'org-finish-function 'org-store-log-note)))
8963 (defvar org-note-abort nil) ; dynamically scoped
8964 (defun org-store-log-note ()
8965 "Finish taking a log note, and insert it to where it belongs."
8966 (let ((txt (buffer-string))
8967 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8968 lines ind)
8969 (kill-buffer (current-buffer))
8970 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8971 (setq txt (replace-match "" t t txt)))
8972 (if (string-match "\\s-+\\'" txt)
8973 (setq txt (replace-match "" t t txt)))
8974 (setq lines (org-split-string txt "\n"))
8975 (when (and note (string-match "\\S-" note))
8976 (setq note
8977 (org-replace-escapes
8978 note
8979 (list (cons "%u" (user-login-name))
8980 (cons "%U" user-full-name)
8981 (cons "%t" (format-time-string
8982 (org-time-stamp-format 'long 'inactive)
8983 (current-time)))
8984 (cons "%s" (if org-log-note-state
8985 (concat "\"" org-log-note-state "\"")
8986 "")))))
8987 (if lines (setq note (concat note " \\\\")))
8988 (push note lines))
8989 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8990 (when lines
8991 (save-excursion
8992 (set-buffer (marker-buffer org-log-note-marker))
8993 (save-excursion
8994 (goto-char org-log-note-marker)
8995 (move-marker org-log-note-marker nil)
8996 (end-of-line 1)
8997 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8998 (indent-relative nil)
8999 (insert "- " (pop lines))
9000 (org-indent-line-function)
9001 (beginning-of-line 1)
9002 (looking-at "[ \t]*")
9003 (setq ind (concat (match-string 0) " "))
9004 (end-of-line 1)
9005 (while lines (insert "\n" ind (pop lines)))))))
9006 (set-window-configuration org-log-note-window-configuration)
9007 (with-current-buffer (marker-buffer org-log-note-return-to)
9008 (goto-char org-log-note-return-to))
9009 (move-marker org-log-note-return-to nil)
9010 (and org-log-post-message (message "%s" org-log-post-message)))
9012 (defun org-sparse-tree (&optional arg)
9013 "Create a sparse tree, prompt for the details.
9014 This command can create sparse trees. You first need to select the type
9015 of match used to create the tree:
9017 t Show entries with a specific TODO keyword.
9018 T Show entries selected by a tags match.
9019 p Enter a property name and its value (both with completion on existing
9020 names/values) and show entries with that property.
9021 r Show entries matching a regular expression
9022 d Show deadlines due within `org-deadline-warning-days'."
9023 (interactive "P")
9024 (let (ans kwd value)
9025 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9026 (setq ans (read-char-exclusive))
9027 (cond
9028 ((equal ans ?d)
9029 (call-interactively 'org-check-deadlines))
9030 ((equal ans ?b)
9031 (call-interactively 'org-check-before-date))
9032 ((equal ans ?t)
9033 (org-show-todo-tree '(4)))
9034 ((equal ans ?T)
9035 (call-interactively 'org-tags-sparse-tree))
9036 ((member ans '(?p ?P))
9037 (setq kwd (org-ido-completing-read "Property: "
9038 (mapcar 'list (org-buffer-property-keys))))
9039 (setq value (org-ido-completing-read "Value: "
9040 (mapcar 'list (org-property-values kwd))))
9041 (unless (string-match "\\`{.*}\\'" value)
9042 (setq value (concat "\"" value "\"")))
9043 (org-tags-sparse-tree arg (concat kwd "=" value)))
9044 ((member ans '(?r ?R ?/))
9045 (call-interactively 'org-occur))
9046 (t (error "No such sparse tree command \"%c\"" ans)))))
9048 (defvar org-occur-highlights nil
9049 "List of overlays used for occur matches.")
9050 (make-variable-buffer-local 'org-occur-highlights)
9051 (defvar org-occur-parameters nil
9052 "Parameters of the active org-occur calls.
9053 This is a list, each call to org-occur pushes as cons cell,
9054 containing the regular expression and the callback, onto the list.
9055 The list can contain several entries if `org-occur' has been called
9056 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9057 will only contain one set of parameters. When the highlights are
9058 removed (for example with `C-c C-c', or with the next edit (depending
9059 on `org-remove-highlights-with-change'), this variable is emptied
9060 as well.")
9061 (make-variable-buffer-local 'org-occur-parameters)
9063 (defun org-occur (regexp &optional keep-previous callback)
9064 "Make a compact tree which shows all matches of REGEXP.
9065 The tree will show the lines where the regexp matches, and all higher
9066 headlines above the match. It will also show the heading after the match,
9067 to make sure editing the matching entry is easy.
9068 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9069 call to `org-occur' will be kept, to allow stacking of calls to this
9070 command.
9071 If CALLBACK is non-nil, it is a function which is called to confirm
9072 that the match should indeed be shown."
9073 (interactive "sRegexp: \nP")
9074 (unless keep-previous
9075 (org-remove-occur-highlights nil nil t))
9076 (push (cons regexp callback) org-occur-parameters)
9077 (let ((cnt 0))
9078 (save-excursion
9079 (goto-char (point-min))
9080 (if (or (not keep-previous) ; do not want to keep
9081 (not org-occur-highlights)) ; no previous matches
9082 ;; hide everything
9083 (org-overview))
9084 (while (re-search-forward regexp nil t)
9085 (when (or (not callback)
9086 (save-match-data (funcall callback)))
9087 (setq cnt (1+ cnt))
9088 (when org-highlight-sparse-tree-matches
9089 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9090 (org-show-context 'occur-tree))))
9091 (when org-remove-highlights-with-change
9092 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9093 nil 'local))
9094 (unless org-sparse-tree-open-archived-trees
9095 (org-hide-archived-subtrees (point-min) (point-max)))
9096 (run-hooks 'org-occur-hook)
9097 (if (interactive-p)
9098 (message "%d match(es) for regexp %s" cnt regexp))
9099 cnt))
9101 (defun org-show-context (&optional key)
9102 "Make sure point and context and visible.
9103 How much context is shown depends upon the variables
9104 `org-show-hierarchy-above', `org-show-following-heading'. and
9105 `org-show-siblings'."
9106 (let ((heading-p (org-on-heading-p t))
9107 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9108 (following-p (org-get-alist-option org-show-following-heading key))
9109 (entry-p (org-get-alist-option org-show-entry-below key))
9110 (siblings-p (org-get-alist-option org-show-siblings key)))
9111 (catch 'exit
9112 ;; Show heading or entry text
9113 (if (and heading-p (not entry-p))
9114 (org-flag-heading nil) ; only show the heading
9115 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9116 (org-show-hidden-entry))) ; show entire entry
9117 (when following-p
9118 ;; Show next sibling, or heading below text
9119 (save-excursion
9120 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9121 (org-flag-heading nil))))
9122 (when siblings-p (org-show-siblings))
9123 (when hierarchy-p
9124 ;; show all higher headings, possibly with siblings
9125 (save-excursion
9126 (while (and (condition-case nil
9127 (progn (org-up-heading-all 1) t)
9128 (error nil))
9129 (not (bobp)))
9130 (org-flag-heading nil)
9131 (when siblings-p (org-show-siblings))))))))
9133 (defun org-reveal (&optional siblings)
9134 "Show current entry, hierarchy above it, and the following headline.
9135 This can be used to show a consistent set of context around locations
9136 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9137 not t for the search context.
9139 With optional argument SIBLINGS, on each level of the hierarchy all
9140 siblings are shown. This repairs the tree structure to what it would
9141 look like when opened with hierarchical calls to `org-cycle'."
9142 (interactive "P")
9143 (let ((org-show-hierarchy-above t)
9144 (org-show-following-heading t)
9145 (org-show-siblings (if siblings t org-show-siblings)))
9146 (org-show-context nil)))
9148 (defun org-highlight-new-match (beg end)
9149 "Highlight from BEG to END and mark the highlight is an occur headline."
9150 (let ((ov (org-make-overlay beg end)))
9151 (org-overlay-put ov 'face 'secondary-selection)
9152 (push ov org-occur-highlights)))
9154 (defun org-remove-occur-highlights (&optional beg end noremove)
9155 "Remove the occur highlights from the buffer.
9156 BEG and END are ignored. If NOREMOVE is nil, remove this function
9157 from the `before-change-functions' in the current buffer."
9158 (interactive)
9159 (unless org-inhibit-highlight-removal
9160 (mapc 'org-delete-overlay org-occur-highlights)
9161 (setq org-occur-highlights nil)
9162 (setq org-occur-parameters nil)
9163 (unless noremove
9164 (remove-hook 'before-change-functions
9165 'org-remove-occur-highlights 'local))))
9167 ;;;; Priorities
9169 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9170 "Regular expression matching the priority indicator.")
9172 (defvar org-remove-priority-next-time nil)
9174 (defun org-priority-up ()
9175 "Increase the priority of the current item."
9176 (interactive)
9177 (org-priority 'up))
9179 (defun org-priority-down ()
9180 "Decrease the priority of the current item."
9181 (interactive)
9182 (org-priority 'down))
9184 (defun org-priority (&optional action)
9185 "Change the priority of an item by ARG.
9186 ACTION can be `set', `up', `down', or a character."
9187 (interactive)
9188 (setq action (or action 'set))
9189 (let (current new news have remove)
9190 (save-excursion
9191 (org-back-to-heading)
9192 (if (looking-at org-priority-regexp)
9193 (setq current (string-to-char (match-string 2))
9194 have t)
9195 (setq current org-default-priority))
9196 (cond
9197 ((or (eq action 'set)
9198 (if (featurep 'xemacs) (characterp action) (integerp action)))
9199 (if (not (eq action 'set))
9200 (setq new action)
9201 (message "Priority %c-%c, SPC to remove: "
9202 org-highest-priority org-lowest-priority)
9203 (setq new (read-char-exclusive)))
9204 (if (and (= (upcase org-highest-priority) org-highest-priority)
9205 (= (upcase org-lowest-priority) org-lowest-priority))
9206 (setq new (upcase new)))
9207 (cond ((equal new ?\ ) (setq remove t))
9208 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9209 (error "Priority must be between `%c' and `%c'"
9210 org-highest-priority org-lowest-priority))))
9211 ((eq action 'up)
9212 (if (and (not have) (eq last-command this-command))
9213 (setq new org-lowest-priority)
9214 (setq new (if (and org-priority-start-cycle-with-default (not have))
9215 org-default-priority (1- current)))))
9216 ((eq action 'down)
9217 (if (and (not have) (eq last-command this-command))
9218 (setq new org-highest-priority)
9219 (setq new (if (and org-priority-start-cycle-with-default (not have))
9220 org-default-priority (1+ current)))))
9221 (t (error "Invalid action")))
9222 (if (or (< (upcase new) org-highest-priority)
9223 (> (upcase new) org-lowest-priority))
9224 (setq remove t))
9225 (setq news (format "%c" new))
9226 (if have
9227 (if remove
9228 (replace-match "" t t nil 1)
9229 (replace-match news t t nil 2))
9230 (if remove
9231 (error "No priority cookie found in line")
9232 (looking-at org-todo-line-regexp)
9233 (if (match-end 2)
9234 (progn
9235 (goto-char (match-end 2))
9236 (insert " [#" news "]"))
9237 (goto-char (match-beginning 3))
9238 (insert "[#" news "] ")))))
9239 (org-preserve-lc (org-set-tags nil 'align))
9240 (if remove
9241 (message "Priority removed")
9242 (message "Priority of current item set to %s" news))))
9245 (defun org-get-priority (s)
9246 "Find priority cookie and return priority."
9247 (save-match-data
9248 (if (not (string-match org-priority-regexp s))
9249 (* 1000 (- org-lowest-priority org-default-priority))
9250 (* 1000 (- org-lowest-priority
9251 (string-to-char (match-string 2 s)))))))
9253 ;;;; Tags
9255 (defvar org-agenda-archives-mode)
9256 (defun org-scan-tags (action matcher &optional todo-only)
9257 "Scan headline tags with inheritance and produce output ACTION.
9259 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9260 or `agenda' to produce an entry list for an agenda view. It can also be
9261 a Lisp form or a function that should be called at each matched headline, in
9262 this case the return value is a list of all return values from these calls.
9264 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9265 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9266 only lines with a TODO keyword are included in the output."
9267 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9268 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9269 (org-re
9270 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9271 (props (list 'face 'default
9272 'done-face 'org-done
9273 'undone-face 'default
9274 'mouse-face 'highlight
9275 'org-not-done-regexp org-not-done-regexp
9276 'org-todo-regexp org-todo-regexp
9277 'keymap org-agenda-keymap
9278 'help-echo
9279 (format "mouse-2 or RET jump to org file %s"
9280 (abbreviate-file-name
9281 (or (buffer-file-name (buffer-base-buffer))
9282 (buffer-name (buffer-base-buffer)))))))
9283 (case-fold-search nil)
9284 lspos tags tags-list
9285 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9286 (llast 0) rtn rtn1 level category i txt
9287 todo marker entry priority)
9288 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9289 (setq action (list 'lambda nil action)))
9290 (save-excursion
9291 (goto-char (point-min))
9292 (when (eq action 'sparse-tree)
9293 (org-overview)
9294 (org-remove-occur-highlights))
9295 (while (re-search-forward re nil t)
9296 (catch :skip
9297 (setq todo (if (match-end 1) (match-string 2))
9298 tags (if (match-end 4) (match-string 4)))
9299 (goto-char (setq lspos (1+ (match-beginning 0))))
9300 (setq level (org-reduced-level (funcall outline-level))
9301 category (org-get-category))
9302 (setq i llast llast level)
9303 ;; remove tag lists from same and sublevels
9304 (while (>= i level)
9305 (when (setq entry (assoc i tags-alist))
9306 (setq tags-alist (delete entry tags-alist)))
9307 (setq i (1- i)))
9308 ;; add the next tags
9309 (when tags
9310 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9311 tags-alist
9312 (cons (cons level tags) tags-alist)))
9313 ;; compile tags for current headline
9314 (setq tags-list
9315 (if org-use-tag-inheritance
9316 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9317 tags))
9318 (when org-use-tag-inheritance
9319 (setcdr (car tags-alist)
9320 (mapcar (lambda (x)
9321 (setq x (copy-sequence x))
9322 (org-add-prop-inherited x))
9323 (cdar tags-alist))))
9324 (when (and tags org-use-tag-inheritance
9325 (not (eq t org-use-tag-inheritance)))
9326 ;; selective inheritance, remove uninherited ones
9327 (setcdr (car tags-alist)
9328 (org-remove-uniherited-tags (cdar tags-alist))))
9329 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9330 (let ((case-fold-search t)) (eval matcher))
9332 (not (member org-archive-tag tags-list))
9333 ;; we have an archive tag, should we use this anyway?
9334 (or (not org-agenda-skip-archived-trees)
9335 (and (eq action 'agenda) org-agenda-archives-mode))))
9336 (unless (eq action 'sparse-tree) (org-agenda-skip))
9338 ;; select this headline
9340 (cond
9341 ((eq action 'sparse-tree)
9342 (and org-highlight-sparse-tree-matches
9343 (org-get-heading) (match-end 0)
9344 (org-highlight-new-match
9345 (match-beginning 0) (match-beginning 1)))
9346 (org-show-context 'tags-tree))
9347 ((eq action 'agenda)
9348 (setq txt (org-format-agenda-item
9350 (concat
9351 (if org-tags-match-list-sublevels
9352 (make-string (1- level) ?.) "")
9353 (org-get-heading))
9354 category (org-get-tags-at))
9355 priority (org-get-priority txt))
9356 (goto-char lspos)
9357 (setq marker (org-agenda-new-marker))
9358 (org-add-props txt props
9359 'org-marker marker 'org-hd-marker marker 'org-category category
9360 'priority priority 'type "tagsmatch")
9361 (push txt rtn))
9362 ((functionp action)
9363 (save-excursion
9364 (setq rtn1 (funcall action))
9365 (push rtn1 rtn))
9366 (goto-char (point-at-eol)))
9367 (t (error "Invalid action")))
9369 ;; if we are to skip sublevels, jump to end of subtree
9370 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9371 (when (and (eq action 'sparse-tree)
9372 (not org-sparse-tree-open-archived-trees))
9373 (org-hide-archived-subtrees (point-min) (point-max)))
9374 (nreverse rtn)))
9376 (defun org-remove-uniherited-tags (tags)
9377 "Remove all tags that are not inherited from the list TAGS."
9378 (cond
9379 ((eq org-use-tag-inheritance t)
9380 (if org-tags-exclude-from-inheritance
9381 (org-delete-all org-tags-exclude-from-inheritance tags)
9382 tags))
9383 ((not org-use-tag-inheritance) nil)
9384 ((stringp org-use-tag-inheritance)
9385 (delq nil (mapcar
9386 (lambda (x)
9387 (if (and (string-match org-use-tag-inheritance x)
9388 (not (member x org-tags-exclude-from-inheritance)))
9389 x nil))
9390 tags)))
9391 ((listp org-use-tag-inheritance)
9392 (delq nil (mapcar
9393 (lambda (x)
9394 (if (member x org-use-tag-inheritance) x nil))
9395 tags)))))
9397 (defvar todo-only) ;; dynamically scoped
9399 (defun org-tags-sparse-tree (&optional todo-only match)
9400 "Create a sparse tree according to tags string MATCH.
9401 MATCH can contain positive and negative selection of tags, like
9402 \"+WORK+URGENT-WITHBOSS\".
9403 If optional argument TODO-ONLY is non-nil, only select lines that are
9404 also TODO lines."
9405 (interactive "P")
9406 (org-prepare-agenda-buffers (list (current-buffer)))
9407 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9409 (defvar org-cached-props nil)
9410 (defun org-cached-entry-get (pom property)
9411 (if (or (eq t org-use-property-inheritance)
9412 (and (stringp org-use-property-inheritance)
9413 (string-match org-use-property-inheritance property))
9414 (and (listp org-use-property-inheritance)
9415 (member property org-use-property-inheritance)))
9416 ;; Caching is not possible, check it directly
9417 (org-entry-get pom property 'inherit)
9418 ;; Get all properties, so that we can do complicated checks easily
9419 (cdr (assoc property (or org-cached-props
9420 (setq org-cached-props
9421 (org-entry-properties pom)))))))
9423 (defun org-global-tags-completion-table (&optional files)
9424 "Return the list of all tags in all agenda buffer/files."
9425 (save-excursion
9426 (org-uniquify
9427 (delq nil
9428 (apply 'append
9429 (mapcar
9430 (lambda (file)
9431 (set-buffer (find-file-noselect file))
9432 (append (org-get-buffer-tags)
9433 (mapcar (lambda (x) (if (stringp (car-safe x))
9434 (list (car-safe x)) nil))
9435 org-tag-alist)))
9436 (if (and files (car files))
9437 files
9438 (org-agenda-files))))))))
9440 (defun org-make-tags-matcher (match)
9441 "Create the TAGS//TODO matcher form for the selection string MATCH."
9442 ;; todo-only is scoped dynamically into this function, and the function
9443 ;; may change it if the matcher asks for it.
9444 (unless match
9445 ;; Get a new match request, with completion
9446 (let ((org-last-tags-completion-table
9447 (org-global-tags-completion-table)))
9448 (setq match (org-ido-completing-read
9449 "Match: " 'org-tags-completion-function nil nil nil
9450 'org-tags-history))))
9452 ;; Parse the string and create a lisp form
9453 (let ((match0 match)
9454 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9455 minus tag mm
9456 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9457 orterms term orlist re-p str-p level-p level-op time-p
9458 prop-p pn pv po cat-p gv rest)
9459 (if (string-match "/+" match)
9460 ;; match contains also a todo-matching request
9461 (progn
9462 (setq tagsmatch (substring match 0 (match-beginning 0))
9463 todomatch (substring match (match-end 0)))
9464 (if (string-match "^!" todomatch)
9465 (setq todo-only t todomatch (substring todomatch 1)))
9466 (if (string-match "^\\s-*$" todomatch)
9467 (setq todomatch nil)))
9468 ;; only matching tags
9469 (setq tagsmatch match todomatch nil))
9471 ;; Make the tags matcher
9472 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9473 (setq tagsmatcher t)
9474 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9475 (while (setq term (pop orterms))
9476 (while (and (equal (substring term -1) "\\") orterms)
9477 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9478 (while (string-match re term)
9479 (setq rest (substring term (match-end 0))
9480 minus (and (match-end 1)
9481 (equal (match-string 1 term) "-"))
9482 tag (match-string 2 term)
9483 re-p (equal (string-to-char tag) ?{)
9484 level-p (match-end 4)
9485 prop-p (match-end 5)
9486 mm (cond
9487 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9488 (level-p
9489 (setq level-op (org-op-to-function (match-string 3 term)))
9490 `(,level-op level ,(string-to-number
9491 (match-string 4 term))))
9492 (prop-p
9493 (setq pn (match-string 5 term)
9494 po (match-string 6 term)
9495 pv (match-string 7 term)
9496 cat-p (equal pn "CATEGORY")
9497 re-p (equal (string-to-char pv) ?{)
9498 str-p (equal (string-to-char pv) ?\")
9499 time-p (save-match-data
9500 (string-match "^\"[[<].*[]>]\"$" pv))
9501 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9502 (if time-p (setq pv (org-matcher-time pv)))
9503 (setq po (org-op-to-function po (if time-p 'time str-p)))
9504 (cond
9505 ((equal pn "CATEGORY")
9506 (setq gv '(get-text-property (point) 'org-category)))
9507 ((equal pn "TODO")
9508 (setq gv 'todo))
9510 (setq gv `(org-cached-entry-get nil ,pn))))
9511 (if re-p
9512 (if (eq po 'org<>)
9513 `(not (string-match ,pv (or ,gv "")))
9514 `(string-match ,pv (or ,gv "")))
9515 (if str-p
9516 `(,po (or ,gv "") ,pv)
9517 `(,po (string-to-number (or ,gv ""))
9518 ,(string-to-number pv) ))))
9519 (t `(member ,(downcase tag) tags-list)))
9520 mm (if minus (list 'not mm) mm)
9521 term rest)
9522 (push mm tagsmatcher))
9523 (push (if (> (length tagsmatcher) 1)
9524 (cons 'and tagsmatcher)
9525 (car tagsmatcher))
9526 orlist)
9527 (setq tagsmatcher nil))
9528 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9529 (setq tagsmatcher
9530 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9531 ;; Make the todo matcher
9532 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9533 (setq todomatcher t)
9534 (setq orterms (org-split-string todomatch "|") orlist nil)
9535 (while (setq term (pop orterms))
9536 (while (string-match re term)
9537 (setq minus (and (match-end 1)
9538 (equal (match-string 1 term) "-"))
9539 kwd (match-string 2 term)
9540 re-p (equal (string-to-char kwd) ?{)
9541 term (substring term (match-end 0))
9542 mm (if re-p
9543 `(string-match ,(substring kwd 1 -1) todo)
9544 (list 'equal 'todo kwd))
9545 mm (if minus (list 'not mm) mm))
9546 (push mm todomatcher))
9547 (push (if (> (length todomatcher) 1)
9548 (cons 'and todomatcher)
9549 (car todomatcher))
9550 orlist)
9551 (setq todomatcher nil))
9552 (setq todomatcher (if (> (length orlist) 1)
9553 (cons 'or orlist) (car orlist))))
9555 ;; Return the string and lisp forms of the matcher
9556 (setq matcher (if todomatcher
9557 (list 'and tagsmatcher todomatcher)
9558 tagsmatcher))
9559 (cons match0 matcher)))
9561 (defun org-op-to-function (op &optional stringp)
9562 "Turn an operator into the appropriate function."
9563 (setq op
9564 (cond
9565 ((equal op "<" ) '(< string< org-time<))
9566 ((equal op ">" ) '(> org-string> org-time>))
9567 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9568 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9569 ((member op '("=" "==")) '(= string= org-time=))
9570 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9571 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9573 (defun org<> (a b) (not (= a b)))
9574 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9575 (defun org-string>= (a b) (not (string< a b)))
9576 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9577 (defun org-string<> (a b) (not (string= a b)))
9578 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9579 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9580 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9581 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9582 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9583 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9584 (defun org-2ft (s)
9585 "Convert S to a floating point time.
9586 If S is already a number, just return it. If it is a string, parse
9587 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9588 (cond
9589 ((numberp s) s)
9590 ((stringp s)
9591 (condition-case nil
9592 (float-time (apply 'encode-time (org-parse-time-string s)))
9593 (error 0.)))
9594 (t 0.)))
9596 (defun org-time-today ()
9597 "Time in seconds today at 0:00.
9598 Returns the float number of seconds since the beginning of the
9599 epoch to the beginning of today (00:00)."
9600 (float-time (apply 'encode-time
9601 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9603 (defun org-matcher-time (s)
9604 "Interpret a time comparison value."
9605 (save-match-data
9606 (cond
9607 ((string= s "<now>") (float-time))
9608 ((string= s "<today>") (org-time-today))
9609 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9610 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9611 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9612 (+ (org-time-today)
9613 (* (string-to-number (match-string 1 s))
9614 (cdr (assoc (match-string 2 s)
9615 '(("d" . 86400.0) ("w" . 604800.0)
9616 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9617 (t (org-2ft s)))))
9619 (defun org-match-any-p (re list)
9620 "Does re match any element of list?"
9621 (setq list (mapcar (lambda (x) (string-match re x)) list))
9622 (delq nil list))
9624 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9625 (defvar org-tags-overlay (org-make-overlay 1 1))
9626 (org-detach-overlay org-tags-overlay)
9628 (defun org-get-local-tags-at (&optional pos)
9629 "Get a list of tags defined in the current headline."
9630 (org-get-tags-at pos 'local))
9632 (defun org-get-local-tags ()
9633 "Get a list of tags defined in the current headline."
9634 (org-get-tags-at nil 'local))
9636 (defun org-get-tags-at (&optional pos local)
9637 "Get a list of all headline tags applicable at POS.
9638 POS defaults to point. If tags are inherited, the list contains
9639 the targets in the same sequence as the headlines appear, i.e.
9640 the tags of the current headline come last.
9641 When LOCAL is non-nil, only return tags from the current headline,
9642 ignore inherited ones."
9643 (interactive)
9644 (let (tags ltags lastpos parent)
9645 (save-excursion
9646 (save-restriction
9647 (widen)
9648 (goto-char (or pos (point)))
9649 (save-match-data
9650 (catch 'done
9651 (condition-case nil
9652 (progn
9653 (org-back-to-heading t)
9654 (while (not (equal lastpos (point)))
9655 (setq lastpos (point))
9656 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9657 (setq ltags (org-split-string
9658 (org-match-string-no-properties 1) ":"))
9659 (when parent
9660 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9661 (setq tags (append
9662 (if parent
9663 (org-remove-uniherited-tags ltags)
9664 ltags)
9665 tags)))
9666 (or org-use-tag-inheritance (throw 'done t))
9667 (if local (throw 'done t))
9668 (org-up-heading-all 1)
9669 (setq parent t)))
9670 (error nil)))))
9671 (append (org-remove-uniherited-tags org-file-tags) tags))))
9673 (defun org-add-prop-inherited (s)
9674 (add-text-properties 0 (length s) '(inherited t) s)
9677 (defun org-toggle-tag (tag &optional onoff)
9678 "Toggle the tag TAG for the current line.
9679 If ONOFF is `on' or `off', don't toggle but set to this state."
9680 (let (res current)
9681 (save-excursion
9682 (org-back-to-heading t)
9683 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9684 (point-at-eol) t)
9685 (progn
9686 (setq current (match-string 1))
9687 (replace-match ""))
9688 (setq current ""))
9689 (setq current (nreverse (org-split-string current ":")))
9690 (cond
9691 ((eq onoff 'on)
9692 (setq res t)
9693 (or (member tag current) (push tag current)))
9694 ((eq onoff 'off)
9695 (or (not (member tag current)) (setq current (delete tag current))))
9696 (t (if (member tag current)
9697 (setq current (delete tag current))
9698 (setq res t)
9699 (push tag current))))
9700 (end-of-line 1)
9701 (if current
9702 (progn
9703 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9704 (org-set-tags nil t))
9705 (delete-horizontal-space))
9706 (run-hooks 'org-after-tags-change-hook))
9707 res))
9709 (defun org-align-tags-here (to-col)
9710 ;; Assumes that this is a headline
9711 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9712 (beginning-of-line 1)
9713 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9714 (< pos (match-beginning 2)))
9715 (progn
9716 (setq tags-l (- (match-end 2) (match-beginning 2)))
9717 (goto-char (match-beginning 1))
9718 (insert " ")
9719 (delete-region (point) (1+ (match-beginning 2)))
9720 (setq ncol (max (1+ (current-column))
9721 (1+ col)
9722 (if (> to-col 0)
9723 to-col
9724 (- (abs to-col) tags-l))))
9725 (setq p (point))
9726 (insert (make-string (- ncol (current-column)) ?\ ))
9727 (setq ncol (current-column))
9728 (when indent-tabs-mode (tabify p (point-at-eol)))
9729 (org-move-to-column (min ncol col) t))
9730 (goto-char pos))))
9732 (defun org-set-tags-command (&optional arg just-align)
9733 "Call the set-tags command for the current entry."
9734 (interactive "P")
9735 (if (org-on-heading-p)
9736 (org-set-tags arg just-align)
9737 (save-excursion
9738 (org-back-to-heading t)
9739 (org-set-tags arg just-align))))
9741 (defun org-set-tags (&optional arg just-align)
9742 "Set the tags for the current headline.
9743 With prefix ARG, realign all tags in headings in the current buffer."
9744 (interactive "P")
9745 (let* ((re (concat "^" outline-regexp))
9746 (current (org-get-tags-string))
9747 (col (current-column))
9748 (org-setting-tags t)
9749 table current-tags inherited-tags ; computed below when needed
9750 tags p0 c0 c1 rpl)
9751 (if arg
9752 (save-excursion
9753 (goto-char (point-min))
9754 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9755 (while (re-search-forward re nil t)
9756 (org-set-tags nil t)
9757 (end-of-line 1)))
9758 (message "All tags realigned to column %d" org-tags-column))
9759 (if just-align
9760 (setq tags current)
9761 ;; Get a new set of tags from the user
9762 (save-excursion
9763 (setq table (or org-tag-alist (org-get-buffer-tags))
9764 org-last-tags-completion-table table
9765 current-tags (org-split-string current ":")
9766 inherited-tags (nreverse
9767 (nthcdr (length current-tags)
9768 (nreverse (org-get-tags-at))))
9769 tags
9770 (if (or (eq t org-use-fast-tag-selection)
9771 (and org-use-fast-tag-selection
9772 (delq nil (mapcar 'cdr table))))
9773 (org-fast-tag-selection
9774 current-tags inherited-tags table
9775 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9776 (let ((org-add-colon-after-tag-completion t))
9777 (org-trim
9778 (org-without-partial-completion
9779 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9780 nil nil current 'org-tags-history)))))))
9781 (while (string-match "[-+&]+" tags)
9782 ;; No boolean logic, just a list
9783 (setq tags (replace-match ":" t t tags))))
9785 (if (string-match "\\`[\t ]*\\'" tags)
9786 (setq tags "")
9787 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9788 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9790 ;; Insert new tags at the correct column
9791 (beginning-of-line 1)
9792 (cond
9793 ((and (equal current "") (equal tags "")))
9794 ((re-search-forward
9795 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9796 (point-at-eol) t)
9797 (if (equal tags "")
9798 (setq rpl "")
9799 (goto-char (match-beginning 0))
9800 (setq c0 (current-column) p0 (point)
9801 c1 (max (1+ c0) (if (> org-tags-column 0)
9802 org-tags-column
9803 (- (- org-tags-column) (length tags))))
9804 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9805 (replace-match rpl t t)
9806 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9807 tags)
9808 (t (error "Tags alignment failed")))
9809 (org-move-to-column col)
9810 (unless just-align
9811 (run-hooks 'org-after-tags-change-hook)))))
9813 (defun org-change-tag-in-region (beg end tag off)
9814 "Add or remove TAG for each entry in the region.
9815 This works in the agenda, and also in an org-mode buffer."
9816 (interactive
9817 (list (region-beginning) (region-end)
9818 (let ((org-last-tags-completion-table
9819 (if (org-mode-p)
9820 (org-get-buffer-tags)
9821 (org-global-tags-completion-table))))
9822 (org-ido-completing-read
9823 "Tag: " 'org-tags-completion-function nil nil nil
9824 'org-tags-history))
9825 (progn
9826 (message "[s]et or [r]emove? ")
9827 (equal (read-char-exclusive) ?r))))
9828 (if (fboundp 'deactivate-mark) (deactivate-mark))
9829 (let ((agendap (equal major-mode 'org-agenda-mode))
9830 l1 l2 m buf pos newhead (cnt 0))
9831 (goto-char end)
9832 (setq l2 (1- (org-current-line)))
9833 (goto-char beg)
9834 (setq l1 (org-current-line))
9835 (loop for l from l1 to l2 do
9836 (goto-line l)
9837 (setq m (get-text-property (point) 'org-hd-marker))
9838 (when (or (and (org-mode-p) (org-on-heading-p))
9839 (and agendap m))
9840 (setq buf (if agendap (marker-buffer m) (current-buffer))
9841 pos (if agendap m (point)))
9842 (with-current-buffer buf
9843 (save-excursion
9844 (save-restriction
9845 (goto-char pos)
9846 (setq cnt (1+ cnt))
9847 (org-toggle-tag tag (if off 'off 'on))
9848 (setq newhead (org-get-heading)))))
9849 (and agendap (org-agenda-change-all-lines newhead m))))
9850 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9852 (defun org-tags-completion-function (string predicate &optional flag)
9853 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9854 (confirm (lambda (x) (stringp (car x)))))
9855 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9856 (setq s1 (match-string 1 string)
9857 s2 (match-string 2 string))
9858 (setq s1 "" s2 string))
9859 (cond
9860 ((eq flag nil)
9861 ;; try completion
9862 (setq rtn (try-completion s2 ctable confirm))
9863 (if (stringp rtn)
9864 (setq rtn
9865 (concat s1 s2 (substring rtn (length s2))
9866 (if (and org-add-colon-after-tag-completion
9867 (assoc rtn ctable))
9868 ":" ""))))
9869 rtn)
9870 ((eq flag t)
9871 ;; all-completions
9872 (all-completions s2 ctable confirm)
9874 ((eq flag 'lambda)
9875 ;; exact match?
9876 (assoc s2 ctable)))
9879 (defun org-fast-tag-insert (kwd tags face &optional end)
9880 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9881 (insert (format "%-12s" (concat kwd ":"))
9882 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9883 (or end "")))
9885 (defun org-fast-tag-show-exit (flag)
9886 (save-excursion
9887 (goto-line 3)
9888 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9889 (replace-match ""))
9890 (when flag
9891 (end-of-line 1)
9892 (org-move-to-column (- (window-width) 19) t)
9893 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9895 (defun org-set-current-tags-overlay (current prefix)
9896 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9897 (if (featurep 'xemacs)
9898 (org-overlay-display org-tags-overlay (concat prefix s)
9899 'secondary-selection)
9900 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9901 (org-overlay-display org-tags-overlay (concat prefix s)))))
9903 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9904 "Fast tag selection with single keys.
9905 CURRENT is the current list of tags in the headline, INHERITED is the
9906 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9907 possibly with grouping information. TODO-TABLE is a similar table with
9908 TODO keywords, should these have keys assigned to them.
9909 If the keys are nil, a-z are automatically assigned.
9910 Returns the new tags string, or nil to not change the current settings."
9911 (let* ((fulltable (append table todo-table))
9912 (maxlen (apply 'max (mapcar
9913 (lambda (x)
9914 (if (stringp (car x)) (string-width (car x)) 0))
9915 fulltable)))
9916 (buf (current-buffer))
9917 (expert (eq org-fast-tag-selection-single-key 'expert))
9918 (buffer-tags nil)
9919 (fwidth (+ maxlen 3 1 3))
9920 (ncol (/ (- (window-width) 4) fwidth))
9921 (i-face 'org-done)
9922 (c-face 'org-todo)
9923 tg cnt e c char c1 c2 ntable tbl rtn
9924 ov-start ov-end ov-prefix
9925 (exit-after-next org-fast-tag-selection-single-key)
9926 (done-keywords org-done-keywords)
9927 groups ingroup)
9928 (save-excursion
9929 (beginning-of-line 1)
9930 (if (looking-at
9931 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9932 (setq ov-start (match-beginning 1)
9933 ov-end (match-end 1)
9934 ov-prefix "")
9935 (setq ov-start (1- (point-at-eol))
9936 ov-end (1+ ov-start))
9937 (skip-chars-forward "^\n\r")
9938 (setq ov-prefix
9939 (concat
9940 (buffer-substring (1- (point)) (point))
9941 (if (> (current-column) org-tags-column)
9943 (make-string (- org-tags-column (current-column)) ?\ ))))))
9944 (org-move-overlay org-tags-overlay ov-start ov-end)
9945 (save-window-excursion
9946 (if expert
9947 (set-buffer (get-buffer-create " *Org tags*"))
9948 (delete-other-windows)
9949 (split-window-vertically)
9950 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9951 (erase-buffer)
9952 (org-set-local 'org-done-keywords done-keywords)
9953 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9954 (org-fast-tag-insert "Current" current c-face "\n\n")
9955 (org-fast-tag-show-exit exit-after-next)
9956 (org-set-current-tags-overlay current ov-prefix)
9957 (setq tbl fulltable char ?a cnt 0)
9958 (while (setq e (pop tbl))
9959 (cond
9960 ((equal e '(:startgroup))
9961 (push '() groups) (setq ingroup t)
9962 (when (not (= cnt 0))
9963 (setq cnt 0)
9964 (insert "\n"))
9965 (insert "{ "))
9966 ((equal e '(:endgroup))
9967 (setq ingroup nil cnt 0)
9968 (insert "}\n"))
9970 (setq tg (car e) c2 nil)
9971 (if (cdr e)
9972 (setq c (cdr e))
9973 ;; automatically assign a character.
9974 (setq c1 (string-to-char
9975 (downcase (substring
9976 tg (if (= (string-to-char tg) ?@) 1 0)))))
9977 (if (or (rassoc c1 ntable) (rassoc c1 table))
9978 (while (or (rassoc char ntable) (rassoc char table))
9979 (setq char (1+ char)))
9980 (setq c2 c1))
9981 (setq c (or c2 char)))
9982 (if ingroup (push tg (car groups)))
9983 (setq tg (org-add-props tg nil 'face
9984 (cond
9985 ((not (assoc tg table))
9986 (org-get-todo-face tg))
9987 ((member tg current) c-face)
9988 ((member tg inherited) i-face)
9989 (t nil))))
9990 (if (and (= cnt 0) (not ingroup)) (insert " "))
9991 (insert "[" c "] " tg (make-string
9992 (- fwidth 4 (length tg)) ?\ ))
9993 (push (cons tg c) ntable)
9994 (when (= (setq cnt (1+ cnt)) ncol)
9995 (insert "\n")
9996 (if ingroup (insert " "))
9997 (setq cnt 0)))))
9998 (setq ntable (nreverse ntable))
9999 (insert "\n")
10000 (goto-char (point-min))
10001 (if (not expert) (org-fit-window-to-buffer))
10002 (setq rtn
10003 (catch 'exit
10004 (while t
10005 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10006 (if groups " [!] no groups" " [!]groups")
10007 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10008 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10009 (cond
10010 ((= c ?\r) (throw 'exit t))
10011 ((= c ?!)
10012 (setq groups (not groups))
10013 (goto-char (point-min))
10014 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10015 ((= c ?\C-c)
10016 (if (not expert)
10017 (org-fast-tag-show-exit
10018 (setq exit-after-next (not exit-after-next)))
10019 (setq expert nil)
10020 (delete-other-windows)
10021 (split-window-vertically)
10022 (org-switch-to-buffer-other-window " *Org tags*")
10023 (org-fit-window-to-buffer)))
10024 ((or (= c ?\C-g)
10025 (and (= c ?q) (not (rassoc c ntable))))
10026 (org-detach-overlay org-tags-overlay)
10027 (setq quit-flag t))
10028 ((= c ?\ )
10029 (setq current nil)
10030 (if exit-after-next (setq exit-after-next 'now)))
10031 ((= c ?\t)
10032 (condition-case nil
10033 (setq tg (org-ido-completing-read
10034 "Tag: "
10035 (or buffer-tags
10036 (with-current-buffer buf
10037 (org-get-buffer-tags)))))
10038 (quit (setq tg "")))
10039 (when (string-match "\\S-" tg)
10040 (add-to-list 'buffer-tags (list tg))
10041 (if (member tg current)
10042 (setq current (delete tg current))
10043 (push tg current)))
10044 (if exit-after-next (setq exit-after-next 'now)))
10045 ((setq e (rassoc c todo-table) tg (car e))
10046 (with-current-buffer buf
10047 (save-excursion (org-todo tg)))
10048 (if exit-after-next (setq exit-after-next 'now)))
10049 ((setq e (rassoc c ntable) tg (car e))
10050 (if (member tg current)
10051 (setq current (delete tg current))
10052 (loop for g in groups do
10053 (if (member tg g)
10054 (mapc (lambda (x)
10055 (setq current (delete x current)))
10056 g)))
10057 (push tg current))
10058 (if exit-after-next (setq exit-after-next 'now))))
10060 ;; Create a sorted list
10061 (setq current
10062 (sort current
10063 (lambda (a b)
10064 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10065 (if (eq exit-after-next 'now) (throw 'exit t))
10066 (goto-char (point-min))
10067 (beginning-of-line 2)
10068 (delete-region (point) (point-at-eol))
10069 (org-fast-tag-insert "Current" current c-face)
10070 (org-set-current-tags-overlay current ov-prefix)
10071 (while (re-search-forward
10072 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10073 (setq tg (match-string 1))
10074 (add-text-properties
10075 (match-beginning 1) (match-end 1)
10076 (list 'face
10077 (cond
10078 ((member tg current) c-face)
10079 ((member tg inherited) i-face)
10080 (t (get-text-property (match-beginning 1) 'face))))))
10081 (goto-char (point-min)))))
10082 (org-detach-overlay org-tags-overlay)
10083 (if rtn
10084 (mapconcat 'identity current ":")
10085 nil))))
10087 (defun org-get-tags-string ()
10088 "Get the TAGS string in the current headline."
10089 (unless (org-on-heading-p t)
10090 (error "Not on a heading"))
10091 (save-excursion
10092 (beginning-of-line 1)
10093 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10094 (org-match-string-no-properties 1)
10095 "")))
10097 (defun org-get-tags ()
10098 "Get the list of tags specified in the current headline."
10099 (org-split-string (org-get-tags-string) ":"))
10101 (defun org-get-buffer-tags ()
10102 "Get a table of all tags used in the buffer, for completion."
10103 (let (tags)
10104 (save-excursion
10105 (goto-char (point-min))
10106 (while (re-search-forward
10107 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10108 (when (equal (char-after (point-at-bol 0)) ?*)
10109 (mapc (lambda (x) (add-to-list 'tags x))
10110 (org-split-string (org-match-string-no-properties 1) ":")))))
10111 (mapcar 'list tags)))
10113 ;;;; The mapping API
10115 ;;;###autoload
10116 (defun org-map-entries (func &optional match scope &rest skip)
10117 "Call FUNC at each headline selected by MATCH in SCOPE.
10119 FUNC is a function or a lisp form. The function will be called without
10120 arguments, with the cursor positioned at the beginning of the headline.
10121 The return values of all calls to the function will be collected and
10122 returned as a list.
10124 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10125 Only headlines that are matched by this query will be considered during
10126 the iteration. When MATCH is nil or t, all headlines will be
10127 visited by the iteration.
10129 SCOPE determines the scope of this command. It can be any of:
10131 nil The current buffer, respecting the restriction if any
10132 tree The subtree started with the entry at point
10133 file The current buffer, without restriction
10134 file-with-archives
10135 The current buffer, and any archives associated with it
10136 agenda All agenda files
10137 agenda-with-archives
10138 All agenda files with any archive files associated with them
10139 \(file1 file2 ...)
10140 If this is a list, all files in the list will be scanned
10142 The remaining args are treated as settings for the skipping facilities of
10143 the scanner. The following items can be given here:
10145 archive skip trees with the archive tag.
10146 comment skip trees with the COMMENT keyword
10147 function or Emacs Lisp form:
10148 will be used as value for `org-agenda-skip-function', so whenever
10149 the the function returns t, FUNC will not be called for that
10150 entry and search will continue from the point where the
10151 function leaves it."
10152 (let* ((org-agenda-archives-mode nil) ; just to make sure
10153 (org-agenda-skip-archived-trees (memq 'archive skip))
10154 (org-agenda-skip-comment-trees (memq 'comment skip))
10155 (org-agenda-skip-function
10156 (car (org-delete-all '(comment archive) skip)))
10157 (org-tags-match-list-sublevels t)
10158 matcher pos file res
10159 org-todo-keywords-for-agenda
10160 org-done-keywords-for-agenda
10161 org-todo-keyword-alist-for-agenda
10162 org-tag-alist-for-agenda)
10164 (cond
10165 ((eq match t) (setq matcher t))
10166 ((eq match nil) (setq matcher t))
10167 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10169 (when (eq scope 'tree)
10170 (org-back-to-heading t)
10171 (org-narrow-to-subtree)
10172 (setq scope nil))
10174 (if (not scope)
10175 (progn
10176 (org-prepare-agenda-buffers
10177 (list (buffer-file-name (current-buffer))))
10178 (org-scan-tags func matcher))
10179 ;; Get the right scope
10180 (setq pos (point))
10181 (cond
10182 ((and scope (listp scope) (symbolp (car scope)))
10183 (setq scope (eval scope)))
10184 ((eq scope 'agenda)
10185 (setq scope (org-agenda-files t)))
10186 ((eq scope 'agenda-with-archives)
10187 (setq scope (org-agenda-files t))
10188 (setq scope (org-add-archive-files scope)))
10189 ((eq scope 'file)
10190 (setq scope (list (buffer-file-name))))
10191 ((eq scope 'file-with-archives)
10192 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10193 (org-prepare-agenda-buffers scope)
10194 (while (setq file (pop scope))
10195 (with-current-buffer (org-find-base-buffer-visiting file)
10196 (save-excursion
10197 (save-restriction
10198 (widen)
10199 (goto-char (point-min))
10200 (setq res (append res (org-scan-tags func matcher)))))))
10201 res)))
10203 ;;;; Properties
10205 ;;; Setting and retrieving properties
10207 (defconst org-special-properties
10208 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10209 "TIMESTAMP" "TIMESTAMP_IA")
10210 "The special properties valid in Org-mode.
10212 These are properties that are not defined in the property drawer,
10213 but in some other way.")
10215 (defconst org-default-properties
10216 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10217 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10218 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10219 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10220 "Some properties that are used by Org-mode for various purposes.
10221 Being in this list makes sure that they are offered for completion.")
10223 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10224 "Regular expression matching the first line of a property drawer.")
10226 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10227 "Regular expression matching the first line of a property drawer.")
10229 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10230 "Regular expression matching the first line of a property drawer.")
10232 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10233 "Regular expression matching the first line of a property drawer.")
10235 (defconst org-property-drawer-re
10236 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10237 org-property-end-re "\\)\n?")
10238 "Matches an entire property drawer.")
10240 (defconst org-clock-drawer-re
10241 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10242 org-property-end-re "\\)\n?")
10243 "Matches an entire clock drawer.")
10245 (defun org-property-action ()
10246 "Do an action on properties."
10247 (interactive)
10248 (let (c)
10249 (org-at-property-p)
10250 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10251 (setq c (read-char-exclusive))
10252 (cond
10253 ((equal c ?s)
10254 (call-interactively 'org-set-property))
10255 ((equal c ?d)
10256 (call-interactively 'org-delete-property))
10257 ((equal c ?D)
10258 (call-interactively 'org-delete-property-globally))
10259 ((equal c ?c)
10260 (call-interactively 'org-compute-property-at-point))
10261 (t (error "No such property action %c" c)))))
10263 (defun org-at-property-p ()
10264 "Is the cursor in a property line?"
10265 ;; FIXME: Does not check if we are actually in the drawer.
10266 ;; FIXME: also returns true on any drawers.....
10267 ;; This is used by C-c C-c for property action.
10268 (save-excursion
10269 (beginning-of-line 1)
10270 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10272 (defun org-get-property-block (&optional beg end force)
10273 "Return the (beg . end) range of the body of the property drawer.
10274 BEG and END can be beginning and end of subtree, if not given
10275 they will be found.
10276 If the drawer does not exist and FORCE is non-nil, create the drawer."
10277 (catch 'exit
10278 (save-excursion
10279 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10280 (end (or end (progn (outline-next-heading) (point)))))
10281 (goto-char beg)
10282 (if (re-search-forward org-property-start-re end t)
10283 (setq beg (1+ (match-end 0)))
10284 (if force
10285 (save-excursion
10286 (org-insert-property-drawer)
10287 (setq end (progn (outline-next-heading) (point))))
10288 (throw 'exit nil))
10289 (goto-char beg)
10290 (if (re-search-forward org-property-start-re end t)
10291 (setq beg (1+ (match-end 0)))))
10292 (if (re-search-forward org-property-end-re end t)
10293 (setq end (match-beginning 0))
10294 (or force (throw 'exit nil))
10295 (goto-char beg)
10296 (setq end beg)
10297 (org-indent-line-function)
10298 (insert ":END:\n"))
10299 (cons beg end)))))
10301 (defun org-entry-properties (&optional pom which)
10302 "Get all properties of the entry at point-or-marker POM.
10303 This includes the TODO keyword, the tags, time strings for deadline,
10304 scheduled, and clocking, and any additional properties defined in the
10305 entry. The return value is an alist, keys may occur multiple times
10306 if the property key was used several times.
10307 POM may also be nil, in which case the current entry is used.
10308 If WHICH is nil or `all', get all properties. If WHICH is
10309 `special' or `standard', only get that subclass."
10310 (setq which (or which 'all))
10311 (org-with-point-at pom
10312 (let ((clockstr (substring org-clock-string 0 -1))
10313 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10314 beg end range props sum-props key value string clocksum)
10315 (save-excursion
10316 (when (condition-case nil
10317 (and (org-mode-p) (org-back-to-heading t))
10318 (error nil))
10319 (setq beg (point))
10320 (setq sum-props (get-text-property (point) 'org-summaries))
10321 (setq clocksum (get-text-property (point) :org-clock-minutes))
10322 (outline-next-heading)
10323 (setq end (point))
10324 (when (memq which '(all special))
10325 ;; Get the special properties, like TODO and tags
10326 (goto-char beg)
10327 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10328 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10329 (when (looking-at org-priority-regexp)
10330 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10331 (when (and (setq value (org-get-tags-string))
10332 (string-match "\\S-" value))
10333 (push (cons "TAGS" value) props))
10334 (when (setq value (org-get-tags-at))
10335 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10336 props))
10337 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10338 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10339 string (if (equal key clockstr)
10340 (org-no-properties
10341 (org-trim
10342 (buffer-substring
10343 (match-beginning 3) (goto-char (point-at-eol)))))
10344 (substring (org-match-string-no-properties 3) 1 -1)))
10345 (unless key
10346 (if (= (char-after (match-beginning 3)) ?\[)
10347 (setq key "TIMESTAMP_IA")
10348 (setq key "TIMESTAMP")))
10349 (when (or (equal key clockstr) (not (assoc key props)))
10350 (push (cons key string) props)))
10354 (when (memq which '(all standard))
10355 ;; Get the standard properties, like :PORP: ...
10356 (setq range (org-get-property-block beg end))
10357 (when range
10358 (goto-char (car range))
10359 (while (re-search-forward
10360 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10361 (cdr range) t)
10362 (setq key (org-match-string-no-properties 1)
10363 value (org-trim (or (org-match-string-no-properties 2) "")))
10364 (unless (member key excluded)
10365 (push (cons key (or value "")) props)))))
10366 (if clocksum
10367 (push (cons "CLOCKSUM"
10368 (org-columns-number-to-string (/ (float clocksum) 60.)
10369 'add_times))
10370 props))
10371 (unless (assoc "CATEGORY" props)
10372 (setq value (or (org-get-category)
10373 (progn (org-refresh-category-properties)
10374 (org-get-category))))
10375 (push (cons "CATEGORY" value) props))
10376 (append sum-props (nreverse props)))))))
10378 (defun org-entry-get (pom property &optional inherit)
10379 "Get value of PROPERTY for entry at point-or-marker POM.
10380 If INHERIT is non-nil and the entry does not have the property,
10381 then also check higher levels of the hierarchy.
10382 If INHERIT is the symbol `selective', use inheritance only if the setting
10383 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10384 If the property is present but empty, the return value is the empty string.
10385 If the property is not present at all, nil is returned."
10386 (org-with-point-at pom
10387 (if (and inherit (if (eq inherit 'selective)
10388 (org-property-inherit-p property)
10390 (org-entry-get-with-inheritance property)
10391 (if (member property org-special-properties)
10392 ;; We need a special property. Use brute force, get all properties.
10393 (cdr (assoc property (org-entry-properties nil 'special)))
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 ;; Found the property, return it.
10401 (if (match-end 1)
10402 (org-match-string-no-properties 1)
10403 "")))))))
10405 (defun org-property-or-variable-value (var &optional inherit)
10406 "Check if there is a property fixing the value of VAR.
10407 If yes, return this value. If not, return the current value of the variable."
10408 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10409 (if (and prop (stringp prop) (string-match "\\S-" prop))
10410 (read prop)
10411 (symbol-value var))))
10413 (defun org-entry-delete (pom property)
10414 "Delete the property PROPERTY from entry at point-or-marker POM."
10415 (org-with-point-at pom
10416 (if (member property org-special-properties)
10417 nil ; cannot delete these properties.
10418 (let ((range (org-get-property-block)))
10419 (if (and range
10420 (goto-char (car range))
10421 (re-search-forward
10422 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10423 (cdr range) t))
10424 (progn
10425 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10427 nil)))))
10429 ;; Multi-values properties are properties that contain multiple values
10430 ;; These values are assumed to be single words, separated by whitespace.
10431 (defun org-entry-add-to-multivalued-property (pom property value)
10432 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10433 (let* ((old (org-entry-get pom property))
10434 (values (and old (org-split-string old "[ \t]"))))
10435 (setq value (org-entry-protect-space value))
10436 (unless (member value values)
10437 (setq values (cons value values))
10438 (org-entry-put pom property
10439 (mapconcat 'identity values " ")))))
10441 (defun org-entry-remove-from-multivalued-property (pom property value)
10442 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10443 (let* ((old (org-entry-get pom property))
10444 (values (and old (org-split-string old "[ \t]"))))
10445 (setq value (org-entry-protect-space value))
10446 (when (member value values)
10447 (setq values (delete value values))
10448 (org-entry-put pom property
10449 (mapconcat 'identity values " ")))))
10451 (defun org-entry-member-in-multivalued-property (pom property value)
10452 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10453 (let* ((old (org-entry-get pom property))
10454 (values (and old (org-split-string old "[ \t]"))))
10455 (setq value (org-entry-protect-space value))
10456 (member value values)))
10458 (defun org-entry-get-multivalued-property (pom property)
10459 "Return a list of values in a multivalued property."
10460 (let* ((value (org-entry-get pom property))
10461 (values (and value (org-split-string value "[ \t]"))))
10462 (mapcar 'org-entry-restore-space values)))
10464 (defun org-entry-put-multivalued-property (pom property &rest values)
10465 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10466 VALUES should be a list of strings. Spaces will be protected."
10467 (org-entry-put pom property
10468 (mapconcat 'org-entry-protect-space values " "))
10469 (let* ((value (org-entry-get pom property))
10470 (values (and value (org-split-string value "[ \t]"))))
10471 (mapcar 'org-entry-restore-space values)))
10473 (defun org-entry-protect-space (s)
10474 "Protect spaces and newline in string S."
10475 (while (string-match " " s)
10476 (setq s (replace-match "%20" t t s)))
10477 (while (string-match "\n" s)
10478 (setq s (replace-match "%0A" t t s)))
10481 (defun org-entry-restore-space (s)
10482 "Restore spaces and newline in string S."
10483 (while (string-match "%20" s)
10484 (setq s (replace-match " " t t s)))
10485 (while (string-match "%0A" s)
10486 (setq s (replace-match "\n" t t s)))
10489 (defvar org-entry-property-inherited-from (make-marker)
10490 "Marker pointing to the entry from where a property was inherited.
10491 Each call to `org-entry-get-with-inheritance' will set this marker to the
10492 location of the entry where the inheritance search matched. If there was
10493 no match, the marker will point nowhere.
10494 Note that also `org-entry-get' calls this function, if the INHERIT flag
10495 is set.")
10497 (defun org-entry-get-with-inheritance (property)
10498 "Get entry property, and search higher levels if not present."
10499 (move-marker org-entry-property-inherited-from nil)
10500 (let (tmp)
10501 (save-excursion
10502 (save-restriction
10503 (widen)
10504 (catch 'ex
10505 (while t
10506 (when (setq tmp (org-entry-get nil property))
10507 (org-back-to-heading t)
10508 (move-marker org-entry-property-inherited-from (point))
10509 (throw 'ex tmp))
10510 (or (org-up-heading-safe) (throw 'ex nil)))))
10511 (or tmp
10512 (cdr (assoc property org-file-properties))
10513 (cdr (assoc property org-global-properties))
10514 (cdr (assoc property org-global-properties-fixed))))))
10516 (defun org-entry-put (pom property value)
10517 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10518 (org-with-point-at pom
10519 (org-back-to-heading t)
10520 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10521 range)
10522 (cond
10523 ((equal property "TODO")
10524 (when (and (stringp value) (string-match "\\S-" value)
10525 (not (member value org-todo-keywords-1)))
10526 (error "\"%s\" is not a valid TODO state" value))
10527 (if (or (not value)
10528 (not (string-match "\\S-" value)))
10529 (setq value 'none))
10530 (org-todo value)
10531 (org-set-tags nil 'align))
10532 ((equal property "PRIORITY")
10533 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10534 (string-to-char value) ?\ ))
10535 (org-set-tags nil 'align))
10536 ((equal property "SCHEDULED")
10537 (if (re-search-forward org-scheduled-time-regexp end t)
10538 (cond
10539 ((eq value 'earlier) (org-timestamp-change -1 'day))
10540 ((eq value 'later) (org-timestamp-change 1 'day))
10541 (t (call-interactively 'org-schedule)))
10542 (call-interactively 'org-schedule)))
10543 ((equal property "DEADLINE")
10544 (if (re-search-forward org-deadline-time-regexp end t)
10545 (cond
10546 ((eq value 'earlier) (org-timestamp-change -1 'day))
10547 ((eq value 'later) (org-timestamp-change 1 'day))
10548 (t (call-interactively 'org-deadline)))
10549 (call-interactively 'org-deadline)))
10550 ((member property org-special-properties)
10551 (error "The %s property can not yet be set with `org-entry-put'"
10552 property))
10553 (t ; a non-special property
10554 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10555 (setq range (org-get-property-block beg end 'force))
10556 (goto-char (car range))
10557 (if (re-search-forward
10558 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10559 (progn
10560 (delete-region (match-beginning 1) (match-end 1))
10561 (goto-char (match-beginning 1)))
10562 (goto-char (cdr range))
10563 (insert "\n")
10564 (backward-char 1)
10565 (org-indent-line-function)
10566 (insert ":" property ":"))
10567 (and value (insert " " value))
10568 (org-indent-line-function)))))))
10570 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10571 "Get all property keys in the current buffer.
10572 With INCLUDE-SPECIALS, also list the special properties that reflect things
10573 like tags and TODO state.
10574 With INCLUDE-DEFAULTS, also include properties that has special meaning
10575 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10576 With INCLUDE-COLUMNS, also include property names given in COLUMN
10577 formats in the current buffer."
10578 (let (rtn range cfmt cols s p)
10579 (save-excursion
10580 (save-restriction
10581 (widen)
10582 (goto-char (point-min))
10583 (while (re-search-forward org-property-start-re nil t)
10584 (setq range (org-get-property-block))
10585 (goto-char (car range))
10586 (while (re-search-forward
10587 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10588 (cdr range) t)
10589 (add-to-list 'rtn (org-match-string-no-properties 1)))
10590 (outline-next-heading))))
10592 (when include-specials
10593 (setq rtn (append org-special-properties rtn)))
10595 (when include-defaults
10596 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10598 (when include-columns
10599 (save-excursion
10600 (save-restriction
10601 (widen)
10602 (goto-char (point-min))
10603 (while (re-search-forward
10604 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10605 nil t)
10606 (setq cfmt (match-string 2) s 0)
10607 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10608 cfmt s)
10609 (setq s (match-end 0)
10610 p (match-string 1 cfmt))
10611 (unless (or (equal p "ITEM")
10612 (member p org-special-properties))
10613 (add-to-list 'rtn (match-string 1 cfmt))))))))
10615 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10617 (defun org-property-values (key)
10618 "Return a list of all values of property KEY."
10619 (save-excursion
10620 (save-restriction
10621 (widen)
10622 (goto-char (point-min))
10623 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10624 values)
10625 (while (re-search-forward re nil t)
10626 (add-to-list 'values (org-trim (match-string 1))))
10627 (delete "" values)))))
10629 (defun org-insert-property-drawer ()
10630 "Insert a property drawer into the current entry."
10631 (interactive)
10632 (org-back-to-heading t)
10633 (looking-at outline-regexp)
10634 (let ((indent (- (match-end 0)(match-beginning 0)))
10635 (beg (point))
10636 (re (concat "^[ \t]*" org-keyword-time-regexp))
10637 end hiddenp)
10638 (outline-next-heading)
10639 (setq end (point))
10640 (goto-char beg)
10641 (while (re-search-forward re end t))
10642 (setq hiddenp (org-invisible-p))
10643 (end-of-line 1)
10644 (and (equal (char-after) ?\n) (forward-char 1))
10645 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10646 (beginning-of-line 2))
10647 (org-skip-over-state-notes)
10648 (skip-chars-backward " \t\n\r")
10649 (if (eq (char-before) ?*) (forward-char 1))
10650 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10651 (beginning-of-line 0)
10652 (org-indent-to-column indent)
10653 (beginning-of-line 2)
10654 (org-indent-to-column indent)
10655 (beginning-of-line 0)
10656 (if hiddenp
10657 (save-excursion
10658 (org-back-to-heading t)
10659 (hide-entry))
10660 (org-flag-drawer t))))
10662 (defun org-set-property (property value)
10663 "In the current entry, set PROPERTY to VALUE.
10664 When called interactively, this will prompt for a property name, offering
10665 completion on existing and default properties. And then it will prompt
10666 for a value, offering completion either on allowed values (via an inherited
10667 xxx_ALL property) or on existing values in other instances of this property
10668 in the current file."
10669 (interactive
10670 (let* ((completion-ignore-case t)
10671 (keys (org-buffer-property-keys nil t t))
10672 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10673 (prop (if (member prop0 keys)
10674 prop0
10675 (or (cdr (assoc (downcase prop0)
10676 (mapcar (lambda (x) (cons (downcase x) x))
10677 keys)))
10678 prop0)))
10679 (cur (org-entry-get nil prop))
10680 (allowed (org-property-get-allowed-values nil prop 'table))
10681 (existing (mapcar 'list (org-property-values prop)))
10682 (val (if allowed
10683 (org-completing-read "Value: " allowed nil 'req-match)
10684 (org-completing-read
10685 (concat "Value" (if (and cur (string-match "\\S-" cur))
10686 (concat "[" cur "]") "")
10687 ": ")
10688 existing nil nil "" nil cur))))
10689 (list prop (if (equal val "") cur val))))
10690 (unless (equal (org-entry-get nil property) value)
10691 (org-entry-put nil property value)))
10693 (defun org-delete-property (property)
10694 "In the current entry, delete PROPERTY."
10695 (interactive
10696 (let* ((completion-ignore-case t)
10697 (prop (org-ido-completing-read
10698 "Property: " (org-entry-properties nil 'standard))))
10699 (list prop)))
10700 (message "Property %s %s" property
10701 (if (org-entry-delete nil property)
10702 "deleted"
10703 "was not present in the entry")))
10705 (defun org-delete-property-globally (property)
10706 "Remove PROPERTY globally, from all entries."
10707 (interactive
10708 (let* ((completion-ignore-case t)
10709 (prop (org-ido-completing-read
10710 "Globally remove property: "
10711 (mapcar 'list (org-buffer-property-keys)))))
10712 (list prop)))
10713 (save-excursion
10714 (save-restriction
10715 (widen)
10716 (goto-char (point-min))
10717 (let ((cnt 0))
10718 (while (re-search-forward
10719 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10720 nil t)
10721 (setq cnt (1+ cnt))
10722 (replace-match ""))
10723 (message "Property \"%s\" removed from %d entries" property cnt)))))
10725 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10727 (defun org-compute-property-at-point ()
10728 "Compute the property at point.
10729 This looks for an enclosing column format, extracts the operator and
10730 then applies it to the property in the column format's scope."
10731 (interactive)
10732 (unless (org-at-property-p)
10733 (error "Not at a property"))
10734 (let ((prop (org-match-string-no-properties 2)))
10735 (org-columns-get-format-and-top-level)
10736 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10737 (error "No operator defined for property %s" prop))
10738 (org-columns-compute prop)))
10740 (defun org-property-get-allowed-values (pom property &optional table)
10741 "Get allowed values for the property PROPERTY.
10742 When TABLE is non-nil, return an alist that can directly be used for
10743 completion."
10744 (let (vals)
10745 (cond
10746 ((equal property "TODO")
10747 (setq vals (org-with-point-at pom
10748 (append org-todo-keywords-1 '("")))))
10749 ((equal property "PRIORITY")
10750 (let ((n org-lowest-priority))
10751 (while (>= n org-highest-priority)
10752 (push (char-to-string n) vals)
10753 (setq n (1- n)))))
10754 ((member property org-special-properties))
10756 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10758 (when (and vals (string-match "\\S-" vals))
10759 (setq vals (car (read-from-string (concat "(" vals ")"))))
10760 (setq vals (mapcar (lambda (x)
10761 (cond ((stringp x) x)
10762 ((numberp x) (number-to-string x))
10763 ((symbolp x) (symbol-name x))
10764 (t "???")))
10765 vals)))))
10766 (if table (mapcar 'list vals) vals)))
10768 (defun org-property-previous-allowed-value (&optional previous)
10769 "Switch to the next allowed value for this property."
10770 (interactive)
10771 (org-property-next-allowed-value t))
10773 (defun org-property-next-allowed-value (&optional previous)
10774 "Switch to the next allowed value for this property."
10775 (interactive)
10776 (unless (org-at-property-p)
10777 (error "Not at a property"))
10778 (let* ((key (match-string 2))
10779 (value (match-string 3))
10780 (allowed (or (org-property-get-allowed-values (point) key)
10781 (and (member value '("[ ]" "[-]" "[X]"))
10782 '("[ ]" "[X]"))))
10783 nval)
10784 (unless allowed
10785 (error "Allowed values for this property have not been defined"))
10786 (if previous (setq allowed (reverse allowed)))
10787 (if (member value allowed)
10788 (setq nval (car (cdr (member value allowed)))))
10789 (setq nval (or nval (car allowed)))
10790 (if (equal nval value)
10791 (error "Only one allowed value for this property"))
10792 (org-at-property-p)
10793 (replace-match (concat " :" key ": " nval) t t)
10794 (org-indent-line-function)
10795 (beginning-of-line 1)
10796 (skip-chars-forward " \t")))
10798 (defun org-find-entry-with-id (ident)
10799 "Locate the entry that contains the ID property with exact value IDENT.
10800 IDENT can be a string, a symbol or a number, this function will search for
10801 the string representation of it.
10802 Return the position where this entry starts, or nil if there is no such entry."
10803 (interactive "sID: ")
10804 (let ((id (cond
10805 ((stringp ident) ident)
10806 ((symbol-name ident) (symbol-name ident))
10807 ((numberp ident) (number-to-string ident))
10808 (t (error "IDENT %s must be a string, symbol or number" ident))))
10809 (case-fold-search nil))
10810 (save-excursion
10811 (save-restriction
10812 (widen)
10813 (goto-char (point-min))
10814 (when (re-search-forward
10815 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10816 nil t)
10817 (org-back-to-heading)
10818 (point))))))
10820 ;;;; Timestamps
10822 (defvar org-last-changed-timestamp nil)
10823 (defvar org-last-inserted-timestamp nil
10824 "The last time stamp inserted with `org-insert-time-stamp'.")
10825 (defvar org-time-was-given) ; dynamically scoped parameter
10826 (defvar org-end-time-was-given) ; dynamically scoped parameter
10827 (defvar org-ts-what) ; dynamically scoped parameter
10829 (defun org-time-stamp (arg &optional inactive)
10830 "Prompt for a date/time and insert a time stamp.
10831 If the user specifies a time like HH:MM, or if this command is called
10832 with a prefix argument, the time stamp will contain date and time.
10833 Otherwise, only the date will be included. All parts of a date not
10834 specified by the user will be filled in from the current date/time.
10835 So if you press just return without typing anything, the time stamp
10836 will represent the current date/time. If there is already a timestamp
10837 at the cursor, it will be modified."
10838 (interactive "P")
10839 (let* ((ts nil)
10840 (default-time
10841 ;; Default time is either today, or, when entering a range,
10842 ;; the range start.
10843 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10844 (save-excursion
10845 (re-search-backward
10846 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10847 (- (point) 20) t)))
10848 (apply 'encode-time (org-parse-time-string (match-string 1)))
10849 (current-time)))
10850 (default-input (and ts (org-get-compact-tod ts)))
10851 org-time-was-given org-end-time-was-given time)
10852 (cond
10853 ((and (org-at-timestamp-p t)
10854 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10855 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10856 (insert "--")
10857 (setq time (let ((this-command this-command))
10858 (org-read-date arg 'totime nil nil
10859 default-time default-input)))
10860 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10861 ((org-at-timestamp-p t)
10862 (setq time (let ((this-command this-command))
10863 (org-read-date arg 'totime nil nil default-time default-input)))
10864 (when (org-at-timestamp-p t) ; just to get the match data
10865 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10866 (replace-match "")
10867 (setq org-last-changed-timestamp
10868 (org-insert-time-stamp
10869 time (or org-time-was-given arg)
10870 inactive nil nil (list org-end-time-was-given))))
10871 (message "Timestamp updated"))
10873 (setq time (let ((this-command this-command))
10874 (org-read-date arg 'totime nil nil default-time default-input)))
10875 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10876 nil nil (list org-end-time-was-given))))))
10878 ;; FIXME: can we use this for something else, like computing time differences?
10879 (defun org-get-compact-tod (s)
10880 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10881 (let* ((t1 (match-string 1 s))
10882 (h1 (string-to-number (match-string 2 s)))
10883 (m1 (string-to-number (match-string 3 s)))
10884 (t2 (and (match-end 4) (match-string 5 s)))
10885 (h2 (and t2 (string-to-number (match-string 6 s))))
10886 (m2 (and t2 (string-to-number (match-string 7 s))))
10887 dh dm)
10888 (if (not t2)
10890 (setq dh (- h2 h1) dm (- m2 m1))
10891 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10892 (concat t1 "+" (number-to-string dh)
10893 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10895 (defun org-time-stamp-inactive (&optional arg)
10896 "Insert an inactive time stamp.
10897 An inactive time stamp is enclosed in square brackets instead of angle
10898 brackets. It is inactive in the sense that it does not trigger agenda entries,
10899 does not link to the calendar and cannot be changed with the S-cursor keys.
10900 So these are more for recording a certain time/date."
10901 (interactive "P")
10902 (org-time-stamp arg 'inactive))
10904 (defvar org-date-ovl (org-make-overlay 1 1))
10905 (org-overlay-put org-date-ovl 'face 'org-warning)
10906 (org-detach-overlay org-date-ovl)
10908 (defvar org-ans1) ; dynamically scoped parameter
10909 (defvar org-ans2) ; dynamically scoped parameter
10911 (defvar org-plain-time-of-day-regexp) ; defined below
10913 (defvar org-overriding-default-time nil) ; dynamically scoped
10914 (defvar org-read-date-overlay nil)
10915 (defvar org-dcst nil) ; dynamically scoped
10917 (defun org-read-date (&optional with-time to-time from-string prompt
10918 default-time default-input)
10919 "Read a date, possibly a time, and make things smooth for the user.
10920 The prompt will suggest to enter an ISO date, but you can also enter anything
10921 which will at least partially be understood by `parse-time-string'.
10922 Unrecognized parts of the date will default to the current day, month, year,
10923 hour and minute. If this command is called to replace a timestamp at point,
10924 of to enter the second timestamp of a range, the default time is taken from the
10925 existing stamp. For example,
10926 3-2-5 --> 2003-02-05
10927 feb 15 --> currentyear-02-15
10928 sep 12 9 --> 2009-09-12
10929 12:45 --> today 12:45
10930 22 sept 0:34 --> currentyear-09-22 0:34
10931 12 --> currentyear-currentmonth-12
10932 Fri --> nearest Friday (today or later)
10933 etc.
10935 Furthermore you can specify a relative date by giving, as the *first* thing
10936 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10937 change in days weeks, months, years.
10938 With a single plus or minus, the date is relative to today. With a double
10939 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10940 +4d --> four days from today
10941 +4 --> same as above
10942 +2w --> two weeks from today
10943 ++5 --> five days from default date
10945 The function understands only English month and weekday abbreviations,
10946 but this can be configured with the variables `parse-time-months' and
10947 `parse-time-weekdays'.
10949 While prompting, a calendar is popped up - you can also select the
10950 date with the mouse (button 1). The calendar shows a period of three
10951 months. To scroll it to other months, use the keys `>' and `<'.
10952 If you don't like the calendar, turn it off with
10953 \(setq org-read-date-popup-calendar nil)
10955 With optional argument TO-TIME, the date will immediately be converted
10956 to an internal time.
10957 With an optional argument WITH-TIME, the prompt will suggest to also
10958 insert a time. Note that when WITH-TIME is not set, you can still
10959 enter a time, and this function will inform the calling routine about
10960 this change. The calling routine may then choose to change the format
10961 used to insert the time stamp into the buffer to include the time.
10962 With optional argument FROM-STRING, read from this string instead from
10963 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10964 the time/date that is used for everything that is not specified by the
10965 user."
10966 (require 'parse-time)
10967 (let* ((org-time-stamp-rounding-minutes
10968 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10969 (org-dcst org-display-custom-times)
10970 (ct (org-current-time))
10971 (def (or org-overriding-default-time default-time ct))
10972 (defdecode (decode-time def))
10973 (dummy (progn
10974 (when (< (nth 2 defdecode) org-extend-today-until)
10975 (setcar (nthcdr 2 defdecode) -1)
10976 (setcar (nthcdr 1 defdecode) 59)
10977 (setq def (apply 'encode-time defdecode)
10978 defdecode (decode-time def)))))
10979 (calendar-move-hook nil)
10980 (calendar-view-diary-initially-flag nil)
10981 (view-diary-entries-initially nil)
10982 (calendar-view-holidays-initially-flag nil)
10983 (view-calendar-holidays-initially nil)
10984 (timestr (format-time-string
10985 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10986 (prompt (concat (if prompt (concat prompt " ") "")
10987 (format "Date+time [%s]: " timestr)))
10988 ans (org-ans0 "") org-ans1 org-ans2 final)
10990 (cond
10991 (from-string (setq ans from-string))
10992 (org-read-date-popup-calendar
10993 (save-excursion
10994 (save-window-excursion
10995 (calendar)
10996 (calendar-forward-day (- (time-to-days def)
10997 (calendar-absolute-from-gregorian
10998 (calendar-current-date))))
10999 (org-eval-in-calendar nil t)
11000 (let* ((old-map (current-local-map))
11001 (map (copy-keymap calendar-mode-map))
11002 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11003 (org-defkey map (kbd "RET") 'org-calendar-select)
11004 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11005 'org-calendar-select-mouse)
11006 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11007 'org-calendar-select-mouse)
11008 (org-defkey minibuffer-local-map [(meta shift left)]
11009 (lambda () (interactive)
11010 (org-eval-in-calendar '(calendar-backward-month 1))))
11011 (org-defkey minibuffer-local-map [(meta shift right)]
11012 (lambda () (interactive)
11013 (org-eval-in-calendar '(calendar-forward-month 1))))
11014 (org-defkey minibuffer-local-map [(meta shift up)]
11015 (lambda () (interactive)
11016 (org-eval-in-calendar '(calendar-backward-year 1))))
11017 (org-defkey minibuffer-local-map [(meta shift down)]
11018 (lambda () (interactive)
11019 (org-eval-in-calendar '(calendar-forward-year 1))))
11020 (org-defkey minibuffer-local-map [(shift up)]
11021 (lambda () (interactive)
11022 (org-eval-in-calendar '(calendar-backward-week 1))))
11023 (org-defkey minibuffer-local-map [(shift down)]
11024 (lambda () (interactive)
11025 (org-eval-in-calendar '(calendar-forward-week 1))))
11026 (org-defkey minibuffer-local-map [(shift left)]
11027 (lambda () (interactive)
11028 (org-eval-in-calendar '(calendar-backward-day 1))))
11029 (org-defkey minibuffer-local-map [(shift right)]
11030 (lambda () (interactive)
11031 (org-eval-in-calendar '(calendar-forward-day 1))))
11032 (org-defkey minibuffer-local-map ">"
11033 (lambda () (interactive)
11034 (org-eval-in-calendar '(scroll-calendar-left 1))))
11035 (org-defkey minibuffer-local-map "<"
11036 (lambda () (interactive)
11037 (org-eval-in-calendar '(scroll-calendar-right 1))))
11038 (unwind-protect
11039 (progn
11040 (use-local-map map)
11041 (add-hook 'post-command-hook 'org-read-date-display)
11042 (setq org-ans0 (read-string prompt default-input nil nil))
11043 ;; org-ans0: from prompt
11044 ;; org-ans1: from mouse click
11045 ;; org-ans2: from calendar motion
11046 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11047 (remove-hook 'post-command-hook 'org-read-date-display)
11048 (use-local-map old-map)
11049 (when org-read-date-overlay
11050 (org-delete-overlay org-read-date-overlay)
11051 (setq org-read-date-overlay nil)))))))
11053 (t ; Naked prompt only
11054 (unwind-protect
11055 (setq ans (read-string prompt default-input nil timestr))
11056 (when org-read-date-overlay
11057 (org-delete-overlay org-read-date-overlay)
11058 (setq org-read-date-overlay nil)))))
11060 (setq final (org-read-date-analyze ans def defdecode))
11062 (if to-time
11063 (apply 'encode-time final)
11064 (if (and (boundp 'org-time-was-given) org-time-was-given)
11065 (format "%04d-%02d-%02d %02d:%02d"
11066 (nth 5 final) (nth 4 final) (nth 3 final)
11067 (nth 2 final) (nth 1 final))
11068 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11069 (defvar def)
11070 (defvar defdecode)
11071 (defvar with-time)
11072 (defun org-read-date-display ()
11073 "Display the current date prompt interpretation in the minibuffer."
11074 (when org-read-date-display-live
11075 (when org-read-date-overlay
11076 (org-delete-overlay org-read-date-overlay))
11077 (let ((p (point)))
11078 (end-of-line 1)
11079 (while (not (equal (buffer-substring
11080 (max (point-min) (- (point) 4)) (point))
11081 " "))
11082 (insert " "))
11083 (goto-char p))
11084 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11085 " " (or org-ans1 org-ans2)))
11086 (org-end-time-was-given nil)
11087 (f (org-read-date-analyze ans def defdecode))
11088 (fmts (if org-dcst
11089 org-time-stamp-custom-formats
11090 org-time-stamp-formats))
11091 (fmt (if (or with-time
11092 (and (boundp 'org-time-was-given) org-time-was-given))
11093 (cdr fmts)
11094 (car fmts)))
11095 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11096 (when (and org-end-time-was-given
11097 (string-match org-plain-time-of-day-regexp txt))
11098 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11099 org-end-time-was-given
11100 (substring txt (match-end 0)))))
11101 (setq org-read-date-overlay
11102 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11103 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11105 (defun org-read-date-analyze (ans def defdecode)
11106 "Analyse the combined answer of the date prompt."
11107 ;; FIXME: cleanup and comment
11108 (let (delta deltan deltaw deltadef year month day
11109 hour minute second wday pm h2 m2 tl wday1
11110 iso-year iso-weekday iso-week iso-year iso-date)
11112 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11113 (setq ans "+0"))
11115 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11116 (setq ans (replace-match "" t t ans)
11117 deltan (car delta)
11118 deltaw (nth 1 delta)
11119 deltadef (nth 2 delta)))
11121 ;; Check if there is an iso week date in there
11122 ;; If yes, sore the info and postpone interpreting it until the rest
11123 ;; of the parsing is done
11124 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11125 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11126 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11127 iso-week (string-to-number (match-string 2 ans)))
11128 (setq ans (replace-match "" t t ans)))
11130 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11131 (when (string-match
11132 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11133 (setq year (if (match-end 2)
11134 (string-to-number (match-string 2 ans))
11135 (string-to-number (format-time-string "%Y")))
11136 month (string-to-number (match-string 3 ans))
11137 day (string-to-number (match-string 4 ans)))
11138 (if (< year 100) (setq year (+ 2000 year)))
11139 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11140 t nil ans)))
11141 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11142 ;; If there is a time with am/pm, and *no* time without it, we convert
11143 ;; so that matching will be successful.
11144 (loop for i from 1 to 2 do ; twice, for end time as well
11145 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11146 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11147 (setq hour (string-to-number (match-string 1 ans))
11148 minute (if (match-end 3)
11149 (string-to-number (match-string 3 ans))
11151 pm (equal ?p
11152 (string-to-char (downcase (match-string 4 ans)))))
11153 (if (and (= hour 12) (not pm))
11154 (setq hour 0)
11155 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11156 (setq ans (replace-match (format "%02d:%02d" hour minute)
11157 t t ans))))
11159 ;; Check if a time range is given as a duration
11160 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11161 (setq hour (string-to-number (match-string 1 ans))
11162 h2 (+ hour (string-to-number (match-string 3 ans)))
11163 minute (string-to-number (match-string 2 ans))
11164 m2 (+ minute (if (match-end 5) (string-to-number
11165 (match-string 5 ans))0)))
11166 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11167 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11168 t t ans)))
11170 ;; Check if there is a time range
11171 (when (boundp 'org-end-time-was-given)
11172 (setq org-time-was-given nil)
11173 (when (and (string-match org-plain-time-of-day-regexp ans)
11174 (match-end 8))
11175 (setq org-end-time-was-given (match-string 8 ans))
11176 (setq ans (concat (substring ans 0 (match-beginning 7))
11177 (substring ans (match-end 7))))))
11179 (setq tl (parse-time-string ans)
11180 day (or (nth 3 tl) (nth 3 defdecode))
11181 month (or (nth 4 tl)
11182 (if (and org-read-date-prefer-future
11183 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11184 (1+ (nth 4 defdecode))
11185 (nth 4 defdecode)))
11186 year (or (nth 5 tl)
11187 (if (and org-read-date-prefer-future
11188 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11189 (1+ (nth 5 defdecode))
11190 (nth 5 defdecode)))
11191 hour (or (nth 2 tl) (nth 2 defdecode))
11192 minute (or (nth 1 tl) (nth 1 defdecode))
11193 second (or (nth 0 tl) 0)
11194 wday (nth 6 tl))
11196 ;; Special date definitions below
11197 (cond
11198 (iso-week
11199 ;; There was an iso week
11200 (setq year (or iso-year year)
11201 day (or iso-weekday wday 1)
11202 wday nil ; to make sure that the trigger below does not match
11203 iso-date (calendar-gregorian-from-absolute
11204 (calendar-absolute-from-iso
11205 (list iso-week day year))))
11206 ; FIXME: Should we also push ISO weeks into the future?
11207 ; (when (and org-read-date-prefer-future
11208 ; (not iso-year)
11209 ; (< (calendar-absolute-from-gregorian iso-date)
11210 ; (time-to-days (current-time))))
11211 ; (setq year (1+ year)
11212 ; iso-date (calendar-gregorian-from-absolute
11213 ; (calendar-absolute-from-iso
11214 ; (list iso-week day year)))))
11215 (setq month (car iso-date)
11216 year (nth 2 iso-date)
11217 day (nth 1 iso-date)))
11218 (deltan
11219 (unless deltadef
11220 (let ((now (decode-time (current-time))))
11221 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11222 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11223 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11224 ((equal deltaw "m") (setq month (+ month deltan)))
11225 ((equal deltaw "y") (setq year (+ year deltan)))))
11226 ((and wday (not (nth 3 tl)))
11227 ;; Weekday was given, but no day, so pick that day in the week
11228 ;; on or after the derived date.
11229 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11230 (unless (equal wday wday1)
11231 (setq day (+ day (% (- wday wday1 -7) 7))))))
11232 (if (and (boundp 'org-time-was-given)
11233 (nth 2 tl))
11234 (setq org-time-was-given t))
11235 (if (< year 100) (setq year (+ 2000 year)))
11236 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11237 (list second minute hour day month year)))
11239 (defvar parse-time-weekdays)
11241 (defun org-read-date-get-relative (s today default)
11242 "Check string S for special relative date string.
11243 TODAY and DEFAULT are internal times, for today and for a default.
11244 Return shift list (N what def-flag)
11245 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11246 N is the number of WHATs to shift.
11247 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11248 the DEFAULT date rather than TODAY."
11249 (when (and
11250 (string-match
11251 (concat
11252 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11253 "\\([0-9]+\\)?"
11254 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11255 "\\([ \t]\\|$\\)") s)
11256 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11257 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11258 (string-to-char (substring (match-string 1 s) -1))
11259 ?+))
11260 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11261 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11262 (what (if (match-end 3) (match-string 3 s) "d"))
11263 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11264 (date (if rel default today))
11265 (wday (nth 6 (decode-time date)))
11266 delta)
11267 (if wday1
11268 (progn
11269 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11270 (if (= dir ?-) (setq delta (- delta 7)))
11271 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11272 (list delta "d" rel))
11273 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11275 (defun org-eval-in-calendar (form &optional keepdate)
11276 "Eval FORM in the calendar window and return to current window.
11277 Also, store the cursor date in variable org-ans2."
11278 (let ((sw (selected-window)))
11279 (select-window (get-buffer-window "*Calendar*"))
11280 (eval form)
11281 (when (and (not keepdate) (calendar-cursor-to-date))
11282 (let* ((date (calendar-cursor-to-date))
11283 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11284 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11285 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11286 (select-window sw)))
11288 (defun org-calendar-select ()
11289 "Return to `org-read-date' with the date currently selected.
11290 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11291 (interactive)
11292 (when (calendar-cursor-to-date)
11293 (let* ((date (calendar-cursor-to-date))
11294 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11295 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11296 (if (active-minibuffer-window) (exit-minibuffer))))
11298 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11299 "Insert a date stamp for the date given by the internal TIME.
11300 WITH-HM means, use the stamp format that includes the time of the day.
11301 INACTIVE means use square brackets instead of angular ones, so that the
11302 stamp will not contribute to the agenda.
11303 PRE and POST are optional strings to be inserted before and after the
11304 stamp.
11305 The command returns the inserted time stamp."
11306 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11307 stamp)
11308 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11309 (insert-before-markers (or pre ""))
11310 (insert-before-markers (setq stamp (format-time-string fmt time)))
11311 (when (listp extra)
11312 (setq extra (car extra))
11313 (if (and (stringp extra)
11314 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11315 (setq extra (format "-%02d:%02d"
11316 (string-to-number (match-string 1 extra))
11317 (string-to-number (match-string 2 extra))))
11318 (setq extra nil)))
11319 (when extra
11320 (backward-char 1)
11321 (insert-before-markers extra)
11322 (forward-char 1))
11323 (insert-before-markers (or post ""))
11324 (setq org-last-inserted-timestamp stamp)))
11326 (defun org-toggle-time-stamp-overlays ()
11327 "Toggle the use of custom time stamp formats."
11328 (interactive)
11329 (setq org-display-custom-times (not org-display-custom-times))
11330 (unless org-display-custom-times
11331 (let ((p (point-min)) (bmp (buffer-modified-p)))
11332 (while (setq p (next-single-property-change p 'display))
11333 (if (and (get-text-property p 'display)
11334 (eq (get-text-property p 'face) 'org-date))
11335 (remove-text-properties
11336 p (setq p (next-single-property-change p 'display))
11337 '(display t))))
11338 (set-buffer-modified-p bmp)))
11339 (if (featurep 'xemacs)
11340 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11341 (org-restart-font-lock)
11342 (setq org-table-may-need-update t)
11343 (if org-display-custom-times
11344 (message "Time stamps are overlayed with custom format")
11345 (message "Time stamp overlays removed")))
11347 (defun org-display-custom-time (beg end)
11348 "Overlay modified time stamp format over timestamp between BEG and END."
11349 (let* ((ts (buffer-substring beg end))
11350 t1 w1 with-hm tf time str w2 (off 0))
11351 (save-match-data
11352 (setq t1 (org-parse-time-string ts t))
11353 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11354 (setq off (- (match-end 0) (match-beginning 0)))))
11355 (setq end (- end off))
11356 (setq w1 (- end beg)
11357 with-hm (and (nth 1 t1) (nth 2 t1))
11358 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11359 time (org-fix-decoded-time t1)
11360 str (org-add-props
11361 (format-time-string
11362 (substring tf 1 -1) (apply 'encode-time time))
11363 nil 'mouse-face 'highlight)
11364 w2 (length str))
11365 (if (not (= w2 w1))
11366 (add-text-properties (1+ beg) (+ 2 beg)
11367 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11368 (if (featurep 'xemacs)
11369 (progn
11370 (put-text-property beg end 'invisible t)
11371 (put-text-property beg end 'end-glyph (make-glyph str)))
11372 (put-text-property beg end 'display str))))
11374 (defun org-translate-time (string)
11375 "Translate all timestamps in STRING to custom format.
11376 But do this only if the variable `org-display-custom-times' is set."
11377 (when org-display-custom-times
11378 (save-match-data
11379 (let* ((start 0)
11380 (re org-ts-regexp-both)
11381 t1 with-hm inactive tf time str beg end)
11382 (while (setq start (string-match re string start))
11383 (setq beg (match-beginning 0)
11384 end (match-end 0)
11385 t1 (save-match-data
11386 (org-parse-time-string (substring string beg end) t))
11387 with-hm (and (nth 1 t1) (nth 2 t1))
11388 inactive (equal (substring string beg (1+ beg)) "[")
11389 tf (funcall (if with-hm 'cdr 'car)
11390 org-time-stamp-custom-formats)
11391 time (org-fix-decoded-time t1)
11392 str (format-time-string
11393 (concat
11394 (if inactive "[" "<") (substring tf 1 -1)
11395 (if inactive "]" ">"))
11396 (apply 'encode-time time))
11397 string (replace-match str t t string)
11398 start (+ start (length str)))))))
11399 string)
11401 (defun org-fix-decoded-time (time)
11402 "Set 0 instead of nil for the first 6 elements of time.
11403 Don't touch the rest."
11404 (let ((n 0))
11405 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11407 (defun org-days-to-time (timestamp-string)
11408 "Difference between TIMESTAMP-STRING and now in days."
11409 (- (time-to-days (org-time-string-to-time timestamp-string))
11410 (time-to-days (current-time))))
11412 (defun org-deadline-close (timestamp-string &optional ndays)
11413 "Is the time in TIMESTAMP-STRING close to the current date?"
11414 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11415 (and (< (org-days-to-time timestamp-string) ndays)
11416 (not (org-entry-is-done-p))))
11418 (defun org-get-wdays (ts)
11419 "Get the deadline lead time appropriate for timestring TS."
11420 (cond
11421 ((<= org-deadline-warning-days 0)
11422 ;; 0 or negative, enforce this value no matter what
11423 (- org-deadline-warning-days))
11424 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11425 ;; lead time is specified.
11426 (floor (* (string-to-number (match-string 1 ts))
11427 (cdr (assoc (match-string 2 ts)
11428 '(("d" . 1) ("w" . 7)
11429 ("m" . 30.4) ("y" . 365.25)))))))
11430 ;; go for the default.
11431 (t org-deadline-warning-days)))
11433 (defun org-calendar-select-mouse (ev)
11434 "Return to `org-read-date' with the date currently selected.
11435 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11436 (interactive "e")
11437 (mouse-set-point ev)
11438 (when (calendar-cursor-to-date)
11439 (let* ((date (calendar-cursor-to-date))
11440 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11441 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11442 (if (active-minibuffer-window) (exit-minibuffer))))
11444 (defun org-check-deadlines (ndays)
11445 "Check if there are any deadlines due or past due.
11446 A deadline is considered due if it happens within `org-deadline-warning-days'
11447 days from today's date. If the deadline appears in an entry marked DONE,
11448 it is not shown. The prefix arg NDAYS can be used to test that many
11449 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11450 (interactive "P")
11451 (let* ((org-warn-days
11452 (cond
11453 ((equal ndays '(4)) 100000)
11454 (ndays (prefix-numeric-value ndays))
11455 (t (abs org-deadline-warning-days))))
11456 (case-fold-search nil)
11457 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11458 (callback
11459 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11461 (message "%d deadlines past-due or due within %d days"
11462 (org-occur regexp nil callback)
11463 org-warn-days)))
11465 (defun org-check-before-date (date)
11466 "Check if there are deadlines or scheduled entries before DATE."
11467 (interactive (list (org-read-date)))
11468 (let ((case-fold-search nil)
11469 (regexp (concat "\\<\\(" org-deadline-string
11470 "\\|" org-scheduled-string
11471 "\\) *<\\([^>]+\\)>"))
11472 (callback
11473 (lambda () (time-less-p
11474 (org-time-string-to-time (match-string 2))
11475 (org-time-string-to-time date)))))
11476 (message "%d entries before %s"
11477 (org-occur regexp nil callback) date)))
11479 (defun org-evaluate-time-range (&optional to-buffer)
11480 "Evaluate a time range by computing the difference between start and end.
11481 Normally the result is just printed in the echo area, but with prefix arg
11482 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11483 If the time range is actually in a table, the result is inserted into the
11484 next column.
11485 For time difference computation, a year is assumed to be exactly 365
11486 days in order to avoid rounding problems."
11487 (interactive "P")
11489 (org-clock-update-time-maybe)
11490 (save-excursion
11491 (unless (org-at-date-range-p t)
11492 (goto-char (point-at-bol))
11493 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11494 (if (not (org-at-date-range-p t))
11495 (error "Not at a time-stamp range, and none found in current line")))
11496 (let* ((ts1 (match-string 1))
11497 (ts2 (match-string 2))
11498 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11499 (match-end (match-end 0))
11500 (time1 (org-time-string-to-time ts1))
11501 (time2 (org-time-string-to-time ts2))
11502 (t1 (time-to-seconds time1))
11503 (t2 (time-to-seconds time2))
11504 (diff (abs (- t2 t1)))
11505 (negative (< (- t2 t1) 0))
11506 ;; (ys (floor (* 365 24 60 60)))
11507 (ds (* 24 60 60))
11508 (hs (* 60 60))
11509 (fy "%dy %dd %02d:%02d")
11510 (fy1 "%dy %dd")
11511 (fd "%dd %02d:%02d")
11512 (fd1 "%dd")
11513 (fh "%02d:%02d")
11514 y d h m align)
11515 (if havetime
11516 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11518 d (floor (/ diff ds)) diff (mod diff ds)
11519 h (floor (/ diff hs)) diff (mod diff hs)
11520 m (floor (/ diff 60)))
11521 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11523 d (floor (+ (/ diff ds) 0.5))
11524 h 0 m 0))
11525 (if (not to-buffer)
11526 (message "%s" (org-make-tdiff-string y d h m))
11527 (if (org-at-table-p)
11528 (progn
11529 (goto-char match-end)
11530 (setq align t)
11531 (and (looking-at " *|") (goto-char (match-end 0))))
11532 (goto-char match-end))
11533 (if (looking-at
11534 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11535 (replace-match ""))
11536 (if negative (insert " -"))
11537 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11538 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11539 (insert " " (format fh h m))))
11540 (if align (org-table-align))
11541 (message "Time difference inserted")))))
11543 (defun org-make-tdiff-string (y d h m)
11544 (let ((fmt "")
11545 (l nil))
11546 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11547 l (push y l)))
11548 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11549 l (push d l)))
11550 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11551 l (push h l)))
11552 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11553 l (push m l)))
11554 (apply 'format fmt (nreverse l))))
11556 (defun org-time-string-to-time (s)
11557 (apply 'encode-time (org-parse-time-string s)))
11559 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11560 "Convert a time stamp to an absolute day number.
11561 If there is a specifyer for a cyclic time stamp, get the closest date to
11562 DAYNR.
11563 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11564 (cond
11565 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11566 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11567 daynr
11568 (+ daynr 1000)))
11569 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11570 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11571 (time-to-days (current-time))) (match-string 0 s)
11572 prefer show-all))
11573 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11575 (defun org-days-to-iso-week (days)
11576 "Return the iso week number."
11577 (require 'cal-iso)
11578 (car (calendar-iso-from-absolute days)))
11580 (defun org-small-year-to-year (year)
11581 "Convert 2-digit years into 4-digit years.
11582 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11583 The year 2000 cannot be abbreviated. Any year larger than 99
11584 is returned unchanged."
11585 (if (< year 38)
11586 (setq year (+ 2000 year))
11587 (if (< year 100)
11588 (setq year (+ 1900 year))))
11589 year)
11591 (defun org-time-from-absolute (d)
11592 "Return the time corresponding to date D.
11593 D may be an absolute day number, or a calendar-type list (month day year)."
11594 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11595 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11597 (defun org-calendar-holiday ()
11598 "List of holidays, for Diary display in Org-mode."
11599 (require 'holidays)
11600 (let ((hl (funcall
11601 (if (fboundp 'calendar-check-holidays)
11602 'calendar-check-holidays 'check-calendar-holidays) date)))
11603 (if hl (mapconcat 'identity hl "; "))))
11605 (defun org-diary-sexp-entry (sexp entry date)
11606 "Process a SEXP diary ENTRY for DATE."
11607 (require 'diary-lib)
11608 (let ((result (if calendar-debug-sexp
11609 (let ((stack-trace-on-error t))
11610 (eval (car (read-from-string sexp))))
11611 (condition-case nil
11612 (eval (car (read-from-string sexp)))
11613 (error
11614 (beep)
11615 (message "Bad sexp at line %d in %s: %s"
11616 (org-current-line)
11617 (buffer-file-name) sexp)
11618 (sleep-for 2))))))
11619 (cond ((stringp result) result)
11620 ((and (consp result)
11621 (stringp (cdr result))) (cdr result))
11622 (result entry)
11623 (t nil))))
11625 (defun org-diary-to-ical-string (frombuf)
11626 "Get iCalendar entries from diary entries in buffer FROMBUF.
11627 This uses the icalendar.el library."
11628 (let* ((tmpdir (if (featurep 'xemacs)
11629 (temp-directory)
11630 temporary-file-directory))
11631 (tmpfile (make-temp-name
11632 (expand-file-name "orgics" tmpdir)))
11633 buf rtn b e)
11634 (save-excursion
11635 (set-buffer frombuf)
11636 (icalendar-export-region (point-min) (point-max) tmpfile)
11637 (setq buf (find-buffer-visiting tmpfile))
11638 (set-buffer buf)
11639 (goto-char (point-min))
11640 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11641 (setq b (match-beginning 0)))
11642 (goto-char (point-max))
11643 (if (re-search-backward "^END:VEVENT" nil t)
11644 (setq e (match-end 0)))
11645 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11646 (kill-buffer buf)
11647 (delete-file tmpfile)
11648 rtn))
11650 (defun org-closest-date (start current change prefer show-all)
11651 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11652 When PREFER is `past' return a date that is either CURRENT or past.
11653 When PREFER is `future', return a date that is either CURRENT or future.
11654 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11655 ;; Make the proper lists from the dates
11656 (catch 'exit
11657 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11658 dn dw sday cday n1 n2 n0
11659 d m y y1 y2 date1 date2 nmonths nm ny m2)
11661 (setq start (org-date-to-gregorian start)
11662 current (org-date-to-gregorian
11663 (if show-all
11664 current
11665 (time-to-days (current-time))))
11666 sday (calendar-absolute-from-gregorian start)
11667 cday (calendar-absolute-from-gregorian current))
11669 (if (<= cday sday) (throw 'exit sday))
11671 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11672 (setq dn (string-to-number (match-string 1 change))
11673 dw (cdr (assoc (match-string 2 change) a1)))
11674 (error "Invalid change specifyer: %s" change))
11675 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11676 (cond
11677 ((eq dw 'day)
11678 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11679 n2 (+ n1 dn)))
11680 ((eq dw 'year)
11681 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11682 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11683 (setq date1 (list m d y1)
11684 n1 (calendar-absolute-from-gregorian date1)
11685 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11686 n2 (calendar-absolute-from-gregorian date2)))
11687 ((eq dw 'month)
11688 ;; approx number of month between the two dates
11689 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11690 ;; How often does dn fit in there?
11691 (setq d (nth 1 start) m (car start) y (nth 2 start)
11692 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11693 m (+ m nm)
11694 ny (floor (/ m 12))
11695 y (+ y ny)
11696 m (- m (* ny 12)))
11697 (while (> m 12) (setq m (- m 12) y (1+ y)))
11698 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11699 (setq m2 (+ m dn) y2 y)
11700 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11701 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11702 (while (<= n2 cday)
11703 (setq n1 n2 m m2 y y2)
11704 (setq m2 (+ m dn) y2 y)
11705 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11706 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11707 ;; Make sure n1 is the earlier date
11708 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11709 (if show-all
11710 (cond
11711 ((eq prefer 'past) n1)
11712 ((eq prefer 'future) (if (= cday n1) n1 n2))
11713 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11714 (cond
11715 ((eq prefer 'past) n1)
11716 ((eq prefer 'future) (if (= cday n1) n1 n2))
11717 (t (if (= cday n1) n1 n2)))))))
11719 (defun org-date-to-gregorian (date)
11720 "Turn any specification of DATE into a gregorian date for the calendar."
11721 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11722 ((and (listp date) (= (length date) 3)) date)
11723 ((stringp date)
11724 (setq date (org-parse-time-string date))
11725 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11726 ((listp date)
11727 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11729 (defun org-parse-time-string (s &optional nodefault)
11730 "Parse the standard Org-mode time string.
11731 This should be a lot faster than the normal `parse-time-string'.
11732 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11733 hour and minute fields will be nil if not given."
11734 (if (string-match org-ts-regexp0 s)
11735 (list 0
11736 (if (or (match-beginning 8) (not nodefault))
11737 (string-to-number (or (match-string 8 s) "0")))
11738 (if (or (match-beginning 7) (not nodefault))
11739 (string-to-number (or (match-string 7 s) "0")))
11740 (string-to-number (match-string 4 s))
11741 (string-to-number (match-string 3 s))
11742 (string-to-number (match-string 2 s))
11743 nil nil nil)
11744 (make-list 9 0)))
11746 (defun org-timestamp-up (&optional arg)
11747 "Increase the date item at the cursor by one.
11748 If the cursor is on the year, change the year. If it is on the month or
11749 the day, change that.
11750 With prefix ARG, change by that many units."
11751 (interactive "p")
11752 (org-timestamp-change (prefix-numeric-value arg)))
11754 (defun org-timestamp-down (&optional arg)
11755 "Decrease the date item at the cursor by one.
11756 If the cursor is on the year, change the year. If it is on the month or
11757 the day, change that.
11758 With prefix ARG, change by that many units."
11759 (interactive "p")
11760 (org-timestamp-change (- (prefix-numeric-value arg))))
11762 (defun org-timestamp-up-day (&optional arg)
11763 "Increase the date in the time stamp by one day.
11764 With prefix ARG, change that many days."
11765 (interactive "p")
11766 (if (and (not (org-at-timestamp-p t))
11767 (org-on-heading-p))
11768 (org-todo 'up)
11769 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11771 (defun org-timestamp-down-day (&optional arg)
11772 "Decrease the date in the time stamp by one day.
11773 With prefix ARG, change that many days."
11774 (interactive "p")
11775 (if (and (not (org-at-timestamp-p t))
11776 (org-on-heading-p))
11777 (org-todo 'down)
11778 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11780 (defun org-at-timestamp-p (&optional inactive-ok)
11781 "Determine if the cursor is in or at a timestamp."
11782 (interactive)
11783 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11784 (pos (point))
11785 (ans (or (looking-at tsr)
11786 (save-excursion
11787 (skip-chars-backward "^[<\n\r\t")
11788 (if (> (point) (point-min)) (backward-char 1))
11789 (and (looking-at tsr)
11790 (> (- (match-end 0) pos) -1))))))
11791 (and ans
11792 (boundp 'org-ts-what)
11793 (setq org-ts-what
11794 (cond
11795 ((= pos (match-beginning 0)) 'bracket)
11796 ((= pos (1- (match-end 0))) 'bracket)
11797 ((org-pos-in-match-range pos 2) 'year)
11798 ((org-pos-in-match-range pos 3) 'month)
11799 ((org-pos-in-match-range pos 7) 'hour)
11800 ((org-pos-in-match-range pos 8) 'minute)
11801 ((or (org-pos-in-match-range pos 4)
11802 (org-pos-in-match-range pos 5)) 'day)
11803 ((and (> pos (or (match-end 8) (match-end 5)))
11804 (< pos (match-end 0)))
11805 (- pos (or (match-end 8) (match-end 5))))
11806 (t 'day))))
11807 ans))
11809 (defun org-toggle-timestamp-type ()
11810 "Toggle the type (<active> or [inactive]) of a time stamp."
11811 (interactive)
11812 (when (org-at-timestamp-p t)
11813 (let ((beg (match-beginning 0)) (end (match-end 0))
11814 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11815 (save-excursion
11816 (goto-char beg)
11817 (while (re-search-forward "[][<>]" end t)
11818 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11819 t t)))
11820 (message "Timestamp is now %sactive"
11821 (if (equal (char-after beg) ?<) "" "in")))))
11823 (defun org-timestamp-change (n &optional what)
11824 "Change the date in the time stamp at point.
11825 The date will be changed by N times WHAT. WHAT can be `day', `month',
11826 `year', `minute', `second'. If WHAT is not given, the cursor position
11827 in the timestamp determines what will be changed."
11828 (let ((pos (point))
11829 with-hm inactive
11830 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11831 org-ts-what
11832 extra rem
11833 ts time time0)
11834 (if (not (org-at-timestamp-p t))
11835 (error "Not at a timestamp"))
11836 (if (and (not what) (eq org-ts-what 'bracket))
11837 (org-toggle-timestamp-type)
11838 (if (and (not what) (not (eq org-ts-what 'day))
11839 org-display-custom-times
11840 (get-text-property (point) 'display)
11841 (not (get-text-property (1- (point)) 'display)))
11842 (setq org-ts-what 'day))
11843 (setq org-ts-what (or what org-ts-what)
11844 inactive (= (char-after (match-beginning 0)) ?\[)
11845 ts (match-string 0))
11846 (replace-match "")
11847 (if (string-match
11848 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11850 (setq extra (match-string 1 ts)))
11851 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11852 (setq with-hm t))
11853 (setq time0 (org-parse-time-string ts))
11854 (when (and (eq org-ts-what 'minute)
11855 (eq current-prefix-arg nil))
11856 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11857 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11858 (setcar (cdr time0) (+ (nth 1 time0)
11859 (if (> n 0) (- rem) (- dm rem))))))
11860 (setq time
11861 (encode-time (or (car time0) 0)
11862 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11863 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11864 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11865 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11866 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11867 (nthcdr 6 time0)))
11868 (when (integerp org-ts-what)
11869 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11870 (if (eq what 'calendar)
11871 (let ((cal-date (org-get-date-from-calendar)))
11872 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11873 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11874 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11875 (setcar time0 (or (car time0) 0))
11876 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11877 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11878 (setq time (apply 'encode-time time0))))
11879 (setq org-last-changed-timestamp
11880 (org-insert-time-stamp time with-hm inactive nil nil extra))
11881 (org-clock-update-time-maybe)
11882 (goto-char pos)
11883 ;; Try to recenter the calendar window, if any
11884 (if (and org-calendar-follow-timestamp-change
11885 (get-buffer-window "*Calendar*" t)
11886 (memq org-ts-what '(day month year)))
11887 (org-recenter-calendar (time-to-days time))))))
11889 (defun org-modify-ts-extra (s pos n dm)
11890 "Change the different parts of the lead-time and repeat fields in timestamp."
11891 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11892 ng h m new rem)
11893 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11894 (cond
11895 ((or (org-pos-in-match-range pos 2)
11896 (org-pos-in-match-range pos 3))
11897 (setq m (string-to-number (match-string 3 s))
11898 h (string-to-number (match-string 2 s)))
11899 (if (org-pos-in-match-range pos 2)
11900 (setq h (+ h n))
11901 (setq n (* dm (org-no-warnings (signum n))))
11902 (when (not (= 0 (setq rem (% m dm))))
11903 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11904 (setq m (+ m n)))
11905 (if (< m 0) (setq m (+ m 60) h (1- h)))
11906 (if (> m 59) (setq m (- m 60) h (1+ h)))
11907 (setq h (min 24 (max 0 h)))
11908 (setq ng 1 new (format "-%02d:%02d" h m)))
11909 ((org-pos-in-match-range pos 6)
11910 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11911 ((org-pos-in-match-range pos 5)
11912 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11914 ((org-pos-in-match-range pos 9)
11915 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11916 ((org-pos-in-match-range pos 8)
11917 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11919 (when ng
11920 (setq s (concat
11921 (substring s 0 (match-beginning ng))
11923 (substring s (match-end ng))))))
11926 (defun org-recenter-calendar (date)
11927 "If the calendar is visible, recenter it to DATE."
11928 (let* ((win (selected-window))
11929 (cwin (get-buffer-window "*Calendar*" t))
11930 (calendar-move-hook nil))
11931 (when cwin
11932 (select-window cwin)
11933 (calendar-goto-date (if (listp date) date
11934 (calendar-gregorian-from-absolute date)))
11935 (select-window win))))
11937 (defun org-goto-calendar (&optional arg)
11938 "Go to the Emacs calendar at the current date.
11939 If there is a time stamp in the current line, go to that date.
11940 A prefix ARG can be used to force the current date."
11941 (interactive "P")
11942 (let ((tsr org-ts-regexp) diff
11943 (calendar-move-hook nil)
11944 (calendar-view-holidays-initially-flag nil)
11945 (view-calendar-holidays-initially nil)
11946 (calendar-view-diary-initially-flag nil)
11947 (view-diary-entries-initially nil))
11948 (if (or (org-at-timestamp-p)
11949 (save-excursion
11950 (beginning-of-line 1)
11951 (looking-at (concat ".*" tsr))))
11952 (let ((d1 (time-to-days (current-time)))
11953 (d2 (time-to-days
11954 (org-time-string-to-time (match-string 1)))))
11955 (setq diff (- d2 d1))))
11956 (calendar)
11957 (calendar-goto-today)
11958 (if (and diff (not arg)) (calendar-forward-day diff))))
11960 (defun org-get-date-from-calendar ()
11961 "Return a list (month day year) of date at point in calendar."
11962 (with-current-buffer "*Calendar*"
11963 (save-match-data
11964 (calendar-cursor-to-date))))
11966 (defun org-date-from-calendar ()
11967 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11968 If there is already a time stamp at the cursor position, update it."
11969 (interactive)
11970 (if (org-at-timestamp-p t)
11971 (org-timestamp-change 0 'calendar)
11972 (let ((cal-date (org-get-date-from-calendar)))
11973 (org-insert-time-stamp
11974 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11976 (defun org-minutes-to-hh:mm-string (m)
11977 "Compute H:MM from a number of minutes."
11978 (let ((h (/ m 60)))
11979 (setq m (- m (* 60 h)))
11980 (format org-time-clocksum-format h m)))
11982 (defun org-hh:mm-string-to-minutes (s)
11983 "Convert a string H:MM to a number of minutes."
11984 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11985 (+ (* (string-to-number (match-string 1 s)) 60)
11986 (string-to-number (match-string 2 s)))
11989 ;;;; Agenda files
11991 ;;;###autoload
11992 (defun org-iswitchb (&optional arg)
11993 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11994 With a prefix argument, restrict available to files.
11995 With two prefix arguments, restrict available buffers to agenda files.
11997 Due to some yet unresolved reason, the global function
11998 `iswitchb-mode' needs to be active for this function to work."
11999 (interactive "P")
12000 (require 'iswitchb)
12001 (let ((enabled iswitchb-mode) blist)
12002 (or enabled (iswitchb-mode 1))
12003 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12004 ((equal arg '(16)) (org-buffer-list 'agenda))
12005 (t (org-buffer-list))))
12006 (unwind-protect
12007 (let ((iswitchb-make-buflist-hook
12008 (lambda ()
12009 (setq iswitchb-temp-buflist
12010 (mapcar 'buffer-name blist)))))
12011 (switch-to-buffer
12012 (iswitchb-read-buffer
12013 "Switch-to: " nil t))
12014 (or enabled (iswitchb-mode -1))))))
12016 ;;;###autoload
12017 (defun org-ido-switchb (&optional arg)
12018 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12019 With a prefix argument, restrict available to files.
12020 With two prefix arguments, restrict available buffers to agenda files."
12021 (interactive "P")
12022 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12023 ((equal arg '(16)) (org-buffer-list 'agenda))
12024 (t (org-buffer-list)))))
12025 (switch-to-buffer
12026 (org-ido-completing-read "Org buffer: "
12027 (mapcar 'buffer-name blist)
12028 nil t))))
12030 (defun org-buffer-list (&optional predicate exclude-tmp)
12031 "Return a list of Org buffers.
12032 PREDICATE can be `export', `files' or `agenda'.
12034 export restrict the list to Export buffers.
12035 files restrict the list to buffers visiting Org files.
12036 agenda restrict the list to buffers visiting agenda files.
12038 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12039 (let* ((bfn nil)
12040 (agenda-files (and (eq predicate 'agenda)
12041 (mapcar 'file-truename (org-agenda-files t))))
12042 (filter
12043 (cond
12044 ((eq predicate 'files)
12045 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12046 ((eq predicate 'export)
12047 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12048 ((eq predicate 'agenda)
12049 (lambda (b)
12050 (with-current-buffer b
12051 (and (eq major-mode 'org-mode)
12052 (setq bfn (buffer-file-name b))
12053 (member (file-truename bfn) agenda-files)))))
12054 (t (lambda (b) (with-current-buffer b
12055 (or (eq major-mode 'org-mode)
12056 (string-match "\*Org .*Export"
12057 (buffer-name b)))))))))
12058 (delq nil
12059 (mapcar
12060 (lambda(b)
12061 (if (and (funcall filter b)
12062 (or (not exclude-tmp)
12063 (not (string-match "tmp" (buffer-name b)))))
12065 nil))
12066 (buffer-list)))))
12068 (defun org-agenda-files (&optional unrestricted archives)
12069 "Get the list of agenda files.
12070 Optional UNRESTRICTED means return the full list even if a restriction
12071 is currently in place.
12072 When ARCHIVES is t, include all archive files hat are really being
12073 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12074 `org-agenda-archives-mode' is t."
12075 (let ((files
12076 (cond
12077 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12078 ((stringp org-agenda-files) (org-read-agenda-file-list))
12079 ((listp org-agenda-files) org-agenda-files)
12080 (t (error "Invalid value of `org-agenda-files'")))))
12081 (setq files (apply 'append
12082 (mapcar (lambda (f)
12083 (if (file-directory-p f)
12084 (directory-files
12085 f t org-agenda-file-regexp)
12086 (list f)))
12087 files)))
12088 (when org-agenda-skip-unavailable-files
12089 (setq files (delq nil
12090 (mapcar (function
12091 (lambda (file)
12092 (and (file-readable-p file) file)))
12093 files))))
12094 (when (or (eq archives t)
12095 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12096 (setq files (org-add-archive-files files)))
12097 files))
12099 (defun org-edit-agenda-file-list ()
12100 "Edit the list of agenda files.
12101 Depending on setup, this either uses customize to edit the variable
12102 `org-agenda-files', or it visits the file that is holding the list. In the
12103 latter case, the buffer is set up in a way that saving it automatically kills
12104 the buffer and restores the previous window configuration."
12105 (interactive)
12106 (if (stringp org-agenda-files)
12107 (let ((cw (current-window-configuration)))
12108 (find-file org-agenda-files)
12109 (org-set-local 'org-window-configuration cw)
12110 (org-add-hook 'after-save-hook
12111 (lambda ()
12112 (set-window-configuration
12113 (prog1 org-window-configuration
12114 (kill-buffer (current-buffer))))
12115 (org-install-agenda-files-menu)
12116 (message "New agenda file list installed"))
12117 nil 'local)
12118 (message "%s" (substitute-command-keys
12119 "Edit list and finish with \\[save-buffer]")))
12120 (customize-variable 'org-agenda-files)))
12122 (defun org-store-new-agenda-file-list (list)
12123 "Set new value for the agenda file list and save it correctly."
12124 (if (stringp org-agenda-files)
12125 (let ((f org-agenda-files) b)
12126 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12127 (with-temp-file f
12128 (insert (mapconcat 'identity list "\n") "\n")))
12129 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12130 (setq org-agenda-files list)
12131 (customize-save-variable 'org-agenda-files org-agenda-files))))
12133 (defun org-read-agenda-file-list ()
12134 "Read the list of agenda files from a file."
12135 (when (file-directory-p org-agenda-files)
12136 (error "`org-agenda-files' cannot be a single directory"))
12137 (when (stringp org-agenda-files)
12138 (with-temp-buffer
12139 (insert-file-contents org-agenda-files)
12140 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12143 ;;;###autoload
12144 (defun org-cycle-agenda-files ()
12145 "Cycle through the files in `org-agenda-files'.
12146 If the current buffer visits an agenda file, find the next one in the list.
12147 If the current buffer does not, find the first agenda file."
12148 (interactive)
12149 (let* ((fs (org-agenda-files t))
12150 (files (append fs (list (car fs))))
12151 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12152 file)
12153 (unless files (error "No agenda files"))
12154 (catch 'exit
12155 (while (setq file (pop files))
12156 (if (equal (file-truename file) tcf)
12157 (when (car files)
12158 (find-file (car files))
12159 (throw 'exit t))))
12160 (find-file (car fs)))
12161 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12163 (defun org-agenda-file-to-front (&optional to-end)
12164 "Move/add the current file to the top of the agenda file list.
12165 If the file is not present in the list, it is added to the front. If it is
12166 present, it is moved there. With optional argument TO-END, add/move to the
12167 end of the list."
12168 (interactive "P")
12169 (let ((org-agenda-skip-unavailable-files nil)
12170 (file-alist (mapcar (lambda (x)
12171 (cons (file-truename x) x))
12172 (org-agenda-files t)))
12173 (ctf (file-truename buffer-file-name))
12174 x had)
12175 (setq x (assoc ctf file-alist) had x)
12177 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12178 (if to-end
12179 (setq file-alist (append (delq x file-alist) (list x)))
12180 (setq file-alist (cons x (delq x file-alist))))
12181 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12182 (org-install-agenda-files-menu)
12183 (message "File %s to %s of agenda file list"
12184 (if had "moved" "added") (if to-end "end" "front"))))
12186 (defun org-remove-file (&optional file)
12187 "Remove current file from the list of files in variable `org-agenda-files'.
12188 These are the files which are being checked for agenda entries.
12189 Optional argument FILE means, use this file instead of the current."
12190 (interactive)
12191 (let* ((org-agenda-skip-unavailable-files nil)
12192 (file (or file buffer-file-name))
12193 (true-file (file-truename file))
12194 (afile (abbreviate-file-name file))
12195 (files (delq nil (mapcar
12196 (lambda (x)
12197 (if (equal true-file
12198 (file-truename x))
12199 nil x))
12200 (org-agenda-files t)))))
12201 (if (not (= (length files) (length (org-agenda-files t))))
12202 (progn
12203 (org-store-new-agenda-file-list files)
12204 (org-install-agenda-files-menu)
12205 (message "Removed file: %s" afile))
12206 (message "File was not in list: %s (not removed)" afile))))
12208 (defun org-file-menu-entry (file)
12209 (vector file (list 'find-file file) t))
12211 (defun org-check-agenda-file (file)
12212 "Make sure FILE exists. If not, ask user what to do."
12213 (when (not (file-exists-p file))
12214 (message "non-existent file %s. [R]emove from list or [A]bort?"
12215 (abbreviate-file-name file))
12216 (let ((r (downcase (read-char-exclusive))))
12217 (cond
12218 ((equal r ?r)
12219 (org-remove-file file)
12220 (throw 'nextfile t))
12221 (t (error "Abort"))))))
12223 (defun org-get-agenda-file-buffer (file)
12224 "Get a buffer visiting FILE. If the buffer needs to be created, add
12225 it to the list of buffers which might be released later."
12226 (let ((buf (org-find-base-buffer-visiting file)))
12227 (if buf
12228 buf ; just return it
12229 ;; Make a new buffer and remember it
12230 (setq buf (find-file-noselect file))
12231 (if buf (push buf org-agenda-new-buffers))
12232 buf)))
12234 (defun org-release-buffers (blist)
12235 "Release all buffers in list, asking the user for confirmation when needed.
12236 When a buffer is unmodified, it is just killed. When modified, it is saved
12237 \(if the user agrees) and then killed."
12238 (let (buf file)
12239 (while (setq buf (pop blist))
12240 (setq file (buffer-file-name buf))
12241 (when (and (buffer-modified-p buf)
12242 file
12243 (y-or-n-p (format "Save file %s? " file)))
12244 (with-current-buffer buf (save-buffer)))
12245 (kill-buffer buf))))
12247 (defun org-prepare-agenda-buffers (files)
12248 "Create buffers for all agenda files, protect archived trees and comments."
12249 (interactive)
12250 (let ((pa '(:org-archived t))
12251 (pc '(:org-comment t))
12252 (pall '(:org-archived t :org-comment t))
12253 (inhibit-read-only t)
12254 (rea (concat ":" org-archive-tag ":"))
12255 bmp file re)
12256 (save-excursion
12257 (save-restriction
12258 (while (setq file (pop files))
12259 (if (bufferp file)
12260 (set-buffer file)
12261 (org-check-agenda-file file)
12262 (set-buffer (org-get-agenda-file-buffer file)))
12263 (widen)
12264 (setq bmp (buffer-modified-p))
12265 (org-refresh-category-properties)
12266 (setq org-todo-keywords-for-agenda
12267 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12268 (setq org-done-keywords-for-agenda
12269 (append org-done-keywords-for-agenda org-done-keywords))
12270 (setq org-todo-keyword-alist-for-agenda
12271 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12272 (setq org-tag-alist-for-agenda
12273 (append org-tag-alist-for-agenda org-tag-alist))
12275 (save-excursion
12276 (remove-text-properties (point-min) (point-max) pall)
12277 (when org-agenda-skip-archived-trees
12278 (goto-char (point-min))
12279 (while (re-search-forward rea nil t)
12280 (if (org-on-heading-p t)
12281 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12282 (goto-char (point-min))
12283 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12284 (while (re-search-forward re nil t)
12285 (add-text-properties
12286 (match-beginning 0) (org-end-of-subtree t) pc)))
12287 (set-buffer-modified-p bmp))))
12288 (setq org-todo-keyword-alist-for-agenda
12289 (org-uniquify org-todo-keyword-alist-for-agenda)
12290 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12292 ;;;; Embedded LaTeX
12294 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12295 "Keymap for the minor `org-cdlatex-mode'.")
12297 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12298 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12299 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12300 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12301 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12303 (defvar org-cdlatex-texmathp-advice-is-done nil
12304 "Flag remembering if we have applied the advice to texmathp already.")
12306 (define-minor-mode org-cdlatex-mode
12307 "Toggle the minor `org-cdlatex-mode'.
12308 This mode supports entering LaTeX environment and math in LaTeX fragments
12309 in Org-mode.
12310 \\{org-cdlatex-mode-map}"
12311 nil " OCDL" nil
12312 (when org-cdlatex-mode (require 'cdlatex))
12313 (unless org-cdlatex-texmathp-advice-is-done
12314 (setq org-cdlatex-texmathp-advice-is-done t)
12315 (defadvice texmathp (around org-math-always-on activate)
12316 "Always return t in org-mode buffers.
12317 This is because we want to insert math symbols without dollars even outside
12318 the LaTeX math segments. If Orgmode thinks that point is actually inside
12319 an embedded LaTeX fragment, let texmathp do its job.
12320 \\[org-cdlatex-mode-map]"
12321 (interactive)
12322 (let (p)
12323 (cond
12324 ((not (org-mode-p)) ad-do-it)
12325 ((eq this-command 'cdlatex-math-symbol)
12326 (setq ad-return-value t
12327 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12329 (let ((p (org-inside-LaTeX-fragment-p)))
12330 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12331 (setq ad-return-value t
12332 texmathp-why '("Org-mode embedded math" . 0))
12333 (if p ad-do-it)))))))))
12335 (defun turn-on-org-cdlatex ()
12336 "Unconditionally turn on `org-cdlatex-mode'."
12337 (org-cdlatex-mode 1))
12339 (defun org-inside-LaTeX-fragment-p ()
12340 "Test if point is inside a LaTeX fragment.
12341 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12342 sequence appearing also before point.
12343 Even though the matchers for math are configurable, this function assumes
12344 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12345 delimiters are skipped when they have been removed by customization.
12346 The return value is nil, or a cons cell with the delimiter and
12347 and the position of this delimiter.
12349 This function does a reasonably good job, but can locally be fooled by
12350 for example currency specifications. For example it will assume being in
12351 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12352 fragments that are properly closed, but during editing, we have to live
12353 with the uncertainty caused by missing closing delimiters. This function
12354 looks only before point, not after."
12355 (catch 'exit
12356 (let ((pos (point))
12357 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12358 (lim (progn
12359 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12360 (point)))
12361 dd-on str (start 0) m re)
12362 (goto-char pos)
12363 (when dodollar
12364 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12365 re (nth 1 (assoc "$" org-latex-regexps)))
12366 (while (string-match re str start)
12367 (cond
12368 ((= (match-end 0) (length str))
12369 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12370 ((= (match-end 0) (- (length str) 5))
12371 (throw 'exit nil))
12372 (t (setq start (match-end 0))))))
12373 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12374 (goto-char pos)
12375 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12376 (and (match-beginning 2) (throw 'exit nil))
12377 ;; count $$
12378 (while (re-search-backward "\\$\\$" lim t)
12379 (setq dd-on (not dd-on)))
12380 (goto-char pos)
12381 (if dd-on (cons "$$" m))))))
12384 (defun org-try-cdlatex-tab ()
12385 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12386 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12387 - inside a LaTeX fragment, or
12388 - after the first word in a line, where an abbreviation expansion could
12389 insert a LaTeX environment."
12390 (when org-cdlatex-mode
12391 (cond
12392 ((save-excursion
12393 (skip-chars-backward "a-zA-Z0-9*")
12394 (skip-chars-backward " \t")
12395 (bolp))
12396 (cdlatex-tab) t)
12397 ((org-inside-LaTeX-fragment-p)
12398 (cdlatex-tab) t)
12399 (t nil))))
12401 (defun org-cdlatex-underscore-caret (&optional arg)
12402 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12403 Revert to the normal definition outside of these fragments."
12404 (interactive "P")
12405 (if (org-inside-LaTeX-fragment-p)
12406 (call-interactively 'cdlatex-sub-superscript)
12407 (let (org-cdlatex-mode)
12408 (call-interactively (key-binding (vector last-input-event))))))
12410 (defun org-cdlatex-math-modify (&optional arg)
12411 "Execute `cdlatex-math-modify' in LaTeX fragments.
12412 Revert to the normal definition outside of these fragments."
12413 (interactive "P")
12414 (if (org-inside-LaTeX-fragment-p)
12415 (call-interactively 'cdlatex-math-modify)
12416 (let (org-cdlatex-mode)
12417 (call-interactively (key-binding (vector last-input-event))))))
12419 (defvar org-latex-fragment-image-overlays nil
12420 "List of overlays carrying the images of latex fragments.")
12421 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12423 (defun org-remove-latex-fragment-image-overlays ()
12424 "Remove all overlays with LaTeX fragment images in current buffer."
12425 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12426 (setq org-latex-fragment-image-overlays nil))
12428 (defun org-preview-latex-fragment (&optional subtree)
12429 "Preview the LaTeX fragment at point, or all locally or globally.
12430 If the cursor is in a LaTeX fragment, create the image and overlay
12431 it over the source code. If there is no fragment at point, display
12432 all fragments in the current text, from one headline to the next. With
12433 prefix SUBTREE, display all fragments in the current subtree. With a
12434 double prefix `C-u C-u', or when the cursor is before the first headline,
12435 display all fragments in the buffer.
12436 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12437 (interactive "P")
12438 (org-remove-latex-fragment-image-overlays)
12439 (save-excursion
12440 (save-restriction
12441 (let (beg end at msg)
12442 (cond
12443 ((or (equal subtree '(16))
12444 (not (save-excursion
12445 (re-search-backward (concat "^" outline-regexp) nil t))))
12446 (setq beg (point-min) end (point-max)
12447 msg "Creating images for buffer...%s"))
12448 ((equal subtree '(4))
12449 (org-back-to-heading)
12450 (setq beg (point) end (org-end-of-subtree t)
12451 msg "Creating images for subtree...%s"))
12453 (if (setq at (org-inside-LaTeX-fragment-p))
12454 (goto-char (max (point-min) (- (cdr at) 2)))
12455 (org-back-to-heading))
12456 (setq beg (point) end (progn (outline-next-heading) (point))
12457 msg (if at "Creating image...%s"
12458 "Creating images for entry...%s"))))
12459 (message msg "")
12460 (narrow-to-region beg end)
12461 (goto-char beg)
12462 (org-format-latex
12463 (concat "ltxpng/" (file-name-sans-extension
12464 (file-name-nondirectory
12465 buffer-file-name)))
12466 default-directory 'overlays msg at 'forbuffer)
12467 (message msg "done. Use `C-c C-c' to remove images.")))))
12469 (defvar org-latex-regexps
12470 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12471 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12472 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12473 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12474 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12475 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12476 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12477 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12478 "Regular expressions for matching embedded LaTeX.")
12480 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12481 "Replace LaTeX fragments with links to an image, and produce images."
12482 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12483 (let* ((prefixnodir (file-name-nondirectory prefix))
12484 (absprefix (expand-file-name prefix dir))
12485 (todir (file-name-directory absprefix))
12486 (opt org-format-latex-options)
12487 (matchers (plist-get opt :matchers))
12488 (re-list org-latex-regexps)
12489 (cnt 0) txt link beg end re e checkdir
12490 m n block linkfile movefile ov)
12491 ;; Check if there are old images files with this prefix, and remove them
12492 (when (file-directory-p todir)
12493 (mapc 'delete-file
12494 (directory-files
12495 todir 'full
12496 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12497 ;; Check the different regular expressions
12498 (while (setq e (pop re-list))
12499 (setq m (car e) re (nth 1 e) n (nth 2 e)
12500 block (if (nth 3 e) "\n\n" ""))
12501 (when (member m matchers)
12502 (goto-char (point-min))
12503 (while (re-search-forward re nil t)
12504 (when (or (not at) (equal (cdr at) (match-beginning n)))
12505 (setq txt (match-string n)
12506 beg (match-beginning n) end (match-end n)
12507 cnt (1+ cnt)
12508 linkfile (format "%s_%04d.png" prefix cnt)
12509 movefile (format "%s_%04d.png" absprefix cnt)
12510 link (concat block "[[file:" linkfile "]]" block))
12511 (if msg (message msg cnt))
12512 (goto-char beg)
12513 (unless checkdir ; make sure the directory exists
12514 (setq checkdir t)
12515 (or (file-directory-p todir) (make-directory todir)))
12516 (org-create-formula-image
12517 txt movefile opt forbuffer)
12518 (if overlays
12519 (progn
12520 (setq ov (org-make-overlay beg end))
12521 (if (featurep 'xemacs)
12522 (progn
12523 (org-overlay-put ov 'invisible t)
12524 (org-overlay-put
12525 ov 'end-glyph
12526 (make-glyph (vector 'png :file movefile))))
12527 (org-overlay-put
12528 ov 'display
12529 (list 'image :type 'png :file movefile :ascent 'center)))
12530 (push ov org-latex-fragment-image-overlays)
12531 (goto-char end))
12532 (delete-region beg end)
12533 (insert link))))))))
12535 ;; This function borrows from Ganesh Swami's latex2png.el
12536 (defun org-create-formula-image (string tofile options buffer)
12537 (let* ((tmpdir (if (featurep 'xemacs)
12538 (temp-directory)
12539 temporary-file-directory))
12540 (texfilebase (make-temp-name
12541 (expand-file-name "orgtex" tmpdir)))
12542 (texfile (concat texfilebase ".tex"))
12543 (dvifile (concat texfilebase ".dvi"))
12544 (pngfile (concat texfilebase ".png"))
12545 (fnh (if (featurep 'xemacs)
12546 (font-height (get-face-font 'default))
12547 (face-attribute 'default :height nil)))
12548 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12549 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12550 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12551 "Black"))
12552 (bg (or (plist-get options (if buffer :background :html-background))
12553 "Transparent")))
12554 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12555 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12556 (with-temp-file texfile
12557 (insert org-format-latex-header
12558 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12559 (let ((dir default-directory))
12560 (condition-case nil
12561 (progn
12562 (cd tmpdir)
12563 (call-process "latex" nil nil nil texfile))
12564 (error nil))
12565 (cd dir))
12566 (if (not (file-exists-p dvifile))
12567 (progn (message "Failed to create dvi file from %s" texfile) nil)
12568 (condition-case nil
12569 (call-process "dvipng" nil nil nil
12570 "-E" "-fg" fg "-bg" bg
12571 "-D" dpi
12572 ;;"-x" scale "-y" scale
12573 "-T" "tight"
12574 "-o" pngfile
12575 dvifile)
12576 (error nil))
12577 (if (not (file-exists-p pngfile))
12578 (progn (message "Failed to create png file from %s" texfile) nil)
12579 ;; Use the requested file name and clean up
12580 (copy-file pngfile tofile 'replace)
12581 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12582 (delete-file (concat texfilebase e)))
12583 pngfile))))
12585 (defun org-dvipng-color (attr)
12586 "Return an rgb color specification for dvipng."
12587 (apply 'format "rgb %s %s %s"
12588 (mapcar 'org-normalize-color
12589 (color-values (face-attribute 'default attr nil)))))
12591 (defun org-normalize-color (value)
12592 "Return string to be used as color value for an RGB component."
12593 (format "%g" (/ value 65535.0)))
12595 ;;;; Key bindings
12597 ;; Make `C-c C-x' a prefix key
12598 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12600 ;; TAB key with modifiers
12601 (org-defkey org-mode-map "\C-i" 'org-cycle)
12602 (org-defkey org-mode-map [(tab)] 'org-cycle)
12603 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12604 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12605 (org-defkey org-mode-map "\M-\t" 'org-complete)
12606 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12607 ;; The following line is necessary under Suse GNU/Linux
12608 (unless (featurep 'xemacs)
12609 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12610 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12611 (define-key org-mode-map [backtab] 'org-shifttab)
12613 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12614 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12615 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12617 ;; Cursor keys with modifiers
12618 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12619 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12620 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12621 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12623 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12624 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12625 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12626 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12628 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12629 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12630 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12631 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12633 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12634 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12636 ;;; Extra keys for tty access.
12637 ;; We only set them when really needed because otherwise the
12638 ;; menus don't show the simple keys
12640 (when (or org-use-extra-keys
12641 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12642 (not window-system))
12643 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12644 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12645 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12646 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12647 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12648 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12649 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12650 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12651 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12652 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12653 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12654 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12655 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12656 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12657 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12658 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12659 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12660 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12661 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12662 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12663 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12664 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12666 ;; All the other keys
12668 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12669 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12670 (if (boundp 'narrow-map)
12671 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12672 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12673 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12674 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12675 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12676 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12677 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12678 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12679 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12680 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12681 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12682 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12683 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12684 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12685 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12686 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12687 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12688 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12689 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12690 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12691 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12692 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12693 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12694 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12695 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12696 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12697 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12698 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12699 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12700 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12701 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12702 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12703 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12704 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12705 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12706 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12707 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12708 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12709 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12710 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12711 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12712 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12713 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12714 (org-defkey org-mode-map "\C-c^" 'org-sort)
12715 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12716 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12717 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12718 (org-defkey org-mode-map "\C-m" 'org-return)
12719 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12720 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12721 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12722 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12723 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12724 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12725 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12726 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12727 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12728 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12729 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12730 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12731 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12732 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12733 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12734 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12735 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12737 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12738 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12739 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12740 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12742 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12743 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12744 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12745 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12746 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12747 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12748 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12749 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12750 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12751 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12752 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12753 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12755 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12756 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12757 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12758 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12760 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12762 (when (featurep 'xemacs)
12763 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12765 (defvar org-table-auto-blank-field) ; defined in org-table.el
12766 (defun org-self-insert-command (N)
12767 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12768 If the cursor is in a table looking at whitespace, the whitespace is
12769 overwritten, and the table is not marked as requiring realignment."
12770 (interactive "p")
12771 (if (and (org-table-p)
12772 (progn
12773 ;; check if we blank the field, and if that triggers align
12774 (and (featurep 'org-table) org-table-auto-blank-field
12775 (member last-command
12776 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12777 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12778 ;; got extra space, this field does not determine column width
12779 (let (org-table-may-need-update) (org-table-blank-field))
12780 ;; no extra space, this field may determine column width
12781 (org-table-blank-field)))
12783 (eq N 1)
12784 (looking-at "[^|\n]* |"))
12785 (let (org-table-may-need-update)
12786 (goto-char (1- (match-end 0)))
12787 (delete-backward-char 1)
12788 (goto-char (match-beginning 0))
12789 (self-insert-command N))
12790 (setq org-table-may-need-update t)
12791 (self-insert-command N)
12792 (org-fix-tags-on-the-fly)))
12794 (defun org-fix-tags-on-the-fly ()
12795 (when (and (equal (char-after (point-at-bol)) ?*)
12796 (org-on-heading-p))
12797 (org-align-tags-here org-tags-column)))
12799 (defun org-delete-backward-char (N)
12800 "Like `delete-backward-char', insert whitespace at field end in tables.
12801 When deleting backwards, in tables this function will insert whitespace in
12802 front of the next \"|\" separator, to keep the table aligned. The table will
12803 still be marked for re-alignment if the field did fill the entire column,
12804 because, in this case the deletion might narrow the column."
12805 (interactive "p")
12806 (if (and (org-table-p)
12807 (eq N 1)
12808 (string-match "|" (buffer-substring (point-at-bol) (point)))
12809 (looking-at ".*?|"))
12810 (let ((pos (point))
12811 (noalign (looking-at "[^|\n\r]* |"))
12812 (c org-table-may-need-update))
12813 (backward-delete-char N)
12814 (skip-chars-forward "^|")
12815 (insert " ")
12816 (goto-char (1- pos))
12817 ;; noalign: if there were two spaces at the end, this field
12818 ;; does not determine the width of the column.
12819 (if noalign (setq org-table-may-need-update c)))
12820 (backward-delete-char N)
12821 (org-fix-tags-on-the-fly)))
12823 (defun org-delete-char (N)
12824 "Like `delete-char', but insert whitespace at field end in tables.
12825 When deleting characters, in tables this function will insert whitespace in
12826 front of the next \"|\" separator, to keep the table aligned. The table will
12827 still be marked for re-alignment if the field did fill the entire column,
12828 because, in this case the deletion might narrow the column."
12829 (interactive "p")
12830 (if (and (org-table-p)
12831 (not (bolp))
12832 (not (= (char-after) ?|))
12833 (eq N 1))
12834 (if (looking-at ".*?|")
12835 (let ((pos (point))
12836 (noalign (looking-at "[^|\n\r]* |"))
12837 (c org-table-may-need-update))
12838 (replace-match (concat
12839 (substring (match-string 0) 1 -1)
12840 " |"))
12841 (goto-char pos)
12842 ;; noalign: if there were two spaces at the end, this field
12843 ;; does not determine the width of the column.
12844 (if noalign (setq org-table-may-need-update c)))
12845 (delete-char N))
12846 (delete-char N)
12847 (org-fix-tags-on-the-fly)))
12849 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12850 (put 'org-self-insert-command 'delete-selection t)
12851 (put 'orgtbl-self-insert-command 'delete-selection t)
12852 (put 'org-delete-char 'delete-selection 'supersede)
12853 (put 'org-delete-backward-char 'delete-selection 'supersede)
12855 ;; Make `flyspell-mode' delay after some commands
12856 (put 'org-self-insert-command 'flyspell-delayed t)
12857 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12858 (put 'org-delete-char 'flyspell-delayed t)
12859 (put 'org-delete-backward-char 'flyspell-delayed t)
12861 ;; Make pabbrev-mode expand after org-mode commands
12862 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12863 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12865 ;; How to do this: Measure non-white length of current string
12866 ;; If equal to column width, we should realign.
12868 (defun org-remap (map &rest commands)
12869 "In MAP, remap the functions given in COMMANDS.
12870 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12871 (let (new old)
12872 (while commands
12873 (setq old (pop commands) new (pop commands))
12874 (if (fboundp 'command-remapping)
12875 (org-defkey map (vector 'remap old) new)
12876 (substitute-key-definition old new map global-map)))))
12878 (when (eq org-enable-table-editor 'optimized)
12879 ;; If the user wants maximum table support, we need to hijack
12880 ;; some standard editing functions
12881 (org-remap org-mode-map
12882 'self-insert-command 'org-self-insert-command
12883 'delete-char 'org-delete-char
12884 'delete-backward-char 'org-delete-backward-char)
12885 (org-defkey org-mode-map "|" 'org-force-self-insert))
12887 (defun org-shiftcursor-error ()
12888 "Throw an error because Shift-Cursor command was applied in wrong context."
12889 (error "This command is active in special context like tables, headlines or timestamps"))
12891 (defun org-shifttab (&optional arg)
12892 "Global visibility cycling or move to previous table field.
12893 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12894 on context.
12895 See the individual commands for more information."
12896 (interactive "P")
12897 (cond
12898 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12899 ((integerp arg)
12900 (message "Content view to level: %d" arg)
12901 (org-content (prefix-numeric-value arg))
12902 (setq org-cycle-global-status 'overview))
12903 (t (call-interactively 'org-global-cycle))))
12905 (defun org-shiftmetaleft ()
12906 "Promote subtree or delete table column.
12907 Calls `org-promote-subtree', `org-outdent-item',
12908 or `org-table-delete-column', depending on context.
12909 See the individual commands for more information."
12910 (interactive)
12911 (cond
12912 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12913 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12914 ((org-at-item-p) (call-interactively 'org-outdent-item))
12915 (t (org-shiftcursor-error))))
12917 (defun org-shiftmetaright ()
12918 "Demote subtree or insert table column.
12919 Calls `org-demote-subtree', `org-indent-item',
12920 or `org-table-insert-column', depending on context.
12921 See the individual commands for more information."
12922 (interactive)
12923 (cond
12924 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12925 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12926 ((org-at-item-p) (call-interactively 'org-indent-item))
12927 (t (org-shiftcursor-error))))
12929 (defun org-shiftmetaup (&optional arg)
12930 "Move subtree up or kill table row.
12931 Calls `org-move-subtree-up' or `org-table-kill-row' or
12932 `org-move-item-up' depending on context. See the individual commands
12933 for more information."
12934 (interactive "P")
12935 (cond
12936 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12937 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12938 ((org-at-item-p) (call-interactively 'org-move-item-up))
12939 (t (org-shiftcursor-error))))
12940 (defun org-shiftmetadown (&optional arg)
12941 "Move subtree down or insert table row.
12942 Calls `org-move-subtree-down' or `org-table-insert-row' or
12943 `org-move-item-down', depending on context. See the individual
12944 commands for more information."
12945 (interactive "P")
12946 (cond
12947 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12948 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12949 ((org-at-item-p) (call-interactively 'org-move-item-down))
12950 (t (org-shiftcursor-error))))
12952 (defun org-metaleft (&optional arg)
12953 "Promote heading or move table column to left.
12954 Calls `org-do-promote' or `org-table-move-column', depending on context.
12955 With no specific context, calls the Emacs default `backward-word'.
12956 See the individual commands for more information."
12957 (interactive "P")
12958 (cond
12959 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12960 ((or (org-on-heading-p) (org-region-active-p))
12961 (call-interactively 'org-do-promote))
12962 ((org-at-item-p) (call-interactively 'org-outdent-item))
12963 (t (call-interactively 'backward-word))))
12965 (defun org-metaright (&optional arg)
12966 "Demote subtree or move table column to right.
12967 Calls `org-do-demote' or `org-table-move-column', depending on context.
12968 With no specific context, calls the Emacs default `forward-word'.
12969 See the individual commands for more information."
12970 (interactive "P")
12971 (cond
12972 ((org-at-table-p) (call-interactively 'org-table-move-column))
12973 ((or (org-on-heading-p) (org-region-active-p))
12974 (call-interactively 'org-do-demote))
12975 ((org-at-item-p) (call-interactively 'org-indent-item))
12976 (t (call-interactively 'forward-word))))
12978 (defun org-metaup (&optional arg)
12979 "Move subtree up or move table row up.
12980 Calls `org-move-subtree-up' or `org-table-move-row' or
12981 `org-move-item-up', depending on context. See the individual commands
12982 for more information."
12983 (interactive "P")
12984 (cond
12985 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12986 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12987 ((org-at-item-p) (call-interactively 'org-move-item-up))
12988 (t (transpose-lines 1) (beginning-of-line -1))))
12990 (defun org-metadown (&optional arg)
12991 "Move subtree down or move table row down.
12992 Calls `org-move-subtree-down' or `org-table-move-row' or
12993 `org-move-item-down', depending on context. See the individual
12994 commands for more information."
12995 (interactive "P")
12996 (cond
12997 ((org-at-table-p) (call-interactively 'org-table-move-row))
12998 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12999 ((org-at-item-p) (call-interactively 'org-move-item-down))
13000 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13002 (defun org-shiftup (&optional arg)
13003 "Increase item in timestamp or increase priority of current headline.
13004 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13005 depending on context. See the individual commands for more information."
13006 (interactive "P")
13007 (cond
13008 ((org-at-timestamp-p t)
13009 (call-interactively (if org-edit-timestamp-down-means-later
13010 'org-timestamp-down 'org-timestamp-up)))
13011 ((org-on-heading-p) (call-interactively 'org-priority-up))
13012 ((org-at-item-p) (call-interactively 'org-previous-item))
13013 ((org-clocktable-try-shift 'up arg))
13014 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
13016 (defun org-shiftdown (&optional arg)
13017 "Decrease item in timestamp or decrease priority of current headline.
13018 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13019 depending on context. See the individual commands for more information."
13020 (interactive "P")
13021 (cond
13022 ((org-at-timestamp-p t)
13023 (call-interactively (if org-edit-timestamp-down-means-later
13024 'org-timestamp-up 'org-timestamp-down)))
13025 ((org-on-heading-p) (call-interactively 'org-priority-down))
13026 ((org-clocktable-try-shift 'down arg))
13027 (t (call-interactively 'org-next-item))))
13029 (defun org-shiftright (&optional arg)
13030 "Cycle the thing at point or in the current line, depending on context.
13031 Depending on context, this does one of the following:
13033 - switch a timestamp at point one day into the future
13034 - on a headline, switch to the next TODO keyword.
13035 - on an item, switch entire list to the next bullet type
13036 - on a property line, switch to the next allowed value
13037 - on a clocktable definition line, move time block into the future"
13038 (interactive "P")
13039 (cond
13040 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13041 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13042 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13043 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13044 ((org-clocktable-try-shift 'right arg))
13045 (t (org-shiftcursor-error))))
13047 (defun org-shiftleft (&optional arg)
13048 "Cycle the thing at point or in the current line, depending on context.
13049 Depending on context, this does one of the following:
13051 - switch a timestamp at point one day into the past
13052 - on a headline, switch to the previous TODO keyword.
13053 - on an item, switch entire list to the previous bullet type
13054 - on a property line, switch to the previous allowed value
13055 - on a clocktable definition line, move time block into the past"
13056 (interactive "P")
13057 (cond
13058 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13059 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13060 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13061 ((org-at-property-p)
13062 (call-interactively 'org-property-previous-allowed-value))
13063 ((org-clocktable-try-shift 'left arg))
13064 (t (org-shiftcursor-error))))
13066 (defun org-shiftcontrolright ()
13067 "Switch to next TODO set."
13068 (interactive)
13069 (cond
13070 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13071 (t (org-shiftcursor-error))))
13073 (defun org-shiftcontrolleft ()
13074 "Switch to previous TODO set."
13075 (interactive)
13076 (cond
13077 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13078 (t (org-shiftcursor-error))))
13080 (defun org-ctrl-c-ret ()
13081 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13082 (interactive)
13083 (cond
13084 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13085 (t (call-interactively 'org-insert-heading))))
13087 (defun org-copy-special ()
13088 "Copy region in table or copy current subtree.
13089 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13090 See the individual commands for more information."
13091 (interactive)
13092 (call-interactively
13093 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13095 (defun org-cut-special ()
13096 "Cut region in table or cut current subtree.
13097 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13098 See the individual commands for more information."
13099 (interactive)
13100 (call-interactively
13101 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13103 (defun org-paste-special (arg)
13104 "Paste rectangular region into table, or past subtree relative to level.
13105 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13106 See the individual commands for more information."
13107 (interactive "P")
13108 (if (org-at-table-p)
13109 (org-table-paste-rectangle)
13110 (org-paste-subtree arg)))
13112 (defun org-edit-special ()
13113 "Call a special editor for the stuff at point.
13114 When at a table, call the formula editor with `org-table-edit-formulas'.
13115 When at the first line of an src example, call `org-edit-src-code'.
13116 When in an #+include line, visit the include file. Otherwise call
13117 `ffap' to visit the file at point."
13118 (interactive)
13119 (cond
13120 ((org-at-table-p)
13121 (call-interactively 'org-table-edit-formulas))
13122 ((save-excursion
13123 (beginning-of-line 1)
13124 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13125 (find-file (org-trim (match-string 1))))
13126 ((org-edit-src-code))
13127 ((org-edit-fixed-width-region))
13128 (t (call-interactively 'ffap))))
13130 (defun org-ctrl-c-ctrl-c (&optional arg)
13131 "Set tags in headline, or update according to changed information at point.
13133 This command does many different things, depending on context:
13135 - If the cursor is in a headline, prompt for tags and insert them
13136 into the current line, aligned to `org-tags-column'. When called
13137 with prefix arg, realign all tags in the current buffer.
13139 - If the cursor is in one of the special #+KEYWORD lines, this
13140 triggers scanning the buffer for these lines and updating the
13141 information.
13143 - If the cursor is inside a table, realign the table. This command
13144 works even if the automatic table editor has been turned off.
13146 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13147 the entire table.
13149 - If the cursor is at a footnote reference or definition, jump to
13150 the corresponding definition or references, respectively.
13152 - If the cursor is a the beginning of a dynamic block, update it.
13154 - If the cursor is inside a table created by the table.el package,
13155 activate that table.
13157 - If the current buffer is a remember buffer, close note and file
13158 it. A prefix argument of 1 files to the default location
13159 without further interaction. A prefix argument of 2 files to
13160 the currently clocking task.
13162 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13163 links in this buffer.
13165 - If the cursor is on a numbered item in a plain list, renumber the
13166 ordered list.
13168 - If the cursor is on a checkbox, toggle it."
13169 (interactive "P")
13170 (let ((org-enable-table-editor t))
13171 (cond
13172 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13173 org-occur-highlights
13174 org-latex-fragment-image-overlays)
13175 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13176 (org-remove-occur-highlights)
13177 (org-remove-latex-fragment-image-overlays)
13178 (message "Temporary highlights/overlays removed from current buffer"))
13179 ((and (local-variable-p 'org-finish-function (current-buffer))
13180 (fboundp org-finish-function))
13181 (funcall org-finish-function))
13182 ((org-at-property-p)
13183 (call-interactively 'org-property-action))
13184 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13185 ((org-on-heading-p) (call-interactively 'org-set-tags))
13186 ((org-at-table.el-p)
13187 (require 'table)
13188 (beginning-of-line 1)
13189 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13190 (call-interactively 'table-recognize-table))
13191 ((org-at-table-p)
13192 (org-table-maybe-eval-formula)
13193 (if arg
13194 (call-interactively 'org-table-recalculate)
13195 (org-table-maybe-recalculate-line))
13196 (call-interactively 'org-table-align))
13197 ((or (org-footnote-at-reference-p)
13198 (org-footnote-at-definition-p))
13199 (call-interactively 'org-footnote-action))
13200 ((org-at-item-checkbox-p)
13201 (call-interactively 'org-toggle-checkbox))
13202 ((org-at-item-p)
13203 (call-interactively 'org-maybe-renumber-ordered-list))
13204 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13205 ;; Dynamic block
13206 (beginning-of-line 1)
13207 (save-excursion (org-update-dblock)))
13208 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13209 (cond
13210 ((equal (match-string 1) "TBLFM")
13211 ;; Recalculate the table before this line
13212 (save-excursion
13213 (beginning-of-line 1)
13214 (skip-chars-backward " \r\n\t")
13215 (if (org-at-table-p)
13216 (org-call-with-arg 'org-table-recalculate t))))
13218 ; (org-set-regexps-and-options)
13219 ; (org-restart-font-lock)
13220 (let ((org-inhibit-startup t)) (org-mode-restart))
13221 (message "Local setup has been refreshed"))))
13222 (t (error "C-c C-c can do nothing useful at this location.")))))
13224 (defun org-mode-restart ()
13225 "Restart Org-mode, to scan again for special lines.
13226 Also updates the keyword regular expressions."
13227 (interactive)
13228 (org-mode)
13229 (message "Org-mode restarted"))
13231 (defun org-kill-note-or-show-branches ()
13232 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13233 (interactive)
13234 (if (not org-finish-function)
13235 (call-interactively 'show-branches)
13236 (let ((org-note-abort t))
13237 (funcall org-finish-function))))
13239 (defun org-return (&optional indent)
13240 "Goto next table row or insert a newline.
13241 Calls `org-table-next-row' or `newline', depending on context.
13242 See the individual commands for more information."
13243 (interactive)
13244 (cond
13245 ((bobp) (if indent (newline-and-indent) (newline)))
13246 ((and (org-at-heading-p)
13247 (looking-at
13248 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13249 (org-show-entry)
13250 (end-of-line 1)
13251 (newline))
13252 ((org-at-table-p)
13253 (org-table-justify-field-maybe)
13254 (call-interactively 'org-table-next-row))
13255 (t (if indent (newline-and-indent) (newline)))))
13257 (defun org-return-indent ()
13258 "Goto next table row or insert a newline and indent.
13259 Calls `org-table-next-row' or `newline-and-indent', depending on
13260 context. See the individual commands for more information."
13261 (interactive)
13262 (org-return t))
13264 (defun org-ctrl-c-star ()
13265 "Compute table, or change heading status of lines.
13266 Calls `org-table-recalculate' or `org-toggle-region-headings',
13267 depending on context. This will also turn a plain list item or a normal
13268 line into a subheading."
13269 (interactive)
13270 (cond
13271 ((org-at-table-p)
13272 (call-interactively 'org-table-recalculate))
13273 ((org-region-active-p)
13274 ;; Convert all lines in region to list items
13275 (call-interactively 'org-toggle-region-headings))
13276 ((org-on-heading-p)
13277 (org-toggle-region-headings (point-at-bol)
13278 (min (1+ (point-at-eol)) (point-max))))
13279 ((org-at-item-p)
13280 ;; Convert to heading
13281 (let ((level (save-match-data
13282 (save-excursion
13283 (condition-case nil
13284 (progn
13285 (org-back-to-heading t)
13286 (funcall outline-level))
13287 (error 0))))))
13288 (replace-match
13289 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13290 (t (org-toggle-region-headings (point-at-bol)
13291 (min (1+ (point-at-eol)) (point-max))))))
13293 (defun org-ctrl-c-minus ()
13294 "Insert separator line in table or modify bullet status of line.
13295 Also turns a plain line or a region of lines into list items.
13296 Calls `org-table-insert-hline', `org-toggle-region-items', or
13297 `org-cycle-list-bullet', depending on context."
13298 (interactive)
13299 (cond
13300 ((org-at-table-p)
13301 (call-interactively 'org-table-insert-hline))
13302 ((org-on-heading-p)
13303 ;; Convert to item
13304 (save-excursion
13305 (beginning-of-line 1)
13306 (if (looking-at "\\*+ ")
13307 (replace-match
13308 (concat (make-string
13309 (- (match-end 0) (point) (if org-odd-levels-only 2 1)) ?\ )
13310 "- ")))))
13311 ((org-region-active-p)
13312 ;; Convert all lines in region to list items
13313 (call-interactively 'org-toggle-region-items))
13314 ((org-in-item-p)
13315 (call-interactively 'org-cycle-list-bullet))
13316 (t (org-toggle-region-items (point-at-bol)
13317 (min (1+ (point-at-eol)) (point-max))))))
13319 (defun org-toggle-region-items (beg end)
13320 "Convert all lines in region to list items.
13321 If the first line is already an item, convert all list items in the region
13322 to normal lines."
13323 (interactive "r")
13324 (let (l2 l)
13325 (save-excursion
13326 (goto-char end)
13327 (setq l2 (org-current-line))
13328 (goto-char beg)
13329 (beginning-of-line 1)
13330 (setq l (1- (org-current-line)))
13331 (if (org-at-item-p)
13332 ;; We already have items, de-itemize
13333 (while (< (setq l (1+ l)) l2)
13334 (when (org-at-item-p)
13335 (goto-char (match-beginning 2))
13336 (delete-region (match-beginning 2) (match-end 2))
13337 (and (looking-at "[ \t]+") (replace-match "")))
13338 (beginning-of-line 2))
13339 (while (< (setq l (1+ l)) l2)
13340 (unless (org-at-item-p)
13341 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13342 (replace-match "\\1- \\2")))
13343 (beginning-of-line 2))))))
13345 (defun org-toggle-region-headings (beg end)
13346 "Convert all lines in region to list items.
13347 If the first line is already an item, convert all list items in the region
13348 to normal lines."
13349 (interactive "r")
13350 (let (l2 l)
13351 (save-excursion
13352 (goto-char end)
13353 (setq l2 (org-current-line))
13354 (goto-char beg)
13355 (beginning-of-line 1)
13356 (setq l (1- (org-current-line)))
13357 (if (org-on-heading-p)
13358 ;; We already have headlines, de-star them
13359 (while (< (setq l (1+ l)) l2)
13360 (when (org-on-heading-p t)
13361 (and (looking-at outline-regexp) (replace-match "")))
13362 (beginning-of-line 2))
13363 (let* ((stars (save-excursion
13364 (re-search-backward org-complex-heading-regexp nil t)
13365 (or (match-string 1) "*")))
13366 (add-stars (if org-odd-levels-only "**" "*"))
13367 (rpl (concat stars add-stars " \\2")))
13368 (while (< (setq l (1+ l)) l2)
13369 (unless (org-on-heading-p)
13370 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13371 (replace-match rpl)))
13372 (beginning-of-line 2)))))))
13374 (defun org-meta-return (&optional arg)
13375 "Insert a new heading or wrap a region in a table.
13376 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13377 See the individual commands for more information."
13378 (interactive "P")
13379 (cond
13380 ((org-at-table-p)
13381 (call-interactively 'org-table-wrap-region))
13382 (t (call-interactively 'org-insert-heading))))
13384 ;;; Menu entries
13386 ;; Define the Org-mode menus
13387 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13388 '("Tbl"
13389 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13390 ["Next Field" org-cycle (org-at-table-p)]
13391 ["Previous Field" org-shifttab (org-at-table-p)]
13392 ["Next Row" org-return (org-at-table-p)]
13393 "--"
13394 ["Blank Field" org-table-blank-field (org-at-table-p)]
13395 ["Edit Field" org-table-edit-field (org-at-table-p)]
13396 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13397 "--"
13398 ("Column"
13399 ["Move Column Left" org-metaleft (org-at-table-p)]
13400 ["Move Column Right" org-metaright (org-at-table-p)]
13401 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13402 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13403 ("Row"
13404 ["Move Row Up" org-metaup (org-at-table-p)]
13405 ["Move Row Down" org-metadown (org-at-table-p)]
13406 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13407 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13408 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13409 "--"
13410 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13411 ("Rectangle"
13412 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13413 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13414 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13415 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13416 "--"
13417 ("Calculate"
13418 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13419 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13420 ["Edit Formulas" org-edit-special (org-at-table-p)]
13421 "--"
13422 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13423 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13424 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13425 "--"
13426 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13427 "--"
13428 ["Sum Column/Rectangle" org-table-sum
13429 (or (org-at-table-p) (org-region-active-p))]
13430 ["Which Column?" org-table-current-column (org-at-table-p)])
13431 ["Debug Formulas"
13432 org-table-toggle-formula-debugger
13433 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13434 ["Show Col/Row Numbers"
13435 org-table-toggle-coordinate-overlays
13436 :style toggle
13437 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13438 "--"
13439 ["Create" org-table-create (and (not (org-at-table-p))
13440 org-enable-table-editor)]
13441 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13442 ["Import from File" org-table-import (not (org-at-table-p))]
13443 ["Export to File" org-table-export (org-at-table-p)]
13444 "--"
13445 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13447 (easy-menu-define org-org-menu org-mode-map "Org menu"
13448 '("Org"
13449 ("Show/Hide"
13450 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13451 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13452 ["Sparse Tree..." org-sparse-tree t]
13453 ["Reveal Context" org-reveal t]
13454 ["Show All" show-all t]
13455 "--"
13456 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13457 "--"
13458 ["New Heading" org-insert-heading t]
13459 ("Navigate Headings"
13460 ["Up" outline-up-heading t]
13461 ["Next" outline-next-visible-heading t]
13462 ["Previous" outline-previous-visible-heading t]
13463 ["Next Same Level" outline-forward-same-level t]
13464 ["Previous Same Level" outline-backward-same-level t]
13465 "--"
13466 ["Jump" org-goto t])
13467 ("Edit Structure"
13468 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13469 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13470 "--"
13471 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13472 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13473 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13474 "--"
13475 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13476 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13477 ["Demote Heading" org-metaright (not (org-at-table-p))]
13478 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13479 "--"
13480 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13481 "--"
13482 ["Convert to odd levels" org-convert-to-odd-levels t]
13483 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13484 ("Editing"
13485 ["Emphasis..." org-emphasize t]
13486 ["Edit Source Example" org-edit-special t]
13487 "--"
13488 ["Footnote new/jump" org-footnote-action t]
13489 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13490 ("Archive"
13491 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13492 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13493 ; :active t :keys "C-u C-c C-x C-a"]
13494 ["Sparse trees open ARCHIVE trees"
13495 (setq org-sparse-tree-open-archived-trees
13496 (not org-sparse-tree-open-archived-trees))
13497 :style toggle :selected org-sparse-tree-open-archived-trees]
13498 ["Cycling opens ARCHIVE trees"
13499 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13500 :style toggle :selected org-cycle-open-archived-trees]
13501 "--"
13502 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13503 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13504 ; ["Check and Move Children" (org-archive-subtree '(4))
13505 ; :active t :keys "C-u C-c C-x C-s"]
13507 "--"
13508 ("TODO Lists"
13509 ["TODO/DONE/-" org-todo t]
13510 ("Select keyword"
13511 ["Next keyword" org-shiftright (org-on-heading-p)]
13512 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13513 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13514 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13515 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13516 ["Show TODO Tree" org-show-todo-tree t]
13517 ["Global TODO list" org-todo-list t]
13518 "--"
13519 ["Set Priority" org-priority t]
13520 ["Priority Up" org-shiftup t]
13521 ["Priority Down" org-shiftdown t])
13522 ("TAGS and Properties"
13523 ["Set Tags" org-set-tags-command t]
13524 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13525 "--"
13526 ["Set property" org-set-property t]
13527 ["Column view of properties" org-columns t]
13528 ["Insert Column View DBlock" org-insert-columns-dblock t])
13529 ("Dates and Scheduling"
13530 ["Timestamp" org-time-stamp t]
13531 ["Timestamp (inactive)" org-time-stamp-inactive t]
13532 ("Change Date"
13533 ["1 Day Later" org-shiftright t]
13534 ["1 Day Earlier" org-shiftleft t]
13535 ["1 ... Later" org-shiftup t]
13536 ["1 ... Earlier" org-shiftdown t])
13537 ["Compute Time Range" org-evaluate-time-range t]
13538 ["Schedule Item" org-schedule t]
13539 ["Deadline" org-deadline t]
13540 "--"
13541 ["Custom time format" org-toggle-time-stamp-overlays
13542 :style radio :selected org-display-custom-times]
13543 "--"
13544 ["Goto Calendar" org-goto-calendar t]
13545 ["Date from Calendar" org-date-from-calendar t]
13546 "--"
13547 ["Start/Restart Timer" org-timer-start t]
13548 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13549 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13550 ["Insert Timer String" org-timer t]
13551 ["Insert Timer Item" org-timer-item t])
13552 ("Logging work"
13553 ["Clock in" org-clock-in t]
13554 ["Clock out" org-clock-out t]
13555 ["Clock cancel" org-clock-cancel t]
13556 ["Goto running clock" org-clock-goto t]
13557 ["Display times" org-clock-display t]
13558 ["Create clock table" org-clock-report t]
13559 "--"
13560 ["Record DONE time"
13561 (progn (setq org-log-done (not org-log-done))
13562 (message "Switching to %s will %s record a timestamp"
13563 (car org-done-keywords)
13564 (if org-log-done "automatically" "not")))
13565 :style toggle :selected org-log-done])
13566 "--"
13567 ["Agenda Command..." org-agenda t]
13568 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13569 ("File List for Agenda")
13570 ("Special views current file"
13571 ["TODO Tree" org-show-todo-tree t]
13572 ["Check Deadlines" org-check-deadlines t]
13573 ["Timeline" org-timeline t]
13574 ["Tags Tree" org-tags-sparse-tree t])
13575 "--"
13576 ("Hyperlinks"
13577 ["Store Link (Global)" org-store-link t]
13578 ["Insert Link" org-insert-link t]
13579 ["Follow Link" org-open-at-point t]
13580 "--"
13581 ["Next link" org-next-link t]
13582 ["Previous link" org-previous-link t]
13583 "--"
13584 ["Descriptive Links"
13585 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13586 :style radio
13587 :selected (member '(org-link) buffer-invisibility-spec)]
13588 ["Literal Links"
13589 (progn
13590 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13591 :style radio
13592 :selected (not (member '(org-link) buffer-invisibility-spec))])
13593 "--"
13594 ["Export/Publish..." org-export t]
13595 ("LaTeX"
13596 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13597 :selected org-cdlatex-mode]
13598 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13599 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13600 ["Modify math symbol" org-cdlatex-math-modify
13601 (org-inside-LaTeX-fragment-p)]
13602 ["Export LaTeX fragments as images"
13603 (if (featurep 'org-exp)
13604 (setq org-export-with-LaTeX-fragments
13605 (not org-export-with-LaTeX-fragments))
13606 (require 'org-exp))
13607 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13608 org-export-with-LaTeX-fragments)])
13609 "--"
13610 ("Documentation"
13611 ["Show Version" org-version t]
13612 ["Info Documentation" org-info t])
13613 ("Customize"
13614 ["Browse Org Group" org-customize t]
13615 "--"
13616 ["Expand This Menu" org-create-customize-menu
13617 (fboundp 'customize-menu-create)])
13618 "--"
13619 ["Refresh setup" org-mode-restart t]
13622 (defun org-info (&optional node)
13623 "Read documentation for Org-mode in the info system.
13624 With optional NODE, go directly to that node."
13625 (interactive)
13626 (info (format "(org)%s" (or node ""))))
13628 (defun org-install-agenda-files-menu ()
13629 (let ((bl (buffer-list)))
13630 (save-excursion
13631 (while bl
13632 (set-buffer (pop bl))
13633 (if (org-mode-p) (setq bl nil)))
13634 (when (org-mode-p)
13635 (easy-menu-change
13636 '("Org") "File List for Agenda"
13637 (append
13638 (list
13639 ["Edit File List" (org-edit-agenda-file-list) t]
13640 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13641 ["Remove Current File from List" org-remove-file t]
13642 ["Cycle through agenda files" org-cycle-agenda-files t]
13643 ["Occur in all agenda files" org-occur-in-agenda-files t]
13644 "--")
13645 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13647 ;;;; Documentation
13649 ;;;###autoload
13650 (defun org-require-autoloaded-modules ()
13651 (interactive)
13652 (mapc 'require
13653 '(org-agenda org-archive org-clock org-colview
13654 org-exp org-id org-export-latex org-publish
13655 org-remember org-table)))
13657 ;;;###autoload
13658 (defun org-customize ()
13659 "Call the customize function with org as argument."
13660 (interactive)
13661 (org-load-modules-maybe)
13662 (org-require-autoloaded-modules)
13663 (customize-browse 'org))
13665 (defun org-create-customize-menu ()
13666 "Create a full customization menu for Org-mode, insert it into the menu."
13667 (interactive)
13668 (org-load-modules-maybe)
13669 (org-require-autoloaded-modules)
13670 (if (fboundp 'customize-menu-create)
13671 (progn
13672 (easy-menu-change
13673 '("Org") "Customize"
13674 `(["Browse Org group" org-customize t]
13675 "--"
13676 ,(customize-menu-create 'org)
13677 ["Set" Custom-set t]
13678 ["Save" Custom-save t]
13679 ["Reset to Current" Custom-reset-current t]
13680 ["Reset to Saved" Custom-reset-saved t]
13681 ["Reset to Standard Settings" Custom-reset-standard t]))
13682 (message "\"Org\"-menu now contains full customization menu"))
13683 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13685 ;;;; Miscellaneous stuff
13687 ;;; Generally useful functions
13689 (defun org-find-text-property-in-string (prop s)
13690 "Return the first non-nil value of property PROP in string S."
13691 (or (get-text-property 0 prop s)
13692 (get-text-property (or (next-single-property-change 0 prop s) 0)
13693 prop s)))
13695 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13696 "Display the given MESSAGE as a warning."
13697 (if (fboundp 'display-warning)
13698 (display-warning 'org message
13699 (if (featurep 'xemacs)
13700 'warning
13701 :warning))
13702 (let ((buf (get-buffer-create "*Org warnings*")))
13703 (with-current-buffer buf
13704 (goto-char (point-max))
13705 (insert "Warning (Org): " message)
13706 (unless (bolp)
13707 (newline)))
13708 (display-buffer buf)
13709 (sit-for 0))))
13711 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13712 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13713 (if (and marker (marker-buffer marker)
13714 (buffer-live-p (marker-buffer marker)))
13715 (progn
13716 (switch-to-buffer (marker-buffer marker))
13717 (if (or (> marker (point-max)) (< marker (point-min)))
13718 (widen))
13719 (goto-char marker)
13720 (org-show-context 'org-goto))
13721 (if bookmark
13722 (bookmark-jump bookmark)
13723 (error "Cannot find location"))))
13725 (defun org-quote-csv-field (s)
13726 "Quote field for inclusion in CSV material."
13727 (if (string-match "[\",]" s)
13728 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13731 (defun org-plist-delete (plist property)
13732 "Delete PROPERTY from PLIST.
13733 This is in contrast to merely setting it to 0."
13734 (let (p)
13735 (while plist
13736 (if (not (eq property (car plist)))
13737 (setq p (plist-put p (car plist) (nth 1 plist))))
13738 (setq plist (cddr plist)))
13741 (defun org-force-self-insert (N)
13742 "Needed to enforce self-insert under remapping."
13743 (interactive "p")
13744 (self-insert-command N))
13746 (defun org-string-width (s)
13747 "Compute width of string, ignoring invisible characters.
13748 This ignores character with invisibility property `org-link', and also
13749 characters with property `org-cwidth', because these will become invisible
13750 upon the next fontification round."
13751 (let (b l)
13752 (when (or (eq t buffer-invisibility-spec)
13753 (assq 'org-link buffer-invisibility-spec))
13754 (while (setq b (text-property-any 0 (length s)
13755 'invisible 'org-link s))
13756 (setq s (concat (substring s 0 b)
13757 (substring s (or (next-single-property-change
13758 b 'invisible s) (length s)))))))
13759 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13760 (setq s (concat (substring s 0 b)
13761 (substring s (or (next-single-property-change
13762 b 'org-cwidth s) (length s))))))
13763 (setq l (string-width s) b -1)
13764 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13765 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13768 (defun org-get-indentation (&optional line)
13769 "Get the indentation of the current line, interpreting tabs.
13770 When LINE is given, assume it represents a line and compute its indentation."
13771 (if line
13772 (if (string-match "^ *" (org-remove-tabs line))
13773 (match-end 0))
13774 (save-excursion
13775 (beginning-of-line 1)
13776 (skip-chars-forward " \t")
13777 (current-column))))
13779 (defun org-remove-tabs (s &optional width)
13780 "Replace tabulators in S with spaces.
13781 Assumes that s is a single line, starting in column 0."
13782 (setq width (or width tab-width))
13783 (while (string-match "\t" s)
13784 (setq s (replace-match
13785 (make-string
13786 (- (* width (/ (+ (match-beginning 0) width) width))
13787 (match-beginning 0)) ?\ )
13788 t t s)))
13791 (defun org-fix-indentation (line ind)
13792 "Fix indentation in LINE.
13793 IND is a cons cell with target and minimum indentation.
13794 If the current indentation in LINE is smaller than the minimum,
13795 leave it alone. If it is larger than ind, set it to the target."
13796 (let* ((l (org-remove-tabs line))
13797 (i (org-get-indentation l))
13798 (i1 (car ind)) (i2 (cdr ind)))
13799 (if (>= i i2) (setq l (substring line i2)))
13800 (if (> i1 0)
13801 (concat (make-string i1 ?\ ) l)
13802 l)))
13804 (defun org-base-buffer (buffer)
13805 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13806 (if (not buffer)
13807 buffer
13808 (or (buffer-base-buffer buffer)
13809 buffer)))
13811 (defun org-trim (s)
13812 "Remove whitespace at beginning and end of string."
13813 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13814 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13817 (defun org-wrap (string &optional width lines)
13818 "Wrap string to either a number of lines, or a width in characters.
13819 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13820 that costs. If there is a word longer than WIDTH, the text is actually
13821 wrapped to the length of that word.
13822 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13823 many lines, whatever width that takes.
13824 The return value is a list of lines, without newlines at the end."
13825 (let* ((words (org-split-string string "[ \t\n]+"))
13826 (maxword (apply 'max (mapcar 'org-string-width words)))
13827 w ll)
13828 (cond (width
13829 (org-do-wrap words (max maxword width)))
13830 (lines
13831 (setq w maxword)
13832 (setq ll (org-do-wrap words maxword))
13833 (if (<= (length ll) lines)
13835 (setq ll words)
13836 (while (> (length ll) lines)
13837 (setq w (1+ w))
13838 (setq ll (org-do-wrap words w)))
13839 ll))
13840 (t (error "Cannot wrap this")))))
13842 (defun org-do-wrap (words width)
13843 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13844 (let (lines line)
13845 (while words
13846 (setq line (pop words))
13847 (while (and words (< (+ (length line) (length (car words))) width))
13848 (setq line (concat line " " (pop words))))
13849 (setq lines (push line lines)))
13850 (nreverse lines)))
13852 (defun org-split-string (string &optional separators)
13853 "Splits STRING into substrings at SEPARATORS.
13854 No empty strings are returned if there are matches at the beginning
13855 and end of string."
13856 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13857 (start 0)
13858 notfirst
13859 (list nil))
13860 (while (and (string-match rexp string
13861 (if (and notfirst
13862 (= start (match-beginning 0))
13863 (< start (length string)))
13864 (1+ start) start))
13865 (< (match-beginning 0) (length string)))
13866 (setq notfirst t)
13867 (or (eq (match-beginning 0) 0)
13868 (and (eq (match-beginning 0) (match-end 0))
13869 (eq (match-beginning 0) start))
13870 (setq list
13871 (cons (substring string start (match-beginning 0))
13872 list)))
13873 (setq start (match-end 0)))
13874 (or (eq start (length string))
13875 (setq list
13876 (cons (substring string start)
13877 list)))
13878 (nreverse list)))
13880 (defun org-context ()
13881 "Return a list of contexts of the current cursor position.
13882 If several contexts apply, all are returned.
13883 Each context entry is a list with a symbol naming the context, and
13884 two positions indicating start and end of the context. Possible
13885 contexts are:
13887 :headline anywhere in a headline
13888 :headline-stars on the leading stars in a headline
13889 :todo-keyword on a TODO keyword (including DONE) in a headline
13890 :tags on the TAGS in a headline
13891 :priority on the priority cookie in a headline
13892 :item on the first line of a plain list item
13893 :item-bullet on the bullet/number of a plain list item
13894 :checkbox on the checkbox in a plain list item
13895 :table in an org-mode table
13896 :table-special on a special filed in a table
13897 :table-table in a table.el table
13898 :link on a hyperlink
13899 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13900 :target on a <<target>>
13901 :radio-target on a <<<radio-target>>>
13902 :latex-fragment on a LaTeX fragment
13903 :latex-preview on a LaTeX fragment with overlayed preview image
13905 This function expects the position to be visible because it uses font-lock
13906 faces as a help to recognize the following contexts: :table-special, :link,
13907 and :keyword."
13908 (let* ((f (get-text-property (point) 'face))
13909 (faces (if (listp f) f (list f)))
13910 (p (point)) clist o)
13911 ;; First the large context
13912 (cond
13913 ((org-on-heading-p t)
13914 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13915 (when (progn
13916 (beginning-of-line 1)
13917 (looking-at org-todo-line-tags-regexp))
13918 (push (org-point-in-group p 1 :headline-stars) clist)
13919 (push (org-point-in-group p 2 :todo-keyword) clist)
13920 (push (org-point-in-group p 4 :tags) clist))
13921 (goto-char p)
13922 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13923 (if (looking-at "\\[#[A-Z0-9]\\]")
13924 (push (org-point-in-group p 0 :priority) clist)))
13926 ((org-at-item-p)
13927 (push (org-point-in-group p 2 :item-bullet) clist)
13928 (push (list :item (point-at-bol)
13929 (save-excursion (org-end-of-item) (point)))
13930 clist)
13931 (and (org-at-item-checkbox-p)
13932 (push (org-point-in-group p 0 :checkbox) clist)))
13934 ((org-at-table-p)
13935 (push (list :table (org-table-begin) (org-table-end)) clist)
13936 (if (memq 'org-formula faces)
13937 (push (list :table-special
13938 (previous-single-property-change p 'face)
13939 (next-single-property-change p 'face)) clist)))
13940 ((org-at-table-p 'any)
13941 (push (list :table-table) clist)))
13942 (goto-char p)
13944 ;; Now the small context
13945 (cond
13946 ((org-at-timestamp-p)
13947 (push (org-point-in-group p 0 :timestamp) clist))
13948 ((memq 'org-link faces)
13949 (push (list :link
13950 (previous-single-property-change p 'face)
13951 (next-single-property-change p 'face)) clist))
13952 ((memq 'org-special-keyword faces)
13953 (push (list :keyword
13954 (previous-single-property-change p 'face)
13955 (next-single-property-change p 'face)) clist))
13956 ((org-on-target-p)
13957 (push (org-point-in-group p 0 :target) clist)
13958 (goto-char (1- (match-beginning 0)))
13959 (if (looking-at org-radio-target-regexp)
13960 (push (org-point-in-group p 0 :radio-target) clist))
13961 (goto-char p))
13962 ((setq o (car (delq nil
13963 (mapcar
13964 (lambda (x)
13965 (if (memq x org-latex-fragment-image-overlays) x))
13966 (org-overlays-at (point))))))
13967 (push (list :latex-fragment
13968 (org-overlay-start o) (org-overlay-end o)) clist)
13969 (push (list :latex-preview
13970 (org-overlay-start o) (org-overlay-end o)) clist))
13971 ((org-inside-LaTeX-fragment-p)
13972 ;; FIXME: positions wrong.
13973 (push (list :latex-fragment (point) (point)) clist)))
13975 (setq clist (nreverse (delq nil clist)))
13976 clist))
13978 ;; FIXME: Compare with at-regexp-p Do we need both?
13979 (defun org-in-regexp (re &optional nlines visually)
13980 "Check if point is inside a match of regexp.
13981 Normally only the current line is checked, but you can include NLINES extra
13982 lines both before and after point into the search.
13983 If VISUALLY is set, require that the cursor is not after the match but
13984 really on, so that the block visually is on the match."
13985 (catch 'exit
13986 (let ((pos (point))
13987 (eol (point-at-eol (+ 1 (or nlines 0))))
13988 (inc (if visually 1 0)))
13989 (save-excursion
13990 (beginning-of-line (- 1 (or nlines 0)))
13991 (while (re-search-forward re eol t)
13992 (if (and (<= (match-beginning 0) pos)
13993 (>= (+ inc (match-end 0)) pos))
13994 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13996 (defun org-at-regexp-p (regexp)
13997 "Is point inside a match of REGEXP in the current line?"
13998 (catch 'exit
13999 (save-excursion
14000 (let ((pos (point)) (end (point-at-eol)))
14001 (beginning-of-line 1)
14002 (while (re-search-forward regexp end t)
14003 (if (and (<= (match-beginning 0) pos)
14004 (>= (match-end 0) pos))
14005 (throw 'exit t)))
14006 nil))))
14008 (defun org-occur-in-agenda-files (regexp &optional nlines)
14009 "Call `multi-occur' with buffers for all agenda files."
14010 (interactive "sOrg-files matching: \np")
14011 (let* ((files (org-agenda-files))
14012 (tnames (mapcar 'file-truename files))
14013 (extra org-agenda-text-search-extra-files)
14015 (when (eq (car extra) 'agenda-archives)
14016 (setq extra (cdr extra))
14017 (setq files (org-add-archive-files files)))
14018 (while (setq f (pop extra))
14019 (unless (member (file-truename f) tnames)
14020 (add-to-list 'files f 'append)
14021 (add-to-list 'tnames (file-truename f) 'append)))
14022 (multi-occur
14023 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14024 regexp)))
14026 (if (boundp 'occur-mode-find-occurrence-hook)
14027 ;; Emacs 23
14028 (add-hook 'occur-mode-find-occurrence-hook
14029 (lambda ()
14030 (when (org-mode-p)
14031 (org-reveal))))
14032 ;; Emacs 22
14033 (defadvice occur-mode-goto-occurrence
14034 (after org-occur-reveal activate)
14035 (and (org-mode-p) (org-reveal)))
14036 (defadvice occur-mode-goto-occurrence-other-window
14037 (after org-occur-reveal activate)
14038 (and (org-mode-p) (org-reveal)))
14039 (defadvice occur-mode-display-occurrence
14040 (after org-occur-reveal activate)
14041 (when (org-mode-p)
14042 (let ((pos (occur-mode-find-occurrence)))
14043 (with-current-buffer (marker-buffer pos)
14044 (save-excursion
14045 (goto-char pos)
14046 (org-reveal)))))))
14048 (defun org-uniquify (list)
14049 "Remove duplicate elements from LIST."
14050 (let (res)
14051 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14052 res))
14054 (defun org-delete-all (elts list)
14055 "Remove all elements in ELTS from LIST."
14056 (while elts
14057 (setq list (delete (pop elts) list)))
14058 list)
14060 (defun org-back-over-empty-lines ()
14061 "Move backwards over whitespace, to the beginning of the first empty line.
14062 Returns the number of empty lines passed."
14063 (let ((pos (point)))
14064 (skip-chars-backward " \t\n\r")
14065 (beginning-of-line 2)
14066 (goto-char (min (point) pos))
14067 (count-lines (point) pos)))
14069 (defun org-skip-whitespace ()
14070 (skip-chars-forward " \t\n\r"))
14072 (defun org-point-in-group (point group &optional context)
14073 "Check if POINT is in match-group GROUP.
14074 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14075 match. If the match group does ot exist or point is not inside it,
14076 return nil."
14077 (and (match-beginning group)
14078 (>= point (match-beginning group))
14079 (<= point (match-end group))
14080 (if context
14081 (list context (match-beginning group) (match-end group))
14082 t)))
14084 (defun org-switch-to-buffer-other-window (&rest args)
14085 "Switch to buffer in a second window on the current frame.
14086 In particular, do not allow pop-up frames."
14087 (let (pop-up-frames special-display-buffer-names special-display-regexps
14088 special-display-function)
14089 (apply 'switch-to-buffer-other-window args)))
14091 (defun org-combine-plists (&rest plists)
14092 "Create a single property list from all plists in PLISTS.
14093 The process starts by copying the first list, and then setting properties
14094 from the other lists. Settings in the last list are the most significant
14095 ones and overrule settings in the other lists."
14096 (let ((rtn (copy-sequence (pop plists)))
14097 p v ls)
14098 (while plists
14099 (setq ls (pop plists))
14100 (while ls
14101 (setq p (pop ls) v (pop ls))
14102 (setq rtn (plist-put rtn p v))))
14103 rtn))
14105 (defun org-move-line-down (arg)
14106 "Move the current line down. With prefix argument, move it past ARG lines."
14107 (interactive "p")
14108 (let ((col (current-column))
14109 beg end pos)
14110 (beginning-of-line 1) (setq beg (point))
14111 (beginning-of-line 2) (setq end (point))
14112 (beginning-of-line (+ 1 arg))
14113 (setq pos (move-marker (make-marker) (point)))
14114 (insert (delete-and-extract-region beg end))
14115 (goto-char pos)
14116 (org-move-to-column col)))
14118 (defun org-move-line-up (arg)
14119 "Move the current line up. With prefix argument, move it past ARG lines."
14120 (interactive "p")
14121 (let ((col (current-column))
14122 beg end pos)
14123 (beginning-of-line 1) (setq beg (point))
14124 (beginning-of-line 2) (setq end (point))
14125 (beginning-of-line (- arg))
14126 (setq pos (move-marker (make-marker) (point)))
14127 (insert (delete-and-extract-region beg end))
14128 (goto-char pos)
14129 (org-move-to-column col)))
14131 (defun org-replace-escapes (string table)
14132 "Replace %-escapes in STRING with values in TABLE.
14133 TABLE is an association list with keys like \"%a\" and string values.
14134 The sequences in STRING may contain normal field width and padding information,
14135 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14136 so values can contain further %-escapes if they are define later in TABLE."
14137 (let ((case-fold-search nil)
14138 e re rpl)
14139 (while (setq e (pop table))
14140 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14141 (while (string-match re string)
14142 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14143 (cdr e)))
14144 (setq string (replace-match rpl t t string))))
14145 string))
14148 (defun org-sublist (list start end)
14149 "Return a section of LIST, from START to END.
14150 Counting starts at 1."
14151 (let (rtn (c start))
14152 (setq list (nthcdr (1- start) list))
14153 (while (and list (<= c end))
14154 (push (pop list) rtn)
14155 (setq c (1+ c)))
14156 (nreverse rtn)))
14158 (defun org-find-base-buffer-visiting (file)
14159 "Like `find-buffer-visiting' but alway return the base buffer and
14160 not an indirect buffer."
14161 (let ((buf (find-buffer-visiting file)))
14162 (if buf
14163 (or (buffer-base-buffer buf) buf)
14164 nil)))
14166 (defun org-image-file-name-regexp ()
14167 "Return regexp matching the file names of images."
14168 (if (fboundp 'image-file-name-regexp)
14169 (image-file-name-regexp)
14170 (let ((image-file-name-extensions
14171 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14172 "xbm" "xpm" "pbm" "pgm" "ppm")))
14173 (concat "\\."
14174 (regexp-opt (nconc (mapcar 'upcase
14175 image-file-name-extensions)
14176 image-file-name-extensions)
14178 "\\'"))))
14180 (defun org-file-image-p (file)
14181 "Return non-nil if FILE is an image."
14182 (save-match-data
14183 (string-match (org-image-file-name-regexp) file)))
14185 (defun org-get-cursor-date ()
14186 "Return the date at cursor in as a time.
14187 This works in the calendar and in the agenda, anywhere else it just
14188 returns the current time."
14189 (let (date day defd)
14190 (cond
14191 ((eq major-mode 'calendar-mode)
14192 (setq date (calendar-cursor-to-date)
14193 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14194 ((eq major-mode 'org-agenda-mode)
14195 (setq day (get-text-property (point) 'day))
14196 (if day
14197 (setq date (calendar-gregorian-from-absolute day)
14198 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14199 (nth 2 date))))))
14200 (or defd (current-time))))
14202 (defvar org-agenda-action-marker (make-marker)
14203 "Marker pointing to the entry for the next agenda action.")
14205 (defun org-mark-entry-for-agenda-action ()
14206 "Mark the current entry as target of an agenda action.
14207 Agenda actions are actions executed from the agenda with the key `k',
14208 which make use of the date at the cursor."
14209 (interactive)
14210 (move-marker org-agenda-action-marker
14211 (save-excursion (org-back-to-heading t) (point))
14212 (current-buffer))
14213 (message
14214 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14216 ;;; Paragraph filling stuff.
14217 ;; We want this to be just right, so use the full arsenal.
14219 (defun org-indent-line-function ()
14220 "Indent line like previous, but further if previous was headline or item."
14221 (interactive)
14222 (let* ((pos (point))
14223 (itemp (org-at-item-p))
14224 column bpos bcol tpos tcol bullet btype bullet-type)
14225 ;; Find the previous relevant line
14226 (beginning-of-line 1)
14227 (cond
14228 ((looking-at "#") (setq column 0))
14229 ((looking-at "\\*+ ") (setq column 0))
14231 (beginning-of-line 0)
14232 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14233 (beginning-of-line 0))
14234 (cond
14235 ((looking-at "\\*+[ \t]+")
14236 (if (not org-adapt-indentation)
14237 (setq column 0)
14238 (goto-char (match-end 0))
14239 (setq column (current-column))))
14240 ((org-in-item-p)
14241 (org-beginning-of-item)
14242 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14243 (setq bpos (match-beginning 1) tpos (match-end 0)
14244 bcol (progn (goto-char bpos) (current-column))
14245 tcol (progn (goto-char tpos) (current-column))
14246 bullet (match-string 1)
14247 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14248 (if (> tcol (+ bcol org-description-max-indent))
14249 (setq tcol (+ bcol 5)))
14250 (if (not itemp)
14251 (setq column tcol)
14252 (goto-char pos)
14253 (beginning-of-line 1)
14254 (if (looking-at "\\S-")
14255 (progn
14256 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14257 (setq bullet (match-string 1)
14258 btype (if (string-match "[0-9]" bullet) "n" bullet))
14259 (setq column (if (equal btype bullet-type) bcol tcol)))
14260 (setq column (org-get-indentation)))))
14261 (t (setq column (org-get-indentation))))))
14262 (goto-char pos)
14263 (if (<= (current-column) (current-indentation))
14264 (org-indent-line-to column)
14265 (save-excursion (org-indent-line-to column)))
14266 (setq column (current-column))
14267 (beginning-of-line 1)
14268 (if (looking-at
14269 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14270 (replace-match (concat "\\1" (format org-property-format
14271 (match-string 2) (match-string 3)))
14272 t nil))
14273 (org-move-to-column column)))
14275 (defun org-set-autofill-regexps ()
14276 (interactive)
14277 ;; In the paragraph separator we include headlines, because filling
14278 ;; text in a line directly attached to a headline would otherwise
14279 ;; fill the headline as well.
14280 (org-set-local 'comment-start-skip "^#+[ \t]*")
14281 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14282 ;; The paragraph starter includes hand-formatted lists.
14283 (org-set-local 'paragraph-start
14284 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14285 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14286 ;; But only if the user has not turned off tables or fixed-width regions
14287 (org-set-local
14288 'auto-fill-inhibit-regexp
14289 (concat "\\*+ \\|#\\+"
14290 "\\|[ \t]*" org-keyword-time-regexp
14291 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14292 (concat
14293 "\\|[ \t]*["
14294 (if org-enable-table-editor "|" "")
14295 (if org-enable-fixed-width-editor ":" "")
14296 "]"))))
14297 ;; We use our own fill-paragraph function, to make sure that tables
14298 ;; and fixed-width regions are not wrapped. That function will pass
14299 ;; through to `fill-paragraph' when appropriate.
14300 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14301 ; Adaptive filling: To get full control, first make sure that
14302 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14303 (org-set-local 'adaptive-fill-regexp "\000")
14304 (org-set-local 'adaptive-fill-function
14305 'org-adaptive-fill-function)
14306 (org-set-local
14307 'align-mode-rules-list
14308 '((org-in-buffer-settings
14309 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14310 (modes . '(org-mode))))))
14312 (defun org-fill-paragraph (&optional justify)
14313 "Re-align a table, pass through to fill-paragraph if no table."
14314 (let ((table-p (org-at-table-p))
14315 (table.el-p (org-at-table.el-p)))
14316 (cond ((and (equal (char-after (point-at-bol)) ?*)
14317 (save-excursion (goto-char (point-at-bol))
14318 (looking-at outline-regexp)))
14319 t) ; skip headlines
14320 (table.el-p t) ; skip table.el tables
14321 (table-p (org-table-align) t) ; align org-mode tables
14322 (t nil)))) ; call paragraph-fill
14324 ;; For reference, this is the default value of adaptive-fill-regexp
14325 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14327 (defun org-adaptive-fill-function ()
14328 "Return a fill prefix for org-mode files.
14329 In particular, this makes sure hanging paragraphs for hand-formatted lists
14330 work correctly."
14331 (cond ((looking-at "#[ \t]+")
14332 (match-string 0))
14333 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14334 (save-excursion
14335 (if (> (match-end 1) (+ (match-beginning 1)
14336 org-description-max-indent))
14337 (goto-char (+ (match-beginning 1) 5))
14338 (goto-char (match-end 0)))
14339 (make-string (current-column) ?\ )))
14340 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14341 (save-excursion
14342 (goto-char (match-end 0))
14343 (make-string (current-column) ?\ )))
14344 (t nil)))
14346 ;;; Other stuff.
14348 (defun org-toggle-fixed-width-section (arg)
14349 "Toggle the fixed-width export.
14350 If there is no active region, the QUOTE keyword at the current headline is
14351 inserted or removed. When present, it causes the text between this headline
14352 and the next to be exported as fixed-width text, and unmodified.
14353 If there is an active region, this command adds or removes a colon as the
14354 first character of this line. If the first character of a line is a colon,
14355 this line is also exported in fixed-width font."
14356 (interactive "P")
14357 (let* ((cc 0)
14358 (regionp (org-region-active-p))
14359 (beg (if regionp (region-beginning) (point)))
14360 (end (if regionp (region-end)))
14361 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14362 (case-fold-search nil)
14363 (re "[ \t]*\\(:\\)")
14364 off)
14365 (if regionp
14366 (save-excursion
14367 (goto-char beg)
14368 (setq cc (current-column))
14369 (beginning-of-line 1)
14370 (setq off (looking-at re))
14371 (while (> nlines 0)
14372 (setq nlines (1- nlines))
14373 (beginning-of-line 1)
14374 (cond
14375 (arg
14376 (org-move-to-column cc t)
14377 (insert ":\n")
14378 (forward-line -1))
14379 ((and off (looking-at re))
14380 (replace-match "" t t nil 1))
14381 ((not off) (org-move-to-column cc t) (insert ":")))
14382 (forward-line 1)))
14383 (save-excursion
14384 (org-back-to-heading)
14385 (if (looking-at (concat outline-regexp
14386 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14387 (replace-match "" t t nil 1)
14388 (if (looking-at outline-regexp)
14389 (progn
14390 (goto-char (match-end 0))
14391 (insert org-quote-string " "))))))))
14393 ;;;; Functions extending outline functionality
14395 (defun org-beginning-of-line (&optional arg)
14396 "Go to the beginning of the current line. If that is invisible, continue
14397 to a visible line beginning. This makes the function of C-a more intuitive.
14398 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14399 first attempt, and only move to after the tags when the cursor is already
14400 beyond the end of the headline."
14401 (interactive "P")
14402 (let ((pos (point)) refpos)
14403 (beginning-of-line 1)
14404 (if (bobp)
14406 (backward-char 1)
14407 (if (org-invisible-p)
14408 (while (and (not (bobp)) (org-invisible-p))
14409 (backward-char 1)
14410 (beginning-of-line 1))
14411 (forward-char 1)))
14412 (when org-special-ctrl-a/e
14413 (cond
14414 ((and (looking-at org-complex-heading-regexp)
14415 (= (char-after (match-end 1)) ?\ ))
14416 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14417 (point-at-eol)))
14418 (goto-char
14419 (if (eq org-special-ctrl-a/e t)
14420 (cond ((> pos refpos) refpos)
14421 ((= pos (point)) refpos)
14422 (t (point)))
14423 (cond ((> pos (point)) (point))
14424 ((not (eq last-command this-command)) (point))
14425 (t refpos)))))
14426 ((org-at-item-p)
14427 (goto-char
14428 (if (eq org-special-ctrl-a/e t)
14429 (cond ((> pos (match-end 4)) (match-end 4))
14430 ((= pos (point)) (match-end 4))
14431 (t (point)))
14432 (cond ((> pos (point)) (point))
14433 ((not (eq last-command this-command)) (point))
14434 (t (match-end 4))))))))
14435 (org-no-warnings
14436 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14438 (defun org-end-of-line (&optional arg)
14439 "Go to the end of the line.
14440 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14441 first attempt, and only move to after the tags when the cursor is already
14442 beyond the end of the headline."
14443 (interactive "P")
14444 (if (or (not org-special-ctrl-a/e)
14445 (not (org-on-heading-p)))
14446 (end-of-line arg)
14447 (let ((pos (point)))
14448 (beginning-of-line 1)
14449 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14450 (if (eq org-special-ctrl-a/e t)
14451 (if (or (< pos (match-beginning 1))
14452 (= pos (match-end 0)))
14453 (goto-char (match-beginning 1))
14454 (goto-char (match-end 0)))
14455 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14456 (goto-char (match-end 0))
14457 (goto-char (match-beginning 1))))
14458 (end-of-line arg))))
14459 (org-no-warnings
14460 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14463 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14464 (define-key org-mode-map "\C-e" 'org-end-of-line)
14466 (defun org-kill-line (&optional arg)
14467 "Kill line, to tags or end of line."
14468 (interactive "P")
14469 (cond
14470 ((or (not org-special-ctrl-k)
14471 (bolp)
14472 (not (org-on-heading-p)))
14473 (call-interactively 'kill-line))
14474 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14475 (kill-region (point) (match-beginning 1))
14476 (org-set-tags nil t))
14477 (t (kill-region (point) (point-at-eol)))))
14479 (define-key org-mode-map "\C-k" 'org-kill-line)
14481 (defun org-yank (&optional arg)
14482 "Yank. If the kill is a subtree, treat it specially.
14483 This command will look at the current kill and check if is a single
14484 subtree, or a series of subtrees[1]. If it passes the test, and if the
14485 cursor is at the beginning of a line or after the stars of a currently
14486 empty headline, then the yank is handled specially. How exactly depends
14487 on the value of the following variables, both set by default.
14489 org-yank-folded-subtrees
14490 When set, the subtree(s) will be folded after insertion, but only
14491 if doing so would now swallow text after the yanked text.
14493 org-yank-adjusted-subtrees
14494 When set, the subtree will be promoted or demoted in order to
14495 fit into the local outline tree structure, which means that the level
14496 will be adjusted so that it becomes the smaller one of the two
14497 *visible* surrounding headings.
14499 Any prefix to this command will cause `yank' to be called directly with
14500 no special treatment. In particular, a simple `C-u' prefix will just
14501 plainly yank the text as it is.
14503 \[1] Basically, the test checks if the first non-white line is a heading
14504 and if there are no other headings with fewer stars."
14505 (interactive "P")
14506 (setq this-command 'yank)
14507 (if arg
14508 (call-interactively 'yank)
14509 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14510 (and (org-kill-is-subtree-p)
14511 (or (bolp)
14512 (and (looking-at "[ \t]*$")
14513 (string-match
14514 "\\`\\*+\\'"
14515 (buffer-substring (point-at-bol) (point)))))))
14516 swallowp)
14517 (cond
14518 ((and subtreep org-yank-folded-subtrees)
14519 (let ((beg (point))
14520 end)
14521 (if (and subtreep org-yank-adjusted-subtrees)
14522 (org-paste-subtree nil nil 'for-yank)
14523 (call-interactively 'yank))
14524 (setq end (point))
14525 (goto-char beg)
14526 (when (and (bolp) subtreep
14527 (not (setq swallowp
14528 (org-yank-folding-would-swallow-text beg end))))
14529 (or (looking-at outline-regexp)
14530 (re-search-forward (concat "^" outline-regexp) end t))
14531 (while (and (< (point) end) (looking-at outline-regexp))
14532 (hide-subtree)
14533 (org-cycle-show-empty-lines 'folded)
14534 (condition-case nil
14535 (outline-forward-same-level 1)
14536 (error (goto-char end)))))
14537 (when swallowp
14538 (message
14539 "Yanked text not folded because that would swallow text"))
14540 (goto-char end)
14541 (skip-chars-forward " \t\n\r")
14542 (beginning-of-line 1)
14543 (push-mark beg 'nomsg)))
14544 ((and subtreep org-yank-adjusted-subtrees)
14545 (let ((beg (point-at-bol)))
14546 (org-paste-subtree nil nil 'for-yank)
14547 (push-mark beg 'nomsg)))
14549 (call-interactively 'yank))))))
14551 (defun org-yank-folding-would-swallow-text (beg end)
14552 "Would hide-subtree at BEG swallow any text after END?"
14553 (let (level)
14554 (save-excursion
14555 (goto-char beg)
14556 (when (or (looking-at outline-regexp)
14557 (re-search-forward (concat "^" outline-regexp) end t))
14558 (setq level (org-outline-level)))
14559 (goto-char end)
14560 (skip-chars-forward " \t\r\n\v\f")
14561 (if (or (eobp)
14562 (and (bolp) (looking-at org-outline-regexp)
14563 (<= (org-outline-level) level)))
14564 nil ; Nothing would be swallowed
14565 t)))) ; something would swallow
14567 (define-key org-mode-map "\C-y" 'org-yank)
14569 (defun org-invisible-p ()
14570 "Check if point is at a character currently not visible."
14571 ;; Early versions of noutline don't have `outline-invisible-p'.
14572 (if (fboundp 'outline-invisible-p)
14573 (outline-invisible-p)
14574 (get-char-property (point) 'invisible)))
14576 (defun org-invisible-p2 ()
14577 "Check if point is at a character currently not visible."
14578 (save-excursion
14579 (if (and (eolp) (not (bobp))) (backward-char 1))
14580 ;; Early versions of noutline don't have `outline-invisible-p'.
14581 (if (fboundp 'outline-invisible-p)
14582 (outline-invisible-p)
14583 (get-char-property (point) 'invisible))))
14585 (defun org-back-to-heading (&optional invisible-ok)
14586 "Call `outline-back-to-heading', but provide a better error message."
14587 (condition-case nil
14588 (outline-back-to-heading invisible-ok)
14589 (error (error "Before first headline at position %d in buffer %s"
14590 (point) (current-buffer)))))
14592 (defun org-before-first-heading-p ()
14593 "Before first heading?"
14594 (save-excursion
14595 (null (re-search-backward "^\\*+ " nil t))))
14597 (defalias 'org-on-heading-p 'outline-on-heading-p)
14598 (defalias 'org-at-heading-p 'outline-on-heading-p)
14599 (defun org-at-heading-or-item-p ()
14600 (or (org-on-heading-p) (org-at-item-p)))
14602 (defun org-on-target-p ()
14603 (or (org-in-regexp org-radio-target-regexp)
14604 (org-in-regexp org-target-regexp)))
14606 (defun org-up-heading-all (arg)
14607 "Move to the heading line of which the present line is a subheading.
14608 This function considers both visible and invisible heading lines.
14609 With argument, move up ARG levels."
14610 (if (fboundp 'outline-up-heading-all)
14611 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14612 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14614 (defun org-up-heading-safe ()
14615 "Move to the heading line of which the present line is a subheading.
14616 This version will not throw an error. It will return the level of the
14617 headline found, or nil if no higher level is found."
14618 (let (start-level re)
14619 (org-back-to-heading t)
14620 (setq start-level (funcall outline-level))
14621 (if (equal start-level 1)
14623 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14624 (if (re-search-backward re nil t)
14625 (funcall outline-level)))))
14627 (defun org-first-sibling-p ()
14628 "Is this heading the first child of its parents?"
14629 (interactive)
14630 (let ((re (concat "^" outline-regexp))
14631 level l)
14632 (unless (org-at-heading-p t)
14633 (error "Not at a heading"))
14634 (setq level (funcall outline-level))
14635 (save-excursion
14636 (if (not (re-search-backward re nil t))
14638 (setq l (funcall outline-level))
14639 (< l level)))))
14641 (defun org-goto-sibling (&optional previous)
14642 "Goto the next sibling, even if it is invisible.
14643 When PREVIOUS is set, go to the previous sibling instead. Returns t
14644 when a sibling was found. When none is found, return nil and don't
14645 move point."
14646 (let ((fun (if previous 're-search-backward 're-search-forward))
14647 (pos (point))
14648 (re (concat "^" outline-regexp))
14649 level l)
14650 (when (condition-case nil (org-back-to-heading t) (error nil))
14651 (setq level (funcall outline-level))
14652 (catch 'exit
14653 (or previous (forward-char 1))
14654 (while (funcall fun re nil t)
14655 (setq l (funcall outline-level))
14656 (when (< l level) (goto-char pos) (throw 'exit nil))
14657 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14658 (goto-char pos)
14659 nil))))
14661 (defun org-show-siblings ()
14662 "Show all siblings of the current headline."
14663 (save-excursion
14664 (while (org-goto-sibling) (org-flag-heading nil)))
14665 (save-excursion
14666 (while (org-goto-sibling 'previous)
14667 (org-flag-heading nil))))
14669 (defun org-show-hidden-entry ()
14670 "Show an entry where even the heading is hidden."
14671 (save-excursion
14672 (org-show-entry)))
14674 (defun org-flag-heading (flag &optional entry)
14675 "Flag the current heading. FLAG non-nil means make invisible.
14676 When ENTRY is non-nil, show the entire entry."
14677 (save-excursion
14678 (org-back-to-heading t)
14679 ;; Check if we should show the entire entry
14680 (if entry
14681 (progn
14682 (org-show-entry)
14683 (save-excursion
14684 (and (outline-next-heading)
14685 (org-flag-heading nil))))
14686 (outline-flag-region (max (point-min) (1- (point)))
14687 (save-excursion (outline-end-of-heading) (point))
14688 flag))))
14690 (defun org-forward-same-level (arg)
14691 "Move forward to the ARG'th subheading at same level as this one.
14692 Stop at the first and last subheadings of a superior heading.
14693 This is like outline-forward-same-level, but invisible headings are ok."
14694 (interactive "p")
14695 (org-back-to-heading t)
14696 (while (> arg 0)
14697 (let ((point-to-move-to (save-excursion
14698 (org-get-next-sibling))))
14699 (if point-to-move-to
14700 (progn
14701 (goto-char point-to-move-to)
14702 (setq arg (1- arg)))
14703 (progn
14704 (setq arg 0)
14705 (error "No following same-level heading"))))))
14707 (defun org-get-next-sibling ()
14708 "Move to next heading of the same level, and return point.
14709 If there is no such heading, return nil.
14710 This is like outline-next-sibling, but invisible headings are ok."
14711 (let ((level (funcall outline-level)))
14712 (outline-next-heading)
14713 (while (and (not (eobp)) (> (funcall outline-level) level))
14714 (outline-next-heading))
14715 (if (or (eobp) (< (funcall outline-level) level))
14717 (point))))
14719 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14720 ;; This is an exact copy of the original function, but it uses
14721 ;; `org-back-to-heading', to make it work also in invisible
14722 ;; trees. And is uses an invisible-OK argument.
14723 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14724 (org-back-to-heading invisible-OK)
14725 (let ((first t)
14726 (level (funcall outline-level)))
14727 (while (and (not (eobp))
14728 (or first (> (funcall outline-level) level)))
14729 (setq first nil)
14730 (outline-next-heading))
14731 (unless to-heading
14732 (if (memq (preceding-char) '(?\n ?\^M))
14733 (progn
14734 ;; Go to end of line before heading
14735 (forward-char -1)
14736 (if (memq (preceding-char) '(?\n ?\^M))
14737 ;; leave blank line before heading
14738 (forward-char -1))))))
14739 (point))
14741 (defun org-show-subtree ()
14742 "Show everything after this heading at deeper levels."
14743 (outline-flag-region
14744 (point)
14745 (save-excursion
14746 (outline-end-of-subtree) (outline-next-heading) (point))
14747 nil))
14749 (defun org-show-entry ()
14750 "Show the body directly following this heading.
14751 Show the heading too, if it is currently invisible."
14752 (interactive)
14753 (save-excursion
14754 (condition-case nil
14755 (progn
14756 (org-back-to-heading t)
14757 (outline-flag-region
14758 (max (point-min) (1- (point)))
14759 (save-excursion
14760 (re-search-forward
14761 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14762 (or (match-beginning 1) (point-max)))
14763 nil))
14764 (error nil))))
14766 (defun org-make-options-regexp (kwds)
14767 "Make a regular expression for keyword lines."
14768 (concat
14770 "#?[ \t]*\\+\\("
14771 (mapconcat 'regexp-quote kwds "\\|")
14772 "\\):[ \t]*"
14773 "\\(.+\\)"))
14775 ;; Make isearch reveal the necessary context
14776 (defun org-isearch-end ()
14777 "Reveal context after isearch exits."
14778 (when isearch-success ; only if search was successful
14779 (if (featurep 'xemacs)
14780 ;; Under XEmacs, the hook is run in the correct place,
14781 ;; we directly show the context.
14782 (org-show-context 'isearch)
14783 ;; In Emacs the hook runs *before* restoring the overlays.
14784 ;; So we have to use a one-time post-command-hook to do this.
14785 ;; (Emacs 22 has a special variable, see function `org-mode')
14786 (unless (and (boundp 'isearch-mode-end-hook-quit)
14787 isearch-mode-end-hook-quit)
14788 ;; Only when the isearch was not quitted.
14789 (org-add-hook 'post-command-hook 'org-isearch-post-command
14790 'append 'local)))))
14792 (defun org-isearch-post-command ()
14793 "Remove self from hook, and show context."
14794 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14795 (org-show-context 'isearch))
14798 ;;;; Integration with and fixes for other packages
14800 ;;; Imenu support
14802 (defvar org-imenu-markers nil
14803 "All markers currently used by Imenu.")
14804 (make-variable-buffer-local 'org-imenu-markers)
14806 (defun org-imenu-new-marker (&optional pos)
14807 "Return a new marker for use by Imenu, and remember the marker."
14808 (let ((m (make-marker)))
14809 (move-marker m (or pos (point)))
14810 (push m org-imenu-markers)
14813 (defun org-imenu-get-tree ()
14814 "Produce the index for Imenu."
14815 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14816 (setq org-imenu-markers nil)
14817 (let* ((n org-imenu-depth)
14818 (re (concat "^" outline-regexp))
14819 (subs (make-vector (1+ n) nil))
14820 (last-level 0)
14821 m tree level head)
14822 (save-excursion
14823 (save-restriction
14824 (widen)
14825 (goto-char (point-max))
14826 (while (re-search-backward re nil t)
14827 (setq level (org-reduced-level (funcall outline-level)))
14828 (when (<= level n)
14829 (looking-at org-complex-heading-regexp)
14830 (setq head (org-link-display-format
14831 (org-match-string-no-properties 4))
14832 m (org-imenu-new-marker))
14833 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14834 (if (>= level last-level)
14835 (push (cons head m) (aref subs level))
14836 (push (cons head (aref subs (1+ level))) (aref subs level))
14837 (loop for i from (1+ level) to n do (aset subs i nil)))
14838 (setq last-level level)))))
14839 (aref subs 1)))
14841 (eval-after-load "imenu"
14842 '(progn
14843 (add-hook 'imenu-after-jump-hook
14844 (lambda ()
14845 (if (eq major-mode 'org-mode)
14846 (org-show-context 'org-goto))))))
14848 (defun org-link-display-format (link)
14849 "Replace a link with either the description, or the link target
14850 if no description is present"
14851 (save-match-data
14852 (if (string-match org-bracket-link-analytic-regexp link)
14853 (replace-match (or (match-string 5 link)
14854 (concat (match-string 1 link)
14855 (match-string 3 link)))
14856 nil nil link)
14857 link)))
14859 ;; Speedbar support
14861 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14862 "Overlay marking the agenda restriction line in speedbar.")
14863 (org-overlay-put org-speedbar-restriction-lock-overlay
14864 'face 'org-agenda-restriction-lock)
14865 (org-overlay-put org-speedbar-restriction-lock-overlay
14866 'help-echo "Agendas are currently limited to this item.")
14867 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14869 (defun org-speedbar-set-agenda-restriction ()
14870 "Restrict future agenda commands to the location at point in speedbar.
14871 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14872 (interactive)
14873 (require 'org-agenda)
14874 (let (p m tp np dir txt w)
14875 (cond
14876 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14877 'org-imenu t))
14878 (setq m (get-text-property p 'org-imenu-marker))
14879 (save-excursion
14880 (save-restriction
14881 (set-buffer (marker-buffer m))
14882 (goto-char m)
14883 (org-agenda-set-restriction-lock 'subtree))))
14884 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14885 'speedbar-function 'speedbar-find-file))
14886 (setq tp (previous-single-property-change
14887 (1+ p) 'speedbar-function)
14888 np (next-single-property-change
14889 tp 'speedbar-function)
14890 dir (speedbar-line-directory)
14891 txt (buffer-substring-no-properties (or tp (point-min))
14892 (or np (point-max))))
14893 (save-excursion
14894 (save-restriction
14895 (set-buffer (find-file-noselect
14896 (let ((default-directory dir))
14897 (expand-file-name txt))))
14898 (unless (org-mode-p)
14899 (error "Cannot restrict to non-Org-mode file"))
14900 (org-agenda-set-restriction-lock 'file))))
14901 (t (error "Don't know how to restrict Org-mode's agenda")))
14902 (org-move-overlay org-speedbar-restriction-lock-overlay
14903 (point-at-bol) (point-at-eol))
14904 (setq current-prefix-arg nil)
14905 (org-agenda-maybe-redo)))
14907 (eval-after-load "speedbar"
14908 '(progn
14909 (speedbar-add-supported-extension ".org")
14910 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14911 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14912 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14913 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14914 (add-hook 'speedbar-visiting-tag-hook
14915 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14918 ;;; Fixes and Hacks for problems with other packages
14920 ;; Make flyspell not check words in links, to not mess up our keymap
14921 (defun org-mode-flyspell-verify ()
14922 "Don't let flyspell put overlays at active buttons."
14923 (not (get-text-property (point) 'keymap)))
14925 ;; Make `bookmark-jump' show the jump location if it was hidden.
14926 (eval-after-load "bookmark"
14927 '(if (boundp 'bookmark-after-jump-hook)
14928 ;; We can use the hook
14929 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14930 ;; Hook not available, use advice
14931 (defadvice bookmark-jump (after org-make-visible activate)
14932 "Make the position visible."
14933 (org-bookmark-jump-unhide))))
14935 ;; Make sure saveplace show the location if it was hidden
14936 (eval-after-load "saveplace"
14937 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14938 "Make the position visible."
14939 (org-bookmark-jump-unhide)))
14941 (defun org-bookmark-jump-unhide ()
14942 "Unhide the current position, to show the bookmark location."
14943 (and (org-mode-p)
14944 (or (org-invisible-p)
14945 (save-excursion (goto-char (max (point-min) (1- (point))))
14946 (org-invisible-p)))
14947 (org-show-context 'bookmark-jump)))
14949 ;; Make session.el ignore our circular variable
14950 (eval-after-load "session"
14951 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14953 ;;;; Experimental code
14955 (defun org-closed-in-range ()
14956 "Sparse tree of items closed in a certain time range.
14957 Still experimental, may disappear in the future."
14958 (interactive)
14959 ;; Get the time interval from the user.
14960 (let* ((time1 (time-to-seconds
14961 (org-read-date nil 'to-time nil "Starting date: ")))
14962 (time2 (time-to-seconds
14963 (org-read-date nil 'to-time nil "End date:")))
14964 ;; callback function
14965 (callback (lambda ()
14966 (let ((time
14967 (time-to-seconds
14968 (apply 'encode-time
14969 (org-parse-time-string
14970 (match-string 1))))))
14971 ;; check if time in interval
14972 (and (>= time time1) (<= time time2))))))
14973 ;; make tree, check each match with the callback
14974 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14977 ;;;; Finish up
14979 (provide 'org)
14981 (run-hooks 'org-load-hook)
14983 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14985 ;;; org.el ends here