Editing: Automatic empty lines before new entries.
[org-mode.git] / lisp / org.el
blobbde379027798fae7b25b3ef3cfb6923d6f88ab20
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" "$" "$$" "\\(" "\\["))
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 \"$\" find math expressions surrounded by $...$
2252 \"$$\" find math expressions surrounded by $$....$$
2253 \"\\(\" find math expressions surrounded by \\(...\\)
2254 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2255 :group 'org-latex
2256 :type 'plist)
2258 (defcustom org-format-latex-header "\\documentclass{article}
2259 \\usepackage{fullpage} % do not remove
2260 \\usepackage{amssymb}
2261 \\usepackage[usenames]{color}
2262 \\usepackage{amsmath}
2263 \\usepackage{latexsym}
2264 \\usepackage[mathscr]{eucal}
2265 \\pagestyle{empty} % do not remove"
2266 "The document header used for processing LaTeX fragments."
2267 :group 'org-latex
2268 :type 'string)
2271 (defgroup org-font-lock nil
2272 "Font-lock settings for highlighting in Org-mode."
2273 :tag "Org Font Lock"
2274 :group 'org)
2276 (defcustom org-level-color-stars-only nil
2277 "Non-nil means fontify only the stars in each headline.
2278 When nil, the entire headline is fontified.
2279 Changing it requires restart of `font-lock-mode' to become effective
2280 also in regions already fontified."
2281 :group 'org-font-lock
2282 :type 'boolean)
2284 (defcustom org-hide-leading-stars nil
2285 "Non-nil means, hide the first N-1 stars in a headline.
2286 This works by using the face `org-hide' for these stars. This
2287 face is white for a light background, and black for a dark
2288 background. You may have to customize the face `org-hide' to
2289 make this work.
2290 Changing it requires restart of `font-lock-mode' to become effective
2291 also in regions already fontified.
2292 You may also set this on a per-file basis by adding one of the following
2293 lines to the buffer:
2295 #+STARTUP: hidestars
2296 #+STARTUP: showstars"
2297 :group 'org-font-lock
2298 :type 'boolean)
2300 (defcustom org-fontify-done-headline nil
2301 "Non-nil means, change the face of a headline if it is marked DONE.
2302 Normally, only the TODO/DONE keyword indicates the state of a headline.
2303 When this is non-nil, the headline after the keyword is set to the
2304 `org-headline-done' as an additional indication."
2305 :group 'org-font-lock
2306 :type 'boolean)
2308 (defcustom org-fontify-emphasized-text t
2309 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2310 Changing this variable requires a restart of Emacs to take effect."
2311 :group 'org-font-lock
2312 :type 'boolean)
2314 (defcustom org-highlight-latex-fragments-and-specials nil
2315 "Non-nil means, fontify what is treated specially by the exporters."
2316 :group 'org-font-lock
2317 :type 'boolean)
2319 (defcustom org-hide-emphasis-markers nil
2320 "Non-nil mean font-lock should hide the emphasis marker characters."
2321 :group 'org-font-lock
2322 :type 'boolean)
2324 (defvar org-emph-re nil
2325 "Regular expression for matching emphasis.")
2326 (defvar org-verbatim-re nil
2327 "Regular expression for matching verbatim text.")
2328 (defvar org-emphasis-regexp-components) ; defined just below
2329 (defvar org-emphasis-alist) ; defined just below
2330 (defun org-set-emph-re (var val)
2331 "Set variable and compute the emphasis regular expression."
2332 (set var val)
2333 (when (and (boundp 'org-emphasis-alist)
2334 (boundp 'org-emphasis-regexp-components)
2335 org-emphasis-alist org-emphasis-regexp-components)
2336 (let* ((e org-emphasis-regexp-components)
2337 (pre (car e))
2338 (post (nth 1 e))
2339 (border (nth 2 e))
2340 (body (nth 3 e))
2341 (nl (nth 4 e))
2342 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2343 (body1 (concat body "*?"))
2344 (markers (mapconcat 'car org-emphasis-alist ""))
2345 (vmarkers (mapconcat
2346 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2347 org-emphasis-alist "")))
2348 ;; make sure special characters appear at the right position in the class
2349 (if (string-match "\\^" markers)
2350 (setq markers (concat (replace-match "" t t markers) "^")))
2351 (if (string-match "-" markers)
2352 (setq markers (concat (replace-match "" t t markers) "-")))
2353 (if (string-match "\\^" vmarkers)
2354 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2355 (if (string-match "-" vmarkers)
2356 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2357 (if (> nl 0)
2358 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2359 (int-to-string nl) "\\}")))
2360 ;; Make the regexp
2361 (setq org-emph-re
2362 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2363 "\\("
2364 "\\([" markers "]\\)"
2365 "\\("
2366 "[^" border "]\\|"
2367 "[^" border (if (and nil stacked) markers) "]"
2368 body1
2369 "[^" border (if (and nil stacked) markers) "]"
2370 "\\)"
2371 "\\3\\)"
2372 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2373 (setq org-verbatim-re
2374 (concat "\\([" pre "]\\|^\\)"
2375 "\\("
2376 "\\([" vmarkers "]\\)"
2377 "\\("
2378 "[^" border "]\\|"
2379 "[^" border "]"
2380 body1
2381 "[^" border "]"
2382 "\\)"
2383 "\\3\\)"
2384 "\\([" post "]\\|$\\)")))))
2386 (defcustom org-emphasis-regexp-components
2387 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2388 "Components used to build the regular expression for emphasis.
2389 This is a list with 6 entries. Terminology: In an emphasis string
2390 like \" *strong word* \", we call the initial space PREMATCH, the final
2391 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2392 and \"trong wor\" is the body. The different components in this variable
2393 specify what is allowed/forbidden in each part:
2395 pre Chars allowed as prematch. Beginning of line will be allowed too.
2396 post Chars allowed as postmatch. End of line will be allowed too.
2397 border The chars *forbidden* as border characters.
2398 body-regexp A regexp like \".\" to match a body character. Don't use
2399 non-shy groups here, and don't allow newline here.
2400 newline The maximum number of newlines allowed in an emphasis exp.
2402 Use customize to modify this, or restart Emacs after changing it."
2403 :group 'org-font-lock
2404 :set 'org-set-emph-re
2405 :type '(list
2406 (sexp :tag "Allowed chars in pre ")
2407 (sexp :tag "Allowed chars in post ")
2408 (sexp :tag "Forbidden chars in border ")
2409 (sexp :tag "Regexp for body ")
2410 (integer :tag "number of newlines allowed")
2411 (option (boolean :tag "Please ignore this button"))))
2413 (defcustom org-emphasis-alist
2414 `(("*" bold "<b>" "</b>")
2415 ("/" italic "<i>" "</i>")
2416 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2417 ("=" org-code "<code>" "</code>" verbatim)
2418 ("~" org-verbatim "<code>" "</code>" verbatim)
2419 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2420 "<del>" "</del>")
2422 "Special syntax for emphasized text.
2423 Text starting and ending with a special character will be emphasized, for
2424 example *bold*, _underlined_ and /italic/. This variable sets the marker
2425 characters, the face to be used by font-lock for highlighting in Org-mode
2426 Emacs buffers, and the HTML tags to be used for this.
2427 Use customize to modify this, or restart Emacs after changing it."
2428 :group 'org-font-lock
2429 :set 'org-set-emph-re
2430 :type '(repeat
2431 (list
2432 (string :tag "Marker character")
2433 (choice
2434 (face :tag "Font-lock-face")
2435 (plist :tag "Face property list"))
2436 (string :tag "HTML start tag")
2437 (string :tag "HTML end tag")
2438 (option (const verbatim)))))
2440 ;;; Miscellaneous options
2442 (defgroup org-completion nil
2443 "Completion in Org-mode."
2444 :tag "Org Completion"
2445 :group 'org)
2447 (defcustom org-completion-use-ido nil
2448 "Non-nil means, use ido completion wherever possible.
2449 Note that `ido-mode' must be active for this variable to be relevant.
2450 If you decide to turn this variable on, you might well want to turn off
2451 `org-outline-path-complete-in-steps'."
2452 :group 'org-completion
2453 :type 'boolean)
2455 (defcustom org-completion-fallback-command 'hippie-expand
2456 "The expansion command called by \\[org-complete] in normal context.
2457 Normal means, no org-mode-specific context."
2458 :group 'org-completion
2459 :type 'function)
2461 ;;; Functions and variables from ther packages
2462 ;; Declared here to avoid compiler warnings
2464 ;; XEmacs only
2465 (defvar outline-mode-menu-heading)
2466 (defvar outline-mode-menu-show)
2467 (defvar outline-mode-menu-hide)
2468 (defvar zmacs-regions) ; XEmacs regions
2470 ;; Emacs only
2471 (defvar mark-active)
2473 ;; Various packages
2474 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2475 (declare-function calendar-forward-day "cal-move" (arg))
2476 (declare-function calendar-goto-date "cal-move" (date))
2477 (declare-function calendar-goto-today "cal-move" ())
2478 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2479 (defvar calc-embedded-close-formula)
2480 (defvar calc-embedded-open-formula)
2481 (declare-function cdlatex-tab "ext:cdlatex" ())
2482 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2483 (defvar font-lock-unfontify-region-function)
2484 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2485 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2486 (defvar iswitchb-temp-buflist)
2487 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2488 (declare-function org-agenda-skip "org-agenda" ())
2489 (declare-function org-format-agenda-item "org-agenda"
2490 (extra txt &optional category tags dotime noprefix remove-re))
2491 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2492 (declare-function org-agenda-change-all-lines "org-agenda"
2493 (newhead hdmarker &optional fixface just-this))
2494 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2495 (declare-function org-agenda-maybe-redo "org-agenda" ())
2496 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2497 (beg end))
2498 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2499 (declare-function parse-time-string "parse-time" (string))
2500 (declare-function remember "remember" (&optional initial))
2501 (declare-function remember-buffer-desc "remember" ())
2502 (declare-function remember-finalize "remember" ())
2503 (defvar remember-save-after-remembering)
2504 (defvar remember-data-file)
2505 (defvar remember-register)
2506 (defvar remember-buffer)
2507 (defvar remember-handler-functions)
2508 (defvar remember-annotation-functions)
2509 (defvar texmathp-why)
2510 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2511 (declare-function table--at-cell-p "table" (position &optional object at-column))
2513 (defvar w3m-current-url)
2514 (defvar w3m-current-title)
2516 (defvar org-latex-regexps)
2518 ;;; Autoload and prepare some org modules
2520 ;; Some table stuff that needs to be defined here, because it is used
2521 ;; by the functions setting up org-mode or checking for table context.
2523 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2524 "Detects an org-type or table-type table.")
2525 (defconst org-table-line-regexp "^[ \t]*|"
2526 "Detects an org-type table line.")
2527 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2528 "Detects an org-type table line.")
2529 (defconst org-table-hline-regexp "^[ \t]*|-"
2530 "Detects an org-type table hline.")
2531 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2532 "Detects a table-type table hline.")
2533 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2534 "Searching from within a table (any type) this finds the first line
2535 outside the table.")
2537 ;; Autoload the functions in org-table.el that are needed by functions here.
2539 (eval-and-compile
2540 (org-autoload "org-table"
2541 '(org-table-align org-table-begin org-table-blank-field
2542 org-table-convert org-table-convert-region org-table-copy-down
2543 org-table-copy-region org-table-create
2544 org-table-create-or-convert-from-region
2545 org-table-create-with-table.el org-table-current-dline
2546 org-table-cut-region org-table-delete-column org-table-edit-field
2547 org-table-edit-formulas org-table-end org-table-eval-formula
2548 org-table-export org-table-field-info
2549 org-table-get-stored-formulas org-table-goto-column
2550 org-table-hline-and-move org-table-import org-table-insert-column
2551 org-table-insert-hline org-table-insert-row org-table-iterate
2552 org-table-justify-field-maybe org-table-kill-row
2553 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2554 org-table-move-column org-table-move-column-left
2555 org-table-move-column-right org-table-move-row
2556 org-table-move-row-down org-table-move-row-up
2557 org-table-next-field org-table-next-row org-table-paste-rectangle
2558 org-table-previous-field org-table-recalculate
2559 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2560 org-table-toggle-coordinate-overlays
2561 org-table-toggle-formula-debugger org-table-wrap-region
2562 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2564 (defun org-at-table-p (&optional table-type)
2565 "Return t if the cursor is inside an org-type table.
2566 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2567 (if org-enable-table-editor
2568 (save-excursion
2569 (beginning-of-line 1)
2570 (looking-at (if table-type org-table-any-line-regexp
2571 org-table-line-regexp)))
2572 nil))
2573 (defsubst org-table-p () (org-at-table-p))
2575 (defun org-at-table.el-p ()
2576 "Return t if and only if we are at a table.el table."
2577 (and (org-at-table-p 'any)
2578 (save-excursion
2579 (goto-char (org-table-begin 'any))
2580 (looking-at org-table1-hline-regexp))))
2581 (defun org-table-recognize-table.el ()
2582 "If there is a table.el table nearby, recognize it and move into it."
2583 (if org-table-tab-recognizes-table.el
2584 (if (org-at-table.el-p)
2585 (progn
2586 (beginning-of-line 1)
2587 (if (looking-at org-table-dataline-regexp)
2589 (if (looking-at org-table1-hline-regexp)
2590 (progn
2591 (beginning-of-line 2)
2592 (if (looking-at org-table-any-border-regexp)
2593 (beginning-of-line -1)))))
2594 (if (re-search-forward "|" (org-table-end t) t)
2595 (progn
2596 (require 'table)
2597 (if (table--at-cell-p (point))
2599 (message "recognizing table.el table...")
2600 (table-recognize-table)
2601 (message "recognizing table.el table...done")))
2602 (error "This should not happen..."))
2604 nil)
2605 nil))
2607 (defun org-at-table-hline-p ()
2608 "Return t if the cursor is inside a hline in a table."
2609 (if org-enable-table-editor
2610 (save-excursion
2611 (beginning-of-line 1)
2612 (looking-at org-table-hline-regexp))
2613 nil))
2615 (defvar org-table-clean-did-remove-column nil)
2617 (defun org-table-map-tables (function)
2618 "Apply FUNCTION to the start of all tables in the buffer."
2619 (save-excursion
2620 (save-restriction
2621 (widen)
2622 (goto-char (point-min))
2623 (while (re-search-forward org-table-any-line-regexp nil t)
2624 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2625 (beginning-of-line 1)
2626 (if (looking-at org-table-line-regexp)
2627 (save-excursion (funcall function)))
2628 (re-search-forward org-table-any-border-regexp nil 1))))
2629 (message "Mapping tables: done"))
2631 ;; Declare and autoload functions from org-exp.el
2633 (declare-function org-default-export-plist "org-exp")
2634 (declare-function org-infile-export-plist "org-exp")
2635 (declare-function org-get-current-options "org-exp")
2636 (eval-and-compile
2637 (org-autoload "org-exp"
2638 '(org-export org-export-as-ascii org-export-visible
2639 org-insert-export-options-template org-export-as-html-and-open
2640 org-export-as-html-batch org-export-as-html-to-buffer
2641 org-replace-region-by-html org-export-region-as-html
2642 org-export-as-html org-export-icalendar-this-file
2643 org-export-icalendar-all-agenda-files
2644 org-table-clean-before-export
2645 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2647 ;; Declare and autoload functions from org-agenda.el
2649 (eval-and-compile
2650 (org-autoload "org-agenda"
2651 '(org-agenda org-agenda-list org-search-view
2652 org-todo-list org-tags-view org-agenda-list-stuck-projects
2653 org-diary org-agenda-to-appt)))
2655 ;; Autoload org-remember
2657 (eval-and-compile
2658 (org-autoload "org-remember"
2659 '(org-remember-insinuate org-remember-annotation
2660 org-remember-apply-template org-remember org-remember-handler)))
2662 ;; Autoload org-clock.el
2665 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2666 (beg end))
2667 (declare-function org-update-mode-line "org-clock" ())
2668 (defvar org-clock-start-time)
2669 (defvar org-clock-marker (make-marker)
2670 "Marker recording the last clock-in.")
2672 (eval-and-compile
2673 (org-autoload
2674 "org-clock"
2675 '(org-clock-in org-clock-out org-clock-cancel
2676 org-clock-goto org-clock-sum org-clock-display
2677 org-remove-clock-overlays org-clock-report
2678 org-clocktable-shift org-dblock-write:clocktable
2679 org-get-clocktable)))
2681 (defun org-clock-update-time-maybe ()
2682 "If this is a CLOCK line, update it and return t.
2683 Otherwise, return nil."
2684 (interactive)
2685 (save-excursion
2686 (beginning-of-line 1)
2687 (skip-chars-forward " \t")
2688 (when (looking-at org-clock-string)
2689 (let ((re (concat "[ \t]*" org-clock-string
2690 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2691 "\\([ \t]*=>.*\\)?\\)?"))
2692 ts te h m s neg)
2693 (cond
2694 ((not (looking-at re))
2695 nil)
2696 ((not (match-end 2))
2697 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2698 (> org-clock-marker (point))
2699 (<= org-clock-marker (point-at-eol)))
2700 ;; The clock is running here
2701 (setq org-clock-start-time
2702 (apply 'encode-time
2703 (org-parse-time-string (match-string 1))))
2704 (org-update-mode-line)))
2706 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2707 (end-of-line 1)
2708 (setq ts (match-string 1)
2709 te (match-string 3))
2710 (setq s (- (time-to-seconds
2711 (apply 'encode-time (org-parse-time-string te)))
2712 (time-to-seconds
2713 (apply 'encode-time (org-parse-time-string ts))))
2714 neg (< s 0)
2715 s (abs s)
2716 h (floor (/ s 3600))
2717 s (- s (* 3600 h))
2718 m (floor (/ s 60))
2719 s (- s (* 60 s)))
2720 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2721 t))))))
2723 (defun org-check-running-clock ()
2724 "Check if the current buffer contains the running clock.
2725 If yes, offer to stop it and to save the buffer with the changes."
2726 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2727 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2728 (buffer-name))))
2729 (org-clock-out)
2730 (when (y-or-n-p "Save changed buffer?")
2731 (save-buffer))))
2733 (defun org-clocktable-try-shift (dir n)
2734 "Check if this line starts a clock table, if yes, shift the time block."
2735 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2736 (org-clocktable-shift dir n)))
2738 ;; Autoload org-timer.el
2740 ;(declare-function org-timer "org-timer")
2742 (eval-and-compile
2743 (org-autoload
2744 "org-timer"
2745 '(org-timer-start org-timer org-timer-item
2746 org-timer-change-times-in-region)))
2749 ;; Autoload archiving code
2750 ;; The stuff that is needed for cycling and tags has to be defined here.
2752 (defgroup org-archive nil
2753 "Options concerning archiving in Org-mode."
2754 :tag "Org Archive"
2755 :group 'org-structure)
2757 (defcustom org-archive-location "%s_archive::"
2758 "The location where subtrees should be archived.
2760 The value of this variable is a string, consisting of two parts,
2761 separated by a double-colon. The first part is a filename and
2762 the second part is a headline.
2764 When the filename is omitted, archiving happens in the same file.
2765 %s in the filename will be replaced by the current file
2766 name (without the directory part). Archiving to a different file
2767 is useful to keep archived entries from contributing to the
2768 Org-mode Agenda.
2770 The archived entries will be filed as subtrees of the specified
2771 headline. When the headline is omitted, the subtrees are simply
2772 filed away at the end of the file, as top-level entries.
2774 Here are a few examples:
2775 \"%s_archive::\"
2776 If the current file is Projects.org, archive in file
2777 Projects.org_archive, as top-level trees. This is the default.
2779 \"::* Archived Tasks\"
2780 Archive in the current file, under the top-level headline
2781 \"* Archived Tasks\".
2783 \"~/org/archive.org::\"
2784 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2786 \"basement::** Finished Tasks\"
2787 Archive in file ./basement (relative path), as level 3 trees
2788 below the level 2 heading \"** Finished Tasks\".
2790 You may set this option on a per-file basis by adding to the buffer a
2791 line like
2793 #+ARCHIVE: basement::** Finished Tasks
2795 You may also define it locally for a subtree by setting an ARCHIVE property
2796 in the entry. If such a property is found in an entry, or anywhere up
2797 the hierarchy, it will be used."
2798 :group 'org-archive
2799 :type 'string)
2801 (defcustom org-archive-tag "ARCHIVE"
2802 "The tag that marks a subtree as archived.
2803 An archived subtree does not open during visibility cycling, and does
2804 not contribute to the agenda listings.
2805 After changing this, font-lock must be restarted in the relevant buffers to
2806 get the proper fontification."
2807 :group 'org-archive
2808 :group 'org-keywords
2809 :type 'string)
2811 (defcustom org-agenda-skip-archived-trees t
2812 "Non-nil means, the agenda will skip any items located in archived trees.
2813 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2814 variable is no longer recommended, you should leave it at the value t.
2815 Instead, use the key `v' to cycle the archives-mode in the agenda."
2816 :group 'org-archive
2817 :group 'org-agenda-skip
2818 :type 'boolean)
2820 (defcustom org-cycle-open-archived-trees nil
2821 "Non-nil means, `org-cycle' will open archived trees.
2822 An archived tree is a tree marked with the tag ARCHIVE.
2823 When nil, archived trees will stay folded. You can still open them with
2824 normal outline commands like `show-all', but not with the cycling commands."
2825 :group 'org-archive
2826 :group 'org-cycle
2827 :type 'boolean)
2829 (defcustom org-sparse-tree-open-archived-trees nil
2830 "Non-nil means sparse tree construction shows matches in archived trees.
2831 When nil, matches in these trees are highlighted, but the trees are kept in
2832 collapsed state."
2833 :group 'org-archive
2834 :group 'org-sparse-trees
2835 :type 'boolean)
2837 (defun org-cycle-hide-archived-subtrees (state)
2838 "Re-hide all archived subtrees after a visibility state change."
2839 (when (and (not org-cycle-open-archived-trees)
2840 (not (memq state '(overview folded))))
2841 (save-excursion
2842 (let* ((globalp (memq state '(contents all)))
2843 (beg (if globalp (point-min) (point)))
2844 (end (if globalp (point-max) (org-end-of-subtree t))))
2845 (org-hide-archived-subtrees beg end)
2846 (goto-char beg)
2847 (if (looking-at (concat ".*:" org-archive-tag ":"))
2848 (message "%s" (substitute-command-keys
2849 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2851 (defun org-force-cycle-archived ()
2852 "Cycle subtree even if it is archived."
2853 (interactive)
2854 (setq this-command 'org-cycle)
2855 (let ((org-cycle-open-archived-trees t))
2856 (call-interactively 'org-cycle)))
2858 (defun org-hide-archived-subtrees (beg end)
2859 "Re-hide all archived subtrees after a visibility state change."
2860 (save-excursion
2861 (let* ((re (concat ":" org-archive-tag ":")))
2862 (goto-char beg)
2863 (while (re-search-forward re end t)
2864 (and (org-on-heading-p) (hide-subtree))
2865 (org-end-of-subtree t)))))
2867 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2869 (eval-and-compile
2870 (org-autoload "org-archive"
2871 '(org-add-archive-files org-archive-subtree
2872 org-archive-to-archive-sibling org-toggle-archive-tag)))
2874 ;; Autoload Column View Code
2876 (declare-function org-columns-number-to-string "org-colview")
2877 (declare-function org-columns-get-format-and-top-level "org-colview")
2878 (declare-function org-columns-compute "org-colview")
2880 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2881 '(org-columns-number-to-string org-columns-get-format-and-top-level
2882 org-columns-compute org-agenda-columns org-columns-remove-overlays
2883 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2885 ;; Autoload ID code
2887 (declare-function org-id-store-link "org-id")
2888 (org-autoload "org-id"
2889 '(org-id-get-create org-id-new org-id-copy org-id-get
2890 org-id-get-with-outline-path-completion
2891 org-id-get-with-outline-drilling
2892 org-id-goto org-id-find org-id-store-link))
2894 ;;; Variables for pre-computed regular expressions, all buffer local
2896 (defvar org-drawer-regexp nil
2897 "Matches first line of a hidden block.")
2898 (make-variable-buffer-local 'org-drawer-regexp)
2899 (defvar org-todo-regexp nil
2900 "Matches any of the TODO state keywords.")
2901 (make-variable-buffer-local 'org-todo-regexp)
2902 (defvar org-not-done-regexp nil
2903 "Matches any of the TODO state keywords except the last one.")
2904 (make-variable-buffer-local 'org-not-done-regexp)
2905 (defvar org-todo-line-regexp nil
2906 "Matches a headline and puts TODO state into group 2 if present.")
2907 (make-variable-buffer-local 'org-todo-line-regexp)
2908 (defvar org-complex-heading-regexp nil
2909 "Matches a headline and puts everything into groups:
2910 group 1: the stars
2911 group 2: The todo keyword, maybe
2912 group 3: Priority cookie
2913 group 4: True headline
2914 group 5: Tags")
2915 (make-variable-buffer-local 'org-complex-heading-regexp)
2916 (defvar org-todo-line-tags-regexp nil
2917 "Matches a headline and puts TODO state into group 2 if present.
2918 Also put tags into group 4 if tags are present.")
2919 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2920 (defvar org-nl-done-regexp nil
2921 "Matches newline followed by a headline with the DONE keyword.")
2922 (make-variable-buffer-local 'org-nl-done-regexp)
2923 (defvar org-looking-at-done-regexp nil
2924 "Matches the DONE keyword a point.")
2925 (make-variable-buffer-local 'org-looking-at-done-regexp)
2926 (defvar org-ds-keyword-length 12
2927 "Maximum length of the Deadline and SCHEDULED keywords.")
2928 (make-variable-buffer-local 'org-ds-keyword-length)
2929 (defvar org-deadline-regexp nil
2930 "Matches the DEADLINE keyword.")
2931 (make-variable-buffer-local 'org-deadline-regexp)
2932 (defvar org-deadline-time-regexp nil
2933 "Matches the DEADLINE keyword together with a time stamp.")
2934 (make-variable-buffer-local 'org-deadline-time-regexp)
2935 (defvar org-deadline-line-regexp nil
2936 "Matches the DEADLINE keyword and the rest of the line.")
2937 (make-variable-buffer-local 'org-deadline-line-regexp)
2938 (defvar org-scheduled-regexp nil
2939 "Matches the SCHEDULED keyword.")
2940 (make-variable-buffer-local 'org-scheduled-regexp)
2941 (defvar org-scheduled-time-regexp nil
2942 "Matches the SCHEDULED keyword together with a time stamp.")
2943 (make-variable-buffer-local 'org-scheduled-time-regexp)
2944 (defvar org-closed-time-regexp nil
2945 "Matches the CLOSED keyword together with a time stamp.")
2946 (make-variable-buffer-local 'org-closed-time-regexp)
2948 (defvar org-keyword-time-regexp nil
2949 "Matches any of the 4 keywords, together with the time stamp.")
2950 (make-variable-buffer-local 'org-keyword-time-regexp)
2951 (defvar org-keyword-time-not-clock-regexp nil
2952 "Matches any of the 3 keywords, together with the time stamp.")
2953 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2954 (defvar org-maybe-keyword-time-regexp nil
2955 "Matches a timestamp, possibly preceeded by a keyword.")
2956 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2957 (defvar org-planning-or-clock-line-re nil
2958 "Matches a line with planning or clock info.")
2959 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2961 (defconst org-plain-time-of-day-regexp
2962 (concat
2963 "\\(\\<[012]?[0-9]"
2964 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2965 "\\(--?"
2966 "\\(\\<[012]?[0-9]"
2967 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2968 "\\)?")
2969 "Regular expression to match a plain time or time range.
2970 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2971 groups carry important information:
2972 0 the full match
2973 1 the first time, range or not
2974 8 the second time, if it is a range.")
2976 (defconst org-plain-time-extension-regexp
2977 (concat
2978 "\\(\\<[012]?[0-9]"
2979 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2980 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2981 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2982 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2983 groups carry important information:
2984 0 the full match
2985 7 hours of duration
2986 9 minutes of duration")
2988 (defconst org-stamp-time-of-day-regexp
2989 (concat
2990 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2991 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2992 "\\(--?"
2993 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2994 "Regular expression to match a timestamp time or time range.
2995 After a match, the following groups carry important information:
2996 0 the full match
2997 1 date plus weekday, for backreferencing to make sure both times on same day
2998 2 the first time, range or not
2999 4 the second time, if it is a range.")
3001 (defconst org-startup-options
3002 '(("fold" org-startup-folded t)
3003 ("overview" org-startup-folded t)
3004 ("nofold" org-startup-folded nil)
3005 ("showall" org-startup-folded nil)
3006 ("content" org-startup-folded content)
3007 ("hidestars" org-hide-leading-stars t)
3008 ("showstars" org-hide-leading-stars nil)
3009 ("odd" org-odd-levels-only t)
3010 ("oddeven" org-odd-levels-only nil)
3011 ("align" org-startup-align-all-tables t)
3012 ("noalign" org-startup-align-all-tables nil)
3013 ("customtime" org-display-custom-times t)
3014 ("logdone" org-log-done time)
3015 ("lognotedone" org-log-done note)
3016 ("nologdone" org-log-done nil)
3017 ("lognoteclock-out" org-log-note-clock-out t)
3018 ("nolognoteclock-out" org-log-note-clock-out nil)
3019 ("logrepeat" org-log-repeat state)
3020 ("lognoterepeat" org-log-repeat note)
3021 ("nologrepeat" org-log-repeat nil)
3022 ("fninline" org-footnote-define-inline t)
3023 ("nofninline" org-footnote-define-inline nil)
3024 ("fnlocal" org-footnote-section nil)
3025 ("fnauto" org-footnote-auto-label t)
3026 ("fnprompt" org-footnote-auto-label nil)
3027 ("fnconfirm" org-footnote-auto-label confirm)
3028 ("fnplain" org-footnote-auto-label plain)
3029 ("constcgs" constants-unit-system cgs)
3030 ("constSI" constants-unit-system SI))
3031 "Variable associated with STARTUP options for org-mode.
3032 Each element is a list of three items: The startup options as written
3033 in the #+STARTUP line, the corresponding variable, and the value to
3034 set this variable to if the option is found. An optional forth element PUSH
3035 means to push this value onto the list in the variable.")
3037 (defun org-set-regexps-and-options ()
3038 "Precompute regular expressions for current buffer."
3039 (when (org-mode-p)
3040 (org-set-local 'org-todo-kwd-alist nil)
3041 (org-set-local 'org-todo-key-alist nil)
3042 (org-set-local 'org-todo-key-trigger nil)
3043 (org-set-local 'org-todo-keywords-1 nil)
3044 (org-set-local 'org-done-keywords nil)
3045 (org-set-local 'org-todo-heads nil)
3046 (org-set-local 'org-todo-sets nil)
3047 (org-set-local 'org-todo-log-states nil)
3048 (org-set-local 'org-file-properties nil)
3049 (org-set-local 'org-file-tags nil)
3050 (let ((re (org-make-options-regexp
3051 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3052 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3053 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3054 (splitre "[ \t]+")
3055 kwds kws0 kwsa key log value cat arch tags const links hw dws
3056 tail sep kws1 prio props ftags drawers
3057 ext-setup-or-nil setup-contents (start 0))
3058 (save-excursion
3059 (save-restriction
3060 (widen)
3061 (goto-char (point-min))
3062 (while (or (and ext-setup-or-nil
3063 (string-match re ext-setup-or-nil start)
3064 (setq start (match-end 0)))
3065 (and (setq ext-setup-or-nil nil start 0)
3066 (re-search-forward re nil t)))
3067 (setq key (upcase (match-string 1 ext-setup-or-nil))
3068 value (org-match-string-no-properties 2 ext-setup-or-nil))
3069 (cond
3070 ((equal key "CATEGORY")
3071 (if (string-match "[ \t]+$" value)
3072 (setq value (replace-match "" t t value)))
3073 (setq cat value))
3074 ((member key '("SEQ_TODO" "TODO"))
3075 (push (cons 'sequence (org-split-string value splitre)) kwds))
3076 ((equal key "TYP_TODO")
3077 (push (cons 'type (org-split-string value splitre)) kwds))
3078 ((equal key "TAGS")
3079 (setq tags (append tags (org-split-string value splitre))))
3080 ((equal key "COLUMNS")
3081 (org-set-local 'org-columns-default-format value))
3082 ((equal key "LINK")
3083 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3084 (push (cons (match-string 1 value)
3085 (org-trim (match-string 2 value)))
3086 links)))
3087 ((equal key "PRIORITIES")
3088 (setq prio (org-split-string value " +")))
3089 ((equal key "PROPERTY")
3090 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3091 (push (cons (match-string 1 value) (match-string 2 value))
3092 props)))
3093 ((equal key "FILETAGS")
3094 (when (string-match "\\S-" value)
3095 (setq ftags
3096 (append
3097 ftags
3098 (apply 'append
3099 (mapcar (lambda (x) (org-split-string x ":"))
3100 (org-split-string value)))))))
3101 ((equal key "DRAWERS")
3102 (setq drawers (org-split-string value splitre)))
3103 ((equal key "CONSTANTS")
3104 (setq const (append const (org-split-string value splitre))))
3105 ((equal key "STARTUP")
3106 (let ((opts (org-split-string value splitre))
3107 l var val)
3108 (while (setq l (pop opts))
3109 (when (setq l (assoc l org-startup-options))
3110 (setq var (nth 1 l) val (nth 2 l))
3111 (if (not (nth 3 l))
3112 (set (make-local-variable var) val)
3113 (if (not (listp (symbol-value var)))
3114 (set (make-local-variable var) nil))
3115 (set (make-local-variable var) (symbol-value var))
3116 (add-to-list var val))))))
3117 ((equal key "ARCHIVE")
3118 (string-match " *$" value)
3119 (setq arch (replace-match "" t t value))
3120 (remove-text-properties 0 (length arch)
3121 '(face t fontified t) arch))
3122 ((equal key "SETUPFILE")
3123 (setq setup-contents (org-file-contents
3124 (expand-file-name
3125 (org-remove-double-quotes value))
3126 'noerror))
3127 (if (not ext-setup-or-nil)
3128 (setq ext-setup-or-nil setup-contents start 0)
3129 (setq ext-setup-or-nil
3130 (concat (substring ext-setup-or-nil 0 start)
3131 "\n" setup-contents "\n"
3132 (substring ext-setup-or-nil start)))))
3133 ))))
3134 (when cat
3135 (org-set-local 'org-category (intern cat))
3136 (push (cons "CATEGORY" cat) props))
3137 (when prio
3138 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3139 (setq prio (mapcar 'string-to-char prio))
3140 (org-set-local 'org-highest-priority (nth 0 prio))
3141 (org-set-local 'org-lowest-priority (nth 1 prio))
3142 (org-set-local 'org-default-priority (nth 2 prio)))
3143 (and props (org-set-local 'org-file-properties (nreverse props)))
3144 (and ftags (org-set-local 'org-file-tags ftags))
3145 (and drawers (org-set-local 'org-drawers drawers))
3146 (and arch (org-set-local 'org-archive-location arch))
3147 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3148 ;; Process the TODO keywords
3149 (unless kwds
3150 ;; Use the global values as if they had been given locally.
3151 (setq kwds (default-value 'org-todo-keywords))
3152 (if (stringp (car kwds))
3153 (setq kwds (list (cons org-todo-interpretation
3154 (default-value 'org-todo-keywords)))))
3155 (setq kwds (reverse kwds)))
3156 (setq kwds (nreverse kwds))
3157 (let (inter kws kw)
3158 (while (setq kws (pop kwds))
3159 (setq inter (pop kws) sep (member "|" kws)
3160 kws0 (delete "|" (copy-sequence kws))
3161 kwsa nil
3162 kws1 (mapcar
3163 (lambda (x)
3164 ;; 1 2
3165 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3166 (progn
3167 (setq kw (match-string 1 x)
3168 key (and (match-end 2) (match-string 2 x))
3169 log (org-extract-log-state-settings x))
3170 (push (cons kw (and key (string-to-char key))) kwsa)
3171 (and log (push log org-todo-log-states))
3173 (error "Invalid TODO keyword %s" x)))
3174 kws0)
3175 kwsa (if kwsa (append '((:startgroup))
3176 (nreverse kwsa)
3177 '((:endgroup))))
3178 hw (car kws1)
3179 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3180 tail (list inter hw (car dws) (org-last dws)))
3181 (add-to-list 'org-todo-heads hw 'append)
3182 (push kws1 org-todo-sets)
3183 (setq org-done-keywords (append org-done-keywords dws nil))
3184 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3185 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3186 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3187 (setq org-todo-sets (nreverse org-todo-sets)
3188 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3189 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3190 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3191 ;; Process the constants
3192 (when const
3193 (let (e cst)
3194 (while (setq e (pop const))
3195 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3196 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3197 (setq org-table-formula-constants-local cst)))
3199 ;; Process the tags.
3200 (when tags
3201 (let (e tgs)
3202 (while (setq e (pop tags))
3203 (cond
3204 ((equal e "{") (push '(:startgroup) tgs))
3205 ((equal e "}") (push '(:endgroup) tgs))
3206 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3207 (push (cons (match-string 1 e)
3208 (string-to-char (match-string 2 e)))
3209 tgs))
3210 (t (push (list e) tgs))))
3211 (org-set-local 'org-tag-alist nil)
3212 (while (setq e (pop tgs))
3213 (or (and (stringp (car e))
3214 (assoc (car e) org-tag-alist))
3215 (push e org-tag-alist)))))
3217 ;; Compute the regular expressions and other local variables
3218 (if (not org-done-keywords)
3219 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3220 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3221 (length org-scheduled-string)
3222 (length org-clock-string)
3223 (length org-closed-string)))
3224 org-drawer-regexp
3225 (concat "^[ \t]*:\\("
3226 (mapconcat 'regexp-quote org-drawers "\\|")
3227 "\\):[ \t]*$")
3228 org-not-done-keywords
3229 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3230 org-todo-regexp
3231 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3232 "\\|") "\\)\\>")
3233 org-not-done-regexp
3234 (concat "\\<\\("
3235 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3236 "\\)\\>")
3237 org-todo-line-regexp
3238 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3239 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3240 "\\)\\>\\)?[ \t]*\\(.*\\)")
3241 org-complex-heading-regexp
3242 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3243 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3244 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3245 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3246 org-nl-done-regexp
3247 (concat "\n\\*+[ \t]+"
3248 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3249 "\\)" "\\>")
3250 org-todo-line-tags-regexp
3251 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3252 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3253 (org-re
3254 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3255 org-looking-at-done-regexp
3256 (concat "^" "\\(?:"
3257 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3258 "\\>")
3259 org-deadline-regexp (concat "\\<" org-deadline-string)
3260 org-deadline-time-regexp
3261 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3262 org-deadline-line-regexp
3263 (concat "\\<\\(" org-deadline-string "\\).*")
3264 org-scheduled-regexp
3265 (concat "\\<" org-scheduled-string)
3266 org-scheduled-time-regexp
3267 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3268 org-closed-time-regexp
3269 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3270 org-keyword-time-regexp
3271 (concat "\\<\\(" org-scheduled-string
3272 "\\|" org-deadline-string
3273 "\\|" org-closed-string
3274 "\\|" org-clock-string "\\)"
3275 " *[[<]\\([^]>]+\\)[]>]")
3276 org-keyword-time-not-clock-regexp
3277 (concat "\\<\\(" org-scheduled-string
3278 "\\|" org-deadline-string
3279 "\\|" org-closed-string
3280 "\\)"
3281 " *[[<]\\([^]>]+\\)[]>]")
3282 org-maybe-keyword-time-regexp
3283 (concat "\\(\\<\\(" org-scheduled-string
3284 "\\|" org-deadline-string
3285 "\\|" org-closed-string
3286 "\\|" org-clock-string "\\)\\)?"
3287 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3288 org-planning-or-clock-line-re
3289 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3290 "\\|" org-deadline-string
3291 "\\|" org-closed-string "\\|" org-clock-string
3292 "\\)\\>\\)")
3294 (org-compute-latex-and-specials-regexp)
3295 (org-set-font-lock-defaults))))
3297 (defun org-file-contents (file &optional noerror)
3298 "Return the contents of FILE, as a string."
3299 (if (or (not file)
3300 (not (file-readable-p file)))
3301 (if noerror
3302 (progn
3303 (message "Cannot read file %s" file)
3304 (ding) (sit-for 2)
3306 (error "Cannot read file %s" file))
3307 (with-temp-buffer
3308 (insert-file-contents file)
3309 (buffer-string))))
3311 (defun org-extract-log-state-settings (x)
3312 "Extract the log state setting from a TODO keyword string.
3313 This will extract info from a string like \"WAIT(w@/!)\"."
3314 (let (kw key log1 log2)
3315 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3316 (setq kw (match-string 1 x)
3317 key (and (match-end 2) (match-string 2 x))
3318 log1 (and (match-end 3) (match-string 3 x))
3319 log2 (and (match-end 4) (match-string 4 x)))
3320 (and (or log1 log2)
3321 (list kw
3322 (and log1 (if (equal log1 "!") 'time 'note))
3323 (and log2 (if (equal log2 "!") 'time 'note)))))))
3325 (defun org-remove-keyword-keys (list)
3326 "Remove a pair of parenthesis at the end of each string in LIST."
3327 (mapcar (lambda (x)
3328 (if (string-match "(.*)$" x)
3329 (substring x 0 (match-beginning 0))
3331 list))
3333 ;; FIXME: this could be done much better, using second characters etc.
3334 (defun org-assign-fast-keys (alist)
3335 "Assign fast keys to a keyword-key alist.
3336 Respect keys that are already there."
3337 (let (new e k c c1 c2 (char ?a))
3338 (while (setq e (pop alist))
3339 (cond
3340 ((equal e '(:startgroup)) (push e new))
3341 ((equal e '(:endgroup)) (push e new))
3343 (setq k (car e) c2 nil)
3344 (if (cdr e)
3345 (setq c (cdr e))
3346 ;; automatically assign a character.
3347 (setq c1 (string-to-char
3348 (downcase (substring
3349 k (if (= (string-to-char k) ?@) 1 0)))))
3350 (if (or (rassoc c1 new) (rassoc c1 alist))
3351 (while (or (rassoc char new) (rassoc char alist))
3352 (setq char (1+ char)))
3353 (setq c2 c1))
3354 (setq c (or c2 char)))
3355 (push (cons k c) new))))
3356 (nreverse new)))
3358 ;;; Some variables used in various places
3360 (defvar org-window-configuration nil
3361 "Used in various places to store a window configuration.")
3362 (defvar org-finish-function nil
3363 "Function to be called when `C-c C-c' is used.
3364 This is for getting out of special buffers like remember.")
3367 ;; FIXME: Occasionally check by commenting these, to make sure
3368 ;; no other functions uses these, forgetting to let-bind them.
3369 (defvar entry)
3370 (defvar state)
3371 (defvar last-state)
3372 (defvar date)
3373 (defvar description)
3375 ;; Defined somewhere in this file, but used before definition.
3376 (defvar org-html-entities)
3377 (defvar org-struct-menu)
3378 (defvar org-org-menu)
3379 (defvar org-tbl-menu)
3380 (defvar org-agenda-keymap)
3382 ;;;; Define the Org-mode
3384 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3385 (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."))
3388 ;; We use a before-change function to check if a table might need
3389 ;; an update.
3390 (defvar org-table-may-need-update t
3391 "Indicates that a table might need an update.
3392 This variable is set by `org-before-change-function'.
3393 `org-table-align' sets it back to nil.")
3394 (defun org-before-change-function (beg end)
3395 "Every change indicates that a table might need an update."
3396 (setq org-table-may-need-update t))
3397 (defvar org-mode-map)
3398 (defvar org-mode-hook nil
3399 "Mode hook for Org-mode, run after the mode was turned on.")
3400 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3401 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3402 (defvar org-table-buffer-is-an nil)
3403 (defconst org-outline-regexp "\\*+ ")
3405 ;;;###autoload
3406 (define-derived-mode org-mode outline-mode "Org"
3407 "Outline-based notes management and organizer, alias
3408 \"Carsten's outline-mode for keeping track of everything.\"
3410 Org-mode develops organizational tasks around a NOTES file which
3411 contains information about projects as plain text. Org-mode is
3412 implemented on top of outline-mode, which is ideal to keep the content
3413 of large files well structured. It supports ToDo items, deadlines and
3414 time stamps, which magically appear in the diary listing of the Emacs
3415 calendar. Tables are easily created with a built-in table editor.
3416 Plain text URL-like links connect to websites, emails (VM), Usenet
3417 messages (Gnus), BBDB entries, and any files related to the project.
3418 For printing and sharing of notes, an Org-mode file (or a part of it)
3419 can be exported as a structured ASCII or HTML file.
3421 The following commands are available:
3423 \\{org-mode-map}"
3425 ;; Get rid of Outline menus, they are not needed
3426 ;; Need to do this here because define-derived-mode sets up
3427 ;; the keymap so late. Still, it is a waste to call this each time
3428 ;; we switch another buffer into org-mode.
3429 (if (featurep 'xemacs)
3430 (when (boundp 'outline-mode-menu-heading)
3431 ;; Assume this is Greg's port, it used easymenu
3432 (easy-menu-remove outline-mode-menu-heading)
3433 (easy-menu-remove outline-mode-menu-show)
3434 (easy-menu-remove outline-mode-menu-hide))
3435 (define-key org-mode-map [menu-bar headings] 'undefined)
3436 (define-key org-mode-map [menu-bar hide] 'undefined)
3437 (define-key org-mode-map [menu-bar show] 'undefined))
3439 (org-load-modules-maybe)
3440 (easy-menu-add org-org-menu)
3441 (easy-menu-add org-tbl-menu)
3442 (org-install-agenda-files-menu)
3443 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3444 (org-add-to-invisibility-spec '(org-cwidth))
3445 (when (featurep 'xemacs)
3446 (org-set-local 'line-move-ignore-invisible t))
3447 (org-set-local 'outline-regexp org-outline-regexp)
3448 (org-set-local 'outline-level 'org-outline-level)
3449 (when (and org-ellipsis
3450 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3451 (fboundp 'make-glyph-code))
3452 (unless org-display-table
3453 (setq org-display-table (make-display-table)))
3454 (set-display-table-slot
3455 org-display-table 4
3456 (vconcat (mapcar
3457 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3458 org-ellipsis)))
3459 (if (stringp org-ellipsis) org-ellipsis "..."))))
3460 (setq buffer-display-table org-display-table))
3461 (org-set-regexps-and-options)
3462 (when (and org-tag-faces (not org-tags-special-faces-re))
3463 ;; tag faces set outside customize.... force initialization.
3464 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3465 ;; Calc embedded
3466 (org-set-local 'calc-embedded-open-mode "# ")
3467 (modify-syntax-entry ?# "<")
3468 (modify-syntax-entry ?@ "w")
3469 (if org-startup-truncated (setq truncate-lines t))
3470 (org-set-local 'font-lock-unfontify-region-function
3471 'org-unfontify-region)
3472 ;; Activate before-change-function
3473 (org-set-local 'org-table-may-need-update t)
3474 (org-add-hook 'before-change-functions 'org-before-change-function nil
3475 'local)
3476 ;; Check for running clock before killing a buffer
3477 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3478 ;; Paragraphs and auto-filling
3479 (org-set-autofill-regexps)
3480 (setq indent-line-function 'org-indent-line-function)
3481 (org-update-radio-target-regexp)
3483 ;; Comment characters
3484 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3485 (org-set-local 'comment-padding " ")
3487 ;; Align options lines
3488 (org-set-local
3489 'align-mode-rules-list
3490 '((org-in-buffer-settings
3491 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3492 (modes . '(org-mode)))))
3494 ;; Imenu
3495 (org-set-local 'imenu-create-index-function
3496 'org-imenu-get-tree)
3498 ;; Make isearch reveal context
3499 (if (or (featurep 'xemacs)
3500 (not (boundp 'outline-isearch-open-invisible-function)))
3501 ;; Emacs 21 and XEmacs make use of the hook
3502 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3503 ;; Emacs 22 deals with this through a special variable
3504 (org-set-local 'outline-isearch-open-invisible-function
3505 (lambda (&rest ignore) (org-show-context 'isearch))))
3507 ;; If empty file that did not turn on org-mode automatically, make it to.
3508 (if (and org-insert-mode-line-in-empty-file
3509 (interactive-p)
3510 (= (point-min) (point-max)))
3511 (insert "# -*- mode: org -*-\n\n"))
3513 (unless org-inhibit-startup
3514 (when org-startup-align-all-tables
3515 (let ((bmp (buffer-modified-p)))
3516 (org-table-map-tables 'org-table-align)
3517 (set-buffer-modified-p bmp)))
3518 (org-set-startup-visibility)))
3520 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3522 (defun org-current-time ()
3523 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3524 (if (> (car org-time-stamp-rounding-minutes) 1)
3525 (let ((r (car org-time-stamp-rounding-minutes))
3526 (time (decode-time)))
3527 (apply 'encode-time
3528 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3529 (nthcdr 2 time))))
3530 (current-time)))
3532 ;;;; Font-Lock stuff, including the activators
3534 (defvar org-mouse-map (make-sparse-keymap))
3535 (org-defkey org-mouse-map
3536 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3537 (org-defkey org-mouse-map
3538 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3539 (when org-mouse-1-follows-link
3540 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3541 (when org-tab-follows-link
3542 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3543 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3544 (when org-return-follows-link
3545 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3546 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3548 (require 'font-lock)
3550 (defconst org-non-link-chars "]\t\n\r<>")
3551 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3552 "shell" "elisp"))
3553 (defvar org-link-types-re nil
3554 "Matches a link that has a url-like prefix like \"http:\"")
3555 (defvar org-link-re-with-space nil
3556 "Matches a link with spaces, optional angular brackets around it.")
3557 (defvar org-link-re-with-space2 nil
3558 "Matches a link with spaces, optional angular brackets around it.")
3559 (defvar org-link-re-with-space3 nil
3560 "Matches a link with spaces, only for internal part in bracket links.")
3561 (defvar org-angle-link-re nil
3562 "Matches link with angular brackets, spaces are allowed.")
3563 (defvar org-plain-link-re nil
3564 "Matches plain link, without spaces.")
3565 (defvar org-bracket-link-regexp nil
3566 "Matches a link in double brackets.")
3567 (defvar org-bracket-link-analytic-regexp nil
3568 "Regular expression used to analyze links.
3569 Here is what the match groups contain after a match:
3570 1: http:
3571 2: http
3572 3: path
3573 4: [desc]
3574 5: desc")
3575 (defvar org-bracket-link-analytic-regexp++ nil
3576 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3577 (defvar org-any-link-re nil
3578 "Regular expression matching any link.")
3580 (defun org-make-link-regexps ()
3581 "Update the link regular expressions.
3582 This should be called after the variable `org-link-types' has changed."
3583 (setq org-link-types-re
3584 (concat
3585 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3586 org-link-re-with-space
3587 (concat
3588 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3589 "\\([^" org-non-link-chars " ]"
3590 "[^" org-non-link-chars "]*"
3591 "[^" org-non-link-chars " ]\\)>?")
3592 org-link-re-with-space2
3593 (concat
3594 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3595 "\\([^" org-non-link-chars " ]"
3596 "[^\t\n\r]*"
3597 "[^" org-non-link-chars " ]\\)>?")
3598 org-link-re-with-space3
3599 (concat
3600 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3601 "\\([^" org-non-link-chars " ]"
3602 "[^\t\n\r]*\\)")
3603 org-angle-link-re
3604 (concat
3605 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3606 "\\([^" org-non-link-chars " ]"
3607 "[^" org-non-link-chars "]*"
3608 "\\)>")
3609 org-plain-link-re
3610 (concat
3611 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3612 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3613 org-bracket-link-regexp
3614 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3615 org-bracket-link-analytic-regexp
3616 (concat
3617 "\\[\\["
3618 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3619 "\\([^]]+\\)"
3620 "\\]"
3621 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3622 "\\]")
3623 org-bracket-link-analytic-regexp++
3624 (concat
3625 "\\[\\["
3626 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3627 "\\([^]]+\\)"
3628 "\\]"
3629 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3630 "\\]")
3631 org-any-link-re
3632 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3633 org-angle-link-re "\\)\\|\\("
3634 org-plain-link-re "\\)")))
3636 (org-make-link-regexps)
3638 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3639 "Regular expression for fast time stamp matching.")
3640 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3641 "Regular expression for fast time stamp matching.")
3642 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3643 "Regular expression matching time strings for analysis.
3644 This one does not require the space after the date, so it can be used
3645 on a string that terminates immediately after the date.")
3646 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3647 "Regular expression matching time strings for analysis.")
3648 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3649 "Regular expression matching time stamps, with groups.")
3650 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3651 "Regular expression matching time stamps (also [..]), with groups.")
3652 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3653 "Regular expression matching a time stamp range.")
3654 (defconst org-tr-regexp-both
3655 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3656 "Regular expression matching a time stamp range.")
3657 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3658 org-ts-regexp "\\)?")
3659 "Regular expression matching a time stamp or time stamp range.")
3660 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3661 org-ts-regexp-both "\\)?")
3662 "Regular expression matching a time stamp or time stamp range.
3663 The time stamps may be either active or inactive.")
3665 (defvar org-emph-face nil)
3667 (defun org-do-emphasis-faces (limit)
3668 "Run through the buffer and add overlays to links."
3669 (let (rtn)
3670 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3671 (if (not (= (char-after (match-beginning 3))
3672 (char-after (match-beginning 4))))
3673 (progn
3674 (setq rtn t)
3675 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3676 'face
3677 (nth 1 (assoc (match-string 3)
3678 org-emphasis-alist)))
3679 (add-text-properties (match-beginning 2) (match-end 2)
3680 '(font-lock-multiline t))
3681 (when org-hide-emphasis-markers
3682 (add-text-properties (match-end 4) (match-beginning 5)
3683 '(invisible org-link))
3684 (add-text-properties (match-beginning 3) (match-end 3)
3685 '(invisible org-link)))))
3686 (backward-char 1))
3687 rtn))
3689 (defun org-emphasize (&optional char)
3690 "Insert or change an emphasis, i.e. a font like bold or italic.
3691 If there is an active region, change that region to a new emphasis.
3692 If there is no region, just insert the marker characters and position
3693 the cursor between them.
3694 CHAR should be either the marker character, or the first character of the
3695 HTML tag associated with that emphasis. If CHAR is a space, the means
3696 to remove the emphasis of the selected region.
3697 If char is not given (for example in an interactive call) it
3698 will be prompted for."
3699 (interactive)
3700 (let ((eal org-emphasis-alist) e det
3701 (erc org-emphasis-regexp-components)
3702 (prompt "")
3703 (string "") beg end move tag c s)
3704 (if (org-region-active-p)
3705 (setq beg (region-beginning) end (region-end)
3706 string (buffer-substring beg end))
3707 (setq move t))
3709 (while (setq e (pop eal))
3710 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3711 c (aref tag 0))
3712 (push (cons c (string-to-char (car e))) det)
3713 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3714 (substring tag 1)))))
3715 (setq det (nreverse det))
3716 (unless char
3717 (message "%s" (concat "Emphasis marker or tag:" prompt))
3718 (setq char (read-char-exclusive)))
3719 (setq char (or (cdr (assoc char det)) char))
3720 (if (equal char ?\ )
3721 (setq s "" move nil)
3722 (unless (assoc (char-to-string char) org-emphasis-alist)
3723 (error "No such emphasis marker: \"%c\"" char))
3724 (setq s (char-to-string char)))
3725 (while (and (> (length string) 1)
3726 (equal (substring string 0 1) (substring string -1))
3727 (assoc (substring string 0 1) org-emphasis-alist))
3728 (setq string (substring string 1 -1)))
3729 (setq string (concat s string s))
3730 (if beg (delete-region beg end))
3731 (unless (or (bolp)
3732 (string-match (concat "[" (nth 0 erc) "\n]")
3733 (char-to-string (char-before (point)))))
3734 (insert " "))
3735 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3736 (char-to-string (char-after (point))))
3737 (insert " ") (backward-char 1))
3738 (insert string)
3739 (and move (backward-char 1))))
3741 (defconst org-nonsticky-props
3742 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3745 (defun org-activate-plain-links (limit)
3746 "Run through the buffer and add overlays to links."
3747 (catch 'exit
3748 (let (f)
3749 (while (re-search-forward org-plain-link-re limit t)
3750 (setq f (get-text-property (match-beginning 0) 'face))
3751 (if (or (eq f 'org-tag)
3752 (and (listp f) (memq 'org-tag f)))
3754 (add-text-properties (match-beginning 0) (match-end 0)
3755 (list 'mouse-face 'highlight
3756 'rear-nonsticky org-nonsticky-props
3757 'keymap org-mouse-map
3759 (throw 'exit t))))))
3761 (defun org-activate-code (limit)
3762 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3763 (progn
3764 (remove-text-properties (match-beginning 0) (match-end 0)
3765 '(display t invisible t intangible t))
3766 t)))
3768 (defun org-activate-angle-links (limit)
3769 "Run through the buffer and add overlays to links."
3770 (if (re-search-forward org-angle-link-re limit t)
3771 (progn
3772 (add-text-properties (match-beginning 0) (match-end 0)
3773 (list 'mouse-face 'highlight
3774 'rear-nonsticky org-nonsticky-props
3775 'keymap org-mouse-map
3777 t)))
3779 (defun org-activate-footnote-links (limit)
3780 "Run through the buffer and add overlays to links."
3781 (if (re-search-forward "\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)"
3782 limit t)
3783 (progn
3784 (add-text-properties (match-beginning 0) (match-end 0)
3785 (list 'mouse-face 'highlight
3786 'rear-nonsticky org-nonsticky-props
3787 'keymap org-mouse-map
3788 'help-echo
3789 (if (= (point-at-bol) (match-beginning 0))
3790 "Footnote definition"
3791 "Footnote reference")
3793 t)))
3795 (defun org-activate-bracket-links (limit)
3796 "Run through the buffer and add overlays to bracketed links."
3797 (if (re-search-forward org-bracket-link-regexp limit t)
3798 (let* ((help (concat "LINK: "
3799 (org-match-string-no-properties 1)))
3800 ;; FIXME: above we should remove the escapes.
3801 ;; but that requires another match, protecting match data,
3802 ;; a lot of overhead for font-lock.
3803 (ip (org-maybe-intangible
3804 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3805 'keymap org-mouse-map 'mouse-face 'highlight
3806 'font-lock-multiline t 'help-echo help)))
3807 (vp (list 'rear-nonsticky org-nonsticky-props
3808 'keymap org-mouse-map 'mouse-face 'highlight
3809 ' font-lock-multiline t 'help-echo help)))
3810 ;; We need to remove the invisible property here. Table narrowing
3811 ;; may have made some of this invisible.
3812 (remove-text-properties (match-beginning 0) (match-end 0)
3813 '(invisible nil))
3814 (if (match-end 3)
3815 (progn
3816 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3817 (add-text-properties (match-beginning 3) (match-end 3) vp)
3818 (add-text-properties (match-end 3) (match-end 0) ip))
3819 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3820 (add-text-properties (match-beginning 1) (match-end 1) vp)
3821 (add-text-properties (match-end 1) (match-end 0) ip))
3822 t)))
3824 (defun org-activate-dates (limit)
3825 "Run through the buffer and add overlays to dates."
3826 (if (re-search-forward org-tsr-regexp-both limit t)
3827 (progn
3828 (add-text-properties (match-beginning 0) (match-end 0)
3829 (list 'mouse-face 'highlight
3830 'rear-nonsticky org-nonsticky-props
3831 'keymap org-mouse-map))
3832 (when org-display-custom-times
3833 (if (match-end 3)
3834 (org-display-custom-time (match-beginning 3) (match-end 3)))
3835 (org-display-custom-time (match-beginning 1) (match-end 1)))
3836 t)))
3838 (defvar org-target-link-regexp nil
3839 "Regular expression matching radio targets in plain text.")
3840 (make-variable-buffer-local 'org-target-link-regexp)
3841 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3842 "Regular expression matching a link target.")
3843 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3844 "Regular expression matching a radio target.")
3845 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3846 "Regular expression matching any target.")
3848 (defun org-activate-target-links (limit)
3849 "Run through the buffer and add overlays to target matches."
3850 (when org-target-link-regexp
3851 (let ((case-fold-search t))
3852 (if (re-search-forward org-target-link-regexp limit t)
3853 (progn
3854 (add-text-properties (match-beginning 0) (match-end 0)
3855 (list 'mouse-face 'highlight
3856 'rear-nonsticky org-nonsticky-props
3857 'keymap org-mouse-map
3858 'help-echo "Radio target link"
3859 'org-linked-text t))
3860 t)))))
3862 (defun org-update-radio-target-regexp ()
3863 "Find all radio targets in this file and update the regular expression."
3864 (interactive)
3865 (when (memq 'radio org-activate-links)
3866 (setq org-target-link-regexp
3867 (org-make-target-link-regexp (org-all-targets 'radio)))
3868 (org-restart-font-lock)))
3870 (defun org-hide-wide-columns (limit)
3871 (let (s e)
3872 (setq s (text-property-any (point) (or limit (point-max))
3873 'org-cwidth t))
3874 (when s
3875 (setq e (next-single-property-change s 'org-cwidth))
3876 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3877 (goto-char e)
3878 t)))
3880 (defvar org-latex-and-specials-regexp nil
3881 "Regular expression for highlighting export special stuff.")
3882 (defvar org-match-substring-regexp)
3883 (defvar org-match-substring-with-braces-regexp)
3884 (defvar org-export-html-special-string-regexps)
3886 (defun org-compute-latex-and-specials-regexp ()
3887 "Compute regular expression for stuff treated specially by exporters."
3888 (if (not org-highlight-latex-fragments-and-specials)
3889 (org-set-local 'org-latex-and-specials-regexp nil)
3890 (require 'org-exp)
3891 (let*
3892 ((matchers (plist-get org-format-latex-options :matchers))
3893 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3894 org-latex-regexps)))
3895 (options (org-combine-plists (org-default-export-plist)
3896 (org-infile-export-plist)))
3897 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3898 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3899 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3900 (org-export-html-expand (plist-get options :expand-quoted-html))
3901 (org-export-with-special-strings (plist-get options :special-strings))
3902 (re-sub
3903 (cond
3904 ((equal org-export-with-sub-superscripts '{})
3905 (list org-match-substring-with-braces-regexp))
3906 (org-export-with-sub-superscripts
3907 (list org-match-substring-regexp))
3908 (t nil)))
3909 (re-latex
3910 (if org-export-with-LaTeX-fragments
3911 (mapcar (lambda (x) (nth 1 x)) latexs)))
3912 (re-macros
3913 (if org-export-with-TeX-macros
3914 (list (concat "\\\\"
3915 (regexp-opt
3916 (append (mapcar 'car org-html-entities)
3917 (if (boundp 'org-latex-entities)
3918 org-latex-entities nil))
3919 'words))) ; FIXME
3921 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3922 (re-special (if org-export-with-special-strings
3923 (mapcar (lambda (x) (car x))
3924 org-export-html-special-string-regexps)))
3925 (re-rest
3926 (delq nil
3927 (list
3928 (if org-export-html-expand "@<[^>\n]+>")
3929 ))))
3930 (org-set-local
3931 'org-latex-and-specials-regexp
3932 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3933 re-rest) "\\|")))))
3935 (defun org-do-latex-and-special-faces (limit)
3936 "Run through the buffer and add overlays to links."
3937 (when org-latex-and-specials-regexp
3938 (let (rtn d)
3939 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3940 limit t))
3941 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3942 'face))
3943 '(org-code org-verbatim underline)))
3944 (progn
3945 (setq rtn t
3946 d (cond ((member (char-after (1+ (match-beginning 0)))
3947 '(?_ ?^)) 1)
3948 (t 0)))
3949 (font-lock-prepend-text-property
3950 (+ d (match-beginning 0)) (match-end 0)
3951 'face 'org-latex-and-export-specials)
3952 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3953 '(font-lock-multiline t)))))
3954 rtn)))
3956 (defun org-restart-font-lock ()
3957 "Restart font-lock-mode, to force refontification."
3958 (when (and (boundp 'font-lock-mode) font-lock-mode)
3959 (font-lock-mode -1)
3960 (font-lock-mode 1)))
3962 (defun org-all-targets (&optional radio)
3963 "Return a list of all targets in this file.
3964 With optional argument RADIO, only find radio targets."
3965 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3966 rtn)
3967 (save-excursion
3968 (goto-char (point-min))
3969 (while (re-search-forward re nil t)
3970 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3971 rtn)))
3973 (defun org-make-target-link-regexp (targets)
3974 "Make regular expression matching all strings in TARGETS.
3975 The regular expression finds the targets also if there is a line break
3976 between words."
3977 (and targets
3978 (concat
3979 "\\<\\("
3980 (mapconcat
3981 (lambda (x)
3982 (while (string-match " +" x)
3983 (setq x (replace-match "\\s-+" t t x)))
3985 targets
3986 "\\|")
3987 "\\)\\>")))
3989 (defun org-activate-tags (limit)
3990 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3991 (progn
3992 (add-text-properties (match-beginning 1) (match-end 1)
3993 (list 'mouse-face 'highlight
3994 'rear-nonsticky org-nonsticky-props
3995 'keymap org-mouse-map))
3996 t)))
3998 (defun org-outline-level ()
3999 (save-excursion
4000 (looking-at outline-regexp)
4001 (if (match-beginning 1)
4002 (+ (org-get-string-indentation (match-string 1)) 1000)
4003 (1- (- (match-end 0) (match-beginning 0))))))
4005 (defvar org-font-lock-keywords nil)
4007 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4008 "Regular expression matching a property line.")
4010 (defvar org-font-lock-hook nil
4011 "Functions to be called for special font lock stuff.")
4013 (defun org-font-lock-hook (limit)
4014 (run-hook-with-args 'org-font-lock-hook limit))
4016 (defun org-set-font-lock-defaults ()
4017 (let* ((em org-fontify-emphasized-text)
4018 (lk org-activate-links)
4019 (org-font-lock-extra-keywords
4020 (list
4021 ;; Call the hook
4022 '(org-font-lock-hook)
4023 ;; Headlines
4024 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4025 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4026 ;; Table lines
4027 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4028 (1 'org-table t))
4029 ;; Table internals
4030 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4031 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4032 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4033 ;; Drawers
4034 (list org-drawer-regexp '(0 'org-special-keyword t))
4035 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4036 ;; Properties
4037 (list org-property-re
4038 '(1 'org-special-keyword t)
4039 '(3 'org-property-value t))
4040 (if org-format-transports-properties-p
4041 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4042 ;; Links
4043 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4044 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4045 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4046 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4047 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4048 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4049 (if (memq 'footnote lk) '(org-activate-footnote-links
4050 (0 'org-footnote t)))
4051 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4052 '(org-hide-wide-columns (0 nil append))
4053 ;; TODO lines
4054 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4055 '(1 (org-get-todo-face 1) t))
4056 ;; DONE
4057 (if org-fontify-done-headline
4058 (list (concat "^[*]+ +\\<\\("
4059 (mapconcat 'regexp-quote org-done-keywords "\\|")
4060 "\\)\\(.*\\)")
4061 '(2 'org-headline-done t))
4062 nil)
4063 ;; Priorities
4064 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4065 ;; Tags
4066 '(org-font-lock-add-tag-faces)
4067 ;; Special keywords
4068 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4069 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4070 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4071 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4072 ;; Emphasis
4073 (if em
4074 (if (featurep 'xemacs)
4075 '(org-do-emphasis-faces (0 nil append))
4076 '(org-do-emphasis-faces)))
4077 ;; Checkboxes
4078 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4079 2 'bold prepend)
4080 (if org-provide-checkbox-statistics
4081 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4082 (0 (org-get-checkbox-statistics-face) t)))
4083 ;; Description list items
4084 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4085 2 'bold prepend)
4086 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4087 '(1 'org-archived prepend))
4088 ;; Specials
4089 '(org-do-latex-and-special-faces)
4090 ;; Code
4091 '(org-activate-code (1 'org-code t))
4092 ;; COMMENT
4093 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4094 "\\|" org-quote-string "\\)\\>")
4095 '(1 'org-special-keyword t))
4096 '("^#.*" (0 'font-lock-comment-face t))
4098 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4099 ;; Now set the full font-lock-keywords
4100 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4101 (org-set-local 'font-lock-defaults
4102 '(org-font-lock-keywords t nil nil backward-paragraph))
4103 (kill-local-variable 'font-lock-keywords) nil))
4105 (defvar org-m nil)
4106 (defvar org-l nil)
4107 (defvar org-f nil)
4108 (defun org-get-level-face (n)
4109 "Get the right face for match N in font-lock matching of headlines."
4110 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4111 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4112 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4113 (cond
4114 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4115 ((eq n 2) org-f)
4116 (t (if org-level-color-stars-only nil org-f))))
4118 (defun org-get-todo-face (kwd)
4119 "Get the right face for a TODO keyword KWD.
4120 If KWD is a number, get the corresponding match group."
4121 (if (numberp kwd) (setq kwd (match-string kwd)))
4122 (or (cdr (assoc kwd org-todo-keyword-faces))
4123 (and (member kwd org-done-keywords) 'org-done)
4124 'org-todo))
4126 (defun org-font-lock-add-tag-faces (limit)
4127 "Add the special tag faces."
4128 (when (and org-tag-faces org-tags-special-faces-re)
4129 (while (re-search-forward org-tags-special-faces-re limit t)
4130 (add-text-properties (match-beginning 1) (match-end 1)
4131 (list 'face (org-get-tag-face 1)
4132 'font-lock-fontified t))
4133 (backward-char 1))))
4135 (defun org-get-tag-face (kwd)
4136 "Get the right face for a TODO keyword KWD.
4137 If KWD is a number, get the corresponding match group."
4138 (if (numberp kwd) (setq kwd (match-string kwd)))
4139 (or (cdr (assoc kwd org-tag-faces))
4140 'org-tag))
4142 (defun org-unfontify-region (beg end &optional maybe_loudly)
4143 "Remove fontification and activation overlays from links."
4144 (font-lock-default-unfontify-region beg end)
4145 (let* ((buffer-undo-list t)
4146 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4147 (inhibit-modification-hooks t)
4148 deactivate-mark buffer-file-name buffer-file-truename)
4149 (remove-text-properties beg end
4150 '(mouse-face t keymap t org-linked-text t
4151 invisible t intangible t))))
4153 ;;;; Visibility cycling, including org-goto and indirect buffer
4155 ;;; Cycling
4157 (defvar org-cycle-global-status nil)
4158 (make-variable-buffer-local 'org-cycle-global-status)
4159 (defvar org-cycle-subtree-status nil)
4160 (make-variable-buffer-local 'org-cycle-subtree-status)
4162 ;;;###autoload
4163 (defun org-cycle (&optional arg)
4164 "Visibility cycling for Org-mode.
4166 - When this function is called with a prefix argument, rotate the entire
4167 buffer through 3 states (global cycling)
4168 1. OVERVIEW: Show only top-level headlines.
4169 2. CONTENTS: Show all headlines of all levels, but no body text.
4170 3. SHOW ALL: Show everything.
4171 When called with two C-u C-u prefixes, switch to the startup visibility,
4172 determined by the variable `org-startup-folded', and by any VISIBILITY
4173 properties in the buffer.
4174 When called with three C-u C-u C-u prefixed, show the entire buffer,
4175 including drawers.
4177 - When point is at the beginning of a headline, rotate the subtree started
4178 by this line through 3 different states (local cycling)
4179 1. FOLDED: Only the main headline is shown.
4180 2. CHILDREN: The main headline and the direct children are shown.
4181 From this state, you can move to one of the children
4182 and zoom in further.
4183 3. SUBTREE: Show the entire subtree, including body text.
4185 - When there is a numeric prefix, go up to a heading with level ARG, do
4186 a `show-subtree' and return to the previous cursor position. If ARG
4187 is negative, go up that many levels.
4189 - When point is not at the beginning of a headline, execute the global
4190 binding for TAB, which is re-indenting the line. See the option
4191 `org-cycle-emulate-tab' for details.
4193 - Special case: if point is at the beginning of the buffer and there is
4194 no headline in line 1, this function will act as if called with prefix arg.
4195 But only if also the variable `org-cycle-global-at-bob' is t."
4196 (interactive "P")
4197 (org-load-modules-maybe)
4198 (let* ((outline-regexp
4199 (if (and (org-mode-p) org-cycle-include-plain-lists)
4200 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4201 outline-regexp))
4202 (bob-special (and org-cycle-global-at-bob (bobp)
4203 (not (looking-at outline-regexp))))
4204 (org-cycle-hook
4205 (if bob-special
4206 (delq 'org-optimize-window-after-visibility-change
4207 (copy-sequence org-cycle-hook))
4208 org-cycle-hook))
4209 (pos (point)))
4211 (if (or bob-special (equal arg '(4)))
4212 ;; special case: use global cycling
4213 (setq arg t))
4215 (cond
4217 ((equal arg '(16))
4218 (org-set-startup-visibility)
4219 (message "Startup visibility, plus VISIBILITY properties"))
4221 ((equal arg '(64))
4222 (show-all)
4223 (message "Entire buffer visible, including drawers"))
4225 ((org-at-table-p 'any)
4226 ;; Enter the table or move to the next field in the table
4227 (or (org-table-recognize-table.el)
4228 (progn
4229 (if arg (org-table-edit-field t)
4230 (org-table-justify-field-maybe)
4231 (call-interactively 'org-table-next-field)))))
4233 ((eq arg t) ;; Global cycling
4235 (cond
4236 ((and (eq last-command this-command)
4237 (eq org-cycle-global-status 'overview))
4238 ;; We just created the overview - now do table of contents
4239 ;; This can be slow in very large buffers, so indicate action
4240 (message "CONTENTS...")
4241 (org-content)
4242 (message "CONTENTS...done")
4243 (setq org-cycle-global-status 'contents)
4244 (run-hook-with-args 'org-cycle-hook 'contents))
4246 ((and (eq last-command this-command)
4247 (eq org-cycle-global-status 'contents))
4248 ;; We just showed the table of contents - now show everything
4249 (show-all)
4250 (message "SHOW ALL")
4251 (setq org-cycle-global-status 'all)
4252 (run-hook-with-args 'org-cycle-hook 'all))
4255 ;; Default action: go to overview
4256 (org-overview)
4257 (message "OVERVIEW")
4258 (setq org-cycle-global-status 'overview)
4259 (run-hook-with-args 'org-cycle-hook 'overview))))
4261 ((and org-drawers org-drawer-regexp
4262 (save-excursion
4263 (beginning-of-line 1)
4264 (looking-at org-drawer-regexp)))
4265 ;; Toggle block visibility
4266 (org-flag-drawer
4267 (not (get-char-property (match-end 0) 'invisible))))
4269 ((integerp arg)
4270 ;; Show-subtree, ARG levels up from here.
4271 (save-excursion
4272 (org-back-to-heading)
4273 (outline-up-heading (if (< arg 0) (- arg)
4274 (- (funcall outline-level) arg)))
4275 (org-show-subtree)))
4277 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4278 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4279 ;; At a heading: rotate between three different views
4280 (org-back-to-heading)
4281 (let ((goal-column 0) eoh eol eos)
4282 ;; First, some boundaries
4283 (save-excursion
4284 (org-back-to-heading)
4285 (save-excursion
4286 (beginning-of-line 2)
4287 (while (and (not (eobp)) ;; this is like `next-line'
4288 (get-char-property (1- (point)) 'invisible))
4289 (beginning-of-line 2)) (setq eol (point)))
4290 (outline-end-of-heading) (setq eoh (point))
4291 (org-end-of-subtree t)
4292 (unless (eobp)
4293 (skip-chars-forward " \t\n")
4294 (beginning-of-line 1) ; in case this is an item
4296 (setq eos (1- (point))))
4297 ;; Find out what to do next and set `this-command'
4298 (cond
4299 ((= eos eoh)
4300 ;; Nothing is hidden behind this heading
4301 (message "EMPTY ENTRY")
4302 (setq org-cycle-subtree-status nil)
4303 (save-excursion
4304 (goto-char eos)
4305 (outline-next-heading)
4306 (if (org-invisible-p) (org-flag-heading nil))))
4307 ((or (>= eol eos)
4308 (not (string-match "\\S-" (buffer-substring eol eos))))
4309 ;; Entire subtree is hidden in one line: open it
4310 (org-show-entry)
4311 (show-children)
4312 (message "CHILDREN")
4313 (save-excursion
4314 (goto-char eos)
4315 (outline-next-heading)
4316 (if (org-invisible-p) (org-flag-heading nil)))
4317 (setq org-cycle-subtree-status 'children)
4318 (run-hook-with-args 'org-cycle-hook 'children))
4319 ((and (eq last-command this-command)
4320 (eq org-cycle-subtree-status 'children))
4321 ;; We just showed the children, now show everything.
4322 (org-show-subtree)
4323 (message "SUBTREE")
4324 (setq org-cycle-subtree-status 'subtree)
4325 (run-hook-with-args 'org-cycle-hook 'subtree))
4327 ;; Default action: hide the subtree.
4328 (hide-subtree)
4329 (message "FOLDED")
4330 (setq org-cycle-subtree-status 'folded)
4331 (run-hook-with-args 'org-cycle-hook 'folded)))))
4333 ;; TAB emulation and template completion
4334 (buffer-read-only (org-back-to-heading))
4336 ((org-try-structure-completion))
4338 ((org-try-cdlatex-tab))
4340 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4341 (or (not (bolp))
4342 (not (looking-at outline-regexp))))
4343 (call-interactively (global-key-binding "\t")))
4345 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4346 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4347 (or (and (eq org-cycle-emulate-tab 'white)
4348 (= (match-end 0) (point-at-eol)))
4349 (and (eq org-cycle-emulate-tab 'whitestart)
4350 (>= (match-end 0) pos))))
4352 (eq org-cycle-emulate-tab t))
4353 (call-interactively (global-key-binding "\t")))
4355 (t (save-excursion
4356 (org-back-to-heading)
4357 (org-cycle))))))
4359 ;;;###autoload
4360 (defun org-global-cycle (&optional arg)
4361 "Cycle the global visibility. For details see `org-cycle'.
4362 With C-u prefix arg, switch to startup visibility.
4363 With a numeric prefix, show all headlines up to that level."
4364 (interactive "P")
4365 (let ((org-cycle-include-plain-lists
4366 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4367 (cond
4368 ((integerp arg)
4369 (show-all)
4370 (hide-sublevels arg)
4371 (setq org-cycle-global-status 'contents))
4372 ((equal arg '(4))
4373 (org-set-startup-visibility)
4374 (message "Startup visibility, plus VISIBILITY properties."))
4376 (org-cycle '(4))))))
4378 (defun org-set-startup-visibility ()
4379 "Set the visibility required by startup options and properties."
4380 (cond
4381 ((eq org-startup-folded t)
4382 (org-cycle '(4)))
4383 ((eq org-startup-folded 'content)
4384 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4385 (org-cycle '(4)) (org-cycle '(4)))))
4386 (org-set-visibility-according-to-property 'no-cleanup)
4387 (org-cycle-hide-archived-subtrees 'all)
4388 (org-cycle-hide-drawers 'all)
4389 (org-cycle-show-empty-lines 'all))
4391 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4392 "Switch subtree visibilities according to :VISIBILITY: property."
4393 (interactive)
4394 (let (state)
4395 (save-excursion
4396 (goto-char (point-min))
4397 (while (re-search-forward
4398 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4399 nil t)
4400 (setq state (match-string 1))
4401 (save-excursion
4402 (org-back-to-heading t)
4403 (hide-subtree)
4404 (org-reveal)
4405 (cond
4406 ((equal state '("fold" "folded"))
4407 (hide-subtree))
4408 ((equal state "children")
4409 (org-show-hidden-entry)
4410 (show-children))
4411 ((equal state "content")
4412 (save-excursion
4413 (save-restriction
4414 (org-narrow-to-subtree)
4415 (org-content))))
4416 ((member state '("all" "showall"))
4417 (show-subtree)))))
4418 (unless no-cleanup
4419 (org-cycle-hide-archived-subtrees 'all)
4420 (org-cycle-hide-drawers 'all)
4421 (org-cycle-show-empty-lines 'all)))))
4423 (defun org-overview ()
4424 "Switch to overview mode, showing only top-level headlines.
4425 Really, this shows all headlines with level equal or greater than the level
4426 of the first headline in the buffer. This is important, because if the
4427 first headline is not level one, then (hide-sublevels 1) gives confusing
4428 results."
4429 (interactive)
4430 (let ((level (save-excursion
4431 (goto-char (point-min))
4432 (if (re-search-forward (concat "^" outline-regexp) nil t)
4433 (progn
4434 (goto-char (match-beginning 0))
4435 (funcall outline-level))))))
4436 (and level (hide-sublevels level))))
4438 (defun org-content (&optional arg)
4439 "Show all headlines in the buffer, like a table of contents.
4440 With numerical argument N, show content up to level N."
4441 (interactive "P")
4442 (save-excursion
4443 ;; Visit all headings and show their offspring
4444 (and (integerp arg) (org-overview))
4445 (goto-char (point-max))
4446 (catch 'exit
4447 (while (and (progn (condition-case nil
4448 (outline-previous-visible-heading 1)
4449 (error (goto-char (point-min))))
4451 (looking-at outline-regexp))
4452 (if (integerp arg)
4453 (show-children (1- arg))
4454 (show-branches))
4455 (if (bobp) (throw 'exit nil))))))
4458 (defun org-optimize-window-after-visibility-change (state)
4459 "Adjust the window after a change in outline visibility.
4460 This function is the default value of the hook `org-cycle-hook'."
4461 (when (get-buffer-window (current-buffer))
4462 (cond
4463 ; ((eq state 'overview) (org-first-headline-recenter 1))
4464 ; ((eq state 'overview) (org-beginning-of-line))
4465 ((eq state 'content) nil)
4466 ((eq state 'all) nil)
4467 ((eq state 'folded) nil)
4468 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4469 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4471 (defun org-compact-display-after-subtree-move ()
4472 (let (beg end)
4473 (save-excursion
4474 (if (org-up-heading-safe)
4475 (progn
4476 (hide-subtree)
4477 (show-entry)
4478 (show-children)
4479 (org-cycle-show-empty-lines 'children)
4480 (org-cycle-hide-drawers 'children))
4481 (org-overview)))))
4483 (defun org-cycle-show-empty-lines (state)
4484 "Show empty lines above all visible headlines.
4485 The region to be covered depends on STATE when called through
4486 `org-cycle-hook'. Lisp program can use t for STATE to get the
4487 entire buffer covered. Note that an empty line is only shown if there
4488 are at least `org-cycle-separator-lines' empty lines before the headline."
4489 (when (> org-cycle-separator-lines 0)
4490 (save-excursion
4491 (let* ((n org-cycle-separator-lines)
4492 (re (cond
4493 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4494 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4495 (t (let ((ns (number-to-string (- n 2))))
4496 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4497 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4498 beg end)
4499 (cond
4500 ((memq state '(overview contents t))
4501 (setq beg (point-min) end (point-max)))
4502 ((memq state '(children folded))
4503 (setq beg (point) end (progn (org-end-of-subtree t t)
4504 (beginning-of-line 2)
4505 (point)))))
4506 (when beg
4507 (goto-char beg)
4508 (while (re-search-forward re end t)
4509 (if (not (get-char-property (match-end 1) 'invisible))
4510 (outline-flag-region
4511 (match-beginning 1) (match-end 1) nil)))))))
4512 ;; Never hide empty lines at the end of the file.
4513 (save-excursion
4514 (goto-char (point-max))
4515 (outline-previous-heading)
4516 (outline-end-of-heading)
4517 (if (and (looking-at "[ \t\n]+")
4518 (= (match-end 0) (point-max)))
4519 (outline-flag-region (point) (match-end 0) nil))))
4521 (defun org-show-empty-lines-in-parent ()
4522 "Move to the parent and re-show empty lines before visible headlines."
4523 (save-excursion
4524 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4525 (org-cycle-show-empty-lines context))))
4527 (defun org-cycle-hide-drawers (state)
4528 "Re-hide all drawers after a visibility state change."
4529 (when (and (org-mode-p)
4530 (not (memq state '(overview folded))))
4531 (save-excursion
4532 (let* ((globalp (memq state '(contents all)))
4533 (beg (if globalp (point-min) (point)))
4534 (end (if globalp (point-max) (org-end-of-subtree t))))
4535 (goto-char beg)
4536 (while (re-search-forward org-drawer-regexp end t)
4537 (org-flag-drawer t))))))
4539 (defun org-flag-drawer (flag)
4540 (save-excursion
4541 (beginning-of-line 1)
4542 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4543 (let ((b (match-end 0))
4544 (outline-regexp org-outline-regexp))
4545 (if (re-search-forward
4546 "^[ \t]*:END:"
4547 (save-excursion (outline-next-heading) (point)) t)
4548 (outline-flag-region b (point-at-eol) flag)
4549 (error ":END: line missing"))))))
4551 (defun org-subtree-end-visible-p ()
4552 "Is the end of the current subtree visible?"
4553 (pos-visible-in-window-p
4554 (save-excursion (org-end-of-subtree t) (point))))
4556 (defun org-first-headline-recenter (&optional N)
4557 "Move cursor to the first headline and recenter the headline.
4558 Optional argument N means, put the headline into the Nth line of the window."
4559 (goto-char (point-min))
4560 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4561 (beginning-of-line)
4562 (recenter (prefix-numeric-value N))))
4564 ;;; Org-goto
4566 (defvar org-goto-window-configuration nil)
4567 (defvar org-goto-marker nil)
4568 (defvar org-goto-map
4569 (let ((map (make-sparse-keymap)))
4570 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4571 (while (setq cmd (pop cmds))
4572 (substitute-key-definition cmd cmd map global-map)))
4573 (suppress-keymap map)
4574 (org-defkey map "\C-m" 'org-goto-ret)
4575 (org-defkey map [(return)] 'org-goto-ret)
4576 (org-defkey map [(left)] 'org-goto-left)
4577 (org-defkey map [(right)] 'org-goto-right)
4578 (org-defkey map [(control ?g)] 'org-goto-quit)
4579 (org-defkey map "\C-i" 'org-cycle)
4580 (org-defkey map [(tab)] 'org-cycle)
4581 (org-defkey map [(down)] 'outline-next-visible-heading)
4582 (org-defkey map [(up)] 'outline-previous-visible-heading)
4583 (if org-goto-auto-isearch
4584 (if (fboundp 'define-key-after)
4585 (define-key-after map [t] 'org-goto-local-auto-isearch)
4586 nil)
4587 (org-defkey map "q" 'org-goto-quit)
4588 (org-defkey map "n" 'outline-next-visible-heading)
4589 (org-defkey map "p" 'outline-previous-visible-heading)
4590 (org-defkey map "f" 'outline-forward-same-level)
4591 (org-defkey map "b" 'outline-backward-same-level)
4592 (org-defkey map "u" 'outline-up-heading))
4593 (org-defkey map "/" 'org-occur)
4594 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4595 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4596 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4597 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4598 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4599 map))
4601 (defconst org-goto-help
4602 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4603 RET=jump to location [Q]uit and return to previous location
4604 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4606 (defvar org-goto-start-pos) ; dynamically scoped parameter
4608 ;; FIXME: Docstring doe not mention both interfaces
4609 (defun org-goto (&optional alternative-interface)
4610 "Look up a different location in the current file, keeping current visibility.
4612 When you want look-up or go to a different location in a document, the
4613 fastest way is often to fold the entire buffer and then dive into the tree.
4614 This method has the disadvantage, that the previous location will be folded,
4615 which may not be what you want.
4617 This command works around this by showing a copy of the current buffer
4618 in an indirect buffer, in overview mode. You can dive into the tree in
4619 that copy, use org-occur and incremental search to find a location.
4620 When pressing RET or `Q', the command returns to the original buffer in
4621 which the visibility is still unchanged. After RET is will also jump to
4622 the location selected in the indirect buffer and expose the
4623 the headline hierarchy above."
4624 (interactive "P")
4625 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4626 (org-refile-use-outline-path t)
4627 (interface
4628 (if (not alternative-interface)
4629 org-goto-interface
4630 (if (eq org-goto-interface 'outline)
4631 'outline-path-completion
4632 'outline)))
4633 (org-goto-start-pos (point))
4634 (selected-point
4635 (if (eq interface 'outline)
4636 (car (org-get-location (current-buffer) org-goto-help))
4637 (nth 3 (org-refile-get-location "Goto: ")))))
4638 (if selected-point
4639 (progn
4640 (org-mark-ring-push org-goto-start-pos)
4641 (goto-char selected-point)
4642 (if (or (org-invisible-p) (org-invisible-p2))
4643 (org-show-context 'org-goto)))
4644 (message "Quit"))))
4646 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4647 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4648 (defvar org-goto-local-auto-isearch-map) ; defined below
4650 (defun org-get-location (buf help)
4651 "Let the user select a location in the Org-mode buffer BUF.
4652 This function uses a recursive edit. It returns the selected position
4653 or nil."
4654 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4655 (isearch-hide-immediately nil)
4656 (isearch-search-fun-function
4657 (lambda () 'org-goto-local-search-headings))
4658 (org-goto-selected-point org-goto-exit-command))
4659 (save-excursion
4660 (save-window-excursion
4661 (delete-other-windows)
4662 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4663 (switch-to-buffer
4664 (condition-case nil
4665 (make-indirect-buffer (current-buffer) "*org-goto*")
4666 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4667 (with-output-to-temp-buffer "*Help*"
4668 (princ help))
4669 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4670 (setq buffer-read-only nil)
4671 (let ((org-startup-truncated t)
4672 (org-startup-folded nil)
4673 (org-startup-align-all-tables nil))
4674 (org-mode)
4675 (org-overview))
4676 (setq buffer-read-only t)
4677 (if (and (boundp 'org-goto-start-pos)
4678 (integer-or-marker-p org-goto-start-pos))
4679 (let ((org-show-hierarchy-above t)
4680 (org-show-siblings t)
4681 (org-show-following-heading t))
4682 (goto-char org-goto-start-pos)
4683 (and (org-invisible-p) (org-show-context)))
4684 (goto-char (point-min)))
4685 (org-beginning-of-line)
4686 (message "Select location and press RET")
4687 (use-local-map org-goto-map)
4688 (recursive-edit)
4690 (kill-buffer "*org-goto*")
4691 (cons org-goto-selected-point org-goto-exit-command)))
4693 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4694 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4695 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4696 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4698 (defun org-goto-local-search-headings (string bound noerror)
4699 "Search and make sure that any matches are in headlines."
4700 (catch 'return
4701 (while (if isearch-forward
4702 (search-forward string bound noerror)
4703 (search-backward string bound noerror))
4704 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4705 (and (member :headline context)
4706 (not (member :tags context))))
4707 (throw 'return (point))))))
4709 (defun org-goto-local-auto-isearch ()
4710 "Start isearch."
4711 (interactive)
4712 (goto-char (point-min))
4713 (let ((keys (this-command-keys)))
4714 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4715 (isearch-mode t)
4716 (isearch-process-search-char (string-to-char keys)))))
4718 (defun org-goto-ret (&optional arg)
4719 "Finish `org-goto' by going to the new location."
4720 (interactive "P")
4721 (setq org-goto-selected-point (point)
4722 org-goto-exit-command 'return)
4723 (throw 'exit nil))
4725 (defun org-goto-left ()
4726 "Finish `org-goto' by going to the new location."
4727 (interactive)
4728 (if (org-on-heading-p)
4729 (progn
4730 (beginning-of-line 1)
4731 (setq org-goto-selected-point (point)
4732 org-goto-exit-command 'left)
4733 (throw 'exit nil))
4734 (error "Not on a heading")))
4736 (defun org-goto-right ()
4737 "Finish `org-goto' by going to the new location."
4738 (interactive)
4739 (if (org-on-heading-p)
4740 (progn
4741 (setq org-goto-selected-point (point)
4742 org-goto-exit-command 'right)
4743 (throw 'exit nil))
4744 (error "Not on a heading")))
4746 (defun org-goto-quit ()
4747 "Finish `org-goto' without cursor motion."
4748 (interactive)
4749 (setq org-goto-selected-point nil)
4750 (setq org-goto-exit-command 'quit)
4751 (throw 'exit nil))
4753 ;;; Indirect buffer display of subtrees
4755 (defvar org-indirect-dedicated-frame nil
4756 "This is the frame being used for indirect tree display.")
4757 (defvar org-last-indirect-buffer nil)
4759 (defun org-tree-to-indirect-buffer (&optional arg)
4760 "Create indirect buffer and narrow it to current subtree.
4761 With numerical prefix ARG, go up to this level and then take that tree.
4762 If ARG is negative, go up that many levels.
4763 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4764 indirect buffer previously made with this command, to avoid proliferation of
4765 indirect buffers. However, when you call the command with a `C-u' prefix, or
4766 when `org-indirect-buffer-display' is `new-frame', the last buffer
4767 is kept so that you can work with several indirect buffers at the same time.
4768 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4769 requests that a new frame be made for the new buffer, so that the dedicated
4770 frame is not changed."
4771 (interactive "P")
4772 (let ((cbuf (current-buffer))
4773 (cwin (selected-window))
4774 (pos (point))
4775 beg end level heading ibuf)
4776 (save-excursion
4777 (org-back-to-heading t)
4778 (when (numberp arg)
4779 (setq level (org-outline-level))
4780 (if (< arg 0) (setq arg (+ level arg)))
4781 (while (> (setq level (org-outline-level)) arg)
4782 (outline-up-heading 1 t)))
4783 (setq beg (point)
4784 heading (org-get-heading))
4785 (org-end-of-subtree t) (setq end (point)))
4786 (if (and (buffer-live-p org-last-indirect-buffer)
4787 (not (eq org-indirect-buffer-display 'new-frame))
4788 (not arg))
4789 (kill-buffer org-last-indirect-buffer))
4790 (setq ibuf (org-get-indirect-buffer cbuf)
4791 org-last-indirect-buffer ibuf)
4792 (cond
4793 ((or (eq org-indirect-buffer-display 'new-frame)
4794 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4795 (select-frame (make-frame))
4796 (delete-other-windows)
4797 (switch-to-buffer ibuf)
4798 (org-set-frame-title heading))
4799 ((eq org-indirect-buffer-display 'dedicated-frame)
4800 (raise-frame
4801 (select-frame (or (and org-indirect-dedicated-frame
4802 (frame-live-p org-indirect-dedicated-frame)
4803 org-indirect-dedicated-frame)
4804 (setq org-indirect-dedicated-frame (make-frame)))))
4805 (delete-other-windows)
4806 (switch-to-buffer ibuf)
4807 (org-set-frame-title (concat "Indirect: " heading)))
4808 ((eq org-indirect-buffer-display 'current-window)
4809 (switch-to-buffer ibuf))
4810 ((eq org-indirect-buffer-display 'other-window)
4811 (pop-to-buffer ibuf))
4812 (t (error "Invalid value.")))
4813 (if (featurep 'xemacs)
4814 (save-excursion (org-mode) (turn-on-font-lock)))
4815 (narrow-to-region beg end)
4816 (show-all)
4817 (goto-char pos)
4818 (and (window-live-p cwin) (select-window cwin))))
4820 (defun org-get-indirect-buffer (&optional buffer)
4821 (setq buffer (or buffer (current-buffer)))
4822 (let ((n 1) (base (buffer-name buffer)) bname)
4823 (while (buffer-live-p
4824 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4825 (setq n (1+ n)))
4826 (condition-case nil
4827 (make-indirect-buffer buffer bname 'clone)
4828 (error (make-indirect-buffer buffer bname)))))
4830 (defun org-set-frame-title (title)
4831 "Set the title of the current frame to the string TITLE."
4832 ;; FIXME: how to name a single frame in XEmacs???
4833 (unless (featurep 'xemacs)
4834 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4836 ;;;; Structure editing
4838 ;;; Inserting headlines
4840 (defun org-previous-line-empty-p ()
4841 (save-excursion
4842 (and (not (bobp))
4843 (or (beginning-of-line 0) t)
4844 (save-match-data
4845 (looking-at "[ \t]*$")))))
4847 (defun org-insert-heading (&optional force-heading)
4848 "Insert a new heading or item with same depth at point.
4849 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4850 If point is at the beginning of a headline, insert a sibling before the
4851 current headline. If point is not at the beginning, do not split the line,
4852 but create the new headline after the current line."
4853 (interactive "P")
4854 (if (= (buffer-size) 0)
4855 (insert "\n* ")
4856 (when (or force-heading (not (org-insert-item)))
4857 (let* ((empty-line-p nil)
4858 (head (save-excursion
4859 (condition-case nil
4860 (progn
4861 (org-back-to-heading)
4862 (setq empty-line-p (org-previous-line-empty-p))
4863 (match-string 0))
4864 (error "*"))))
4865 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4866 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4867 pos hide-previous previous-pos)
4868 (cond
4869 ((and (org-on-heading-p) (bolp)
4870 (or (bobp)
4871 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4872 ;; insert before the current line
4873 (open-line (if blank 2 1)))
4874 ((and (bolp)
4875 (or (bobp)
4876 (save-excursion
4877 (backward-char 1) (not (org-invisible-p)))))
4878 ;; insert right here
4879 nil)
4881 ;; somewhere in the line
4882 (save-excursion
4883 (setq previous-pos (point-at-bol))
4884 (end-of-line)
4885 (setq hide-previous (org-invisible-p)))
4886 (and org-insert-heading-respect-content (org-show-subtree))
4887 (let ((split
4888 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4889 (save-excursion
4890 (let ((p (point)))
4891 (goto-char (point-at-bol))
4892 (and (looking-at org-complex-heading-regexp)
4893 (> p (match-beginning 4)))))))
4894 tags pos)
4895 (cond
4896 (org-insert-heading-respect-content
4897 (org-end-of-subtree nil t)
4898 (or (bolp) (newline))
4899 (or (org-previous-line-empty-p)
4900 (and blank (newline)))
4901 (open-line 1))
4902 ((org-on-heading-p)
4903 (when hide-previous
4904 (show-children)
4905 (org-show-entry))
4906 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4907 (setq tags (and (match-end 2) (match-string 2)))
4908 (and (match-end 1)
4909 (delete-region (match-beginning 1) (match-end 1)))
4910 (setq pos (point-at-bol))
4911 (or split (end-of-line 1))
4912 (delete-horizontal-space)
4913 (newline (if blank 2 1))
4914 (when tags
4915 (save-excursion
4916 (goto-char pos)
4917 (end-of-line 1)
4918 (insert " " tags)
4919 (org-set-tags nil 'align))))
4921 (or split (end-of-line 1))
4922 (newline (if blank 2 1)))))))
4923 (insert head) (just-one-space)
4924 (setq pos (point))
4925 (end-of-line 1)
4926 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4927 (when (and org-insert-heading-respect-content hide-previous)
4928 (save-excursion
4929 (goto-char previous-pos)
4930 (hide-subtree)))
4931 (run-hooks 'org-insert-heading-hook)))))
4933 (defun org-get-heading (&optional no-tags)
4934 "Return the heading of the current entry, without the stars."
4935 (save-excursion
4936 (org-back-to-heading t)
4937 (if (looking-at
4938 (if no-tags
4939 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4940 "\\*+[ \t]+\\([^\r\n]*\\)"))
4941 (match-string 1) "")))
4943 (defun org-insert-heading-after-current ()
4944 "Insert a new heading with same level as current, after current subtree."
4945 (interactive)
4946 (org-back-to-heading)
4947 (org-insert-heading)
4948 (org-move-subtree-down)
4949 (end-of-line 1))
4951 (defun org-insert-heading-respect-content ()
4952 (interactive)
4953 (let ((org-insert-heading-respect-content t))
4954 (org-insert-heading t)))
4956 (defun org-insert-todo-heading-respect-content (&optional force-state)
4957 (interactive "P")
4958 (let ((org-insert-heading-respect-content t))
4959 (org-insert-todo-heading force-state t)))
4961 (defun org-insert-todo-heading (arg &optional force-heading)
4962 "Insert a new heading with the same level and TODO state as current heading.
4963 If the heading has no TODO state, or if the state is DONE, use the first
4964 state (TODO by default). Also with prefix arg, force first state."
4965 (interactive "P")
4966 (when (or force-heading (not (org-insert-item 'checkbox)))
4967 (org-insert-heading force-heading)
4968 (save-excursion
4969 (org-back-to-heading)
4970 (outline-previous-heading)
4971 (looking-at org-todo-line-regexp))
4972 (if (or arg
4973 (not (match-beginning 2))
4974 (member (match-string 2) org-done-keywords))
4975 (insert (car org-todo-keywords-1) " ")
4976 (insert (match-string 2) " "))
4977 (when org-provide-todo-statistics
4978 (org-update-parent-todo-statistics))))
4980 (defun org-insert-subheading (arg)
4981 "Insert a new subheading and demote it.
4982 Works for outline headings and for plain lists alike."
4983 (interactive "P")
4984 (org-insert-heading arg)
4985 (cond
4986 ((org-on-heading-p) (org-do-demote))
4987 ((org-at-item-p) (org-indent-item 1))))
4989 (defun org-insert-todo-subheading (arg)
4990 "Insert a new subheading with TODO keyword or checkbox and demote it.
4991 Works for outline headings and for plain lists alike."
4992 (interactive "P")
4993 (org-insert-todo-heading arg)
4994 (cond
4995 ((org-on-heading-p) (org-do-demote))
4996 ((org-at-item-p) (org-indent-item 1))))
4998 ;;; Promotion and Demotion
5000 (defun org-promote-subtree ()
5001 "Promote the entire subtree.
5002 See also `org-promote'."
5003 (interactive)
5004 (save-excursion
5005 (org-map-tree 'org-promote))
5006 (org-fix-position-after-promote))
5008 (defun org-demote-subtree ()
5009 "Demote the entire subtree. See `org-demote'.
5010 See also `org-promote'."
5011 (interactive)
5012 (save-excursion
5013 (org-map-tree 'org-demote))
5014 (org-fix-position-after-promote))
5017 (defun org-do-promote ()
5018 "Promote the current heading higher up the tree.
5019 If the region is active in `transient-mark-mode', promote all headings
5020 in the region."
5021 (interactive)
5022 (save-excursion
5023 (if (org-region-active-p)
5024 (org-map-region 'org-promote (region-beginning) (region-end))
5025 (org-promote)))
5026 (org-fix-position-after-promote))
5028 (defun org-do-demote ()
5029 "Demote the current heading lower down the tree.
5030 If the region is active in `transient-mark-mode', demote all headings
5031 in the region."
5032 (interactive)
5033 (save-excursion
5034 (if (org-region-active-p)
5035 (org-map-region 'org-demote (region-beginning) (region-end))
5036 (org-demote)))
5037 (org-fix-position-after-promote))
5039 (defun org-fix-position-after-promote ()
5040 "Make sure that after pro/demotion cursor position is right."
5041 (let ((pos (point)))
5042 (when (save-excursion
5043 (beginning-of-line 1)
5044 (looking-at org-todo-line-regexp)
5045 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5046 (cond ((eobp) (insert " "))
5047 ((eolp) (insert " "))
5048 ((equal (char-after) ?\ ) (forward-char 1))))))
5050 (defun org-reduced-level (l)
5051 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5053 (defun org-get-valid-level (level &optional change)
5054 "Rectify a level change under the influence of `org-odd-levels-only'
5055 LEVEL is a current level, CHANGE is by how much the level should be
5056 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5057 even level numbers will become the next higher odd number."
5058 (if org-odd-levels-only
5059 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5060 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5061 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5062 (max 1 (+ level change))))
5064 (if (boundp 'define-obsolete-function-alias)
5065 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5066 (define-obsolete-function-alias 'org-get-legal-level
5067 'org-get-valid-level)
5068 (define-obsolete-function-alias 'org-get-legal-level
5069 'org-get-valid-level "23.1")))
5071 (defun org-promote ()
5072 "Promote the current heading higher up the tree.
5073 If the region is active in `transient-mark-mode', promote all headings
5074 in the region."
5075 (org-back-to-heading t)
5076 (let* ((level (save-match-data (funcall outline-level)))
5077 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5078 (diff (abs (- level (length up-head) -1))))
5079 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5080 (replace-match up-head nil t)
5081 ;; Fixup tag positioning
5082 (and org-auto-align-tags (org-set-tags nil t))
5083 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5085 (defun org-demote ()
5086 "Demote the current heading lower down the tree.
5087 If the region is active in `transient-mark-mode', demote all headings
5088 in the region."
5089 (org-back-to-heading t)
5090 (let* ((level (save-match-data (funcall outline-level)))
5091 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5092 (diff (abs (- level (length down-head) -1))))
5093 (replace-match down-head nil t)
5094 ;; Fixup tag positioning
5095 (and org-auto-align-tags (org-set-tags nil t))
5096 (if org-adapt-indentation (org-fixup-indentation diff))))
5098 (defun org-map-tree (fun)
5099 "Call FUN for every heading underneath the current one."
5100 (org-back-to-heading)
5101 (let ((level (funcall outline-level)))
5102 (save-excursion
5103 (funcall fun)
5104 (while (and (progn
5105 (outline-next-heading)
5106 (> (funcall outline-level) level))
5107 (not (eobp)))
5108 (funcall fun)))))
5110 (defun org-map-region (fun beg end)
5111 "Call FUN for every heading between BEG and END."
5112 (let ((org-ignore-region t))
5113 (save-excursion
5114 (setq end (copy-marker end))
5115 (goto-char beg)
5116 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5117 (< (point) end))
5118 (funcall fun))
5119 (while (and (progn
5120 (outline-next-heading)
5121 (< (point) end))
5122 (not (eobp)))
5123 (funcall fun)))))
5125 (defun org-fixup-indentation (diff)
5126 "Change the indentation in the current entry by DIFF
5127 However, if any line in the current entry has no indentation, or if it
5128 would end up with no indentation after the change, nothing at all is done."
5129 (save-excursion
5130 (let ((end (save-excursion (outline-next-heading)
5131 (point-marker)))
5132 (prohibit (if (> diff 0)
5133 "^\\S-"
5134 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5135 col)
5136 (unless (save-excursion (end-of-line 1)
5137 (re-search-forward prohibit end t))
5138 (while (and (< (point) end)
5139 (re-search-forward "^[ \t]+" end t))
5140 (goto-char (match-end 0))
5141 (setq col (current-column))
5142 (if (< diff 0) (replace-match ""))
5143 (org-indent-to-column (+ diff col))))
5144 (move-marker end nil))))
5146 (defun org-convert-to-odd-levels ()
5147 "Convert an org-mode file with all levels allowed to one with odd levels.
5148 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5149 level 5 etc."
5150 (interactive)
5151 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5152 (let ((org-odd-levels-only nil) n)
5153 (save-excursion
5154 (goto-char (point-min))
5155 (while (re-search-forward "^\\*\\*+ " nil t)
5156 (setq n (- (length (match-string 0)) 2))
5157 (while (>= (setq n (1- n)) 0)
5158 (org-demote))
5159 (end-of-line 1))))))
5162 (defun org-convert-to-oddeven-levels ()
5163 "Convert an org-mode file with only odd levels to one with odd and even levels.
5164 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5165 section with an even level, conversion would destroy the structure of the file. An error
5166 is signaled in this case."
5167 (interactive)
5168 (goto-char (point-min))
5169 ;; First check if there are no even levels
5170 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5171 (org-show-context t)
5172 (error "Not all levels are odd in this file. Conversion not possible."))
5173 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5174 (let ((org-odd-levels-only nil) n)
5175 (save-excursion
5176 (goto-char (point-min))
5177 (while (re-search-forward "^\\*\\*+ " nil t)
5178 (setq n (/ (1- (length (match-string 0))) 2))
5179 (while (>= (setq n (1- n)) 0)
5180 (org-promote))
5181 (end-of-line 1))))))
5183 (defun org-tr-level (n)
5184 "Make N odd if required."
5185 (if org-odd-levels-only (1+ (/ n 2)) n))
5187 ;;; Vertical tree motion, cutting and pasting of subtrees
5189 (defun org-move-subtree-up (&optional arg)
5190 "Move the current subtree up past ARG headlines of the same level."
5191 (interactive "p")
5192 (org-move-subtree-down (- (prefix-numeric-value arg))))
5194 (defun org-move-subtree-down (&optional arg)
5195 "Move the current subtree down past ARG headlines of the same level."
5196 (interactive "p")
5197 (setq arg (prefix-numeric-value arg))
5198 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5199 'outline-get-last-sibling))
5200 (ins-point (make-marker))
5201 (cnt (abs arg))
5202 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5203 ;; Select the tree
5204 (org-back-to-heading)
5205 (setq beg0 (point))
5206 (save-excursion
5207 (setq ne-beg (org-back-over-empty-lines))
5208 (setq beg (point)))
5209 (save-match-data
5210 (save-excursion (outline-end-of-heading)
5211 (setq folded (org-invisible-p)))
5212 (outline-end-of-subtree))
5213 (outline-next-heading)
5214 (setq ne-end (org-back-over-empty-lines))
5215 (setq end (point))
5216 (goto-char beg0)
5217 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5218 ;; include less whitespace
5219 (save-excursion
5220 (goto-char beg)
5221 (forward-line (- ne-beg ne-end))
5222 (setq beg (point))))
5223 ;; Find insertion point, with error handling
5224 (while (> cnt 0)
5225 (or (and (funcall movfunc) (looking-at outline-regexp))
5226 (progn (goto-char beg0)
5227 (error "Cannot move past superior level or buffer limit")))
5228 (setq cnt (1- cnt)))
5229 (if (> arg 0)
5230 ;; Moving forward - still need to move over subtree
5231 (progn (org-end-of-subtree t t)
5232 (save-excursion
5233 (org-back-over-empty-lines)
5234 (or (bolp) (newline)))))
5235 (setq ne-ins (org-back-over-empty-lines))
5236 (move-marker ins-point (point))
5237 (setq txt (buffer-substring beg end))
5238 (org-save-markers-in-region beg end)
5239 (delete-region beg end)
5240 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5241 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5242 (let ((bbb (point)))
5243 (insert-before-markers txt)
5244 (org-reinstall-markers-in-region bbb)
5245 (move-marker ins-point bbb))
5246 (or (bolp) (insert "\n"))
5247 (setq ins-end (point))
5248 (goto-char ins-point)
5249 (org-skip-whitespace)
5250 (when (and (< arg 0)
5251 (org-first-sibling-p)
5252 (> ne-ins ne-beg))
5253 ;; Move whitespace back to beginning
5254 (save-excursion
5255 (goto-char ins-end)
5256 (let ((kill-whole-line t))
5257 (kill-line (- ne-ins ne-beg)) (point)))
5258 (insert (make-string (- ne-ins ne-beg) ?\n)))
5259 (move-marker ins-point nil)
5260 (org-compact-display-after-subtree-move)
5261 (org-show-empty-lines-in-parent)
5262 (unless folded
5263 (org-show-entry)
5264 (show-children)
5265 (org-cycle-hide-drawers 'children))))
5267 (defvar org-subtree-clip ""
5268 "Clipboard for cut and paste of subtrees.
5269 This is actually only a copy of the kill, because we use the normal kill
5270 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5272 (defvar org-subtree-clip-folded nil
5273 "Was the last copied subtree folded?
5274 This is used to fold the tree back after pasting.")
5276 (defun org-cut-subtree (&optional n)
5277 "Cut the current subtree into the clipboard.
5278 With prefix arg N, cut this many sequential subtrees.
5279 This is a short-hand for marking the subtree and then cutting it."
5280 (interactive "p")
5281 (org-copy-subtree n 'cut))
5283 (defun org-copy-subtree (&optional n cut force-store-markers)
5284 "Cut the current subtree into the clipboard.
5285 With prefix arg N, cut this many sequential subtrees.
5286 This is a short-hand for marking the subtree and then copying it.
5287 If CUT is non-nil, actually cut the subtree.
5288 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5289 of some markers in the region, even if CUT is non-nil. This is
5290 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5291 (interactive "p")
5292 (let (beg end folded (beg0 (point)))
5293 (if (interactive-p)
5294 (org-back-to-heading nil) ; take what looks like a subtree
5295 (org-back-to-heading t)) ; take what is really there
5296 (org-back-over-empty-lines)
5297 (setq beg (point))
5298 (skip-chars-forward " \t\r\n")
5299 (save-match-data
5300 (save-excursion (outline-end-of-heading)
5301 (setq folded (org-invisible-p)))
5302 (condition-case nil
5303 (outline-forward-same-level (1- n))
5304 (error nil))
5305 (org-end-of-subtree t t))
5306 (org-back-over-empty-lines)
5307 (setq end (point))
5308 (goto-char beg0)
5309 (when (> end beg)
5310 (setq org-subtree-clip-folded folded)
5311 (when (or cut force-store-markers)
5312 (org-save-markers-in-region beg end))
5313 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5314 (setq org-subtree-clip (current-kill 0))
5315 (message "%s: Subtree(s) with %d characters"
5316 (if cut "Cut" "Copied")
5317 (length org-subtree-clip)))))
5319 (defun org-paste-subtree (&optional level tree for-yank)
5320 "Paste the clipboard as a subtree, with modification of headline level.
5321 The entire subtree is promoted or demoted in order to match a new headline
5322 level.
5324 If the cursor is at the beginning of a headline, the same level as
5325 that headline is used to paste the tree
5327 If not, the new level is derived from the *visible* headings
5328 before and after the insertion point, and taken to be the inferior headline
5329 level of the two. So if the previous visible heading is level 3 and the
5330 next is level 4 (or vice versa), level 4 will be used for insertion.
5331 This makes sure that the subtree remains an independent subtree and does
5332 not swallow low level entries.
5334 You can also force a different level, either by using a numeric prefix
5335 argument, or by inserting the heading marker by hand. For example, if the
5336 cursor is after \"*****\", then the tree will be shifted to level 5.
5338 If optional TREE is given, use this text instead of the kill ring.
5340 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5341 move back over whitespace before inserting, and move point to the end of
5342 the inserted text when done."
5343 (interactive "P")
5344 (unless (org-kill-is-subtree-p tree)
5345 (error "%s"
5346 (substitute-command-keys
5347 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5348 (let* ((visp (not (org-invisible-p)))
5349 (txt (or tree (and kill-ring (current-kill 0))))
5350 (^re (concat "^\\(" outline-regexp "\\)"))
5351 (re (concat "\\(" outline-regexp "\\)"))
5352 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5354 (old-level (if (string-match ^re txt)
5355 (- (match-end 0) (match-beginning 0) 1)
5356 -1))
5357 (force-level (cond (level (prefix-numeric-value level))
5358 ((and (looking-at "[ \t]*$")
5359 (string-match
5360 ^re_ (buffer-substring
5361 (point-at-bol) (point))))
5362 (- (match-end 1) (match-beginning 1)))
5363 ((and (bolp)
5364 (looking-at org-outline-regexp))
5365 (- (match-end 0) (point) 1))
5366 (t nil)))
5367 (previous-level (save-excursion
5368 (condition-case nil
5369 (progn
5370 (outline-previous-visible-heading 1)
5371 (if (looking-at re)
5372 (- (match-end 0) (match-beginning 0) 1)
5374 (error 1))))
5375 (next-level (save-excursion
5376 (condition-case nil
5377 (progn
5378 (or (looking-at outline-regexp)
5379 (outline-next-visible-heading 1))
5380 (if (looking-at re)
5381 (- (match-end 0) (match-beginning 0) 1)
5383 (error 1))))
5384 (new-level (or force-level (max previous-level next-level)))
5385 (shift (if (or (= old-level -1)
5386 (= new-level -1)
5387 (= old-level new-level))
5389 (- new-level old-level)))
5390 (delta (if (> shift 0) -1 1))
5391 (func (if (> shift 0) 'org-demote 'org-promote))
5392 (org-odd-levels-only nil)
5393 beg end newend)
5394 ;; Remove the forced level indicator
5395 (if force-level
5396 (delete-region (point-at-bol) (point)))
5397 ;; Paste
5398 (beginning-of-line 1)
5399 (unless for-yank (org-back-over-empty-lines))
5400 (setq beg (point))
5401 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5402 (insert-before-markers txt)
5403 (unless (string-match "\n\\'" txt) (insert "\n"))
5404 (setq newend (point))
5405 (org-reinstall-markers-in-region beg)
5406 (setq end (point))
5407 (goto-char beg)
5408 (skip-chars-forward " \t\n\r")
5409 (setq beg (point))
5410 (if (and (org-invisible-p) visp)
5411 (save-excursion (outline-show-heading)))
5412 ;; Shift if necessary
5413 (unless (= shift 0)
5414 (save-restriction
5415 (narrow-to-region beg end)
5416 (while (not (= shift 0))
5417 (org-map-region func (point-min) (point-max))
5418 (setq shift (+ delta shift)))
5419 (goto-char (point-min))
5420 (setq newend (point-max))))
5421 (when (or (interactive-p) for-yank)
5422 (message "Clipboard pasted as level %d subtree" new-level))
5423 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5424 kill-ring
5425 (eq org-subtree-clip (current-kill 0))
5426 org-subtree-clip-folded)
5427 ;; The tree was folded before it was killed/copied
5428 (hide-subtree))
5429 (and for-yank (goto-char newend))))
5431 (defun org-kill-is-subtree-p (&optional txt)
5432 "Check if the current kill is an outline subtree, or a set of trees.
5433 Returns nil if kill does not start with a headline, or if the first
5434 headline level is not the largest headline level in the tree.
5435 So this will actually accept several entries of equal levels as well,
5436 which is OK for `org-paste-subtree'.
5437 If optional TXT is given, check this string instead of the current kill."
5438 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5439 (start-level (and kill
5440 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5441 org-outline-regexp "\\)")
5442 kill)
5443 (- (match-end 2) (match-beginning 2) 1)))
5444 (re (concat "^" org-outline-regexp))
5445 (start (1+ (or (match-beginning 2) -1))))
5446 (if (not start-level)
5447 (progn
5448 nil) ;; does not even start with a heading
5449 (catch 'exit
5450 (while (setq start (string-match re kill (1+ start)))
5451 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5452 (throw 'exit nil)))
5453 t))))
5455 (defvar org-markers-to-move nil
5456 "Markers that should be moved with a cut-and-paste operation.
5457 Those markers are stored together with their positions relative to
5458 the start of the region.")
5460 (defun org-save-markers-in-region (beg end)
5461 "Check markers in region.
5462 If these markers are between BEG and END, record their position relative
5463 to BEG, so that after moving the block of text, we can put the markers back
5464 into place.
5465 This function gets called just before an entry or tree gets cut from the
5466 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5467 called immediately, to move the markers with the entries."
5468 (setq org-markers-to-move nil)
5469 (when (featurep 'org-clock)
5470 (org-clock-save-markers-for-cut-and-paste beg end))
5471 (when (featurep 'org-agenda)
5472 (org-agenda-save-markers-for-cut-and-paste beg end)))
5474 (defun org-check-and-save-marker (marker beg end)
5475 "Check if MARKER is between BEG and END.
5476 If yes, remember the marker and the distance to BEG."
5477 (when (and (marker-buffer marker)
5478 (equal (marker-buffer marker) (current-buffer)))
5479 (if (and (>= marker beg) (< marker end))
5480 (push (cons marker (- marker beg)) org-markers-to-move))))
5482 (defun org-reinstall-markers-in-region (beg)
5483 "Move all remembered markers to their position relative to BEG."
5484 (mapc (lambda (x)
5485 (move-marker (car x) (+ beg (cdr x))))
5486 org-markers-to-move)
5487 (setq org-markers-to-move nil))
5489 (defun org-narrow-to-subtree ()
5490 "Narrow buffer to the current subtree."
5491 (interactive)
5492 (save-excursion
5493 (save-match-data
5494 (narrow-to-region
5495 (progn (org-back-to-heading) (point))
5496 (progn (org-end-of-subtree t) (point))))))
5499 ;;; Outline Sorting
5501 (defun org-sort (with-case)
5502 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5503 Optional argument WITH-CASE means sort case-sensitively."
5504 (interactive "P")
5505 (if (org-at-table-p)
5506 (org-call-with-arg 'org-table-sort-lines with-case)
5507 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5509 (defun org-sort-remove-invisible (s)
5510 (remove-text-properties 0 (length s) org-rm-props s)
5511 (while (string-match org-bracket-link-regexp s)
5512 (setq s (replace-match (if (match-end 2)
5513 (match-string 3 s)
5514 (match-string 1 s)) t t s)))
5517 (defvar org-priority-regexp) ; defined later in the file
5519 (defun org-sort-entries-or-items
5520 (&optional with-case sorting-type getkey-func compare-func property)
5521 "Sort entries on a certain level of an outline tree.
5522 If there is an active region, the entries in the region are sorted.
5523 Else, if the cursor is before the first entry, sort the top-level items.
5524 Else, the children of the entry at point are sorted.
5526 Sorting can be alphabetically, numerically, and by date/time as given by
5527 the first time stamp in the entry. The command prompts for the sorting
5528 type unless it has been given to the function through the SORTING-TYPE
5529 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5530 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5531 called with point at the beginning of the record. It must return either
5532 a string or a number that should serve as the sorting key for that record.
5534 Comparing entries ignores case by default. However, with an optional argument
5535 WITH-CASE, the sorting considers case as well."
5536 (interactive "P")
5537 (let ((case-func (if with-case 'identity 'downcase))
5538 start beg end stars re re2
5539 txt what tmp plain-list-p)
5540 ;; Find beginning and end of region to sort
5541 (cond
5542 ((org-region-active-p)
5543 ;; we will sort the region
5544 (setq end (region-end)
5545 what "region")
5546 (goto-char (region-beginning))
5547 (if (not (org-on-heading-p)) (outline-next-heading))
5548 (setq start (point)))
5549 ((org-at-item-p)
5550 ;; we will sort this plain list
5551 (org-beginning-of-item-list) (setq start (point))
5552 (org-end-of-item-list) (setq end (point))
5553 (goto-char start)
5554 (setq plain-list-p t
5555 what "plain list"))
5556 ((or (org-on-heading-p)
5557 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5558 ;; we will sort the children of the current headline
5559 (org-back-to-heading)
5560 (setq start (point)
5561 end (progn (org-end-of-subtree t t)
5562 (org-back-over-empty-lines)
5563 (point))
5564 what "children")
5565 (goto-char start)
5566 (show-subtree)
5567 (outline-next-heading))
5569 ;; we will sort the top-level entries in this file
5570 (goto-char (point-min))
5571 (or (org-on-heading-p) (outline-next-heading))
5572 (setq start (point) end (point-max) what "top-level")
5573 (goto-char start)
5574 (show-all)))
5576 (setq beg (point))
5577 (if (>= beg end) (error "Nothing to sort"))
5579 (unless plain-list-p
5580 (looking-at "\\(\\*+\\)")
5581 (setq stars (match-string 1)
5582 re (concat "^" (regexp-quote stars) " +")
5583 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5584 txt (buffer-substring beg end))
5585 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5586 (if (and (not (equal stars "*")) (string-match re2 txt))
5587 (error "Region to sort contains a level above the first entry")))
5589 (unless sorting-type
5590 (message
5591 (if plain-list-p
5592 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5593 "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:")
5594 what)
5595 (setq sorting-type (read-char-exclusive))
5597 (and (= (downcase sorting-type) ?f)
5598 (setq getkey-func
5599 (org-ido-completing-read "Sort using function: "
5600 obarray 'fboundp t nil nil))
5601 (setq getkey-func (intern getkey-func)))
5603 (and (= (downcase sorting-type) ?r)
5604 (setq property
5605 (org-ido-completing-read "Property: "
5606 (mapcar 'list (org-buffer-property-keys t))
5607 nil t))))
5609 (message "Sorting entries...")
5611 (save-restriction
5612 (narrow-to-region start end)
5614 (let ((dcst (downcase sorting-type))
5615 (now (current-time)))
5616 (sort-subr
5617 (/= dcst sorting-type)
5618 ;; This function moves to the beginning character of the "record" to
5619 ;; be sorted.
5620 (if plain-list-p
5621 (lambda nil
5622 (if (org-at-item-p) t (goto-char (point-max))))
5623 (lambda nil
5624 (if (re-search-forward re nil t)
5625 (goto-char (match-beginning 0))
5626 (goto-char (point-max)))))
5627 ;; This function moves to the last character of the "record" being
5628 ;; sorted.
5629 (if plain-list-p
5630 'org-end-of-item
5631 (lambda nil
5632 (save-match-data
5633 (condition-case nil
5634 (outline-forward-same-level 1)
5635 (error
5636 (goto-char (point-max)))))))
5638 ;; This function returns the value that gets sorted against.
5639 (if plain-list-p
5640 (lambda nil
5641 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5642 (cond
5643 ((= dcst ?n)
5644 (string-to-number (buffer-substring (match-end 0)
5645 (point-at-eol))))
5646 ((= dcst ?a)
5647 (buffer-substring (match-end 0) (point-at-eol)))
5648 ((= dcst ?t)
5649 (if (re-search-forward org-ts-regexp
5650 (point-at-eol) t)
5651 (org-time-string-to-time (match-string 0))
5652 now))
5653 ((= dcst ?f)
5654 (if getkey-func
5655 (progn
5656 (setq tmp (funcall getkey-func))
5657 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5658 tmp)
5659 (error "Invalid key function `%s'" getkey-func)))
5660 (t (error "Invalid sorting type `%c'" sorting-type)))))
5661 (lambda nil
5662 (cond
5663 ((= dcst ?n)
5664 (if (looking-at org-complex-heading-regexp)
5665 (string-to-number (match-string 4))
5666 nil))
5667 ((= dcst ?a)
5668 (if (looking-at org-complex-heading-regexp)
5669 (funcall case-func (match-string 4))
5670 nil))
5671 ((= dcst ?t)
5672 (if (re-search-forward org-ts-regexp
5673 (save-excursion
5674 (forward-line 2)
5675 (point)) t)
5676 (org-time-string-to-time (match-string 0))
5677 now))
5678 ((= dcst ?p)
5679 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5680 (string-to-char (match-string 2))
5681 org-default-priority))
5682 ((= dcst ?r)
5683 (or (org-entry-get nil property) ""))
5684 ((= dcst ?o)
5685 (if (looking-at org-complex-heading-regexp)
5686 (- 9999 (length (member (match-string 2)
5687 org-todo-keywords-1)))))
5688 ((= dcst ?f)
5689 (if getkey-func
5690 (progn
5691 (setq tmp (funcall getkey-func))
5692 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5693 tmp)
5694 (error "Invalid key function `%s'" getkey-func)))
5695 (t (error "Invalid sorting type `%c'" sorting-type)))))
5697 (cond
5698 ((= dcst ?a) 'string<)
5699 ((= dcst ?t) 'time-less-p)
5700 ((= dcst ?f) compare-func)
5701 (t nil)))))
5702 (message "Sorting entries...done")))
5704 (defun org-do-sort (table what &optional with-case sorting-type)
5705 "Sort TABLE of WHAT according to SORTING-TYPE.
5706 The user will be prompted for the SORTING-TYPE if the call to this
5707 function does not specify it. WHAT is only for the prompt, to indicate
5708 what is being sorted. The sorting key will be extracted from
5709 the car of the elements of the table.
5710 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5711 (unless sorting-type
5712 (message
5713 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5714 what)
5715 (setq sorting-type (read-char-exclusive)))
5716 (let ((dcst (downcase sorting-type))
5717 extractfun comparefun)
5718 ;; Define the appropriate functions
5719 (cond
5720 ((= dcst ?n)
5721 (setq extractfun 'string-to-number
5722 comparefun (if (= dcst sorting-type) '< '>)))
5723 ((= dcst ?a)
5724 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5725 (lambda(x) (downcase (org-sort-remove-invisible x))))
5726 comparefun (if (= dcst sorting-type)
5727 'string<
5728 (lambda (a b) (and (not (string< a b))
5729 (not (string= a b)))))))
5730 ((= dcst ?t)
5731 (setq extractfun
5732 (lambda (x)
5733 (if (string-match org-ts-regexp x)
5734 (time-to-seconds
5735 (org-time-string-to-time (match-string 0 x)))
5737 comparefun (if (= dcst sorting-type) '< '>)))
5738 (t (error "Invalid sorting type `%c'" sorting-type)))
5740 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5741 table)
5742 (lambda (a b) (funcall comparefun (car a) (car b))))))
5744 ;;; Editing source examples
5746 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5747 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5748 (defvar org-edit-src-force-single-line nil)
5749 (defvar org-edit-src-from-org-mode nil)
5750 (defvar org-edit-src-picture nil)
5752 (define-minor-mode org-exit-edit-mode
5753 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5755 (defun org-edit-src-code ()
5756 "Edit the source code example at point.
5757 An indirect buffer is created, and that buffer is then narrowed to the
5758 example at point and switched to the correct language mode. When done,
5759 exit by killing the buffer with \\[org-edit-src-exit]."
5760 (interactive)
5761 (let ((line (org-current-line))
5762 (case-fold-search t)
5763 (msg (substitute-command-keys
5764 "Edit, then exit with C-c ' (C-c and single quote)"))
5765 (info (org-edit-src-find-region-and-lang))
5766 (org-mode-p (eq major-mode 'org-mode))
5767 beg end lang lang-f single lfmt)
5768 (if (not info)
5770 (setq beg (nth 0 info)
5771 end (nth 1 info)
5772 lang (nth 2 info)
5773 single (nth 3 info)
5774 lfmt (nth 4 info)
5775 lang-f (intern (concat lang "-mode")))
5776 (unless (functionp lang-f)
5777 (error "No such language mode: %s" lang-f))
5778 (goto-line line)
5779 (if (get-buffer "*Org Edit Src Example*")
5780 (kill-buffer "*Org Edit Src Example*"))
5781 (switch-to-buffer (make-indirect-buffer (current-buffer)
5782 "*Org Edit Src Example*"))
5783 (narrow-to-region beg end)
5784 (remove-text-properties beg end '(display nil invisible nil
5785 intangible nil))
5786 (let ((org-inhibit-startup t))
5787 (funcall lang-f))
5788 (set (make-local-variable 'org-edit-src-force-single-line) single)
5789 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5790 (when lfmt
5791 (set (make-local-variable 'org-coderef-label-format) lfmt))
5792 (when org-mode-p
5793 (goto-char (point-min))
5794 (while (re-search-forward "^," nil t)
5795 (replace-match "")))
5796 (goto-line line)
5797 (org-exit-edit-mode)
5798 (org-set-local 'header-line-format msg)
5799 (message "%s" msg)
5800 t)))
5802 (defun org-edit-fixed-width-region ()
5803 "Edit the fixed-width ascii drawing at point.
5804 This must be a region where each line starts with a colon followed by
5805 a space character.
5806 An indirect buffer is created, and that buffer is then narrowed to the
5807 example at point and switched to artist-mode. When done,
5808 exit by killing the buffer with \\[org-edit-src-exit]."
5809 (interactive)
5810 (let ((line (org-current-line))
5811 (case-fold-search t)
5812 (msg (substitute-command-keys
5813 "Edit, then exit with C-c ' (C-c and single quote)"))
5814 (org-mode-p (eq major-mode 'org-mode))
5815 beg end lang lang-f)
5816 (beginning-of-line 1)
5817 (if (looking-at "[ \t]*[^:\n \t]")
5819 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5820 (setq beg (point) end beg)
5821 (save-excursion
5822 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5823 (setq beg (point-at-bol 2))
5824 (setq beg (point))))
5825 (save-excursion
5826 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5827 (setq end (1- (match-beginning 0)))
5828 (setq end (point))))
5829 (goto-line line))
5830 (if (get-buffer "*Org Edit Picture*")
5831 (kill-buffer "*Org Edit Picture*"))
5832 (switch-to-buffer (make-indirect-buffer (current-buffer)
5833 "*Org Edit Picture*"))
5834 (narrow-to-region beg end)
5835 (remove-text-properties beg end '(display nil invisible nil
5836 intangible nil))
5837 (when (fboundp 'font-lock-unfontify-region)
5838 (font-lock-unfontify-region (point-min) (point-max)))
5839 (cond
5840 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5841 (fundamental-mode)
5842 (artist-mode 1))
5843 (t (funcall org-edit-fixed-width-region-mode)))
5844 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5845 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5846 (set (make-local-variable 'org-edit-src-picture) t)
5847 (goto-char (point-min))
5848 (while (re-search-forward "^[ \t]*: ?" nil t)
5849 (replace-match ""))
5850 (goto-line line)
5851 (org-exit-edit-mode)
5852 (org-set-local 'header-line-format msg)
5853 (message "%s" msg)
5854 t)))
5857 (defun org-edit-src-find-region-and-lang ()
5858 "Find the region and language for a local edit.
5859 Return a list with beginning and end of the region, a string representing
5860 the language, a switch telling of the content should be in a single line."
5861 (let ((re-list
5862 (append
5863 org-edit-src-region-extra
5865 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5866 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5867 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5868 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5869 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5870 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5871 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5872 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5873 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5874 ("^#\\+html:" "\n" "html" single-line)
5875 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5876 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5877 ("^#\\+latex:" "\n" "latex" single-line)
5878 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5879 ("^#\\+ascii:" "\n" "ascii" single-line)
5881 (pos (point))
5882 re re1 re2 single beg end lang lfmt match-re1)
5883 (catch 'exit
5884 (while (setq entry (pop re-list))
5885 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5886 single (nth 3 entry))
5887 (save-excursion
5888 (if (or (looking-at re1)
5889 (re-search-backward re1 nil t))
5890 (progn
5891 (setq match-re1 (match-string 0))
5892 (setq beg (match-end 0)
5893 lang (org-edit-src-get-lang lang)
5894 lfmt (org-edit-src-get-label-format match-re1))
5895 (if (and (re-search-forward re2 nil t)
5896 (>= (match-end 0) pos))
5897 (throw 'exit (list beg (match-beginning 0)
5898 lang single lfmt))))
5899 (if (or (looking-at re2)
5900 (re-search-forward re2 nil t))
5901 (progn
5902 (setq end (match-beginning 0))
5903 (if (and (re-search-backward re1 nil t)
5904 (<= (match-beginning 0) pos))
5905 (progn
5906 (setq lfmt (org-edit-src-get-label-format
5907 (match-string 0)))
5908 (throw 'exit
5909 (list (match-end 0) end
5910 (org-edit-src-get-lang lang)
5911 single lfmt))))))))))))
5913 (defun org-edit-src-get-lang (lang)
5914 "Extract the src language."
5915 (let ((m (match-string 0)))
5916 (cond
5917 ((stringp lang) lang)
5918 ((integerp lang) (match-string lang))
5919 ((and (eq lang 'lang)
5920 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5921 (match-string 1 m))
5922 ((and (eq lang 'style)
5923 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5924 (match-string 1 m))
5925 (t "fundamental"))))
5927 (defun org-edit-src-get-label-format (s)
5928 "Extract the label format."
5929 (save-match-data
5930 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
5931 (match-string 1 s))))
5933 (defun org-edit-src-exit ()
5934 "Exit special edit and protect problematic lines."
5935 (interactive)
5936 (unless (buffer-base-buffer (current-buffer))
5937 (error "This is not an indirect buffer, something is wrong..."))
5938 (unless (> (point-min) 1)
5939 (error "This buffer is not narrowed, something is wrong..."))
5940 (goto-char (point-min))
5941 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5942 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5943 (when (org-bound-and-true-p org-edit-src-force-single-line)
5944 (goto-char (point-min))
5945 (while (re-search-forward "\n" nil t)
5946 (replace-match " "))
5947 (goto-char (point-min))
5948 (if (looking-at "\\s-*") (replace-match " "))
5949 (if (re-search-forward "\\s-+\\'" nil t)
5950 (replace-match "")))
5951 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5952 (goto-char (point-min))
5953 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5954 (replace-match ",\\1"))
5955 (when font-lock-mode
5956 (font-lock-unfontify-region (point-min) (point-max)))
5957 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5958 (when (org-bound-and-true-p org-edit-src-picture)
5959 (untabify (point-min) (point-max))
5960 (goto-char (point-min))
5961 (while (re-search-forward "^" nil t)
5962 (replace-match ": "))
5963 (when font-lock-mode
5964 (font-lock-unfontify-region (point-min) (point-max)))
5965 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5966 (kill-buffer (current-buffer))
5967 (and (org-mode-p) (org-restart-font-lock)))
5970 ;;; The orgstruct minor mode
5972 ;; Define a minor mode which can be used in other modes in order to
5973 ;; integrate the org-mode structure editing commands.
5975 ;; This is really a hack, because the org-mode structure commands use
5976 ;; keys which normally belong to the major mode. Here is how it
5977 ;; works: The minor mode defines all the keys necessary to operate the
5978 ;; structure commands, but wraps the commands into a function which
5979 ;; tests if the cursor is currently at a headline or a plain list
5980 ;; item. If that is the case, the structure command is used,
5981 ;; temporarily setting many Org-mode variables like regular
5982 ;; expressions for filling etc. However, when any of those keys is
5983 ;; used at a different location, function uses `key-binding' to look
5984 ;; up if the key has an associated command in another currently active
5985 ;; keymap (minor modes, major mode, global), and executes that
5986 ;; command. There might be problems if any of the keys is otherwise
5987 ;; used as a prefix key.
5989 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5990 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5991 ;; addresses this by checking explicitly for both bindings.
5993 (defvar orgstruct-mode-map (make-sparse-keymap)
5994 "Keymap for the minor `orgstruct-mode'.")
5996 (defvar org-local-vars nil
5997 "List of local variables, for use by `orgstruct-mode'")
5999 ;;;###autoload
6000 (define-minor-mode orgstruct-mode
6001 "Toggle the minor more `orgstruct-mode'.
6002 This mode is for using Org-mode structure commands in other modes.
6003 The following key behave as if Org-mode was active, if the cursor
6004 is on a headline, or on a plain list item (both in the definition
6005 of Org-mode).
6007 M-up Move entry/item up
6008 M-down Move entry/item down
6009 M-left Promote
6010 M-right Demote
6011 M-S-up Move entry/item up
6012 M-S-down Move entry/item down
6013 M-S-left Promote subtree
6014 M-S-right Demote subtree
6015 M-q Fill paragraph and items like in Org-mode
6016 C-c ^ Sort entries
6017 C-c - Cycle list bullet
6018 TAB Cycle item visibility
6019 M-RET Insert new heading/item
6020 S-M-RET Insert new TODO heading / Checkbox item
6021 C-c C-c Set tags / toggle checkbox"
6022 nil " OrgStruct" nil
6023 (org-load-modules-maybe)
6024 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6026 ;;;###autoload
6027 (defun turn-on-orgstruct ()
6028 "Unconditionally turn on `orgstruct-mode'."
6029 (orgstruct-mode 1))
6031 ;;;###autoload
6032 (defun turn-on-orgstruct++ ()
6033 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6034 In addition to setting orgstruct-mode, this also exports all indentation and
6035 autofilling variables from org-mode into the buffer. Note that turning
6036 off orgstruct-mode will *not* remove these additional settings."
6037 (orgstruct-mode 1)
6038 (let (var val)
6039 (mapc
6040 (lambda (x)
6041 (when (string-match
6042 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6043 (symbol-name (car x)))
6044 (setq var (car x) val (nth 1 x))
6045 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6046 org-local-vars)))
6048 (defun orgstruct-error ()
6049 "Error when there is no default binding for a structure key."
6050 (interactive)
6051 (error "This key has no function outside structure elements"))
6053 (defun orgstruct-setup ()
6054 "Setup orgstruct keymaps."
6055 (let ((nfunc 0)
6056 (bindings
6057 (list
6058 '([(meta up)] org-metaup)
6059 '([(meta down)] org-metadown)
6060 '([(meta left)] org-metaleft)
6061 '([(meta right)] org-metaright)
6062 '([(meta shift up)] org-shiftmetaup)
6063 '([(meta shift down)] org-shiftmetadown)
6064 '([(meta shift left)] org-shiftmetaleft)
6065 '([(meta shift right)] org-shiftmetaright)
6066 '([(shift up)] org-shiftup)
6067 '([(shift down)] org-shiftdown)
6068 '([(shift left)] org-shiftleft)
6069 '([(shift right)] org-shiftright)
6070 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6071 '("\M-q" fill-paragraph)
6072 '("\C-c^" org-sort)
6073 '("\C-c-" org-cycle-list-bullet)))
6074 elt key fun cmd)
6075 (while (setq elt (pop bindings))
6076 (setq nfunc (1+ nfunc))
6077 (setq key (org-key (car elt))
6078 fun (nth 1 elt)
6079 cmd (orgstruct-make-binding fun nfunc key))
6080 (org-defkey orgstruct-mode-map key cmd))
6082 ;; Special treatment needed for TAB and RET
6083 (org-defkey orgstruct-mode-map [(tab)]
6084 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6085 (org-defkey orgstruct-mode-map "\C-i"
6086 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6088 (org-defkey orgstruct-mode-map "\M-\C-m"
6089 (orgstruct-make-binding 'org-insert-heading 105
6090 "\M-\C-m" [(meta return)]))
6091 (org-defkey orgstruct-mode-map [(meta return)]
6092 (orgstruct-make-binding 'org-insert-heading 106
6093 [(meta return)] "\M-\C-m"))
6095 (org-defkey orgstruct-mode-map [(shift meta return)]
6096 (orgstruct-make-binding 'org-insert-todo-heading 107
6097 [(meta return)] "\M-\C-m"))
6099 (unless org-local-vars
6100 (setq org-local-vars (org-get-local-variables)))
6104 (defun orgstruct-make-binding (fun n &rest keys)
6105 "Create a function for binding in the structure minor mode.
6106 FUN is the command to call inside a table. N is used to create a unique
6107 command name. KEYS are keys that should be checked in for a command
6108 to execute outside of tables."
6109 (eval
6110 (list 'defun
6111 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6112 '(arg)
6113 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6114 "Outside of structure, run the binding of `"
6115 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6116 "'.")
6117 '(interactive "p")
6118 (list 'if
6119 '(org-context-p 'headline 'item)
6120 (list 'org-run-like-in-org-mode (list 'quote fun))
6121 (list 'let '(orgstruct-mode)
6122 (list 'call-interactively
6123 (append '(or)
6124 (mapcar (lambda (k)
6125 (list 'key-binding k))
6126 keys)
6127 '('orgstruct-error))))))))
6129 (defun org-context-p (&rest contexts)
6130 "Check if local context is any of CONTEXTS.
6131 Possible values in the list of contexts are `table', `headline', and `item'."
6132 (let ((pos (point)))
6133 (goto-char (point-at-bol))
6134 (prog1 (or (and (memq 'table contexts)
6135 (looking-at "[ \t]*|"))
6136 (and (memq 'headline contexts)
6137 ;;????????? (looking-at "\\*+"))
6138 (looking-at outline-regexp))
6139 (and (memq 'item contexts)
6140 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6141 (goto-char pos))))
6143 (defun org-get-local-variables ()
6144 "Return a list of all local variables in an org-mode buffer."
6145 (let (varlist)
6146 (with-current-buffer (get-buffer-create "*Org tmp*")
6147 (erase-buffer)
6148 (org-mode)
6149 (setq varlist (buffer-local-variables)))
6150 (kill-buffer "*Org tmp*")
6151 (delq nil
6152 (mapcar
6153 (lambda (x)
6154 (setq x
6155 (if (symbolp x)
6156 (list x)
6157 (list (car x) (list 'quote (cdr x)))))
6158 (if (string-match
6159 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6160 (symbol-name (car x)))
6161 x nil))
6162 varlist))))
6164 ;;;###autoload
6165 (defun org-run-like-in-org-mode (cmd)
6166 (org-load-modules-maybe)
6167 (unless org-local-vars
6168 (setq org-local-vars (org-get-local-variables)))
6169 (eval (list 'let org-local-vars
6170 (list 'call-interactively (list 'quote cmd)))))
6172 ;;;; Archiving
6174 (defun org-get-category (&optional pos)
6175 "Get the category applying to position POS."
6176 (get-text-property (or pos (point)) 'org-category))
6178 (defun org-refresh-category-properties ()
6179 "Refresh category text properties in the buffer."
6180 (let ((def-cat (cond
6181 ((null org-category)
6182 (if buffer-file-name
6183 (file-name-sans-extension
6184 (file-name-nondirectory buffer-file-name))
6185 "???"))
6186 ((symbolp org-category) (symbol-name org-category))
6187 (t org-category)))
6188 beg end cat pos optionp)
6189 (org-unmodified
6190 (save-excursion
6191 (save-restriction
6192 (widen)
6193 (goto-char (point-min))
6194 (put-text-property (point) (point-max) 'org-category def-cat)
6195 (while (re-search-forward
6196 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6197 (setq pos (match-end 0)
6198 optionp (equal (char-after (match-beginning 0)) ?#)
6199 cat (org-trim (match-string 2)))
6200 (if optionp
6201 (setq beg (point-at-bol) end (point-max))
6202 (org-back-to-heading t)
6203 (setq beg (point) end (org-end-of-subtree t t)))
6204 (put-text-property beg end 'org-category cat)
6205 (goto-char pos)))))))
6208 ;;;; Link Stuff
6210 ;;; Link abbreviations
6212 (defun org-link-expand-abbrev (link)
6213 "Apply replacements as defined in `org-link-abbrev-alist."
6214 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6215 (let* ((key (match-string 1 link))
6216 (as (or (assoc key org-link-abbrev-alist-local)
6217 (assoc key org-link-abbrev-alist)))
6218 (tag (and (match-end 2) (match-string 3 link)))
6219 rpl)
6220 (if (not as)
6221 link
6222 (setq rpl (cdr as))
6223 (cond
6224 ((symbolp rpl) (funcall rpl tag))
6225 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6226 ((string-match "%h" rpl)
6227 (replace-match (url-hexify-string (or tag "")) t t rpl))
6228 (t (concat rpl tag)))))
6229 link))
6231 ;;; Storing and inserting links
6233 (defvar org-insert-link-history nil
6234 "Minibuffer history for links inserted with `org-insert-link'.")
6236 (defvar org-stored-links nil
6237 "Contains the links stored with `org-store-link'.")
6239 (defvar org-store-link-plist nil
6240 "Plist with info about the most recently link created with `org-store-link'.")
6242 (defvar org-link-protocols nil
6243 "Link protocols added to Org-mode using `org-add-link-type'.")
6245 (defvar org-store-link-functions nil
6246 "List of functions that are called to create and store a link.
6247 Each function will be called in turn until one returns a non-nil
6248 value. Each function should check if it is responsible for creating
6249 this link (for example by looking at the major mode).
6250 If not, it must exit and return nil.
6251 If yes, it should return a non-nil value after a calling
6252 `org-store-link-props' with a list of properties and values.
6253 Special properties are:
6255 :type The link prefix. like \"http\". This must be given.
6256 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6257 This is obligatory as well.
6258 :description Optional default description for the second pair
6259 of brackets in an Org-mode link. The user can still change
6260 this when inserting this link into an Org-mode buffer.
6262 In addition to these, any additional properties can be specified
6263 and then used in remember templates.")
6265 (defun org-add-link-type (type &optional follow export)
6266 "Add TYPE to the list of `org-link-types'.
6267 Re-compute all regular expressions depending on `org-link-types'
6269 FOLLOW and EXPORT are two functions.
6271 FOLLOW should take the link path as the single argument and do whatever
6272 is necessary to follow the link, for example find a file or display
6273 a mail message.
6275 EXPORT should format the link path for export to one of the export formats.
6276 It should be a function accepting three arguments:
6278 path the path of the link, the text after the prefix (like \"http:\")
6279 desc the description of the link, if any, nil if there was no description
6280 format the export format, a symbol like `html' or `latex'.
6282 The function may use the FORMAT information to return different values
6283 depending on the format. The return value will be put literally into
6284 the exported file.
6285 Org-mode has a built-in default for exporting links. If you are happy with
6286 this default, there is no need to define an export function for the link
6287 type. For a simple example of an export function, see `org-bbdb.el'."
6288 (add-to-list 'org-link-types type t)
6289 (org-make-link-regexps)
6290 (if (assoc type org-link-protocols)
6291 (setcdr (assoc type org-link-protocols) (list follow export))
6292 (push (list type follow export) org-link-protocols)))
6294 ;;;###autoload
6295 (defun org-store-link (arg)
6296 "\\<org-mode-map>Store an org-link to the current location.
6297 This link is added to `org-stored-links' and can later be inserted
6298 into an org-buffer with \\[org-insert-link].
6300 For some link types, a prefix arg is interpreted:
6301 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6302 For file links, arg negates `org-context-in-file-links'."
6303 (interactive "P")
6304 (org-load-modules-maybe)
6305 (setq org-store-link-plist nil) ; reset
6306 (let (link cpltxt desc description search txt)
6307 (cond
6309 ((run-hook-with-args-until-success 'org-store-link-functions)
6310 (setq link (plist-get org-store-link-plist :link)
6311 desc (or (plist-get org-store-link-plist :description) link)))
6313 ((equal (buffer-name) "*Org Edit Src Example*")
6314 (let (label gc)
6315 (while (or (not label)
6316 (save-excursion
6317 (save-restriction
6318 (widen)
6319 (goto-char (point-min))
6320 (re-search-forward
6321 (regexp-quote (format org-coderef-label-format label))
6322 nil t))))
6323 (when label (message "Label exists already") (sit-for 2))
6324 (setq label (read-string "Code line label: " label)))
6325 (end-of-line 1)
6326 (setq link (format org-coderef-label-format label))
6327 (setq gc (- 79 (length link)))
6328 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6329 (insert link)
6330 (setq link (concat "(" label ")") desc nil)))
6332 ((eq major-mode 'calendar-mode)
6333 (let ((cd (calendar-cursor-to-date)))
6334 (setq link
6335 (format-time-string
6336 (car org-time-stamp-formats)
6337 (apply 'encode-time
6338 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6339 nil nil nil))))
6340 (org-store-link-props :type "calendar" :date cd)))
6342 ((eq major-mode 'w3-mode)
6343 (setq cpltxt (url-view-url t)
6344 link (org-make-link cpltxt))
6345 (org-store-link-props :type "w3" :url (url-view-url t)))
6347 ((eq major-mode 'w3m-mode)
6348 (setq cpltxt (or w3m-current-title w3m-current-url)
6349 link (org-make-link w3m-current-url))
6350 (org-store-link-props :type "w3m" :url (url-view-url t)))
6352 ((setq search (run-hook-with-args-until-success
6353 'org-create-file-search-functions))
6354 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6355 "::" search))
6356 (setq cpltxt (or description link)))
6358 ((eq major-mode 'image-mode)
6359 (setq cpltxt (concat "file:"
6360 (abbreviate-file-name buffer-file-name))
6361 link (org-make-link cpltxt))
6362 (org-store-link-props :type "image" :file buffer-file-name))
6364 ((eq major-mode 'dired-mode)
6365 ;; link to the file in the current line
6366 (setq cpltxt (concat "file:"
6367 (abbreviate-file-name
6368 (expand-file-name
6369 (dired-get-filename nil t))))
6370 link (org-make-link cpltxt)))
6372 ((and buffer-file-name (org-mode-p))
6373 (cond
6374 ((org-in-regexp "<<\\(.*?\\)>>")
6375 (setq cpltxt
6376 (concat "file:"
6377 (abbreviate-file-name buffer-file-name)
6378 "::" (match-string 1))
6379 link (org-make-link cpltxt)))
6380 ((and (featurep 'org-id)
6381 (or (eq org-link-to-org-use-id t)
6382 (and (eq org-link-to-org-use-id 'create-if-interactive)
6383 (interactive-p))
6384 (and org-link-to-org-use-id
6385 (condition-case nil
6386 (org-entry-get nil "ID")
6387 (error nil)))))
6388 ;; We can make a link using the ID.
6389 (setq link (condition-case nil
6390 (prog1 (org-id-store-link)
6391 (setq desc (plist-get org-store-link-plist
6392 :description)))
6393 (error
6394 ;; probably before first headline, link to file only
6395 (concat "file:"
6396 (abbreviate-file-name buffer-file-name))))))
6398 ;; Just link to current headline
6399 (setq cpltxt (concat "file:"
6400 (abbreviate-file-name buffer-file-name)))
6401 ;; Add a context search string
6402 (when (org-xor org-context-in-file-links arg)
6403 (setq txt (cond
6404 ((org-on-heading-p) nil)
6405 ((org-region-active-p)
6406 (buffer-substring (region-beginning) (region-end)))
6407 (t nil)))
6408 (when (or (null txt) (string-match "\\S-" txt))
6409 (setq cpltxt
6410 (concat cpltxt "::"
6411 (condition-case nil
6412 (org-make-org-heading-search-string txt)
6413 (error "")))
6414 desc "NONE")))
6415 (if (string-match "::\\'" cpltxt)
6416 (setq cpltxt (substring cpltxt 0 -2)))
6417 (setq link (org-make-link cpltxt)))))
6419 ((buffer-file-name (buffer-base-buffer))
6420 ;; Just link to this file here.
6421 (setq cpltxt (concat "file:"
6422 (abbreviate-file-name
6423 (buffer-file-name (buffer-base-buffer)))))
6424 ;; Add a context string
6425 (when (org-xor org-context-in-file-links arg)
6426 (setq txt (if (org-region-active-p)
6427 (buffer-substring (region-beginning) (region-end))
6428 (buffer-substring (point-at-bol) (point-at-eol))))
6429 ;; Only use search option if there is some text.
6430 (when (string-match "\\S-" txt)
6431 (setq cpltxt
6432 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6433 desc "NONE")))
6434 (setq link (org-make-link cpltxt)))
6436 ((interactive-p)
6437 (error "Cannot link to a buffer which is not visiting a file"))
6439 (t (setq link nil)))
6441 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6442 (setq link (or link cpltxt)
6443 desc (or desc cpltxt))
6444 (if (equal desc "NONE") (setq desc nil))
6446 (if (and (interactive-p) link)
6447 (progn
6448 (setq org-stored-links
6449 (cons (list link desc) org-stored-links))
6450 (message "Stored: %s" (or desc link)))
6451 (and link (org-make-link-string link desc)))))
6453 (defun org-store-link-props (&rest plist)
6454 "Store link properties, extract names and addresses."
6455 (let (x adr)
6456 (when (setq x (plist-get plist :from))
6457 (setq adr (mail-extract-address-components x))
6458 (setq plist (plist-put plist :fromname (car adr)))
6459 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6460 (when (setq x (plist-get plist :to))
6461 (setq adr (mail-extract-address-components x))
6462 (setq plist (plist-put plist :toname (car adr)))
6463 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6464 (let ((from (plist-get plist :from))
6465 (to (plist-get plist :to)))
6466 (when (and from to org-from-is-user-regexp)
6467 (setq plist
6468 (plist-put plist :fromto
6469 (if (string-match org-from-is-user-regexp from)
6470 (concat "to %t")
6471 (concat "from %f"))))))
6472 (setq org-store-link-plist plist))
6474 (defun org-add-link-props (&rest plist)
6475 "Add these properties to the link property list."
6476 (let (key value)
6477 (while plist
6478 (setq key (pop plist) value (pop plist))
6479 (setq org-store-link-plist
6480 (plist-put org-store-link-plist key value)))))
6482 (defun org-email-link-description (&optional fmt)
6483 "Return the description part of an email link.
6484 This takes information from `org-store-link-plist' and formats it
6485 according to FMT (default from `org-email-link-description-format')."
6486 (setq fmt (or fmt org-email-link-description-format))
6487 (let* ((p org-store-link-plist)
6488 (to (plist-get p :toaddress))
6489 (from (plist-get p :fromaddress))
6490 (table
6491 (list
6492 (cons "%c" (plist-get p :fromto))
6493 (cons "%F" (plist-get p :from))
6494 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6495 (cons "%T" (plist-get p :to))
6496 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6497 (cons "%s" (plist-get p :subject))
6498 (cons "%m" (plist-get p :message-id)))))
6499 (when (string-match "%c" fmt)
6500 ;; Check if the user wrote this message
6501 (if (and org-from-is-user-regexp from to
6502 (save-match-data (string-match org-from-is-user-regexp from)))
6503 (setq fmt (replace-match "to %t" t t fmt))
6504 (setq fmt (replace-match "from %f" t t fmt))))
6505 (org-replace-escapes fmt table)))
6507 (defun org-make-org-heading-search-string (&optional string heading)
6508 "Make search string for STRING or current headline."
6509 (interactive)
6510 (let ((s (or string (org-get-heading))))
6511 (unless (and string (not heading))
6512 ;; We are using a headline, clean up garbage in there.
6513 (if (string-match org-todo-regexp s)
6514 (setq s (replace-match "" t t s)))
6515 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6516 (setq s (replace-match "" t t s)))
6517 (setq s (org-trim s))
6518 (if (string-match (concat "^\\(" org-quote-string "\\|"
6519 org-comment-string "\\)") s)
6520 (setq s (replace-match "" t t s)))
6521 (while (string-match org-ts-regexp s)
6522 (setq s (replace-match "" t t s))))
6523 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6524 (setq s (replace-match " " t t s)))
6525 (or string (setq s (concat "*" s))) ; Add * for headlines
6526 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6528 (defun org-make-link (&rest strings)
6529 "Concatenate STRINGS."
6530 (apply 'concat strings))
6532 (defun org-make-link-string (link &optional description)
6533 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6534 (unless (string-match "\\S-" link)
6535 (error "Empty link"))
6536 (when (stringp description)
6537 ;; Remove brackets from the description, they are fatal.
6538 (while (string-match "\\[" description)
6539 (setq description (replace-match "{" t t description)))
6540 (while (string-match "\\]" description)
6541 (setq description (replace-match "}" t t description))))
6542 (when (equal (org-link-escape link) description)
6543 ;; No description needed, it is identical
6544 (setq description nil))
6545 (when (and (not description)
6546 (not (equal link (org-link-escape link))))
6547 (setq description (org-extract-attributes link)))
6548 (concat "[[" (org-link-escape link) "]"
6549 (if description (concat "[" description "]") "")
6550 "]"))
6552 (defconst org-link-escape-chars
6553 '((?\ . "%20")
6554 (?\[ . "%5B")
6555 (?\] . "%5D")
6556 (?\340 . "%E0") ; `a
6557 (?\342 . "%E2") ; ^a
6558 (?\347 . "%E7") ; ,c
6559 (?\350 . "%E8") ; `e
6560 (?\351 . "%E9") ; 'e
6561 (?\352 . "%EA") ; ^e
6562 (?\356 . "%EE") ; ^i
6563 (?\364 . "%F4") ; ^o
6564 (?\371 . "%F9") ; `u
6565 (?\373 . "%FB") ; ^u
6566 (?\; . "%3B")
6567 (?? . "%3F")
6568 (?= . "%3D")
6569 (?+ . "%2B")
6571 "Association list of escapes for some characters problematic in links.
6572 This is the list that is used for internal purposes.")
6574 (defconst org-link-escape-chars-browser
6575 '((?\ . "%20")) ; 32 for the SPC char
6576 "Association list of escapes for some characters problematic in links.
6577 This is the list that is used before handing over to the browser.")
6579 (defun org-link-escape (text &optional table)
6580 "Escape characters in TEXT that are problematic for links."
6581 (setq table (or table org-link-escape-chars))
6582 (when text
6583 (let ((re (mapconcat (lambda (x) (regexp-quote
6584 (char-to-string (car x))))
6585 table "\\|")))
6586 (while (string-match re text)
6587 (setq text
6588 (replace-match
6589 (cdr (assoc (string-to-char (match-string 0 text))
6590 table))
6591 t t text)))
6592 text)))
6594 (defun org-link-unescape (text &optional table)
6595 "Reverse the action of `org-link-escape'."
6596 (setq table (or table org-link-escape-chars))
6597 (when text
6598 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6599 table "\\|")))
6600 (while (string-match re text)
6601 (setq text
6602 (replace-match
6603 (char-to-string (car (rassoc (match-string 0 text) table)))
6604 t t text)))
6605 text)))
6607 (defun org-xor (a b)
6608 "Exclusive or."
6609 (if a (not b) b))
6611 (defun org-get-header (header)
6612 "Find a header field in the current buffer."
6613 (save-excursion
6614 (goto-char (point-min))
6615 (let ((case-fold-search t) s)
6616 (cond
6617 ((eq header 'from)
6618 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6619 (setq s (match-string 1)))
6620 (while (string-match "\"" s)
6621 (setq s (replace-match "" t t s)))
6622 (if (string-match "[<(].*" s)
6623 (setq s (replace-match "" t t s))))
6624 ((eq header 'message-id)
6625 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6626 (setq s (match-string 1))))
6627 ((eq header 'subject)
6628 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6629 (setq s (match-string 1)))))
6630 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6631 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6632 s)))
6635 (defun org-fixup-message-id-for-http (s)
6636 "Replace special characters in a message id, so it can be used in an http query."
6637 (while (string-match "<" s)
6638 (setq s (replace-match "%3C" t t s)))
6639 (while (string-match ">" s)
6640 (setq s (replace-match "%3E" t t s)))
6641 (while (string-match "@" s)
6642 (setq s (replace-match "%40" t t s)))
6645 ;;;###autoload
6646 (defun org-insert-link-global ()
6647 "Insert a link like Org-mode does.
6648 This command can be called in any mode to insert a link in Org-mode syntax."
6649 (interactive)
6650 (org-load-modules-maybe)
6651 (org-run-like-in-org-mode 'org-insert-link))
6653 (defun org-insert-link (&optional complete-file link-location)
6654 "Insert a link. At the prompt, enter the link.
6656 Completion can be used to insert any of the link protocol prefixes like
6657 http or ftp in use.
6659 The history can be used to select a link previously stored with
6660 `org-store-link'. When the empty string is entered (i.e. if you just
6661 press RET at the prompt), the link defaults to the most recently
6662 stored link. As SPC triggers completion in the minibuffer, you need to
6663 use M-SPC or C-q SPC to force the insertion of a space character.
6665 You will also be prompted for a description, and if one is given, it will
6666 be displayed in the buffer instead of the link.
6668 If there is already a link at point, this command will allow you to edit link
6669 and description parts.
6671 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6672 be selected using completion. The path to the file will be relative to the
6673 current directory if the file is in the current directory or a subdirectory.
6674 Otherwise, the link will be the absolute path as completed in the minibuffer
6675 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6676 option `org-link-file-path-type'.
6678 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6679 the current directory or below.
6681 With three \\[universal-argument] prefixes, negate the meaning of
6682 `org-keep-stored-link-after-insertion'.
6684 If `org-make-link-description-function' is non-nil, this function will be
6685 called with the link target, and the result will be the default
6686 link description.
6688 If the LINK-LOCATION parameter is non-nil, this value will be
6689 used as the link location instead of reading one interactively."
6690 (interactive "P")
6691 (let* ((wcf (current-window-configuration))
6692 (region (if (org-region-active-p)
6693 (buffer-substring (region-beginning) (region-end))))
6694 (remove (and region (list (region-beginning) (region-end))))
6695 (desc region)
6696 tmphist ; byte-compile incorrectly complains about this
6697 (link link-location)
6698 entry file)
6699 (cond
6700 (link-location) ; specified by arg, just use it.
6701 ((org-in-regexp org-bracket-link-regexp 1)
6702 ;; We do have a link at point, and we are going to edit it.
6703 (setq remove (list (match-beginning 0) (match-end 0)))
6704 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6705 (setq link (read-string "Link: "
6706 (org-link-unescape
6707 (org-match-string-no-properties 1)))))
6708 ((or (org-in-regexp org-angle-link-re)
6709 (org-in-regexp org-plain-link-re))
6710 ;; Convert to bracket link
6711 (setq remove (list (match-beginning 0) (match-end 0))
6712 link (read-string "Link: "
6713 (org-remove-angle-brackets (match-string 0)))))
6714 ((member complete-file '((4) (16)))
6715 ;; Completing read for file names.
6716 (setq file (read-file-name "File: "))
6717 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6718 (pwd1 (file-name-as-directory (abbreviate-file-name
6719 (expand-file-name ".")))))
6720 (cond
6721 ((equal complete-file '(16))
6722 (setq link (org-make-link
6723 "file:"
6724 (abbreviate-file-name (expand-file-name file)))))
6725 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6726 (setq link (org-make-link "file:" (match-string 1 file))))
6727 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6728 (expand-file-name file))
6729 (setq link (org-make-link
6730 "file:" (match-string 1 (expand-file-name file)))))
6731 (t (setq link (org-make-link "file:" file))))))
6733 ;; Read link, with completion for stored links.
6734 (with-output-to-temp-buffer "*Org Links*"
6735 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6736 (when org-stored-links
6737 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6738 (princ (mapconcat
6739 (lambda (x)
6740 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6741 (reverse org-stored-links) "\n"))))
6742 (let ((cw (selected-window)))
6743 (select-window (get-buffer-window "*Org Links*"))
6744 (setq truncate-lines t)
6745 (org-fit-window-to-buffer)
6746 (select-window cw))
6747 ;; Fake a link history, containing the stored links.
6748 (setq tmphist (append (mapcar 'car org-stored-links)
6749 org-insert-link-history))
6750 (unwind-protect
6751 (setq link
6752 (let ((org-completion-use-ido nil))
6753 (org-completing-read
6754 "Link: "
6755 (append
6756 (mapcar (lambda (x) (list (concat (car x) ":")))
6757 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6758 (mapcar (lambda (x) (list (concat x ":")))
6759 org-link-types))
6760 nil nil nil
6761 'tmphist
6762 (or (car (car org-stored-links))))))
6763 (set-window-configuration wcf)
6764 (kill-buffer "*Org Links*"))
6765 (setq entry (assoc link org-stored-links))
6766 (or entry (push link org-insert-link-history))
6767 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6768 (not org-keep-stored-link-after-insertion))
6769 (setq org-stored-links (delq (assoc link org-stored-links)
6770 org-stored-links)))
6771 (setq desc (or desc (nth 1 entry)))))
6773 (if (string-match org-plain-link-re link)
6774 ;; URL-like link, normalize the use of angular brackets.
6775 (setq link (org-make-link (org-remove-angle-brackets link))))
6777 ;; Check if we are linking to the current file with a search option
6778 ;; If yes, simplify the link by using only the search option.
6779 (when (and buffer-file-name
6780 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6781 (let* ((path (match-string 1 link))
6782 (case-fold-search nil)
6783 (search (match-string 2 link)))
6784 (save-match-data
6785 (if (equal (file-truename buffer-file-name) (file-truename path))
6786 ;; We are linking to this same file, with a search option
6787 (setq link search)))))
6789 ;; Check if we can/should use a relative path. If yes, simplify the link
6790 (when (string-match "^file:\\(.*\\)" link)
6791 (let* ((path (match-string 1 link))
6792 (origpath path)
6793 (case-fold-search nil))
6794 (cond
6795 ((or (eq org-link-file-path-type 'absolute)
6796 (equal complete-file '(16)))
6797 (setq path (abbreviate-file-name (expand-file-name path))))
6798 ((eq org-link-file-path-type 'noabbrev)
6799 (setq path (expand-file-name path)))
6800 ((eq org-link-file-path-type 'relative)
6801 (setq path (file-relative-name path)))
6803 (save-match-data
6804 (if (string-match (concat "^" (regexp-quote
6805 (file-name-as-directory
6806 (expand-file-name "."))))
6807 (expand-file-name path))
6808 ;; We are linking a file with relative path name.
6809 (setq path (substring (expand-file-name path)
6810 (match-end 0)))
6811 (setq path (abbreviate-file-name (expand-file-name path)))))))
6812 (setq link (concat "file:" path))
6813 (if (equal desc origpath)
6814 (setq desc path))))
6816 (if org-make-link-description-function
6817 (setq desc (funcall org-make-link-description-function link desc)))
6819 (setq desc (read-string "Description: " desc))
6820 (unless (string-match "\\S-" desc) (setq desc nil))
6821 (if remove (apply 'delete-region remove))
6822 (insert (org-make-link-string link desc))))
6824 (defun org-completing-read (&rest args)
6825 "Completing-read with SPACE being a normal character."
6826 (let ((minibuffer-local-completion-map
6827 (copy-keymap minibuffer-local-completion-map)))
6828 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6829 (apply 'org-ido-completing-read args)))
6831 (defun org-ido-completing-read (&rest args)
6832 "Completing-read using `ido-mode' speedups if available"
6833 (if (and org-completion-use-ido
6834 (fboundp 'ido-completing-read)
6835 (boundp 'ido-mode) ido-mode
6836 (listp (second args)))
6837 (apply 'ido-completing-read (concat (car args)) (cdr args))
6838 (apply 'completing-read args)))
6840 (defun org-extract-attributes (s)
6841 "Extract the attributes cookie from a string and set as text property."
6842 (let (a attr (start 0) key value)
6843 (save-match-data
6844 (when (string-match "{{\\([^}]+\\)}}$" s)
6845 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6846 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6847 (setq key (match-string 1 a) value (match-string 2 a)
6848 start (match-end 0)
6849 attr (plist-put attr (intern key) value))))
6850 (org-add-props s nil 'org-attr attr))
6853 (defun org-attributes-to-string (plist)
6854 "Format a property list into an HTML attribute list."
6855 (let ((s "") key value)
6856 (while plist
6857 (setq key (pop plist) value (pop plist))
6858 (and value
6859 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6862 ;;; Opening/following a link
6864 (defvar org-link-search-failed nil)
6866 (defun org-next-link ()
6867 "Move forward to the next link.
6868 If the link is in hidden text, expose it."
6869 (interactive)
6870 (when (and org-link-search-failed (eq this-command last-command))
6871 (goto-char (point-min))
6872 (message "Link search wrapped back to beginning of buffer"))
6873 (setq org-link-search-failed nil)
6874 (let* ((pos (point))
6875 (ct (org-context))
6876 (a (assoc :link ct)))
6877 (if a (goto-char (nth 2 a)))
6878 (if (re-search-forward org-any-link-re nil t)
6879 (progn
6880 (goto-char (match-beginning 0))
6881 (if (org-invisible-p) (org-show-context)))
6882 (goto-char pos)
6883 (setq org-link-search-failed t)
6884 (error "No further link found"))))
6886 (defun org-previous-link ()
6887 "Move backward to the previous link.
6888 If the link is in hidden text, expose it."
6889 (interactive)
6890 (when (and org-link-search-failed (eq this-command last-command))
6891 (goto-char (point-max))
6892 (message "Link search wrapped back to end of buffer"))
6893 (setq org-link-search-failed nil)
6894 (let* ((pos (point))
6895 (ct (org-context))
6896 (a (assoc :link ct)))
6897 (if a (goto-char (nth 1 a)))
6898 (if (re-search-backward org-any-link-re nil t)
6899 (progn
6900 (goto-char (match-beginning 0))
6901 (if (org-invisible-p) (org-show-context)))
6902 (goto-char pos)
6903 (setq org-link-search-failed t)
6904 (error "No further link found"))))
6906 (defun org-translate-link (s)
6907 "Translate a link string if a translation function has been defined."
6908 (if (and org-link-translation-function
6909 (fboundp org-link-translation-function)
6910 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6911 (progn
6912 (setq s (funcall org-link-translation-function
6913 (match-string 1) (match-string 2)))
6914 (concat (car s) ":" (cdr s)))
6917 (defun org-translate-link-from-planner (type path)
6918 "Translate a link from Emacs Planner syntax so that Org can follow it.
6919 This is still an experimental function, your mileage may vary."
6920 (cond
6921 ((member type '("http" "https" "news" "ftp"))
6922 ;; standard Internet links are the same.
6923 nil)
6924 ((and (equal type "irc") (string-match "^//" path))
6925 ;; Planner has two / at the beginning of an irc link, we have 1.
6926 ;; We should have zero, actually....
6927 (setq path (substring path 1)))
6928 ((and (equal type "lisp") (string-match "^/" path))
6929 ;; Planner has a slash, we do not.
6930 (setq type "elisp" path (substring path 1)))
6931 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6932 ;; A typical message link. Planner has the id after the fina slash,
6933 ;; we separate it with a hash mark
6934 (setq path (concat (match-string 1 path) "#"
6935 (org-remove-angle-brackets (match-string 2 path)))))
6937 (cons type path))
6939 (defun org-find-file-at-mouse (ev)
6940 "Open file link or URL at mouse."
6941 (interactive "e")
6942 (mouse-set-point ev)
6943 (org-open-at-point 'in-emacs))
6945 (defun org-open-at-mouse (ev)
6946 "Open file link or URL at mouse."
6947 (interactive "e")
6948 (mouse-set-point ev)
6949 (if (eq major-mode 'org-agenda-mode)
6950 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6951 (org-open-at-point))
6953 (defvar org-window-config-before-follow-link nil
6954 "The window configuration before following a link.
6955 This is saved in case the need arises to restore it.")
6957 (defvar org-open-link-marker (make-marker)
6958 "Marker pointing to the location where `org-open-at-point; was called.")
6960 ;;;###autoload
6961 (defun org-open-at-point-global ()
6962 "Follow a link like Org-mode does.
6963 This command can be called in any mode to follow a link that has
6964 Org-mode syntax."
6965 (interactive)
6966 (org-run-like-in-org-mode 'org-open-at-point))
6968 ;;;###autoload
6969 (defun org-open-link-from-string (s &optional arg)
6970 "Open a link in the string S, as if it was in Org-mode."
6971 (interactive "sLink: \nP")
6972 (with-temp-buffer
6973 (let ((org-inhibit-startup t))
6974 (org-mode)
6975 (insert s)
6976 (goto-char (point-min))
6977 (org-open-at-point arg))))
6979 (defun org-open-at-point (&optional in-emacs)
6980 "Open link at or after point.
6981 If there is no link at point, this function will search forward up to
6982 the end of the current subtree.
6983 Normally, files will be opened by an appropriate application. If the
6984 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6985 With a double prefix argument, try to open outside of Emacs, in the
6986 application the system uses for this file type."
6987 (interactive "P")
6988 (org-load-modules-maybe)
6989 (move-marker org-open-link-marker (point))
6990 (setq org-window-config-before-follow-link (current-window-configuration))
6991 (org-remove-occur-highlights nil nil t)
6992 (cond
6993 ((org-at-timestamp-p t) (org-follow-timestamp-link))
6994 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
6995 (org-footnote-action))
6997 (let (type path link line search (pos (point)))
6998 (catch 'match
6999 (save-excursion
7000 (skip-chars-forward "^]\n\r")
7001 (when (org-in-regexp org-bracket-link-regexp)
7002 (setq link (org-extract-attributes
7003 (org-link-unescape (org-match-string-no-properties 1))))
7004 (while (string-match " *\n *" link)
7005 (setq link (replace-match " " t t link)))
7006 (setq link (org-link-expand-abbrev link))
7007 (cond
7008 ((or (file-name-absolute-p link)
7009 (string-match "^\\.\\.?/" link))
7010 (setq type "file" path link))
7011 ((string-match org-link-re-with-space3 link)
7012 (setq type (match-string 1 link) path (match-string 2 link)))
7013 (t (setq type "thisfile" path link)))
7014 (throw 'match t)))
7016 (when (get-text-property (point) 'org-linked-text)
7017 (setq type "thisfile"
7018 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7019 (1+ (point)) (point))
7020 path (buffer-substring
7021 (previous-single-property-change pos 'org-linked-text)
7022 (next-single-property-change pos 'org-linked-text)))
7023 (throw 'match t))
7025 (save-excursion
7026 (when (or (org-in-regexp org-angle-link-re)
7027 (org-in-regexp org-plain-link-re))
7028 (setq type (match-string 1) path (match-string 2))
7029 (throw 'match t)))
7030 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7031 (setq type "tree-match"
7032 path (match-string 1))
7033 (throw 'match t))
7034 (save-excursion
7035 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7036 (setq type "tags"
7037 path (match-string 1))
7038 (while (string-match ":" path)
7039 (setq path (replace-match "+" t t path)))
7040 (throw 'match t))))
7041 (unless path
7042 (error "No link found"))
7043 ;; Remove any trailing spaces in path
7044 (if (string-match " +\\'" path)
7045 (setq path (replace-match "" t t path)))
7046 (if (and org-link-translation-function
7047 (fboundp org-link-translation-function))
7048 ;; Check if we need to translate the link
7049 (let ((tmp (funcall org-link-translation-function type path)))
7050 (setq type (car tmp) path (cdr tmp))))
7052 (cond
7054 ((assoc type org-link-protocols)
7055 (funcall (nth 1 (assoc type org-link-protocols)) path))
7057 ((equal type "mailto")
7058 (let ((cmd (car org-link-mailto-program))
7059 (args (cdr org-link-mailto-program)) args1
7060 (address path) (subject "") a)
7061 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7062 (setq address (match-string 1 path)
7063 subject (org-link-escape (match-string 2 path))))
7064 (while args
7065 (cond
7066 ((not (stringp (car args))) (push (pop args) args1))
7067 (t (setq a (pop args))
7068 (if (string-match "%a" a)
7069 (setq a (replace-match address t t a)))
7070 (if (string-match "%s" a)
7071 (setq a (replace-match subject t t a)))
7072 (push a args1))))
7073 (apply cmd (nreverse args1))))
7075 ((member type '("http" "https" "ftp" "news"))
7076 (browse-url (concat type ":" (org-link-escape
7077 path org-link-escape-chars-browser))))
7079 ((member type '("message"))
7080 (browse-url (concat type ":" path)))
7082 ((string= type "tags")
7083 (org-tags-view in-emacs path))
7084 ((string= type "thisfile")
7085 (if in-emacs
7086 (switch-to-buffer-other-window
7087 (org-get-buffer-for-internal-link (current-buffer)))
7088 (org-mark-ring-push))
7089 (let ((cmd `(org-link-search
7090 ,path
7091 ,(cond ((equal in-emacs '(4)) 'occur)
7092 ((equal in-emacs '(16)) 'org-occur)
7093 (t nil))
7094 ,pos)))
7095 (condition-case nil (eval cmd)
7096 (error (progn (widen) (eval cmd))))))
7098 ((string= type "tree-match")
7099 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7101 ((string= type "file")
7102 (if (string-match "::\\([0-9]+\\)\\'" path)
7103 (setq line (string-to-number (match-string 1 path))
7104 path (substring path 0 (match-beginning 0)))
7105 (if (string-match "::\\(.+\\)\\'" path)
7106 (setq search (match-string 1 path)
7107 path (substring path 0 (match-beginning 0)))))
7108 (if (string-match "[*?{]" (file-name-nondirectory path))
7109 (dired path)
7110 (org-open-file path in-emacs line search)))
7112 ((string= type "news")
7113 (require 'org-gnus)
7114 (org-gnus-follow-link path))
7116 ((string= type "shell")
7117 (let ((cmd path))
7118 (if (or (not org-confirm-shell-link-function)
7119 (funcall org-confirm-shell-link-function
7120 (format "Execute \"%s\" in shell? "
7121 (org-add-props cmd nil
7122 'face 'org-warning))))
7123 (progn
7124 (message "Executing %s" cmd)
7125 (shell-command cmd))
7126 (error "Abort"))))
7128 ((string= type "elisp")
7129 (let ((cmd path))
7130 (if (or (not org-confirm-elisp-link-function)
7131 (funcall org-confirm-elisp-link-function
7132 (format "Execute \"%s\" as elisp? "
7133 (org-add-props cmd nil
7134 'face 'org-warning))))
7135 (message "%s => %s" cmd
7136 (if (equal (string-to-char cmd) ?\()
7137 (eval (read cmd))
7138 (call-interactively (read cmd))))
7139 (error "Abort"))))
7142 (browse-url-at-point))))))
7143 (move-marker org-open-link-marker nil)
7144 (run-hook-with-args 'org-follow-link-hook))
7146 ;;;; Time estimates
7148 (defun org-get-effort (&optional pom)
7149 "Get the effort estimate for the current entry."
7150 (org-entry-get pom org-effort-property))
7152 ;;; File search
7154 (defvar org-create-file-search-functions nil
7155 "List of functions to construct the right search string for a file link.
7156 These functions are called in turn with point at the location to
7157 which the link should point.
7159 A function in the hook should first test if it would like to
7160 handle this file type, for example by checking the major-mode or
7161 the file extension. If it decides not to handle this file, it
7162 should just return nil to give other functions a chance. If it
7163 does handle the file, it must return the search string to be used
7164 when following the link. The search string will be part of the
7165 file link, given after a double colon, and `org-open-at-point'
7166 will automatically search for it. If special measures must be
7167 taken to make the search successful, another function should be
7168 added to the companion hook `org-execute-file-search-functions',
7169 which see.
7171 A function in this hook may also use `setq' to set the variable
7172 `description' to provide a suggestion for the descriptive text to
7173 be used for this link when it gets inserted into an Org-mode
7174 buffer with \\[org-insert-link].")
7176 (defvar org-execute-file-search-functions nil
7177 "List of functions to execute a file search triggered by a link.
7179 Functions added to this hook must accept a single argument, the
7180 search string that was part of the file link, the part after the
7181 double colon. The function must first check if it would like to
7182 handle this search, for example by checking the major-mode or the
7183 file extension. If it decides not to handle this search, it
7184 should just return nil to give other functions a chance. If it
7185 does handle the search, it must return a non-nil value to keep
7186 other functions from trying.
7188 Each function can access the current prefix argument through the
7189 variable `current-prefix-argument'. Note that a single prefix is
7190 used to force opening a link in Emacs, so it may be good to only
7191 use a numeric or double prefix to guide the search function.
7193 In case this is needed, a function in this hook can also restore
7194 the window configuration before `org-open-at-point' was called using:
7196 (set-window-configuration org-window-config-before-follow-link)")
7198 (defun org-link-search (s &optional type avoid-pos)
7199 "Search for a link search option.
7200 If S is surrounded by forward slashes, it is interpreted as a
7201 regular expression. In org-mode files, this will create an `org-occur'
7202 sparse tree. In ordinary files, `occur' will be used to list matches.
7203 If the current buffer is in `dired-mode', grep will be used to search
7204 in all files. If AVOID-POS is given, ignore matches near that position."
7205 (let ((case-fold-search t)
7206 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7207 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7208 (append '(("") (" ") ("\t") ("\n"))
7209 org-emphasis-alist)
7210 "\\|") "\\)"))
7211 (pos (point))
7212 (pre nil) (post nil)
7213 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7214 (cond
7215 ;; First check if there are any special
7216 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7217 ;; Now try the builtin stuff
7218 ((save-excursion
7219 (goto-char (point-min))
7220 (and
7221 (re-search-forward
7222 (concat "<<" (regexp-quote s0) ">>") nil t)
7223 (setq type 'dedicated
7224 pos (match-beginning 0))))
7225 ;; There is an exact target for this
7226 (goto-char pos))
7227 ((and (string-match "^(\\(.*\\))$" s0)
7228 (save-excursion
7229 (goto-char (point-min))
7230 (and
7231 (re-search-forward
7232 (concat "[^[]" (regexp-quote
7233 (format org-coderef-label-format
7234 (match-string 1 s0))))
7235 nil t)
7236 (setq type 'dedicated
7237 pos (1+ (match-beginning 0))))))
7238 ;; There is a coderef target for this
7239 (goto-char pos))
7240 ((string-match "^/\\(.*\\)/$" s)
7241 ;; A regular expression
7242 (cond
7243 ((org-mode-p)
7244 (org-occur (match-string 1 s)))
7245 ;;((eq major-mode 'dired-mode)
7246 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7247 (t (org-do-occur (match-string 1 s)))))
7249 ;; A normal search strings
7250 (when (equal (string-to-char s) ?*)
7251 ;; Anchor on headlines, post may include tags.
7252 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7253 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7254 s (substring s 1)))
7255 (remove-text-properties
7256 0 (length s)
7257 '(face nil mouse-face nil keymap nil fontified nil) s)
7258 ;; Make a series of regular expressions to find a match
7259 (setq words (org-split-string s "[ \n\r\t]+")
7261 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7262 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7263 "\\)" markers)
7264 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7265 re2a (concat "[ \t\r\n]" re2a_)
7266 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7267 re4 (concat "[^a-zA-Z_]" re4_)
7269 re1 (concat pre re2 post)
7270 re3 (concat pre (if pre re4_ re4) post)
7271 re5 (concat pre ".*" re4)
7272 re2 (concat pre re2)
7273 re2a (concat pre (if pre re2a_ re2a))
7274 re4 (concat pre (if pre re4_ re4))
7275 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7276 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7277 re5 "\\)"
7279 (cond
7280 ((eq type 'org-occur) (org-occur reall))
7281 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7282 (t (goto-char (point-min))
7283 (setq type 'fuzzy)
7284 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7285 (org-search-not-self 1 re1 nil t)
7286 (org-search-not-self 1 re2 nil t)
7287 (org-search-not-self 1 re2a nil t)
7288 (org-search-not-self 1 re3 nil t)
7289 (org-search-not-self 1 re4 nil t)
7290 (org-search-not-self 1 re5 nil t)
7292 (goto-char (match-beginning 1))
7293 (goto-char pos)
7294 (error "No match")))))
7296 ;; Normal string-search
7297 (goto-char (point-min))
7298 (if (search-forward s nil t)
7299 (goto-char (match-beginning 0))
7300 (error "No match"))))
7301 (and (org-mode-p) (org-show-context 'link-search))
7302 type))
7304 (defun org-search-not-self (group &rest args)
7305 "Execute `re-search-forward', but only accept matches that do not
7306 enclose the position of `org-open-link-marker'."
7307 (let ((m org-open-link-marker))
7308 (catch 'exit
7309 (while (apply 're-search-forward args)
7310 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7311 (goto-char (match-end group))
7312 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7313 (> (match-beginning 0) (marker-position m))
7314 (< (match-end 0) (marker-position m)))
7315 (save-match-data
7316 (or (not (org-in-regexp
7317 org-bracket-link-analytic-regexp 1))
7318 (not (match-end 4)) ; no description
7319 (and (<= (match-beginning 4) (point))
7320 (>= (match-end 4) (point))))))
7321 (throw 'exit (point))))))))
7323 (defun org-get-buffer-for-internal-link (buffer)
7324 "Return a buffer to be used for displaying the link target of internal links."
7325 (cond
7326 ((not org-display-internal-link-with-indirect-buffer)
7327 buffer)
7328 ((string-match "(Clone)$" (buffer-name buffer))
7329 (message "Buffer is already a clone, not making another one")
7330 ;; we also do not modify visibility in this case
7331 buffer)
7332 (t ; make a new indirect buffer for displaying the link
7333 (let* ((bn (buffer-name buffer))
7334 (ibn (concat bn "(Clone)"))
7335 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7336 (with-current-buffer ib (org-overview))
7337 ib))))
7339 (defun org-do-occur (regexp &optional cleanup)
7340 "Call the Emacs command `occur'.
7341 If CLEANUP is non-nil, remove the printout of the regular expression
7342 in the *Occur* buffer. This is useful if the regex is long and not useful
7343 to read."
7344 (occur regexp)
7345 (when cleanup
7346 (let ((cwin (selected-window)) win beg end)
7347 (when (setq win (get-buffer-window "*Occur*"))
7348 (select-window win))
7349 (goto-char (point-min))
7350 (when (re-search-forward "match[a-z]+" nil t)
7351 (setq beg (match-end 0))
7352 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7353 (setq end (1- (match-beginning 0)))))
7354 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7355 (goto-char (point-min))
7356 (select-window cwin))))
7358 ;;; The mark ring for links jumps
7360 (defvar org-mark-ring nil
7361 "Mark ring for positions before jumps in Org-mode.")
7362 (defvar org-mark-ring-last-goto nil
7363 "Last position in the mark ring used to go back.")
7364 ;; Fill and close the ring
7365 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7366 (loop for i from 1 to org-mark-ring-length do
7367 (push (make-marker) org-mark-ring))
7368 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7369 org-mark-ring)
7371 (defun org-mark-ring-push (&optional pos buffer)
7372 "Put the current position or POS into the mark ring and rotate it."
7373 (interactive)
7374 (setq pos (or pos (point)))
7375 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7376 (move-marker (car org-mark-ring)
7377 (or pos (point))
7378 (or buffer (current-buffer)))
7379 (message "%s"
7380 (substitute-command-keys
7381 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7383 (defun org-mark-ring-goto (&optional n)
7384 "Jump to the previous position in the mark ring.
7385 With prefix arg N, jump back that many stored positions. When
7386 called several times in succession, walk through the entire ring.
7387 Org-mode commands jumping to a different position in the current file,
7388 or to another Org-mode file, automatically push the old position
7389 onto the ring."
7390 (interactive "p")
7391 (let (p m)
7392 (if (eq last-command this-command)
7393 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7394 (setq p org-mark-ring))
7395 (setq org-mark-ring-last-goto p)
7396 (setq m (car p))
7397 (switch-to-buffer (marker-buffer m))
7398 (goto-char m)
7399 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7401 (defun org-remove-angle-brackets (s)
7402 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7403 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7405 (defun org-add-angle-brackets (s)
7406 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7407 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7409 (defun org-remove-double-quotes (s)
7410 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7411 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7414 ;;; Following specific links
7416 (defun org-follow-timestamp-link ()
7417 (cond
7418 ((org-at-date-range-p t)
7419 (let ((org-agenda-start-on-weekday)
7420 (t1 (match-string 1))
7421 (t2 (match-string 2)))
7422 (setq t1 (time-to-days (org-time-string-to-time t1))
7423 t2 (time-to-days (org-time-string-to-time t2)))
7424 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7425 ((org-at-timestamp-p t)
7426 (org-agenda-list nil (time-to-days (org-time-string-to-time
7427 (substring (match-string 1) 0 10)))
7429 (t (error "This should not happen"))))
7432 ;;; Following file links
7433 (defvar org-wait nil)
7434 (defun org-open-file (path &optional in-emacs line search)
7435 "Open the file at PATH.
7436 First, this expands any special file name abbreviations. Then the
7437 configuration variable `org-file-apps' is checked if it contains an
7438 entry for this file type, and if yes, the corresponding command is launched.
7440 If no application is found, Emacs simply visits the file.
7442 With optional prefix argument IN-EMACS, Emacs will visit the file.
7443 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7444 and o use an external application to visit the file.
7446 Optional LINE specifies a line to go to, optional SEARCH a string to
7447 search for. If LINE or SEARCH is given, the file will always be
7448 opened in Emacs.
7449 If the file does not exist, an error is thrown."
7450 (setq in-emacs (or in-emacs line search))
7451 (let* ((file (if (equal path "")
7452 buffer-file-name
7453 (substitute-in-file-name (expand-file-name path))))
7454 (apps (append org-file-apps (org-default-apps)))
7455 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7456 (dirp (if remp nil (file-directory-p file)))
7457 (file (if (and dirp org-open-directory-means-index-dot-org)
7458 (concat (file-name-as-directory file) "index.org")
7459 file))
7460 (a-m-a-p (assq 'auto-mode apps))
7461 (dfile (downcase file))
7462 (old-buffer (current-buffer))
7463 (old-pos (point))
7464 (old-mode major-mode)
7465 ext cmd)
7466 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7467 (setq ext (match-string 1 dfile))
7468 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7469 (setq ext (match-string 1 dfile))))
7470 (cond
7471 ((equal in-emacs '(16))
7472 (setq cmd (cdr (assoc 'system apps))))
7473 (in-emacs (setq cmd 'emacs))
7475 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7476 (and dirp (cdr (assoc 'directory apps)))
7477 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7478 'string-match)
7479 (cdr (assoc ext apps))
7480 (cdr (assoc t apps))))))
7481 (when (eq cmd 'system)
7482 (setq cmd (cdr (assoc 'system apps))))
7483 (when (eq cmd 'default)
7484 (setq cmd (cdr (assoc t apps))))
7485 (when (eq cmd 'mailcap)
7486 (require 'mailcap)
7487 (mailcap-parse-mailcaps)
7488 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7489 (command (mailcap-mime-info mime-type)))
7490 (if (stringp command)
7491 (setq cmd command)
7492 (setq cmd 'emacs))))
7493 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7494 (not (file-exists-p file))
7495 (not org-open-non-existing-files))
7496 (error "No such file: %s" file))
7497 (cond
7498 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7499 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7500 (while (string-match "['\"]%s['\"]" cmd)
7501 (setq cmd (replace-match "%s" t t cmd)))
7502 (while (string-match "%s" cmd)
7503 (setq cmd (replace-match
7504 (save-match-data
7505 (shell-quote-argument
7506 (convert-standard-filename file)))
7507 t t cmd)))
7508 (save-window-excursion
7509 (start-process-shell-command cmd nil cmd)
7510 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7512 ((or (stringp cmd)
7513 (eq cmd 'emacs))
7514 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7515 (widen)
7516 (if line (goto-line line)
7517 (if search (org-link-search search))))
7518 ((consp cmd)
7519 (let ((file (convert-standard-filename file)))
7520 (eval cmd)))
7521 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7522 (and (org-mode-p) (eq old-mode 'org-mode)
7523 (or (not (equal old-buffer (current-buffer)))
7524 (not (equal old-pos (point))))
7525 (org-mark-ring-push old-pos old-buffer))))
7527 (defun org-default-apps ()
7528 "Return the default applications for this operating system."
7529 (cond
7530 ((eq system-type 'darwin)
7531 org-file-apps-defaults-macosx)
7532 ((eq system-type 'windows-nt)
7533 org-file-apps-defaults-windowsnt)
7534 (t org-file-apps-defaults-gnu)))
7536 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7537 "Convert extensions to regular expressions in the cars of LIST.
7538 Also, weed out any non-string entries, because the return value is used
7539 only for regexp matching.
7540 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7541 point to the symbol `emacs', indicating that the file should
7542 be opened in Emacs."
7543 (append
7544 (delq nil
7545 (mapcar (lambda (x)
7546 (if (not (stringp (car x)))
7548 (if (string-match "\\W" (car x))
7550 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7551 list))
7552 (if add-auto-mode
7553 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7555 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7556 (defun org-file-remote-p (file)
7557 "Test whether FILE specifies a location on a remote system.
7558 Return non-nil if the location is indeed remote.
7560 For example, the filename \"/user@host:/foo\" specifies a location
7561 on the system \"/user@host:\"."
7562 (cond ((fboundp 'file-remote-p)
7563 (file-remote-p file))
7564 ((fboundp 'tramp-handle-file-remote-p)
7565 (tramp-handle-file-remote-p file))
7566 ((and (boundp 'ange-ftp-name-format)
7567 (string-match (car ange-ftp-name-format) file))
7569 (t nil)))
7572 ;;;; Refiling
7574 (defun org-get-org-file ()
7575 "Read a filename, with default directory `org-directory'."
7576 (let ((default (or org-default-notes-file remember-data-file)))
7577 (read-file-name (format "File name [%s]: " default)
7578 (file-name-as-directory org-directory)
7579 default)))
7581 (defun org-notes-order-reversed-p ()
7582 "Check if the current file should receive notes in reversed order."
7583 (cond
7584 ((not org-reverse-note-order) nil)
7585 ((eq t org-reverse-note-order) t)
7586 ((not (listp org-reverse-note-order)) nil)
7587 (t (catch 'exit
7588 (let ((all org-reverse-note-order)
7589 entry)
7590 (while (setq entry (pop all))
7591 (if (string-match (car entry) buffer-file-name)
7592 (throw 'exit (cdr entry))))
7593 nil)))))
7595 (defvar org-refile-target-table nil
7596 "The list of refile targets, created by `org-refile'.")
7598 (defvar org-agenda-new-buffers nil
7599 "Buffers created to visit agenda files.")
7601 (defun org-get-refile-targets (&optional default-buffer)
7602 "Produce a table with refile targets."
7603 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7604 targets txt re files f desc descre fast-path-p level)
7605 (message "Getting targets...")
7606 (with-current-buffer (or default-buffer (current-buffer))
7607 (while (setq entry (pop entries))
7608 (setq files (car entry) desc (cdr entry))
7609 (setq fast-path-p nil)
7610 (cond
7611 ((null files) (setq files (list (current-buffer))))
7612 ((eq files 'org-agenda-files)
7613 (setq files (org-agenda-files 'unrestricted)))
7614 ((and (symbolp files) (fboundp files))
7615 (setq files (funcall files)))
7616 ((and (symbolp files) (boundp files))
7617 (setq files (symbol-value files))))
7618 (if (stringp files) (setq files (list files)))
7619 (cond
7620 ((eq (car desc) :tag)
7621 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7622 ((eq (car desc) :todo)
7623 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7624 ((eq (car desc) :regexp)
7625 (setq descre (cdr desc)))
7626 ((eq (car desc) :level)
7627 (setq descre (concat "^\\*\\{" (number-to-string
7628 (if org-odd-levels-only
7629 (1- (* 2 (cdr desc)))
7630 (cdr desc)))
7631 "\\}[ \t]")))
7632 ((eq (car desc) :maxlevel)
7633 (setq fast-path-p t)
7634 (setq descre (concat "^\\*\\{1," (number-to-string
7635 (if org-odd-levels-only
7636 (1- (* 2 (cdr desc)))
7637 (cdr desc)))
7638 "\\}[ \t]")))
7639 (t (error "Bad refiling target description %s" desc)))
7640 (while (setq f (pop files))
7641 (save-excursion
7642 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7643 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7644 (setq f (expand-file-name f))
7645 (save-excursion
7646 (save-restriction
7647 (widen)
7648 (goto-char (point-min))
7649 (while (re-search-forward descre nil t)
7650 (goto-char (point-at-bol))
7651 (when (looking-at org-complex-heading-regexp)
7652 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7653 txt (org-link-display-format (match-string 4))
7654 re (concat "^" (regexp-quote
7655 (buffer-substring (match-beginning 1)
7656 (match-end 4)))))
7657 (if (match-end 5) (setq re (concat re "[ \t]+"
7658 (regexp-quote
7659 (match-string 5)))))
7660 (setq re (concat re "[ \t]*$"))
7661 (when org-refile-use-outline-path
7662 (setq txt (mapconcat 'org-protect-slash
7663 (append
7664 (if (eq org-refile-use-outline-path 'file)
7665 (list (file-name-nondirectory
7666 (buffer-file-name (buffer-base-buffer))))
7667 (if (eq org-refile-use-outline-path 'full-file-path)
7668 (list (buffer-file-name (buffer-base-buffer)))))
7669 (org-get-outline-path fast-path-p level txt)
7670 (list txt))
7671 "/")))
7672 (push (list txt f re (point)) targets))
7673 (goto-char (point-at-eol))))))))
7674 (message "Getting targets...done")
7675 (nreverse targets))))
7677 (defun org-protect-slash (s)
7678 (while (string-match "/" s)
7679 (setq s (replace-match "\\" t t s)))
7682 (defvar org-olpa (make-vector 20 nil))
7684 (defun org-get-outline-path (&optional fastp level heading)
7685 "Return the outline path to the current entry, as a list."
7686 (if fastp
7687 (progn
7688 (if (> level 19)
7689 (error "Outline path failure, more than 19 levels."))
7690 (loop for i from level upto 19 do
7691 (aset org-olpa i nil))
7692 (prog1
7693 (delq nil (append org-olpa nil))
7694 (aset org-olpa level heading)))
7695 (let (rtn)
7696 (save-excursion
7697 (while (org-up-heading-safe)
7698 (when (looking-at org-complex-heading-regexp)
7699 (push (org-match-string-no-properties 4) rtn)))
7700 rtn))))
7702 (defvar org-refile-history nil
7703 "History for refiling operations.")
7705 (defun org-refile (&optional goto default-buffer)
7706 "Move the entry at point to another heading.
7707 The list of target headings is compiled using the information in
7708 `org-refile-targets', which see. This list is created before each use
7709 and will therefore always be up-to-date.
7711 At the target location, the entry is filed as a subitem of the target heading.
7712 Depending on `org-reverse-note-order', the new subitem will either be the
7713 first or the last subitem.
7715 If there is an active region, all entries in that region will be moved.
7716 However, the region must fulfil the requirement that the first heading
7717 is the first one sets the top-level of the moved text - at most siblings
7718 below it are allowed.
7720 With prefix arg GOTO, the command will only visit the target location,
7721 not actually move anything.
7722 With a double prefix `C-u C-u', go to the location where the last refiling
7723 operation has put the subtree."
7724 (interactive "P")
7725 (let* ((cbuf (current-buffer))
7726 (regionp (org-region-active-p))
7727 (region-start (and regionp (region-beginning)))
7728 (region-end (and regionp (region-end)))
7729 (region-length (and regionp (- region-end region-start)))
7730 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7731 pos it nbuf file re level reversed)
7732 (when regionp (goto-char region-start)
7733 (unless (org-kill-is-subtree-p
7734 (buffer-substring region-start region-end))
7735 (error "The region is not a (sequence of) subtree(s)")))
7736 (if (equal goto '(16))
7737 (org-refile-goto-last-stored)
7738 (when (setq it (org-refile-get-location
7739 (if goto "Goto: " "Refile to: ") default-buffer))
7740 (setq file (nth 1 it)
7741 re (nth 2 it)
7742 pos (nth 3 it))
7743 (if (and (equal (buffer-file-name) file)
7744 (if regionp
7745 (and (>= pos region-start)
7746 (<= pos region-end))
7747 (and (>= pos (point))
7748 (< pos (save-excursion
7749 (org-end-of-subtree t t))))))
7750 (error "Cannot refile to position inside the tree or region"))
7752 (setq nbuf (or (find-buffer-visiting file)
7753 (find-file-noselect file)))
7754 (if goto
7755 (progn
7756 (switch-to-buffer nbuf)
7757 (goto-char pos)
7758 (org-show-context 'org-goto))
7759 (if regionp
7760 (progn
7761 (kill-new (buffer-substring region-start region-end))
7762 (org-save-markers-in-region region-start region-end))
7763 (org-copy-subtree 1 nil t))
7764 (save-excursion
7765 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7766 (find-file-noselect file))))
7767 (setq reversed (org-notes-order-reversed-p))
7768 (save-excursion
7769 (save-restriction
7770 (widen)
7771 (goto-char pos)
7772 (looking-at outline-regexp)
7773 (setq level (org-get-valid-level (funcall outline-level) 1))
7774 (goto-char
7775 (if reversed
7776 (or (outline-next-heading) (point-max))
7777 (or (save-excursion (outline-get-next-sibling))
7778 (org-end-of-subtree t t)
7779 (point-max))))
7780 (if (not (bolp)) (newline))
7781 (bookmark-set "org-refile-last-stored")
7782 (org-paste-subtree level))))
7783 (if regionp
7784 (delete-region (point) (+ (point) region-length))
7785 (org-cut-subtree))
7786 (setq org-markers-to-move nil)
7787 (message "Refiled to \"%s\"" (car it)))))))
7789 (defun org-refile-goto-last-stored ()
7790 "Go to the location where the last refile was stored."
7791 (interactive)
7792 (bookmark-jump "org-refile-last-stored")
7793 (message "This is the location of the last refile"))
7795 (defun org-refile-get-location (&optional prompt default-buffer)
7796 "Prompt the user for a refile location, using PROMPT."
7797 (let ((org-refile-targets org-refile-targets)
7798 (org-refile-use-outline-path org-refile-use-outline-path))
7799 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7800 (unless org-refile-target-table
7801 (error "No refile targets"))
7802 (let* ((cbuf (current-buffer))
7803 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7804 (cfunc (if (and org-refile-use-outline-path
7805 org-outline-path-complete-in-steps)
7806 'org-olpath-completing-read
7807 'org-ido-completing-read))
7808 (extra (if org-refile-use-outline-path "/" ""))
7809 (filename (and cfn (expand-file-name cfn)))
7810 (tbl (mapcar
7811 (lambda (x)
7812 (if (not (equal filename (nth 1 x)))
7813 (cons (concat (car x) extra " ("
7814 (file-name-nondirectory (nth 1 x)) ")")
7815 (cdr x))
7816 (cons (concat (car x) extra) (cdr x))))
7817 org-refile-target-table))
7818 (completion-ignore-case t))
7819 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7820 tbl)))
7822 (defun org-olpath-completing-read (prompt collection &rest args)
7823 "Read an outline path like a file name."
7824 (let ((thetable collection))
7825 (apply
7826 'org-ido-completing-read prompt
7827 (lambda (string predicate &optional flag)
7828 (let (rtn r s f (l (length string)))
7829 (cond
7830 ((eq flag nil)
7831 ;; try completion
7832 (try-completion string thetable))
7833 ((eq flag t)
7834 ;; all-completions
7835 (setq rtn (all-completions string thetable predicate))
7836 (mapcar
7837 (lambda (x)
7838 (setq r (substring x l))
7839 (if (string-match " ([^)]*)$" x)
7840 (setq f (match-string 0 x))
7841 (setq f ""))
7842 (if (string-match "/" r)
7843 (concat string (substring r 0 (match-end 0)) f)
7845 rtn))
7846 ((eq flag 'lambda)
7847 ;; exact match?
7848 (assoc string thetable)))
7850 args)))
7852 ;;;; Dynamic blocks
7854 (defun org-find-dblock (name)
7855 "Find the first dynamic block with name NAME in the buffer.
7856 If not found, stay at current position and return nil."
7857 (let (pos)
7858 (save-excursion
7859 (goto-char (point-min))
7860 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7861 nil t)
7862 (match-beginning 0))))
7863 (if pos (goto-char pos))
7864 pos))
7866 (defconst org-dblock-start-re
7867 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7868 "Matches the startline of a dynamic block, with parameters.")
7870 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7871 "Matches the end of a dynamic block.")
7873 (defun org-create-dblock (plist)
7874 "Create a dynamic block section, with parameters taken from PLIST.
7875 PLIST must contain a :name entry which is used as name of the block."
7876 (unless (bolp) (newline))
7877 (let ((name (plist-get plist :name)))
7878 (insert "#+BEGIN: " name)
7879 (while plist
7880 (if (eq (car plist) :name)
7881 (setq plist (cddr plist))
7882 (insert " " (prin1-to-string (pop plist)))))
7883 (insert "\n\n#+END:\n")
7884 (beginning-of-line -2)))
7886 (defun org-prepare-dblock ()
7887 "Prepare dynamic block for refresh.
7888 This empties the block, puts the cursor at the insert position and returns
7889 the property list including an extra property :name with the block name."
7890 (unless (looking-at org-dblock-start-re)
7891 (error "Not at a dynamic block"))
7892 (let* ((begdel (1+ (match-end 0)))
7893 (name (org-no-properties (match-string 1)))
7894 (params (append (list :name name)
7895 (read (concat "(" (match-string 3) ")")))))
7896 (unless (re-search-forward org-dblock-end-re nil t)
7897 (error "Dynamic block not terminated"))
7898 (setq params
7899 (append params
7900 (list :content (buffer-substring
7901 begdel (match-beginning 0)))))
7902 (delete-region begdel (match-beginning 0))
7903 (goto-char begdel)
7904 (open-line 1)
7905 params))
7907 (defun org-map-dblocks (&optional command)
7908 "Apply COMMAND to all dynamic blocks in the current buffer.
7909 If COMMAND is not given, use `org-update-dblock'."
7910 (let ((cmd (or command 'org-update-dblock))
7911 pos)
7912 (save-excursion
7913 (goto-char (point-min))
7914 (while (re-search-forward org-dblock-start-re nil t)
7915 (goto-char (setq pos (match-beginning 0)))
7916 (condition-case nil
7917 (funcall cmd)
7918 (error (message "Error during update of dynamic block")))
7919 (goto-char pos)
7920 (unless (re-search-forward org-dblock-end-re nil t)
7921 (error "Dynamic block not terminated"))))))
7923 (defun org-dblock-update (&optional arg)
7924 "User command for updating dynamic blocks.
7925 Update the dynamic block at point. With prefix ARG, update all dynamic
7926 blocks in the buffer."
7927 (interactive "P")
7928 (if arg
7929 (org-update-all-dblocks)
7930 (or (looking-at org-dblock-start-re)
7931 (org-beginning-of-dblock))
7932 (org-update-dblock)))
7934 (defun org-update-dblock ()
7935 "Update the dynamic block at point
7936 This means to empty the block, parse for parameters and then call
7937 the correct writing function."
7938 (save-window-excursion
7939 (let* ((pos (point))
7940 (line (org-current-line))
7941 (params (org-prepare-dblock))
7942 (name (plist-get params :name))
7943 (cmd (intern (concat "org-dblock-write:" name))))
7944 (message "Updating dynamic block `%s' at line %d..." name line)
7945 (funcall cmd params)
7946 (message "Updating dynamic block `%s' at line %d...done" name line)
7947 (goto-char pos))))
7949 (defun org-beginning-of-dblock ()
7950 "Find the beginning of the dynamic block at point.
7951 Error if there is no such block at point."
7952 (let ((pos (point))
7953 beg)
7954 (end-of-line 1)
7955 (if (and (re-search-backward org-dblock-start-re nil t)
7956 (setq beg (match-beginning 0))
7957 (re-search-forward org-dblock-end-re nil t)
7958 (> (match-end 0) pos))
7959 (goto-char beg)
7960 (goto-char pos)
7961 (error "Not in a dynamic block"))))
7963 (defun org-update-all-dblocks ()
7964 "Update all dynamic blocks in the buffer.
7965 This function can be used in a hook."
7966 (when (org-mode-p)
7967 (org-map-dblocks 'org-update-dblock)))
7970 ;;;; Completion
7972 (defconst org-additional-option-like-keywords
7973 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7974 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7975 "BEGIN_EXAMPLE" "END_EXAMPLE"
7976 "BEGIN_QUOTE" "END_QUOTE"
7977 "BEGIN_VERSE" "END_VERSE"
7978 "BEGIN_SRC" "END_SRC"
7979 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7981 (defcustom org-structure-template-alist
7983 ("s" "#+begin_src ?\n\n#+end_src"
7984 "<src lang=\"?\">\n\n</src>")
7985 ("e" "#+begin_example\n?\n#+end_example"
7986 "<example>\n?\n</example>")
7987 ("q" "#+begin_quote\n?\n#+end_quote"
7988 "<quote>\n?\n</quote>")
7989 ("v" "#+begin_verse\n?\n#+end_verse"
7990 "<verse>\n?\n/verse>")
7991 ("l" "#+begin_latex\n?\n#+end_latex"
7992 "<literal style=\"latex\">\n?\n</literal>")
7993 ("L" "#+latex: "
7994 "<literal style=\"latex\">?</literal>")
7995 ("h" "#+begin_html\n?\n#+end_html"
7996 "<literal style=\"html\">\n?\n</literal>")
7997 ("H" "#+html: "
7998 "<literal style=\"html\">?</literal>")
7999 ("a" "#+begin_ascii\n?\n#+end_ascii")
8000 ("A" "#+ascii: ")
8001 ("i" "#+include %file ?"
8002 "<include file=%file markup=\"?\">")
8004 "Structure completion elements.
8005 This is a list of abbreviation keys and values. The value gets inserted
8006 it you type @samp{.} followed by the key and then the completion key,
8007 usually `M-TAB'. %file will be replaced by a file name after prompting
8008 for the file using completion.
8009 There are two templates for each key, the first uses the original Org syntax,
8010 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8011 the default when the /org-mtags.el/ module has been loaded. See also the
8012 variable `org-mtags-prefer-muse-templates'.
8013 This is an experimental feature, it is undecided if it is going to stay in."
8014 :group 'org-completion
8015 :type '(repeat
8016 (string :tag "Key")
8017 (string :tag "Template")
8018 (string :tag "Muse Template")))
8020 (defun org-try-structure-completion ()
8021 "Try to complete a structure template before point.
8022 This looks for strings like \"<e\" on an otherwise empty line and
8023 expands them."
8024 (let ((l (buffer-substring (point-at-bol) (point)))
8026 (when (and (looking-at "[ \t]*$")
8027 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8028 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8029 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8030 (match-beginning 1)) a)
8031 t)))
8033 (defun org-complete-expand-structure-template (start cell)
8034 "Expand a structure template."
8035 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8036 (rpl (nth (if musep 2 1) cell)))
8037 (delete-region start (point))
8038 (when (string-match "\\`#\\+" rpl)
8039 (cond
8040 ((bolp))
8041 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8042 (delete-region (point-at-bol) (point)))
8043 (t (newline))))
8044 (setq start (point))
8045 (if (string-match "%file" rpl)
8046 (setq rpl (replace-match
8047 (concat
8048 "\""
8049 (save-match-data
8050 (abbreviate-file-name (read-file-name "Include file: ")))
8051 "\"")
8052 t t rpl)))
8053 (insert rpl)
8054 (if (re-search-backward "\\?" start t) (delete-char 1))))
8057 (defun org-complete (&optional arg)
8058 "Perform completion on word at point.
8059 At the beginning of a headline, this completes TODO keywords as given in
8060 `org-todo-keywords'.
8061 If the current word is preceded by a backslash, completes the TeX symbols
8062 that are supported for HTML support.
8063 If the current word is preceded by \"#+\", completes special words for
8064 setting file options.
8065 In the line after \"#+STARTUP:, complete valid keywords.\"
8066 At all other locations, this simply calls the value of
8067 `org-completion-fallback-command'."
8068 (interactive "P")
8069 (org-without-partial-completion
8070 (catch 'exit
8071 (let* ((a nil)
8072 (end (point))
8073 (beg1 (save-excursion
8074 (skip-chars-backward (org-re "[:alnum:]_@"))
8075 (point)))
8076 (beg (save-excursion
8077 (skip-chars-backward "a-zA-Z0-9_:$")
8078 (point)))
8079 (confirm (lambda (x) (stringp (car x))))
8080 (searchhead (equal (char-before beg) ?*))
8081 (struct
8082 (when (and (member (char-before beg1) '(?. ?<))
8083 (setq a (assoc (buffer-substring beg1 (point))
8084 org-structure-template-alist)))
8085 (org-complete-expand-structure-template (1- beg1) a)
8086 (throw 'exit t)))
8087 (tag (and (equal (char-before beg1) ?:)
8088 (equal (char-after (point-at-bol)) ?*)))
8089 (prop (and (equal (char-before beg1) ?:)
8090 (not (equal (char-after (point-at-bol)) ?*))))
8091 (texp (equal (char-before beg) ?\\))
8092 (link (equal (char-before beg) ?\[))
8093 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8094 beg)
8095 "#+"))
8096 (startup (string-match "^#\\+STARTUP:.*"
8097 (buffer-substring (point-at-bol) (point))))
8098 (completion-ignore-case opt)
8099 (type nil)
8100 (tbl nil)
8101 (table (cond
8102 (opt
8103 (setq type :opt)
8104 (require 'org-exp)
8105 (append
8106 (mapcar
8107 (lambda (x)
8108 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8109 (cons (match-string 2 x) (match-string 1 x)))
8110 (org-split-string (org-get-current-options) "\n"))
8111 (mapcar 'list org-additional-option-like-keywords)))
8112 (startup
8113 (setq type :startup)
8114 org-startup-options)
8115 (link (append org-link-abbrev-alist-local
8116 org-link-abbrev-alist))
8117 (texp
8118 (setq type :tex)
8119 org-html-entities)
8120 ((string-match "\\`\\*+[ \t]+\\'"
8121 (buffer-substring (point-at-bol) beg))
8122 (setq type :todo)
8123 (mapcar 'list org-todo-keywords-1))
8124 (searchhead
8125 (setq type :searchhead)
8126 (save-excursion
8127 (goto-char (point-min))
8128 (while (re-search-forward org-todo-line-regexp nil t)
8129 (push (list
8130 (org-make-org-heading-search-string
8131 (match-string 3) t))
8132 tbl)))
8133 tbl)
8134 (tag (setq type :tag beg beg1)
8135 (or org-tag-alist (org-get-buffer-tags)))
8136 (prop (setq type :prop beg beg1)
8137 (mapcar 'list (org-buffer-property-keys nil t t)))
8138 (t (progn
8139 (call-interactively org-completion-fallback-command)
8140 (throw 'exit nil)))))
8141 (pattern (buffer-substring-no-properties beg end))
8142 (completion (try-completion pattern table confirm)))
8143 (cond ((eq completion t)
8144 (if (not (assoc (upcase pattern) table))
8145 (message "Already complete")
8146 (if (and (equal type :opt)
8147 (not (member (car (assoc (upcase pattern) table))
8148 org-additional-option-like-keywords)))
8149 (insert (substring (cdr (assoc (upcase pattern) table))
8150 (length pattern)))
8151 (if (memq type '(:tag :prop)) (insert ":")))))
8152 ((null completion)
8153 (message "Can't find completion for \"%s\"" pattern)
8154 (ding))
8155 ((not (string= pattern completion))
8156 (delete-region beg end)
8157 (if (string-match " +$" completion)
8158 (setq completion (replace-match "" t t completion)))
8159 (insert completion)
8160 (if (get-buffer-window "*Completions*")
8161 (delete-window (get-buffer-window "*Completions*")))
8162 (if (assoc completion table)
8163 (if (eq type :todo) (insert " ")
8164 (if (memq type '(:tag :prop)) (insert ":"))))
8165 (if (and (equal type :opt) (assoc completion table))
8166 (message "%s" (substitute-command-keys
8167 "Press \\[org-complete] again to insert example settings"))))
8169 (message "Making completion list...")
8170 (let ((list (sort (all-completions pattern table confirm)
8171 'string<)))
8172 (with-output-to-temp-buffer "*Completions*"
8173 (condition-case nil
8174 ;; Protection needed for XEmacs and emacs 21
8175 (display-completion-list list pattern)
8176 (error (display-completion-list list)))))
8177 (message "Making completion list...%s" "done")))))))
8179 ;;;; TODO, DEADLINE, Comments
8181 (defun org-toggle-comment ()
8182 "Change the COMMENT state of an entry."
8183 (interactive)
8184 (save-excursion
8185 (org-back-to-heading)
8186 (let (case-fold-search)
8187 (if (looking-at (concat outline-regexp
8188 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8189 (replace-match "" t t nil 1)
8190 (if (looking-at outline-regexp)
8191 (progn
8192 (goto-char (match-end 0))
8193 (insert org-comment-string " ")))))))
8195 (defvar org-last-todo-state-is-todo nil
8196 "This is non-nil when the last TODO state change led to a TODO state.
8197 If the last change removed the TODO tag or switched to DONE, then
8198 this is nil.")
8200 (defvar org-setting-tags nil) ; dynamically skipped
8202 (defun org-parse-local-options (string var)
8203 "Parse STRING for startup setting relevant for variable VAR."
8204 (let ((rtn (symbol-value var))
8205 e opts)
8206 (save-match-data
8207 (if (or (not string) (not (string-match "\\S-" string)))
8209 (setq opts (delq nil (mapcar (lambda (x)
8210 (setq e (assoc x org-startup-options))
8211 (if (eq (nth 1 e) var) e nil))
8212 (org-split-string string "[ \t]+"))))
8213 (if (not opts)
8215 (setq rtn nil)
8216 (while (setq e (pop opts))
8217 (if (not (nth 3 e))
8218 (setq rtn (nth 2 e))
8219 (if (not (listp rtn)) (setq rtn nil))
8220 (push (nth 2 e) rtn)))
8221 rtn)))))
8223 (defvar org-blocker-hook nil
8224 "Hook for functions that are allowed to block a state change.
8226 Each function gets as its single argument a property list, see
8227 `org-trigger-hook' for more information about this list.
8229 If any of the functions in this hook returns nil, the state change
8230 is blocked.")
8232 (defvar org-trigger-hook nil
8233 "Hook for functions that are triggered by a state change.
8235 Each function gets as its single argument a property list with at least
8236 the following elements:
8238 (:type type-of-change :position pos-at-entry-start
8239 :from old-state :to new-state)
8241 Depending on the type, more properties may be present.
8243 This mechanism is currently implemented for:
8245 TODO state changes
8246 ------------------
8247 :type todo-state-change
8248 :from previous state (keyword as a string), or nil
8249 :to new state (keyword as a string), or nil")
8251 (defvar org-agenda-headline-snapshot-before-repeat)
8252 (defun org-todo (&optional arg)
8253 "Change the TODO state of an item.
8254 The state of an item is given by a keyword at the start of the heading,
8255 like
8256 *** TODO Write paper
8257 *** DONE Call mom
8259 The different keywords are specified in the variable `org-todo-keywords'.
8260 By default the available states are \"TODO\" and \"DONE\".
8261 So for this example: when the item starts with TODO, it is changed to DONE.
8262 When it starts with DONE, the DONE is removed. And when neither TODO nor
8263 DONE are present, add TODO at the beginning of the heading.
8265 With C-u prefix arg, use completion to determine the new state.
8266 With numeric prefix arg, switch to that state.
8268 For calling through lisp, arg is also interpreted in the following way:
8269 'none -> empty state
8270 \"\"(empty string) -> switch to empty state
8271 'done -> switch to DONE
8272 'nextset -> switch to the next set of keywords
8273 'previousset -> switch to the previous set of keywords
8274 \"WAITING\" -> switch to the specified keyword, but only if it
8275 really is a member of `org-todo-keywords'."
8276 (interactive "P")
8277 (save-excursion
8278 (catch 'exit
8279 (org-back-to-heading)
8280 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8281 (or (looking-at (concat " +" org-todo-regexp " *"))
8282 (looking-at " *"))
8283 (let* ((match-data (match-data))
8284 (startpos (point-at-bol))
8285 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8286 (org-log-done org-log-done)
8287 (org-log-repeat org-log-repeat)
8288 (org-todo-log-states org-todo-log-states)
8289 (this (match-string 1))
8290 (hl-pos (match-beginning 0))
8291 (head (org-get-todo-sequence-head this))
8292 (ass (assoc head org-todo-kwd-alist))
8293 (interpret (nth 1 ass))
8294 (done-word (nth 3 ass))
8295 (final-done-word (nth 4 ass))
8296 (last-state (or this ""))
8297 (completion-ignore-case t)
8298 (member (member this org-todo-keywords-1))
8299 (tail (cdr member))
8300 (state (cond
8301 ((and org-todo-key-trigger
8302 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8303 (and (not arg) org-use-fast-todo-selection
8304 (not (eq org-use-fast-todo-selection 'prefix)))))
8305 ;; Use fast selection
8306 (org-fast-todo-selection))
8307 ((and (equal arg '(4))
8308 (or (not org-use-fast-todo-selection)
8309 (not org-todo-key-trigger)))
8310 ;; Read a state with completion
8311 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8312 org-todo-keywords-1)
8313 nil t))
8314 ((eq arg 'right)
8315 (if this
8316 (if tail (car tail) nil)
8317 (car org-todo-keywords-1)))
8318 ((eq arg 'left)
8319 (if (equal member org-todo-keywords-1)
8321 (if this
8322 (nth (- (length org-todo-keywords-1) (length tail) 2)
8323 org-todo-keywords-1)
8324 (org-last org-todo-keywords-1))))
8325 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8326 (setq arg nil))) ; hack to fall back to cycling
8327 (arg
8328 ;; user or caller requests a specific state
8329 (cond
8330 ((equal arg "") nil)
8331 ((eq arg 'none) nil)
8332 ((eq arg 'done) (or done-word (car org-done-keywords)))
8333 ((eq arg 'nextset)
8334 (or (car (cdr (member head org-todo-heads)))
8335 (car org-todo-heads)))
8336 ((eq arg 'previousset)
8337 (let ((org-todo-heads (reverse org-todo-heads)))
8338 (or (car (cdr (member head org-todo-heads)))
8339 (car org-todo-heads))))
8340 ((car (member arg org-todo-keywords-1)))
8341 ((nth (1- (prefix-numeric-value arg))
8342 org-todo-keywords-1))))
8343 ((null member) (or head (car org-todo-keywords-1)))
8344 ((equal this final-done-word) nil) ;; -> make empty
8345 ((null tail) nil) ;; -> first entry
8346 ((eq interpret 'sequence)
8347 (car tail))
8348 ((memq interpret '(type priority))
8349 (if (eq this-command last-command)
8350 (car tail)
8351 (if (> (length tail) 0)
8352 (or done-word (car org-done-keywords))
8353 nil)))
8354 (t nil)))
8355 (next (if state (concat " " state " ") " "))
8356 (change-plist (list :type 'todo-state-change :from this :to state
8357 :position startpos))
8358 dolog now-done-p)
8359 (when org-blocker-hook
8360 (unless (save-excursion
8361 (save-match-data
8362 (run-hook-with-args-until-failure
8363 'org-blocker-hook change-plist)))
8364 (if (interactive-p)
8365 (error "TODO state change from %s to %s blocked" this state)
8366 ;; fail silently
8367 (message "TODO state change from %s to %s blocked" this state)
8368 (throw 'exit nil))))
8369 (store-match-data match-data)
8370 (replace-match next t t)
8371 (unless (pos-visible-in-window-p hl-pos)
8372 (message "TODO state changed to %s" (org-trim next)))
8373 (unless head
8374 (setq head (org-get-todo-sequence-head state)
8375 ass (assoc head org-todo-kwd-alist)
8376 interpret (nth 1 ass)
8377 done-word (nth 3 ass)
8378 final-done-word (nth 4 ass)))
8379 (when (memq arg '(nextset previousset))
8380 (message "Keyword-Set %d/%d: %s"
8381 (- (length org-todo-sets) -1
8382 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8383 (length org-todo-sets)
8384 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8385 (setq org-last-todo-state-is-todo
8386 (not (member state org-done-keywords)))
8387 (setq now-done-p (and (member state org-done-keywords)
8388 (not (member this org-done-keywords))))
8389 (and logging (org-local-logging logging))
8390 (when (and (or org-todo-log-states org-log-done)
8391 (not (memq arg '(nextset previousset))))
8392 ;; we need to look at recording a time and note
8393 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8394 (nth 2 (assoc this org-todo-log-states))))
8395 (when (and state
8396 (member state org-not-done-keywords)
8397 (not (member this org-not-done-keywords)))
8398 ;; This is now a todo state and was not one before
8399 ;; If there was a CLOSED time stamp, get rid of it.
8400 (org-add-planning-info nil nil 'closed))
8401 (when (and now-done-p org-log-done)
8402 ;; It is now done, and it was not done before
8403 (org-add-planning-info 'closed (org-current-time))
8404 (if (and (not dolog) (eq 'note org-log-done))
8405 (org-add-log-setup 'done state 'findpos 'note)))
8406 (when (and state dolog)
8407 ;; This is a non-nil state, and we need to log it
8408 (org-add-log-setup 'state state 'findpos dolog)))
8409 ;; Fixup tag positioning
8410 (org-todo-trigger-tag-changes state)
8411 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8412 (when org-provide-todo-statistics
8413 (org-update-parent-todo-statistics))
8414 (run-hooks 'org-after-todo-state-change-hook)
8415 (if (and arg (not (member state org-done-keywords)))
8416 (setq head (org-get-todo-sequence-head state)))
8417 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8418 ;; Do we need to trigger a repeat?
8419 (when now-done-p
8420 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8421 ;; This is for the agenda, take a snapshot of the headline.
8422 (save-match-data
8423 (setq org-agenda-headline-snapshot-before-repeat
8424 (org-get-heading))))
8425 (org-auto-repeat-maybe state))
8426 ;; Fixup cursor location if close to the keyword
8427 (if (and (outline-on-heading-p)
8428 (not (bolp))
8429 (save-excursion (beginning-of-line 1)
8430 (looking-at org-todo-line-regexp))
8431 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8432 (progn
8433 (goto-char (or (match-end 2) (match-end 1)))
8434 (just-one-space)))
8435 (when org-trigger-hook
8436 (save-excursion
8437 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8439 (defun org-update-parent-todo-statistics ()
8440 "Update any statistics cookie in the parent of the current headline."
8441 (interactive)
8442 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8443 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8444 (catch 'exit
8445 (save-excursion
8446 (setq level (org-up-heading-safe))
8447 (unless (and level
8448 (re-search-forward box-re (point-at-eol) t))
8449 (throw 'exit nil))
8450 (setq is-percent (match-end 2))
8451 (save-match-data
8452 (unless (outline-next-heading) (throw 'exit nil))
8453 (while (looking-at org-todo-line-regexp)
8454 (setq kwd (match-string 2))
8455 (and kwd (setq cnt-all (1+ cnt-all)))
8456 (and (member kwd org-done-keywords)
8457 (setq cnt-done (1+ cnt-done)))
8458 (condition-case nil
8459 (org-forward-same-level 1)
8460 (error (end-of-line 1)))))
8461 (replace-match
8462 (if is-percent
8463 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8464 (format "[%d/%d]" cnt-done cnt-all)))
8465 (run-hook-with-args 'org-after-todo-statistics-hook
8466 cnt-done (- cnt-all cnt-done))))))
8468 (defvar org-after-todo-statistics-hook nil
8469 "Hook that is called after a TODO statistics cookie has been updated.
8470 Each function is called with two arguments: the number of not-done entries
8471 and the number of done entries.
8473 For example, the following function, when added to this hook, will switch
8474 an entry to DONE when all children are done, and back to TODO when new
8475 entries are set to a TODO status. Note that this hook is only called
8476 when there is a statistics cookie in the headline!
8478 (defun org-summary-todo (n-done n-not-done)
8479 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8480 (let (org-log-done org-log-states) ; turn off logging
8481 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8484 (defun org-todo-trigger-tag-changes (state)
8485 "Apply the changes defined in `org-todo-state-tags-triggers'."
8486 (let ((l org-todo-state-tags-triggers)
8487 changes)
8488 (when (or (not state) (equal state ""))
8489 (setq changes (append changes (cdr (assoc "" l)))))
8490 (when (and (stringp state) (> (length state) 0))
8491 (setq changes (append changes (cdr (assoc state l)))))
8492 (when (member state org-not-done-keywords)
8493 (setq changes (append changes (cdr (assoc 'todo l)))))
8494 (when (member state org-done-keywords)
8495 (setq changes (append changes (cdr (assoc 'done l)))))
8496 (dolist (c changes)
8497 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8499 (defun org-local-logging (value)
8500 "Get logging settings from a property VALUE."
8501 (let* (words w a)
8502 ;; directly set the variables, they are already local.
8503 (setq org-log-done nil
8504 org-log-repeat nil
8505 org-todo-log-states nil)
8506 (setq words (org-split-string value))
8507 (while (setq w (pop words))
8508 (cond
8509 ((setq a (assoc w org-startup-options))
8510 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8511 (set (nth 1 a) (nth 2 a))))
8512 ((setq a (org-extract-log-state-settings w))
8513 (and (member (car a) org-todo-keywords-1)
8514 (push a org-todo-log-states)))))))
8516 (defun org-get-todo-sequence-head (kwd)
8517 "Return the head of the TODO sequence to which KWD belongs.
8518 If KWD is not set, check if there is a text property remembering the
8519 right sequence."
8520 (let (p)
8521 (cond
8522 ((not kwd)
8523 (or (get-text-property (point-at-bol) 'org-todo-head)
8524 (progn
8525 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8526 nil (point-at-eol)))
8527 (get-text-property p 'org-todo-head))))
8528 ((not (member kwd org-todo-keywords-1))
8529 (car org-todo-keywords-1))
8530 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8532 (defun org-fast-todo-selection ()
8533 "Fast TODO keyword selection with single keys.
8534 Returns the new TODO keyword, or nil if no state change should occur."
8535 (let* ((fulltable org-todo-key-alist)
8536 (done-keywords org-done-keywords) ;; needed for the faces.
8537 (maxlen (apply 'max (mapcar
8538 (lambda (x)
8539 (if (stringp (car x)) (string-width (car x)) 0))
8540 fulltable)))
8541 (expert nil)
8542 (fwidth (+ maxlen 3 1 3))
8543 (ncol (/ (- (window-width) 4) fwidth))
8544 tg cnt e c tbl
8545 groups ingroup)
8546 (save-window-excursion
8547 (if expert
8548 (set-buffer (get-buffer-create " *Org todo*"))
8549 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8550 (erase-buffer)
8551 (org-set-local 'org-done-keywords done-keywords)
8552 (setq tbl fulltable cnt 0)
8553 (while (setq e (pop tbl))
8554 (cond
8555 ((equal e '(:startgroup))
8556 (push '() groups) (setq ingroup t)
8557 (when (not (= cnt 0))
8558 (setq cnt 0)
8559 (insert "\n"))
8560 (insert "{ "))
8561 ((equal e '(:endgroup))
8562 (setq ingroup nil cnt 0)
8563 (insert "}\n"))
8565 (setq tg (car e) c (cdr e))
8566 (if ingroup (push tg (car groups)))
8567 (setq tg (org-add-props tg nil 'face
8568 (org-get-todo-face tg)))
8569 (if (and (= cnt 0) (not ingroup)) (insert " "))
8570 (insert "[" c "] " tg (make-string
8571 (- fwidth 4 (length tg)) ?\ ))
8572 (when (= (setq cnt (1+ cnt)) ncol)
8573 (insert "\n")
8574 (if ingroup (insert " "))
8575 (setq cnt 0)))))
8576 (insert "\n")
8577 (goto-char (point-min))
8578 (if (not expert) (org-fit-window-to-buffer))
8579 (message "[a-z..]:Set [SPC]:clear")
8580 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8581 (cond
8582 ((or (= c ?\C-g)
8583 (and (= c ?q) (not (rassoc c fulltable))))
8584 (setq quit-flag t))
8585 ((= c ?\ ) nil)
8586 ((setq e (rassoc c fulltable) tg (car e))
8588 (t (setq quit-flag t))))))
8590 (defun org-entry-is-todo-p ()
8591 (member (org-get-todo-state) org-not-done-keywords))
8593 (defun org-entry-is-done-p ()
8594 (member (org-get-todo-state) org-done-keywords))
8596 (defun org-get-todo-state ()
8597 (save-excursion
8598 (org-back-to-heading t)
8599 (and (looking-at org-todo-line-regexp)
8600 (match-end 2)
8601 (match-string 2))))
8603 (defun org-at-date-range-p (&optional inactive-ok)
8604 "Is the cursor inside a date range?"
8605 (interactive)
8606 (save-excursion
8607 (catch 'exit
8608 (let ((pos (point)))
8609 (skip-chars-backward "^[<\r\n")
8610 (skip-chars-backward "<[")
8611 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8612 (>= (match-end 0) pos)
8613 (throw 'exit t))
8614 (skip-chars-backward "^<[\r\n")
8615 (skip-chars-backward "<[")
8616 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8617 (>= (match-end 0) pos)
8618 (throw 'exit t)))
8619 nil)))
8621 (defun org-get-repeat ()
8622 "Check if there is a deadline/schedule with repeater in this entry."
8623 (save-match-data
8624 (save-excursion
8625 (org-back-to-heading t)
8626 (if (re-search-forward
8627 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8628 (match-string 1)))))
8630 (defvar org-last-changed-timestamp)
8631 (defvar org-last-inserted-timestamp)
8632 (defvar org-log-post-message)
8633 (defvar org-log-note-purpose)
8634 (defvar org-log-note-how)
8635 (defvar org-log-note-extra)
8636 (defun org-auto-repeat-maybe (done-word)
8637 "Check if the current headline contains a repeated deadline/schedule.
8638 If yes, set TODO state back to what it was and change the base date
8639 of repeating deadline/scheduled time stamps to new date.
8640 This function is run automatically after each state change to a DONE state."
8641 ;; last-state is dynamically scoped into this function
8642 (let* ((repeat (org-get-repeat))
8643 (aa (assoc last-state org-todo-kwd-alist))
8644 (interpret (nth 1 aa))
8645 (head (nth 2 aa))
8646 (whata '(("d" . day) ("m" . month) ("y" . year)))
8647 (msg "Entry repeats: ")
8648 (org-log-done nil)
8649 (org-todo-log-states nil)
8650 (nshiftmax 10) (nshift 0)
8651 re type n what ts mb0 time)
8652 (when repeat
8653 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8654 (org-todo (if (eq interpret 'type) last-state head))
8655 (when org-log-repeat
8656 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8657 (memq 'org-add-log-note post-command-hook))
8658 ;; OK, we are already setup for some record
8659 (if (eq org-log-repeat 'note)
8660 ;; make sure we take a note, not only a time stamp
8661 (setq org-log-note-how 'note))
8662 ;; Set up for taking a record
8663 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8664 'findpos org-log-repeat)))
8665 (org-back-to-heading t)
8666 (org-add-planning-info nil nil 'closed)
8667 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8668 org-deadline-time-regexp "\\)\\|\\("
8669 org-ts-regexp "\\)"))
8670 (while (re-search-forward
8671 re (save-excursion (outline-next-heading) (point)) t)
8672 (setq type (if (match-end 1) org-scheduled-string
8673 (if (match-end 3) org-deadline-string "Plain:"))
8674 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8675 mb0 (match-beginning 0))
8676 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8677 (setq n (string-to-number (match-string 2 ts))
8678 what (match-string 3 ts))
8679 (if (equal what "w") (setq n (* n 7) what "d"))
8680 ;; Preparation, see if we need to modify the start date for the change
8681 (when (match-end 1)
8682 (setq time (save-match-data (org-time-string-to-time ts)))
8683 (cond
8684 ((equal (match-string 1 ts) ".")
8685 ;; Shift starting date to today
8686 (org-timestamp-change
8687 (- (time-to-days (current-time)) (time-to-days time))
8688 'day))
8689 ((equal (match-string 1 ts) "+")
8690 (while (or (= nshift 0)
8691 (<= (time-to-days time) (time-to-days (current-time))))
8692 (when (= (incf nshift) nshiftmax)
8693 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8694 (error "Abort")))
8695 (org-timestamp-change n (cdr (assoc what whata)))
8696 (org-at-timestamp-p t)
8697 (setq ts (match-string 1))
8698 (setq time (save-match-data (org-time-string-to-time ts))))
8699 (org-timestamp-change (- n) (cdr (assoc what whata)))
8700 ;; rematch, so that we have everything in place for the real shift
8701 (org-at-timestamp-p t)
8702 (setq ts (match-string 1))
8703 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8704 (org-timestamp-change n (cdr (assoc what whata)))
8705 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8706 (setq org-log-post-message msg)
8707 (message "%s" msg))))
8709 (defun org-show-todo-tree (arg)
8710 "Make a compact tree which shows all headlines marked with TODO.
8711 The tree will show the lines where the regexp matches, and all higher
8712 headlines above the match.
8713 With a \\[universal-argument] prefix, also show the DONE entries.
8714 With a numeric prefix N, construct a sparse tree for the Nth element
8715 of `org-todo-keywords-1'."
8716 (interactive "P")
8717 (let ((case-fold-search nil)
8718 (kwd-re
8719 (cond ((null arg) org-not-done-regexp)
8720 ((equal arg '(4))
8721 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8722 (mapcar 'list org-todo-keywords-1))))
8723 (concat "\\("
8724 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8725 "\\)\\>")))
8726 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8727 (regexp-quote (nth (1- (prefix-numeric-value arg))
8728 org-todo-keywords-1)))
8729 (t (error "Invalid prefix argument: %s" arg)))))
8730 (message "%d TODO entries found"
8731 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8733 (defun org-deadline (&optional remove time)
8734 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8735 With argument REMOVE, remove any deadline from the item.
8736 When TIME is set, it should be an internal time specification, and the
8737 scheduling will use the corresponding date."
8738 (interactive "P")
8739 (if remove
8740 (progn
8741 (org-remove-timestamp-with-keyword org-deadline-string)
8742 (message "Item no longer has a deadline."))
8743 (if (org-get-repeat)
8744 (error "Cannot change deadline on task with repeater, please do that by hand")
8745 (org-add-planning-info 'deadline time 'closed)
8746 (message "Deadline on %s" org-last-inserted-timestamp))))
8748 (defun org-schedule (&optional remove time)
8749 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8750 With argument REMOVE, remove any scheduling date from the item.
8751 When TIME is set, it should be an internal time specification, and the
8752 scheduling will use the corresponding date."
8753 (interactive "P")
8754 (if remove
8755 (progn
8756 (org-remove-timestamp-with-keyword org-scheduled-string)
8757 (message "Item is no longer scheduled."))
8758 (if (org-get-repeat)
8759 (error "Cannot reschedule task with repeater, please do that by hand")
8760 (org-add-planning-info 'scheduled time 'closed)
8761 (message "Scheduled to %s" org-last-inserted-timestamp))))
8763 (defun org-remove-timestamp-with-keyword (keyword)
8764 "Remove all time stamps with KEYWORD in the current entry."
8765 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8766 beg)
8767 (save-excursion
8768 (org-back-to-heading t)
8769 (setq beg (point))
8770 (org-end-of-subtree t t)
8771 (while (re-search-backward re beg t)
8772 (replace-match "")
8773 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8774 (equal (char-before) ?\ ))
8775 (backward-delete-char 1)
8776 (if (string-match "^[ \t]*$" (buffer-substring
8777 (point-at-bol) (point-at-eol)))
8778 (delete-region (point-at-bol)
8779 (min (point-max) (1+ (point-at-eol))))))))))
8781 (defun org-add-planning-info (what &optional time &rest remove)
8782 "Insert new timestamp with keyword in the line directly after the headline.
8783 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8784 If non is given, the user is prompted for a date.
8785 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8786 be removed."
8787 (interactive)
8788 (let (org-time-was-given org-end-time-was-given ts
8789 end default-time default-input)
8791 (when (and (not time) (memq what '(scheduled deadline)))
8792 ;; Try to get a default date/time from existing timestamp
8793 (save-excursion
8794 (org-back-to-heading t)
8795 (setq end (save-excursion (outline-next-heading) (point)))
8796 (when (re-search-forward (if (eq what 'scheduled)
8797 org-scheduled-time-regexp
8798 org-deadline-time-regexp)
8799 end t)
8800 (setq ts (match-string 1)
8801 default-time
8802 (apply 'encode-time (org-parse-time-string ts))
8803 default-input (and ts (org-get-compact-tod ts))))))
8804 (when what
8805 ;; If necessary, get the time from the user
8806 (setq time (or time (org-read-date nil 'to-time nil nil
8807 default-time default-input))))
8809 (when (and org-insert-labeled-timestamps-at-point
8810 (member what '(scheduled deadline)))
8811 (insert
8812 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8813 (org-insert-time-stamp time org-time-was-given
8814 nil nil nil (list org-end-time-was-given))
8815 (setq what nil))
8816 (save-excursion
8817 (save-restriction
8818 (let (col list elt ts buffer-invisibility-spec)
8819 (org-back-to-heading t)
8820 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8821 (goto-char (match-end 1))
8822 (setq col (current-column))
8823 (goto-char (match-end 0))
8824 (if (eobp) (insert "\n") (forward-char 1))
8825 (if (and (not (looking-at outline-regexp))
8826 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8827 "[^\r\n]*"))
8828 (not (equal (match-string 1) org-clock-string)))
8829 (narrow-to-region (match-beginning 0) (match-end 0))
8830 (insert-before-markers "\n")
8831 (backward-char 1)
8832 (narrow-to-region (point) (point))
8833 (and org-adapt-indentation (org-indent-to-column col)))
8834 ;; Check if we have to remove something.
8835 (setq list (cons what remove))
8836 (while list
8837 (setq elt (pop list))
8838 (goto-char (point-min))
8839 (when (or (and (eq elt 'scheduled)
8840 (re-search-forward org-scheduled-time-regexp nil t))
8841 (and (eq elt 'deadline)
8842 (re-search-forward org-deadline-time-regexp nil t))
8843 (and (eq elt 'closed)
8844 (re-search-forward org-closed-time-regexp nil t)))
8845 (replace-match "")
8846 (if (looking-at "--+<[^>]+>") (replace-match ""))
8847 (if (looking-at " +") (replace-match ""))))
8848 (goto-char (point-max))
8849 (when what
8850 (insert
8851 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8852 (cond ((eq what 'scheduled) org-scheduled-string)
8853 ((eq what 'deadline) org-deadline-string)
8854 ((eq what 'closed) org-closed-string))
8855 " ")
8856 (setq ts (org-insert-time-stamp
8857 time
8858 (or org-time-was-given
8859 (and (eq what 'closed) org-log-done-with-time))
8860 (eq what 'closed)
8861 nil nil (list org-end-time-was-given)))
8862 (end-of-line 1))
8863 (goto-char (point-min))
8864 (widen)
8865 (if (and (looking-at "[ \t]+\n")
8866 (equal (char-before) ?\n))
8867 (delete-region (1- (point)) (point-at-eol)))
8868 ts)))))
8870 (defvar org-log-note-marker (make-marker))
8871 (defvar org-log-note-purpose nil)
8872 (defvar org-log-note-state nil)
8873 (defvar org-log-note-how nil)
8874 (defvar org-log-note-extra nil)
8875 (defvar org-log-note-window-configuration nil)
8876 (defvar org-log-note-return-to (make-marker))
8877 (defvar org-log-post-message nil
8878 "Message to be displayed after a log note has been stored.
8879 The auto-repeater uses this.")
8881 (defun org-add-note ()
8882 "Add a note to the current entry.
8883 This is done in the same way as adding a state change note."
8884 (interactive)
8885 (org-add-log-setup 'note nil 'findpos nil))
8887 (defvar org-property-end-re)
8888 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8889 "Set up the post command hook to take a note.
8890 If this is about to TODO state change, the new state is expected in STATE.
8891 When FINDPOS is non-nil, find the correct position for the note in
8892 the current entry. If not, assume that it can be inserted at point.
8893 HOW is an indicator what kind of note should be created.
8894 EXTRA is additional text that will be inserted into the notes buffer."
8895 (save-restriction
8896 (save-excursion
8897 (when findpos
8898 (org-back-to-heading t)
8899 (narrow-to-region (point) (save-excursion
8900 (outline-next-heading) (point)))
8901 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8902 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8903 "[^\r\n]*\\)?"))
8904 (goto-char (match-end 0))
8905 (when (and org-log-state-notes-insert-after-drawers
8906 (save-excursion
8907 (forward-line) (looking-at org-drawer-regexp)))
8908 (progn (forward-line)
8909 (while (looking-at org-drawer-regexp)
8910 (goto-char (match-end 0))
8911 (re-search-forward org-property-end-re (point-max) t)
8912 (forward-line))
8913 (forward-line -1)))
8914 (unless org-log-states-order-reversed
8915 (and (= (char-after) ?\n) (forward-char 1))
8916 (org-skip-over-state-notes)
8917 (skip-chars-backward " \t\n\r")))
8918 (move-marker org-log-note-marker (point))
8919 (setq org-log-note-purpose purpose
8920 org-log-note-state state
8921 org-log-note-how how
8922 org-log-note-extra extra)
8923 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8925 (defun org-skip-over-state-notes ()
8926 "Skip past the list of State notes in an entry."
8927 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8928 (while (looking-at "[ \t]*- State")
8929 (condition-case nil
8930 (org-next-item)
8931 (error (org-end-of-item)))))
8933 (defun org-add-log-note (&optional purpose)
8934 "Pop up a window for taking a note, and add this note later at point."
8935 (remove-hook 'post-command-hook 'org-add-log-note)
8936 (setq org-log-note-window-configuration (current-window-configuration))
8937 (delete-other-windows)
8938 (move-marker org-log-note-return-to (point))
8939 (switch-to-buffer (marker-buffer org-log-note-marker))
8940 (goto-char org-log-note-marker)
8941 (org-switch-to-buffer-other-window "*Org Note*")
8942 (erase-buffer)
8943 (if (memq org-log-note-how '(time state))
8944 (let (current-prefix-arg) (org-store-log-note))
8945 (let ((org-inhibit-startup t)) (org-mode))
8946 (insert (format "# Insert note for %s.
8947 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8948 (cond
8949 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8950 ((eq org-log-note-purpose 'done) "closed todo item")
8951 ((eq org-log-note-purpose 'state)
8952 (format "state change to \"%s\"" org-log-note-state))
8953 ((eq org-log-note-purpose 'note)
8954 "this entry")
8955 (t (error "This should not happen")))))
8956 (if org-log-note-extra (insert org-log-note-extra))
8957 (org-set-local 'org-finish-function 'org-store-log-note)))
8959 (defvar org-note-abort nil) ; dynamically scoped
8960 (defun org-store-log-note ()
8961 "Finish taking a log note, and insert it to where it belongs."
8962 (let ((txt (buffer-string))
8963 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8964 lines ind)
8965 (kill-buffer (current-buffer))
8966 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8967 (setq txt (replace-match "" t t txt)))
8968 (if (string-match "\\s-+\\'" txt)
8969 (setq txt (replace-match "" t t txt)))
8970 (setq lines (org-split-string txt "\n"))
8971 (when (and note (string-match "\\S-" note))
8972 (setq note
8973 (org-replace-escapes
8974 note
8975 (list (cons "%u" (user-login-name))
8976 (cons "%U" user-full-name)
8977 (cons "%t" (format-time-string
8978 (org-time-stamp-format 'long 'inactive)
8979 (current-time)))
8980 (cons "%s" (if org-log-note-state
8981 (concat "\"" org-log-note-state "\"")
8982 "")))))
8983 (if lines (setq note (concat note " \\\\")))
8984 (push note lines))
8985 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8986 (when lines
8987 (save-excursion
8988 (set-buffer (marker-buffer org-log-note-marker))
8989 (save-excursion
8990 (goto-char org-log-note-marker)
8991 (move-marker org-log-note-marker nil)
8992 (end-of-line 1)
8993 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8994 (indent-relative nil)
8995 (insert "- " (pop lines))
8996 (org-indent-line-function)
8997 (beginning-of-line 1)
8998 (looking-at "[ \t]*")
8999 (setq ind (concat (match-string 0) " "))
9000 (end-of-line 1)
9001 (while lines (insert "\n" ind (pop lines)))))))
9002 (set-window-configuration org-log-note-window-configuration)
9003 (with-current-buffer (marker-buffer org-log-note-return-to)
9004 (goto-char org-log-note-return-to))
9005 (move-marker org-log-note-return-to nil)
9006 (and org-log-post-message (message "%s" org-log-post-message)))
9008 (defun org-sparse-tree (&optional arg)
9009 "Create a sparse tree, prompt for the details.
9010 This command can create sparse trees. You first need to select the type
9011 of match used to create the tree:
9013 t Show entries with a specific TODO keyword.
9014 T Show entries selected by a tags match.
9015 p Enter a property name and its value (both with completion on existing
9016 names/values) and show entries with that property.
9017 r Show entries matching a regular expression
9018 d Show deadlines due within `org-deadline-warning-days'."
9019 (interactive "P")
9020 (let (ans kwd value)
9021 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9022 (setq ans (read-char-exclusive))
9023 (cond
9024 ((equal ans ?d)
9025 (call-interactively 'org-check-deadlines))
9026 ((equal ans ?b)
9027 (call-interactively 'org-check-before-date))
9028 ((equal ans ?t)
9029 (org-show-todo-tree '(4)))
9030 ((equal ans ?T)
9031 (call-interactively 'org-tags-sparse-tree))
9032 ((member ans '(?p ?P))
9033 (setq kwd (org-ido-completing-read "Property: "
9034 (mapcar 'list (org-buffer-property-keys))))
9035 (setq value (org-ido-completing-read "Value: "
9036 (mapcar 'list (org-property-values kwd))))
9037 (unless (string-match "\\`{.*}\\'" value)
9038 (setq value (concat "\"" value "\"")))
9039 (org-tags-sparse-tree arg (concat kwd "=" value)))
9040 ((member ans '(?r ?R ?/))
9041 (call-interactively 'org-occur))
9042 (t (error "No such sparse tree command \"%c\"" ans)))))
9044 (defvar org-occur-highlights nil
9045 "List of overlays used for occur matches.")
9046 (make-variable-buffer-local 'org-occur-highlights)
9047 (defvar org-occur-parameters nil
9048 "Parameters of the active org-occur calls.
9049 This is a list, each call to org-occur pushes as cons cell,
9050 containing the regular expression and the callback, onto the list.
9051 The list can contain several entries if `org-occur' has been called
9052 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9053 will only contain one set of parameters. When the highlights are
9054 removed (for example with `C-c C-c', or with the next edit (depending
9055 on `org-remove-highlights-with-change'), this variable is emptied
9056 as well.")
9057 (make-variable-buffer-local 'org-occur-parameters)
9059 (defun org-occur (regexp &optional keep-previous callback)
9060 "Make a compact tree which shows all matches of REGEXP.
9061 The tree will show the lines where the regexp matches, and all higher
9062 headlines above the match. It will also show the heading after the match,
9063 to make sure editing the matching entry is easy.
9064 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9065 call to `org-occur' will be kept, to allow stacking of calls to this
9066 command.
9067 If CALLBACK is non-nil, it is a function which is called to confirm
9068 that the match should indeed be shown."
9069 (interactive "sRegexp: \nP")
9070 (unless keep-previous
9071 (org-remove-occur-highlights nil nil t))
9072 (push (cons regexp callback) org-occur-parameters)
9073 (let ((cnt 0))
9074 (save-excursion
9075 (goto-char (point-min))
9076 (if (or (not keep-previous) ; do not want to keep
9077 (not org-occur-highlights)) ; no previous matches
9078 ;; hide everything
9079 (org-overview))
9080 (while (re-search-forward regexp nil t)
9081 (when (or (not callback)
9082 (save-match-data (funcall callback)))
9083 (setq cnt (1+ cnt))
9084 (when org-highlight-sparse-tree-matches
9085 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9086 (org-show-context 'occur-tree))))
9087 (when org-remove-highlights-with-change
9088 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9089 nil 'local))
9090 (unless org-sparse-tree-open-archived-trees
9091 (org-hide-archived-subtrees (point-min) (point-max)))
9092 (run-hooks 'org-occur-hook)
9093 (if (interactive-p)
9094 (message "%d match(es) for regexp %s" cnt regexp))
9095 cnt))
9097 (defun org-show-context (&optional key)
9098 "Make sure point and context and visible.
9099 How much context is shown depends upon the variables
9100 `org-show-hierarchy-above', `org-show-following-heading'. and
9101 `org-show-siblings'."
9102 (let ((heading-p (org-on-heading-p t))
9103 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9104 (following-p (org-get-alist-option org-show-following-heading key))
9105 (entry-p (org-get-alist-option org-show-entry-below key))
9106 (siblings-p (org-get-alist-option org-show-siblings key)))
9107 (catch 'exit
9108 ;; Show heading or entry text
9109 (if (and heading-p (not entry-p))
9110 (org-flag-heading nil) ; only show the heading
9111 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9112 (org-show-hidden-entry))) ; show entire entry
9113 (when following-p
9114 ;; Show next sibling, or heading below text
9115 (save-excursion
9116 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9117 (org-flag-heading nil))))
9118 (when siblings-p (org-show-siblings))
9119 (when hierarchy-p
9120 ;; show all higher headings, possibly with siblings
9121 (save-excursion
9122 (while (and (condition-case nil
9123 (progn (org-up-heading-all 1) t)
9124 (error nil))
9125 (not (bobp)))
9126 (org-flag-heading nil)
9127 (when siblings-p (org-show-siblings))))))))
9129 (defun org-reveal (&optional siblings)
9130 "Show current entry, hierarchy above it, and the following headline.
9131 This can be used to show a consistent set of context around locations
9132 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9133 not t for the search context.
9135 With optional argument SIBLINGS, on each level of the hierarchy all
9136 siblings are shown. This repairs the tree structure to what it would
9137 look like when opened with hierarchical calls to `org-cycle'."
9138 (interactive "P")
9139 (let ((org-show-hierarchy-above t)
9140 (org-show-following-heading t)
9141 (org-show-siblings (if siblings t org-show-siblings)))
9142 (org-show-context nil)))
9144 (defun org-highlight-new-match (beg end)
9145 "Highlight from BEG to END and mark the highlight is an occur headline."
9146 (let ((ov (org-make-overlay beg end)))
9147 (org-overlay-put ov 'face 'secondary-selection)
9148 (push ov org-occur-highlights)))
9150 (defun org-remove-occur-highlights (&optional beg end noremove)
9151 "Remove the occur highlights from the buffer.
9152 BEG and END are ignored. If NOREMOVE is nil, remove this function
9153 from the `before-change-functions' in the current buffer."
9154 (interactive)
9155 (unless org-inhibit-highlight-removal
9156 (mapc 'org-delete-overlay org-occur-highlights)
9157 (setq org-occur-highlights nil)
9158 (setq org-occur-parameters nil)
9159 (unless noremove
9160 (remove-hook 'before-change-functions
9161 'org-remove-occur-highlights 'local))))
9163 ;;;; Priorities
9165 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9166 "Regular expression matching the priority indicator.")
9168 (defvar org-remove-priority-next-time nil)
9170 (defun org-priority-up ()
9171 "Increase the priority of the current item."
9172 (interactive)
9173 (org-priority 'up))
9175 (defun org-priority-down ()
9176 "Decrease the priority of the current item."
9177 (interactive)
9178 (org-priority 'down))
9180 (defun org-priority (&optional action)
9181 "Change the priority of an item by ARG.
9182 ACTION can be `set', `up', `down', or a character."
9183 (interactive)
9184 (setq action (or action 'set))
9185 (let (current new news have remove)
9186 (save-excursion
9187 (org-back-to-heading)
9188 (if (looking-at org-priority-regexp)
9189 (setq current (string-to-char (match-string 2))
9190 have t)
9191 (setq current org-default-priority))
9192 (cond
9193 ((or (eq action 'set)
9194 (if (featurep 'xemacs) (characterp action) (integerp action)))
9195 (if (not (eq action 'set))
9196 (setq new action)
9197 (message "Priority %c-%c, SPC to remove: "
9198 org-highest-priority org-lowest-priority)
9199 (setq new (read-char-exclusive)))
9200 (if (and (= (upcase org-highest-priority) org-highest-priority)
9201 (= (upcase org-lowest-priority) org-lowest-priority))
9202 (setq new (upcase new)))
9203 (cond ((equal new ?\ ) (setq remove t))
9204 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9205 (error "Priority must be between `%c' and `%c'"
9206 org-highest-priority org-lowest-priority))))
9207 ((eq action 'up)
9208 (if (and (not have) (eq last-command this-command))
9209 (setq new org-lowest-priority)
9210 (setq new (if (and org-priority-start-cycle-with-default (not have))
9211 org-default-priority (1- current)))))
9212 ((eq action 'down)
9213 (if (and (not have) (eq last-command this-command))
9214 (setq new org-highest-priority)
9215 (setq new (if (and org-priority-start-cycle-with-default (not have))
9216 org-default-priority (1+ current)))))
9217 (t (error "Invalid action")))
9218 (if (or (< (upcase new) org-highest-priority)
9219 (> (upcase new) org-lowest-priority))
9220 (setq remove t))
9221 (setq news (format "%c" new))
9222 (if have
9223 (if remove
9224 (replace-match "" t t nil 1)
9225 (replace-match news t t nil 2))
9226 (if remove
9227 (error "No priority cookie found in line")
9228 (looking-at org-todo-line-regexp)
9229 (if (match-end 2)
9230 (progn
9231 (goto-char (match-end 2))
9232 (insert " [#" news "]"))
9233 (goto-char (match-beginning 3))
9234 (insert "[#" news "] ")))))
9235 (org-preserve-lc (org-set-tags nil 'align))
9236 (if remove
9237 (message "Priority removed")
9238 (message "Priority of current item set to %s" news))))
9241 (defun org-get-priority (s)
9242 "Find priority cookie and return priority."
9243 (save-match-data
9244 (if (not (string-match org-priority-regexp s))
9245 (* 1000 (- org-lowest-priority org-default-priority))
9246 (* 1000 (- org-lowest-priority
9247 (string-to-char (match-string 2 s)))))))
9249 ;;;; Tags
9251 (defvar org-agenda-archives-mode)
9252 (defun org-scan-tags (action matcher &optional todo-only)
9253 "Scan headline tags with inheritance and produce output ACTION.
9255 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9256 or `agenda' to produce an entry list for an agenda view. It can also be
9257 a Lisp form or a function that should be called at each matched headline, in
9258 this case the return value is a list of all return values from these calls.
9260 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9261 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9262 only lines with a TODO keyword are included in the output."
9263 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9264 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9265 (org-re
9266 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9267 (props (list 'face 'default
9268 'done-face 'org-done
9269 'undone-face 'default
9270 'mouse-face 'highlight
9271 'org-not-done-regexp org-not-done-regexp
9272 'org-todo-regexp org-todo-regexp
9273 'keymap org-agenda-keymap
9274 'help-echo
9275 (format "mouse-2 or RET jump to org file %s"
9276 (abbreviate-file-name
9277 (or (buffer-file-name (buffer-base-buffer))
9278 (buffer-name (buffer-base-buffer)))))))
9279 (case-fold-search nil)
9280 lspos tags tags-list
9281 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9282 (llast 0) rtn rtn1 level category i txt
9283 todo marker entry priority)
9284 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9285 (setq action (list 'lambda nil action)))
9286 (save-excursion
9287 (goto-char (point-min))
9288 (when (eq action 'sparse-tree)
9289 (org-overview)
9290 (org-remove-occur-highlights))
9291 (while (re-search-forward re nil t)
9292 (catch :skip
9293 (setq todo (if (match-end 1) (match-string 2))
9294 tags (if (match-end 4) (match-string 4)))
9295 (goto-char (setq lspos (1+ (match-beginning 0))))
9296 (setq level (org-reduced-level (funcall outline-level))
9297 category (org-get-category))
9298 (setq i llast llast level)
9299 ;; remove tag lists from same and sublevels
9300 (while (>= i level)
9301 (when (setq entry (assoc i tags-alist))
9302 (setq tags-alist (delete entry tags-alist)))
9303 (setq i (1- i)))
9304 ;; add the next tags
9305 (when tags
9306 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9307 tags-alist
9308 (cons (cons level tags) tags-alist)))
9309 ;; compile tags for current headline
9310 (setq tags-list
9311 (if org-use-tag-inheritance
9312 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9313 tags))
9314 (when org-use-tag-inheritance
9315 (setcdr (car tags-alist)
9316 (mapcar (lambda (x)
9317 (setq x (copy-sequence x))
9318 (org-add-prop-inherited x))
9319 (cdar tags-alist))))
9320 (when (and tags org-use-tag-inheritance
9321 (not (eq t org-use-tag-inheritance)))
9322 ;; selective inheritance, remove uninherited ones
9323 (setcdr (car tags-alist)
9324 (org-remove-uniherited-tags (cdar tags-alist))))
9325 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9326 (let ((case-fold-search t)) (eval matcher))
9328 (not (member org-archive-tag tags-list))
9329 ;; we have an archive tag, should we use this anyway?
9330 (or (not org-agenda-skip-archived-trees)
9331 (and (eq action 'agenda) org-agenda-archives-mode))))
9332 (unless (eq action 'sparse-tree) (org-agenda-skip))
9334 ;; select this headline
9336 (cond
9337 ((eq action 'sparse-tree)
9338 (and org-highlight-sparse-tree-matches
9339 (org-get-heading) (match-end 0)
9340 (org-highlight-new-match
9341 (match-beginning 0) (match-beginning 1)))
9342 (org-show-context 'tags-tree))
9343 ((eq action 'agenda)
9344 (setq txt (org-format-agenda-item
9346 (concat
9347 (if org-tags-match-list-sublevels
9348 (make-string (1- level) ?.) "")
9349 (org-get-heading))
9350 category (org-get-tags-at))
9351 priority (org-get-priority txt))
9352 (goto-char lspos)
9353 (setq marker (org-agenda-new-marker))
9354 (org-add-props txt props
9355 'org-marker marker 'org-hd-marker marker 'org-category category
9356 'priority priority 'type "tagsmatch")
9357 (push txt rtn))
9358 ((functionp action)
9359 (save-excursion
9360 (setq rtn1 (funcall action))
9361 (push rtn1 rtn))
9362 (goto-char (point-at-eol)))
9363 (t (error "Invalid action")))
9365 ;; if we are to skip sublevels, jump to end of subtree
9366 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9367 (when (and (eq action 'sparse-tree)
9368 (not org-sparse-tree-open-archived-trees))
9369 (org-hide-archived-subtrees (point-min) (point-max)))
9370 (nreverse rtn)))
9372 (defun org-remove-uniherited-tags (tags)
9373 "Remove all tags that are not inherited from the list TAGS."
9374 (cond
9375 ((eq org-use-tag-inheritance t)
9376 (if org-tags-exclude-from-inheritance
9377 (org-delete-all org-tags-exclude-from-inheritance tags)
9378 tags))
9379 ((not org-use-tag-inheritance) nil)
9380 ((stringp org-use-tag-inheritance)
9381 (delq nil (mapcar
9382 (lambda (x)
9383 (if (and (string-match org-use-tag-inheritance x)
9384 (not (member x org-tags-exclude-from-inheritance)))
9385 x nil))
9386 tags)))
9387 ((listp org-use-tag-inheritance)
9388 (delq nil (mapcar
9389 (lambda (x)
9390 (if (member x org-use-tag-inheritance) x nil))
9391 tags)))))
9393 (defvar todo-only) ;; dynamically scoped
9395 (defun org-tags-sparse-tree (&optional todo-only match)
9396 "Create a sparse tree according to tags string MATCH.
9397 MATCH can contain positive and negative selection of tags, like
9398 \"+WORK+URGENT-WITHBOSS\".
9399 If optional argument TODO-ONLY is non-nil, only select lines that are
9400 also TODO lines."
9401 (interactive "P")
9402 (org-prepare-agenda-buffers (list (current-buffer)))
9403 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9405 (defvar org-cached-props nil)
9406 (defun org-cached-entry-get (pom property)
9407 (if (or (eq t org-use-property-inheritance)
9408 (and (stringp org-use-property-inheritance)
9409 (string-match org-use-property-inheritance property))
9410 (and (listp org-use-property-inheritance)
9411 (member property org-use-property-inheritance)))
9412 ;; Caching is not possible, check it directly
9413 (org-entry-get pom property 'inherit)
9414 ;; Get all properties, so that we can do complicated checks easily
9415 (cdr (assoc property (or org-cached-props
9416 (setq org-cached-props
9417 (org-entry-properties pom)))))))
9419 (defun org-global-tags-completion-table (&optional files)
9420 "Return the list of all tags in all agenda buffer/files."
9421 (save-excursion
9422 (org-uniquify
9423 (delq nil
9424 (apply 'append
9425 (mapcar
9426 (lambda (file)
9427 (set-buffer (find-file-noselect file))
9428 (append (org-get-buffer-tags)
9429 (mapcar (lambda (x) (if (stringp (car-safe x))
9430 (list (car-safe x)) nil))
9431 org-tag-alist)))
9432 (if (and files (car files))
9433 files
9434 (org-agenda-files))))))))
9436 (defun org-make-tags-matcher (match)
9437 "Create the TAGS//TODO matcher form for the selection string MATCH."
9438 ;; todo-only is scoped dynamically into this function, and the function
9439 ;; may change it if the matcher asks for it.
9440 (unless match
9441 ;; Get a new match request, with completion
9442 (let ((org-last-tags-completion-table
9443 (org-global-tags-completion-table)))
9444 (setq match (org-ido-completing-read
9445 "Match: " 'org-tags-completion-function nil nil nil
9446 'org-tags-history))))
9448 ;; Parse the string and create a lisp form
9449 (let ((match0 match)
9450 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9451 minus tag mm
9452 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9453 orterms term orlist re-p str-p level-p level-op time-p
9454 prop-p pn pv po cat-p gv rest)
9455 (if (string-match "/+" match)
9456 ;; match contains also a todo-matching request
9457 (progn
9458 (setq tagsmatch (substring match 0 (match-beginning 0))
9459 todomatch (substring match (match-end 0)))
9460 (if (string-match "^!" todomatch)
9461 (setq todo-only t todomatch (substring todomatch 1)))
9462 (if (string-match "^\\s-*$" todomatch)
9463 (setq todomatch nil)))
9464 ;; only matching tags
9465 (setq tagsmatch match todomatch nil))
9467 ;; Make the tags matcher
9468 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9469 (setq tagsmatcher t)
9470 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9471 (while (setq term (pop orterms))
9472 (while (and (equal (substring term -1) "\\") orterms)
9473 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9474 (while (string-match re term)
9475 (setq rest (substring term (match-end 0))
9476 minus (and (match-end 1)
9477 (equal (match-string 1 term) "-"))
9478 tag (match-string 2 term)
9479 re-p (equal (string-to-char tag) ?{)
9480 level-p (match-end 4)
9481 prop-p (match-end 5)
9482 mm (cond
9483 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9484 (level-p
9485 (setq level-op (org-op-to-function (match-string 3 term)))
9486 `(,level-op level ,(string-to-number
9487 (match-string 4 term))))
9488 (prop-p
9489 (setq pn (match-string 5 term)
9490 po (match-string 6 term)
9491 pv (match-string 7 term)
9492 cat-p (equal pn "CATEGORY")
9493 re-p (equal (string-to-char pv) ?{)
9494 str-p (equal (string-to-char pv) ?\")
9495 time-p (save-match-data
9496 (string-match "^\"[[<].*[]>]\"$" pv))
9497 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9498 (if time-p (setq pv (org-matcher-time pv)))
9499 (setq po (org-op-to-function po (if time-p 'time str-p)))
9500 (cond
9501 ((equal pn "CATEGORY")
9502 (setq gv '(get-text-property (point) 'org-category)))
9503 ((equal pn "TODO")
9504 (setq gv 'todo))
9506 (setq gv `(org-cached-entry-get nil ,pn))))
9507 (if re-p
9508 (if (eq po 'org<>)
9509 `(not (string-match ,pv (or ,gv "")))
9510 `(string-match ,pv (or ,gv "")))
9511 (if str-p
9512 `(,po (or ,gv "") ,pv)
9513 `(,po (string-to-number (or ,gv ""))
9514 ,(string-to-number pv) ))))
9515 (t `(member ,(downcase tag) tags-list)))
9516 mm (if minus (list 'not mm) mm)
9517 term rest)
9518 (push mm tagsmatcher))
9519 (push (if (> (length tagsmatcher) 1)
9520 (cons 'and tagsmatcher)
9521 (car tagsmatcher))
9522 orlist)
9523 (setq tagsmatcher nil))
9524 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9525 (setq tagsmatcher
9526 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9527 ;; Make the todo matcher
9528 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9529 (setq todomatcher t)
9530 (setq orterms (org-split-string todomatch "|") orlist nil)
9531 (while (setq term (pop orterms))
9532 (while (string-match re term)
9533 (setq minus (and (match-end 1)
9534 (equal (match-string 1 term) "-"))
9535 kwd (match-string 2 term)
9536 re-p (equal (string-to-char kwd) ?{)
9537 term (substring term (match-end 0))
9538 mm (if re-p
9539 `(string-match ,(substring kwd 1 -1) todo)
9540 (list 'equal 'todo kwd))
9541 mm (if minus (list 'not mm) mm))
9542 (push mm todomatcher))
9543 (push (if (> (length todomatcher) 1)
9544 (cons 'and todomatcher)
9545 (car todomatcher))
9546 orlist)
9547 (setq todomatcher nil))
9548 (setq todomatcher (if (> (length orlist) 1)
9549 (cons 'or orlist) (car orlist))))
9551 ;; Return the string and lisp forms of the matcher
9552 (setq matcher (if todomatcher
9553 (list 'and tagsmatcher todomatcher)
9554 tagsmatcher))
9555 (cons match0 matcher)))
9557 (defun org-op-to-function (op &optional stringp)
9558 "Turn an operator into the appropriate function."
9559 (setq op
9560 (cond
9561 ((equal op "<" ) '(< string< org-time<))
9562 ((equal op ">" ) '(> org-string> org-time>))
9563 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9564 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9565 ((member op '("=" "==")) '(= string= org-time=))
9566 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9567 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9569 (defun org<> (a b) (not (= a b)))
9570 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9571 (defun org-string>= (a b) (not (string< a b)))
9572 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9573 (defun org-string<> (a b) (not (string= a b)))
9574 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9575 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9576 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9577 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9578 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9579 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9580 (defun org-2ft (s)
9581 "Convert S to a floating point time.
9582 If S is already a number, just return it. If it is a string, parse
9583 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9584 (cond
9585 ((numberp s) s)
9586 ((stringp s)
9587 (condition-case nil
9588 (float-time (apply 'encode-time (org-parse-time-string s)))
9589 (error 0.)))
9590 (t 0.)))
9592 (defun org-time-today ()
9593 "Time in seconds today at 0:00.
9594 Returns the float number of seconds since the beginning of the
9595 epoch to the beginning of today (00:00)."
9596 (float-time (apply 'encode-time
9597 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9599 (defun org-matcher-time (s)
9600 "Interpret a time comparison value."
9601 (save-match-data
9602 (cond
9603 ((string= s "<now>") (float-time))
9604 ((string= s "<today>") (org-time-today))
9605 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9606 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9607 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9608 (+ (org-time-today)
9609 (* (string-to-number (match-string 1 s))
9610 (cdr (assoc (match-string 2 s)
9611 '(("d" . 86400.0) ("w" . 604800.0)
9612 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9613 (t (org-2ft s)))))
9615 (defun org-match-any-p (re list)
9616 "Does re match any element of list?"
9617 (setq list (mapcar (lambda (x) (string-match re x)) list))
9618 (delq nil list))
9620 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9621 (defvar org-tags-overlay (org-make-overlay 1 1))
9622 (org-detach-overlay org-tags-overlay)
9624 (defun org-get-local-tags-at (&optional pos)
9625 "Get a list of tags defined in the current headline."
9626 (org-get-tags-at pos 'local))
9628 (defun org-get-local-tags ()
9629 "Get a list of tags defined in the current headline."
9630 (org-get-tags-at nil 'local))
9632 (defun org-get-tags-at (&optional pos local)
9633 "Get a list of all headline tags applicable at POS.
9634 POS defaults to point. If tags are inherited, the list contains
9635 the targets in the same sequence as the headlines appear, i.e.
9636 the tags of the current headline come last.
9637 When LOCAL is non-nil, only return tags from the current headline,
9638 ignore inherited ones."
9639 (interactive)
9640 (let (tags ltags lastpos parent)
9641 (save-excursion
9642 (save-restriction
9643 (widen)
9644 (goto-char (or pos (point)))
9645 (save-match-data
9646 (catch 'done
9647 (condition-case nil
9648 (progn
9649 (org-back-to-heading t)
9650 (while (not (equal lastpos (point)))
9651 (setq lastpos (point))
9652 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9653 (setq ltags (org-split-string
9654 (org-match-string-no-properties 1) ":"))
9655 (when parent
9656 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9657 (setq tags (append
9658 (if parent
9659 (org-remove-uniherited-tags ltags)
9660 ltags)
9661 tags)))
9662 (or org-use-tag-inheritance (throw 'done t))
9663 (if local (throw 'done t))
9664 (org-up-heading-all 1)
9665 (setq parent t)))
9666 (error nil)))))
9667 (append (org-remove-uniherited-tags org-file-tags) tags))))
9669 (defun org-add-prop-inherited (s)
9670 (add-text-properties 0 (length s) '(inherited t) s)
9673 (defun org-toggle-tag (tag &optional onoff)
9674 "Toggle the tag TAG for the current line.
9675 If ONOFF is `on' or `off', don't toggle but set to this state."
9676 (let (res current)
9677 (save-excursion
9678 (org-back-to-heading t)
9679 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9680 (point-at-eol) t)
9681 (progn
9682 (setq current (match-string 1))
9683 (replace-match ""))
9684 (setq current ""))
9685 (setq current (nreverse (org-split-string current ":")))
9686 (cond
9687 ((eq onoff 'on)
9688 (setq res t)
9689 (or (member tag current) (push tag current)))
9690 ((eq onoff 'off)
9691 (or (not (member tag current)) (setq current (delete tag current))))
9692 (t (if (member tag current)
9693 (setq current (delete tag current))
9694 (setq res t)
9695 (push tag current))))
9696 (end-of-line 1)
9697 (if current
9698 (progn
9699 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9700 (org-set-tags nil t))
9701 (delete-horizontal-space))
9702 (run-hooks 'org-after-tags-change-hook))
9703 res))
9705 (defun org-align-tags-here (to-col)
9706 ;; Assumes that this is a headline
9707 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9708 (beginning-of-line 1)
9709 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9710 (< pos (match-beginning 2)))
9711 (progn
9712 (setq tags-l (- (match-end 2) (match-beginning 2)))
9713 (goto-char (match-beginning 1))
9714 (insert " ")
9715 (delete-region (point) (1+ (match-beginning 2)))
9716 (setq ncol (max (1+ (current-column))
9717 (1+ col)
9718 (if (> to-col 0)
9719 to-col
9720 (- (abs to-col) tags-l))))
9721 (setq p (point))
9722 (insert (make-string (- ncol (current-column)) ?\ ))
9723 (setq ncol (current-column))
9724 (when indent-tabs-mode (tabify p (point-at-eol)))
9725 (org-move-to-column (min ncol col) t))
9726 (goto-char pos))))
9728 (defun org-set-tags-command (&optional arg just-align)
9729 "Call the set-tags command for the current entry."
9730 (interactive "P")
9731 (if (org-on-heading-p)
9732 (org-set-tags arg just-align)
9733 (save-excursion
9734 (org-back-to-heading t)
9735 (org-set-tags arg just-align))))
9737 (defun org-set-tags (&optional arg just-align)
9738 "Set the tags for the current headline.
9739 With prefix ARG, realign all tags in headings in the current buffer."
9740 (interactive "P")
9741 (let* ((re (concat "^" outline-regexp))
9742 (current (org-get-tags-string))
9743 (col (current-column))
9744 (org-setting-tags t)
9745 table current-tags inherited-tags ; computed below when needed
9746 tags p0 c0 c1 rpl)
9747 (if arg
9748 (save-excursion
9749 (goto-char (point-min))
9750 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9751 (while (re-search-forward re nil t)
9752 (org-set-tags nil t)
9753 (end-of-line 1)))
9754 (message "All tags realigned to column %d" org-tags-column))
9755 (if just-align
9756 (setq tags current)
9757 ;; Get a new set of tags from the user
9758 (save-excursion
9759 (setq table (or org-tag-alist (org-get-buffer-tags))
9760 org-last-tags-completion-table table
9761 current-tags (org-split-string current ":")
9762 inherited-tags (nreverse
9763 (nthcdr (length current-tags)
9764 (nreverse (org-get-tags-at))))
9765 tags
9766 (if (or (eq t org-use-fast-tag-selection)
9767 (and org-use-fast-tag-selection
9768 (delq nil (mapcar 'cdr table))))
9769 (org-fast-tag-selection
9770 current-tags inherited-tags table
9771 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9772 (let ((org-add-colon-after-tag-completion t))
9773 (org-trim
9774 (org-without-partial-completion
9775 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9776 nil nil current 'org-tags-history)))))))
9777 (while (string-match "[-+&]+" tags)
9778 ;; No boolean logic, just a list
9779 (setq tags (replace-match ":" t t tags))))
9781 (if (string-match "\\`[\t ]*\\'" tags)
9782 (setq tags "")
9783 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9784 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9786 ;; Insert new tags at the correct column
9787 (beginning-of-line 1)
9788 (cond
9789 ((and (equal current "") (equal tags "")))
9790 ((re-search-forward
9791 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9792 (point-at-eol) t)
9793 (if (equal tags "")
9794 (setq rpl "")
9795 (goto-char (match-beginning 0))
9796 (setq c0 (current-column) p0 (point)
9797 c1 (max (1+ c0) (if (> org-tags-column 0)
9798 org-tags-column
9799 (- (- org-tags-column) (length tags))))
9800 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9801 (replace-match rpl t t)
9802 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9803 tags)
9804 (t (error "Tags alignment failed")))
9805 (org-move-to-column col)
9806 (unless just-align
9807 (run-hooks 'org-after-tags-change-hook)))))
9809 (defun org-change-tag-in-region (beg end tag off)
9810 "Add or remove TAG for each entry in the region.
9811 This works in the agenda, and also in an org-mode buffer."
9812 (interactive
9813 (list (region-beginning) (region-end)
9814 (let ((org-last-tags-completion-table
9815 (if (org-mode-p)
9816 (org-get-buffer-tags)
9817 (org-global-tags-completion-table))))
9818 (org-ido-completing-read
9819 "Tag: " 'org-tags-completion-function nil nil nil
9820 'org-tags-history))
9821 (progn
9822 (message "[s]et or [r]emove? ")
9823 (equal (read-char-exclusive) ?r))))
9824 (if (fboundp 'deactivate-mark) (deactivate-mark))
9825 (let ((agendap (equal major-mode 'org-agenda-mode))
9826 l1 l2 m buf pos newhead (cnt 0))
9827 (goto-char end)
9828 (setq l2 (1- (org-current-line)))
9829 (goto-char beg)
9830 (setq l1 (org-current-line))
9831 (loop for l from l1 to l2 do
9832 (goto-line l)
9833 (setq m (get-text-property (point) 'org-hd-marker))
9834 (when (or (and (org-mode-p) (org-on-heading-p))
9835 (and agendap m))
9836 (setq buf (if agendap (marker-buffer m) (current-buffer))
9837 pos (if agendap m (point)))
9838 (with-current-buffer buf
9839 (save-excursion
9840 (save-restriction
9841 (goto-char pos)
9842 (setq cnt (1+ cnt))
9843 (org-toggle-tag tag (if off 'off 'on))
9844 (setq newhead (org-get-heading)))))
9845 (and agendap (org-agenda-change-all-lines newhead m))))
9846 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9848 (defun org-tags-completion-function (string predicate &optional flag)
9849 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9850 (confirm (lambda (x) (stringp (car x)))))
9851 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9852 (setq s1 (match-string 1 string)
9853 s2 (match-string 2 string))
9854 (setq s1 "" s2 string))
9855 (cond
9856 ((eq flag nil)
9857 ;; try completion
9858 (setq rtn (try-completion s2 ctable confirm))
9859 (if (stringp rtn)
9860 (setq rtn
9861 (concat s1 s2 (substring rtn (length s2))
9862 (if (and org-add-colon-after-tag-completion
9863 (assoc rtn ctable))
9864 ":" ""))))
9865 rtn)
9866 ((eq flag t)
9867 ;; all-completions
9868 (all-completions s2 ctable confirm)
9870 ((eq flag 'lambda)
9871 ;; exact match?
9872 (assoc s2 ctable)))
9875 (defun org-fast-tag-insert (kwd tags face &optional end)
9876 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9877 (insert (format "%-12s" (concat kwd ":"))
9878 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9879 (or end "")))
9881 (defun org-fast-tag-show-exit (flag)
9882 (save-excursion
9883 (goto-line 3)
9884 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9885 (replace-match ""))
9886 (when flag
9887 (end-of-line 1)
9888 (org-move-to-column (- (window-width) 19) t)
9889 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9891 (defun org-set-current-tags-overlay (current prefix)
9892 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9893 (if (featurep 'xemacs)
9894 (org-overlay-display org-tags-overlay (concat prefix s)
9895 'secondary-selection)
9896 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9897 (org-overlay-display org-tags-overlay (concat prefix s)))))
9899 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9900 "Fast tag selection with single keys.
9901 CURRENT is the current list of tags in the headline, INHERITED is the
9902 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9903 possibly with grouping information. TODO-TABLE is a similar table with
9904 TODO keywords, should these have keys assigned to them.
9905 If the keys are nil, a-z are automatically assigned.
9906 Returns the new tags string, or nil to not change the current settings."
9907 (let* ((fulltable (append table todo-table))
9908 (maxlen (apply 'max (mapcar
9909 (lambda (x)
9910 (if (stringp (car x)) (string-width (car x)) 0))
9911 fulltable)))
9912 (buf (current-buffer))
9913 (expert (eq org-fast-tag-selection-single-key 'expert))
9914 (buffer-tags nil)
9915 (fwidth (+ maxlen 3 1 3))
9916 (ncol (/ (- (window-width) 4) fwidth))
9917 (i-face 'org-done)
9918 (c-face 'org-todo)
9919 tg cnt e c char c1 c2 ntable tbl rtn
9920 ov-start ov-end ov-prefix
9921 (exit-after-next org-fast-tag-selection-single-key)
9922 (done-keywords org-done-keywords)
9923 groups ingroup)
9924 (save-excursion
9925 (beginning-of-line 1)
9926 (if (looking-at
9927 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9928 (setq ov-start (match-beginning 1)
9929 ov-end (match-end 1)
9930 ov-prefix "")
9931 (setq ov-start (1- (point-at-eol))
9932 ov-end (1+ ov-start))
9933 (skip-chars-forward "^\n\r")
9934 (setq ov-prefix
9935 (concat
9936 (buffer-substring (1- (point)) (point))
9937 (if (> (current-column) org-tags-column)
9939 (make-string (- org-tags-column (current-column)) ?\ ))))))
9940 (org-move-overlay org-tags-overlay ov-start ov-end)
9941 (save-window-excursion
9942 (if expert
9943 (set-buffer (get-buffer-create " *Org tags*"))
9944 (delete-other-windows)
9945 (split-window-vertically)
9946 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9947 (erase-buffer)
9948 (org-set-local 'org-done-keywords done-keywords)
9949 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9950 (org-fast-tag-insert "Current" current c-face "\n\n")
9951 (org-fast-tag-show-exit exit-after-next)
9952 (org-set-current-tags-overlay current ov-prefix)
9953 (setq tbl fulltable char ?a cnt 0)
9954 (while (setq e (pop tbl))
9955 (cond
9956 ((equal e '(:startgroup))
9957 (push '() groups) (setq ingroup t)
9958 (when (not (= cnt 0))
9959 (setq cnt 0)
9960 (insert "\n"))
9961 (insert "{ "))
9962 ((equal e '(:endgroup))
9963 (setq ingroup nil cnt 0)
9964 (insert "}\n"))
9966 (setq tg (car e) c2 nil)
9967 (if (cdr e)
9968 (setq c (cdr e))
9969 ;; automatically assign a character.
9970 (setq c1 (string-to-char
9971 (downcase (substring
9972 tg (if (= (string-to-char tg) ?@) 1 0)))))
9973 (if (or (rassoc c1 ntable) (rassoc c1 table))
9974 (while (or (rassoc char ntable) (rassoc char table))
9975 (setq char (1+ char)))
9976 (setq c2 c1))
9977 (setq c (or c2 char)))
9978 (if ingroup (push tg (car groups)))
9979 (setq tg (org-add-props tg nil 'face
9980 (cond
9981 ((not (assoc tg table))
9982 (org-get-todo-face tg))
9983 ((member tg current) c-face)
9984 ((member tg inherited) i-face)
9985 (t nil))))
9986 (if (and (= cnt 0) (not ingroup)) (insert " "))
9987 (insert "[" c "] " tg (make-string
9988 (- fwidth 4 (length tg)) ?\ ))
9989 (push (cons tg c) ntable)
9990 (when (= (setq cnt (1+ cnt)) ncol)
9991 (insert "\n")
9992 (if ingroup (insert " "))
9993 (setq cnt 0)))))
9994 (setq ntable (nreverse ntable))
9995 (insert "\n")
9996 (goto-char (point-min))
9997 (if (not expert) (org-fit-window-to-buffer))
9998 (setq rtn
9999 (catch 'exit
10000 (while t
10001 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10002 (if groups " [!] no groups" " [!]groups")
10003 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10004 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10005 (cond
10006 ((= c ?\r) (throw 'exit t))
10007 ((= c ?!)
10008 (setq groups (not groups))
10009 (goto-char (point-min))
10010 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10011 ((= c ?\C-c)
10012 (if (not expert)
10013 (org-fast-tag-show-exit
10014 (setq exit-after-next (not exit-after-next)))
10015 (setq expert nil)
10016 (delete-other-windows)
10017 (split-window-vertically)
10018 (org-switch-to-buffer-other-window " *Org tags*")
10019 (org-fit-window-to-buffer)))
10020 ((or (= c ?\C-g)
10021 (and (= c ?q) (not (rassoc c ntable))))
10022 (org-detach-overlay org-tags-overlay)
10023 (setq quit-flag t))
10024 ((= c ?\ )
10025 (setq current nil)
10026 (if exit-after-next (setq exit-after-next 'now)))
10027 ((= c ?\t)
10028 (condition-case nil
10029 (setq tg (org-ido-completing-read
10030 "Tag: "
10031 (or buffer-tags
10032 (with-current-buffer buf
10033 (org-get-buffer-tags)))))
10034 (quit (setq tg "")))
10035 (when (string-match "\\S-" tg)
10036 (add-to-list 'buffer-tags (list tg))
10037 (if (member tg current)
10038 (setq current (delete tg current))
10039 (push tg current)))
10040 (if exit-after-next (setq exit-after-next 'now)))
10041 ((setq e (rassoc c todo-table) tg (car e))
10042 (with-current-buffer buf
10043 (save-excursion (org-todo tg)))
10044 (if exit-after-next (setq exit-after-next 'now)))
10045 ((setq e (rassoc c ntable) tg (car e))
10046 (if (member tg current)
10047 (setq current (delete tg current))
10048 (loop for g in groups do
10049 (if (member tg g)
10050 (mapc (lambda (x)
10051 (setq current (delete x current)))
10052 g)))
10053 (push tg current))
10054 (if exit-after-next (setq exit-after-next 'now))))
10056 ;; Create a sorted list
10057 (setq current
10058 (sort current
10059 (lambda (a b)
10060 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10061 (if (eq exit-after-next 'now) (throw 'exit t))
10062 (goto-char (point-min))
10063 (beginning-of-line 2)
10064 (delete-region (point) (point-at-eol))
10065 (org-fast-tag-insert "Current" current c-face)
10066 (org-set-current-tags-overlay current ov-prefix)
10067 (while (re-search-forward
10068 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10069 (setq tg (match-string 1))
10070 (add-text-properties
10071 (match-beginning 1) (match-end 1)
10072 (list 'face
10073 (cond
10074 ((member tg current) c-face)
10075 ((member tg inherited) i-face)
10076 (t (get-text-property (match-beginning 1) 'face))))))
10077 (goto-char (point-min)))))
10078 (org-detach-overlay org-tags-overlay)
10079 (if rtn
10080 (mapconcat 'identity current ":")
10081 nil))))
10083 (defun org-get-tags-string ()
10084 "Get the TAGS string in the current headline."
10085 (unless (org-on-heading-p t)
10086 (error "Not on a heading"))
10087 (save-excursion
10088 (beginning-of-line 1)
10089 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10090 (org-match-string-no-properties 1)
10091 "")))
10093 (defun org-get-tags ()
10094 "Get the list of tags specified in the current headline."
10095 (org-split-string (org-get-tags-string) ":"))
10097 (defun org-get-buffer-tags ()
10098 "Get a table of all tags used in the buffer, for completion."
10099 (let (tags)
10100 (save-excursion
10101 (goto-char (point-min))
10102 (while (re-search-forward
10103 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10104 (when (equal (char-after (point-at-bol 0)) ?*)
10105 (mapc (lambda (x) (add-to-list 'tags x))
10106 (org-split-string (org-match-string-no-properties 1) ":")))))
10107 (mapcar 'list tags)))
10109 ;;;; The mapping API
10111 ;;;###autoload
10112 (defun org-map-entries (func &optional match scope &rest skip)
10113 "Call FUNC at each headline selected by MATCH in SCOPE.
10115 FUNC is a function or a lisp form. The function will be called without
10116 arguments, with the cursor positioned at the beginning of the headline.
10117 The return values of all calls to the function will be collected and
10118 returned as a list.
10120 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10121 Only headlines that are matched by this query will be considered during
10122 the iteration. When MATCH is nil or t, all headlines will be
10123 visited by the iteration.
10125 SCOPE determines the scope of this command. It can be any of:
10127 nil The current buffer, respecting the restriction if any
10128 tree The subtree started with the entry at point
10129 file The current buffer, without restriction
10130 file-with-archives
10131 The current buffer, and any archives associated with it
10132 agenda All agenda files
10133 agenda-with-archives
10134 All agenda files with any archive files associated with them
10135 \(file1 file2 ...)
10136 If this is a list, all files in the list will be scanned
10138 The remaining args are treated as settings for the skipping facilities of
10139 the scanner. The following items can be given here:
10141 archive skip trees with the archive tag.
10142 comment skip trees with the COMMENT keyword
10143 function or Emacs Lisp form:
10144 will be used as value for `org-agenda-skip-function', so whenever
10145 the the function returns t, FUNC will not be called for that
10146 entry and search will continue from the point where the
10147 function leaves it."
10148 (let* ((org-agenda-archives-mode nil) ; just to make sure
10149 (org-agenda-skip-archived-trees (memq 'archive skip))
10150 (org-agenda-skip-comment-trees (memq 'comment skip))
10151 (org-agenda-skip-function
10152 (car (org-delete-all '(comment archive) skip)))
10153 (org-tags-match-list-sublevels t)
10154 matcher pos file res
10155 org-todo-keywords-for-agenda
10156 org-done-keywords-for-agenda
10157 org-todo-keyword-alist-for-agenda
10158 org-tag-alist-for-agenda)
10160 (cond
10161 ((eq match t) (setq matcher t))
10162 ((eq match nil) (setq matcher t))
10163 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10165 (when (eq scope 'tree)
10166 (org-back-to-heading t)
10167 (org-narrow-to-subtree)
10168 (setq scope nil))
10170 (if (not scope)
10171 (progn
10172 (org-prepare-agenda-buffers
10173 (list (buffer-file-name (current-buffer))))
10174 (org-scan-tags func matcher))
10175 ;; Get the right scope
10176 (setq pos (point))
10177 (cond
10178 ((and scope (listp scope) (symbolp (car scope)))
10179 (setq scope (eval scope)))
10180 ((eq scope 'agenda)
10181 (setq scope (org-agenda-files t)))
10182 ((eq scope 'agenda-with-archives)
10183 (setq scope (org-agenda-files t))
10184 (setq scope (org-add-archive-files scope)))
10185 ((eq scope 'file)
10186 (setq scope (list (buffer-file-name))))
10187 ((eq scope 'file-with-archives)
10188 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10189 (org-prepare-agenda-buffers scope)
10190 (while (setq file (pop scope))
10191 (with-current-buffer (org-find-base-buffer-visiting file)
10192 (save-excursion
10193 (save-restriction
10194 (widen)
10195 (goto-char (point-min))
10196 (setq res (append res (org-scan-tags func matcher)))))))
10197 res)))
10199 ;;;; Properties
10201 ;;; Setting and retrieving properties
10203 (defconst org-special-properties
10204 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10205 "TIMESTAMP" "TIMESTAMP_IA")
10206 "The special properties valid in Org-mode.
10208 These are properties that are not defined in the property drawer,
10209 but in some other way.")
10211 (defconst org-default-properties
10212 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10213 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10214 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10215 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10216 "Some properties that are used by Org-mode for various purposes.
10217 Being in this list makes sure that they are offered for completion.")
10219 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10220 "Regular expression matching the first line of a property drawer.")
10222 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10223 "Regular expression matching the first line of a property drawer.")
10225 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10226 "Regular expression matching the first line of a property drawer.")
10228 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10229 "Regular expression matching the first line of a property drawer.")
10231 (defconst org-property-drawer-re
10232 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10233 org-property-end-re "\\)\n?")
10234 "Matches an entire property drawer.")
10236 (defconst org-clock-drawer-re
10237 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10238 org-property-end-re "\\)\n?")
10239 "Matches an entire clock drawer.")
10241 (defun org-property-action ()
10242 "Do an action on properties."
10243 (interactive)
10244 (let (c)
10245 (org-at-property-p)
10246 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10247 (setq c (read-char-exclusive))
10248 (cond
10249 ((equal c ?s)
10250 (call-interactively 'org-set-property))
10251 ((equal c ?d)
10252 (call-interactively 'org-delete-property))
10253 ((equal c ?D)
10254 (call-interactively 'org-delete-property-globally))
10255 ((equal c ?c)
10256 (call-interactively 'org-compute-property-at-point))
10257 (t (error "No such property action %c" c)))))
10259 (defun org-at-property-p ()
10260 "Is the cursor in a property line?"
10261 ;; FIXME: Does not check if we are actually in the drawer.
10262 ;; FIXME: also returns true on any drawers.....
10263 ;; This is used by C-c C-c for property action.
10264 (save-excursion
10265 (beginning-of-line 1)
10266 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10268 (defun org-get-property-block (&optional beg end force)
10269 "Return the (beg . end) range of the body of the property drawer.
10270 BEG and END can be beginning and end of subtree, if not given
10271 they will be found.
10272 If the drawer does not exist and FORCE is non-nil, create the drawer."
10273 (catch 'exit
10274 (save-excursion
10275 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10276 (end (or end (progn (outline-next-heading) (point)))))
10277 (goto-char beg)
10278 (if (re-search-forward org-property-start-re end t)
10279 (setq beg (1+ (match-end 0)))
10280 (if force
10281 (save-excursion
10282 (org-insert-property-drawer)
10283 (setq end (progn (outline-next-heading) (point))))
10284 (throw 'exit nil))
10285 (goto-char beg)
10286 (if (re-search-forward org-property-start-re end t)
10287 (setq beg (1+ (match-end 0)))))
10288 (if (re-search-forward org-property-end-re end t)
10289 (setq end (match-beginning 0))
10290 (or force (throw 'exit nil))
10291 (goto-char beg)
10292 (setq end beg)
10293 (org-indent-line-function)
10294 (insert ":END:\n"))
10295 (cons beg end)))))
10297 (defun org-entry-properties (&optional pom which)
10298 "Get all properties of the entry at point-or-marker POM.
10299 This includes the TODO keyword, the tags, time strings for deadline,
10300 scheduled, and clocking, and any additional properties defined in the
10301 entry. The return value is an alist, keys may occur multiple times
10302 if the property key was used several times.
10303 POM may also be nil, in which case the current entry is used.
10304 If WHICH is nil or `all', get all properties. If WHICH is
10305 `special' or `standard', only get that subclass."
10306 (setq which (or which 'all))
10307 (org-with-point-at pom
10308 (let ((clockstr (substring org-clock-string 0 -1))
10309 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10310 beg end range props sum-props key value string clocksum)
10311 (save-excursion
10312 (when (condition-case nil
10313 (and (org-mode-p) (org-back-to-heading t))
10314 (error nil))
10315 (setq beg (point))
10316 (setq sum-props (get-text-property (point) 'org-summaries))
10317 (setq clocksum (get-text-property (point) :org-clock-minutes))
10318 (outline-next-heading)
10319 (setq end (point))
10320 (when (memq which '(all special))
10321 ;; Get the special properties, like TODO and tags
10322 (goto-char beg)
10323 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10324 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10325 (when (looking-at org-priority-regexp)
10326 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10327 (when (and (setq value (org-get-tags-string))
10328 (string-match "\\S-" value))
10329 (push (cons "TAGS" value) props))
10330 (when (setq value (org-get-tags-at))
10331 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10332 props))
10333 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10334 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10335 string (if (equal key clockstr)
10336 (org-no-properties
10337 (org-trim
10338 (buffer-substring
10339 (match-beginning 3) (goto-char (point-at-eol)))))
10340 (substring (org-match-string-no-properties 3) 1 -1)))
10341 (unless key
10342 (if (= (char-after (match-beginning 3)) ?\[)
10343 (setq key "TIMESTAMP_IA")
10344 (setq key "TIMESTAMP")))
10345 (when (or (equal key clockstr) (not (assoc key props)))
10346 (push (cons key string) props)))
10350 (when (memq which '(all standard))
10351 ;; Get the standard properties, like :PORP: ...
10352 (setq range (org-get-property-block beg end))
10353 (when range
10354 (goto-char (car range))
10355 (while (re-search-forward
10356 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10357 (cdr range) t)
10358 (setq key (org-match-string-no-properties 1)
10359 value (org-trim (or (org-match-string-no-properties 2) "")))
10360 (unless (member key excluded)
10361 (push (cons key (or value "")) props)))))
10362 (if clocksum
10363 (push (cons "CLOCKSUM"
10364 (org-columns-number-to-string (/ (float clocksum) 60.)
10365 'add_times))
10366 props))
10367 (unless (assoc "CATEGORY" props)
10368 (setq value (or (org-get-category)
10369 (progn (org-refresh-category-properties)
10370 (org-get-category))))
10371 (push (cons "CATEGORY" value) props))
10372 (append sum-props (nreverse props)))))))
10374 (defun org-entry-get (pom property &optional inherit)
10375 "Get value of PROPERTY for entry at point-or-marker POM.
10376 If INHERIT is non-nil and the entry does not have the property,
10377 then also check higher levels of the hierarchy.
10378 If INHERIT is the symbol `selective', use inheritance only if the setting
10379 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10380 If the property is present but empty, the return value is the empty string.
10381 If the property is not present at all, nil is returned."
10382 (org-with-point-at pom
10383 (if (and inherit (if (eq inherit 'selective)
10384 (org-property-inherit-p property)
10386 (org-entry-get-with-inheritance property)
10387 (if (member property org-special-properties)
10388 ;; We need a special property. Use brute force, get all properties.
10389 (cdr (assoc property (org-entry-properties nil 'special)))
10390 (let ((range (org-get-property-block)))
10391 (if (and range
10392 (goto-char (car range))
10393 (re-search-forward
10394 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10395 (cdr range) t))
10396 ;; Found the property, return it.
10397 (if (match-end 1)
10398 (org-match-string-no-properties 1)
10399 "")))))))
10401 (defun org-property-or-variable-value (var &optional inherit)
10402 "Check if there is a property fixing the value of VAR.
10403 If yes, return this value. If not, return the current value of the variable."
10404 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10405 (if (and prop (stringp prop) (string-match "\\S-" prop))
10406 (read prop)
10407 (symbol-value var))))
10409 (defun org-entry-delete (pom property)
10410 "Delete the property PROPERTY from entry at point-or-marker POM."
10411 (org-with-point-at pom
10412 (if (member property org-special-properties)
10413 nil ; cannot delete these properties.
10414 (let ((range (org-get-property-block)))
10415 (if (and range
10416 (goto-char (car range))
10417 (re-search-forward
10418 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10419 (cdr range) t))
10420 (progn
10421 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10423 nil)))))
10425 ;; Multi-values properties are properties that contain multiple values
10426 ;; These values are assumed to be single words, separated by whitespace.
10427 (defun org-entry-add-to-multivalued-property (pom property value)
10428 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10429 (let* ((old (org-entry-get pom property))
10430 (values (and old (org-split-string old "[ \t]"))))
10431 (setq value (org-entry-protect-space value))
10432 (unless (member value values)
10433 (setq values (cons value values))
10434 (org-entry-put pom property
10435 (mapconcat 'identity values " ")))))
10437 (defun org-entry-remove-from-multivalued-property (pom property value)
10438 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10439 (let* ((old (org-entry-get pom property))
10440 (values (and old (org-split-string old "[ \t]"))))
10441 (setq value (org-entry-protect-space value))
10442 (when (member value values)
10443 (setq values (delete value values))
10444 (org-entry-put pom property
10445 (mapconcat 'identity values " ")))))
10447 (defun org-entry-member-in-multivalued-property (pom property value)
10448 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10449 (let* ((old (org-entry-get pom property))
10450 (values (and old (org-split-string old "[ \t]"))))
10451 (setq value (org-entry-protect-space value))
10452 (member value values)))
10454 (defun org-entry-get-multivalued-property (pom property)
10455 "Return a list of values in a multivalued property."
10456 (let* ((value (org-entry-get pom property))
10457 (values (and value (org-split-string value "[ \t]"))))
10458 (mapcar 'org-entry-restore-space values)))
10460 (defun org-entry-put-multivalued-property (pom property &rest values)
10461 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10462 VALUES should be a list of strings. Spaces will be protected."
10463 (org-entry-put pom property
10464 (mapconcat 'org-entry-protect-space values " "))
10465 (let* ((value (org-entry-get pom property))
10466 (values (and value (org-split-string value "[ \t]"))))
10467 (mapcar 'org-entry-restore-space values)))
10469 (defun org-entry-protect-space (s)
10470 "Protect spaces and newline in string S."
10471 (while (string-match " " s)
10472 (setq s (replace-match "%20" t t s)))
10473 (while (string-match "\n" s)
10474 (setq s (replace-match "%0A" t t s)))
10477 (defun org-entry-restore-space (s)
10478 "Restore spaces and newline in string S."
10479 (while (string-match "%20" s)
10480 (setq s (replace-match " " t t s)))
10481 (while (string-match "%0A" s)
10482 (setq s (replace-match "\n" t t s)))
10485 (defvar org-entry-property-inherited-from (make-marker)
10486 "Marker pointing to the entry from where a property was inherited.
10487 Each call to `org-entry-get-with-inheritance' will set this marker to the
10488 location of the entry where the inheritance search matched. If there was
10489 no match, the marker will point nowhere.
10490 Note that also `org-entry-get' calls this function, if the INHERIT flag
10491 is set.")
10493 (defun org-entry-get-with-inheritance (property)
10494 "Get entry property, and search higher levels if not present."
10495 (move-marker org-entry-property-inherited-from nil)
10496 (let (tmp)
10497 (save-excursion
10498 (save-restriction
10499 (widen)
10500 (catch 'ex
10501 (while t
10502 (when (setq tmp (org-entry-get nil property))
10503 (org-back-to-heading t)
10504 (move-marker org-entry-property-inherited-from (point))
10505 (throw 'ex tmp))
10506 (or (org-up-heading-safe) (throw 'ex nil)))))
10507 (or tmp
10508 (cdr (assoc property org-file-properties))
10509 (cdr (assoc property org-global-properties))
10510 (cdr (assoc property org-global-properties-fixed))))))
10512 (defun org-entry-put (pom property value)
10513 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10514 (org-with-point-at pom
10515 (org-back-to-heading t)
10516 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10517 range)
10518 (cond
10519 ((equal property "TODO")
10520 (when (and (stringp value) (string-match "\\S-" value)
10521 (not (member value org-todo-keywords-1)))
10522 (error "\"%s\" is not a valid TODO state" value))
10523 (if (or (not value)
10524 (not (string-match "\\S-" value)))
10525 (setq value 'none))
10526 (org-todo value)
10527 (org-set-tags nil 'align))
10528 ((equal property "PRIORITY")
10529 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10530 (string-to-char value) ?\ ))
10531 (org-set-tags nil 'align))
10532 ((equal property "SCHEDULED")
10533 (if (re-search-forward org-scheduled-time-regexp end t)
10534 (cond
10535 ((eq value 'earlier) (org-timestamp-change -1 'day))
10536 ((eq value 'later) (org-timestamp-change 1 'day))
10537 (t (call-interactively 'org-schedule)))
10538 (call-interactively 'org-schedule)))
10539 ((equal property "DEADLINE")
10540 (if (re-search-forward org-deadline-time-regexp end t)
10541 (cond
10542 ((eq value 'earlier) (org-timestamp-change -1 'day))
10543 ((eq value 'later) (org-timestamp-change 1 'day))
10544 (t (call-interactively 'org-deadline)))
10545 (call-interactively 'org-deadline)))
10546 ((member property org-special-properties)
10547 (error "The %s property can not yet be set with `org-entry-put'"
10548 property))
10549 (t ; a non-special property
10550 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10551 (setq range (org-get-property-block beg end 'force))
10552 (goto-char (car range))
10553 (if (re-search-forward
10554 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10555 (progn
10556 (delete-region (match-beginning 1) (match-end 1))
10557 (goto-char (match-beginning 1)))
10558 (goto-char (cdr range))
10559 (insert "\n")
10560 (backward-char 1)
10561 (org-indent-line-function)
10562 (insert ":" property ":"))
10563 (and value (insert " " value))
10564 (org-indent-line-function)))))))
10566 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10567 "Get all property keys in the current buffer.
10568 With INCLUDE-SPECIALS, also list the special properties that reflect things
10569 like tags and TODO state.
10570 With INCLUDE-DEFAULTS, also include properties that has special meaning
10571 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10572 With INCLUDE-COLUMNS, also include property names given in COLUMN
10573 formats in the current buffer."
10574 (let (rtn range cfmt cols s p)
10575 (save-excursion
10576 (save-restriction
10577 (widen)
10578 (goto-char (point-min))
10579 (while (re-search-forward org-property-start-re nil t)
10580 (setq range (org-get-property-block))
10581 (goto-char (car range))
10582 (while (re-search-forward
10583 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10584 (cdr range) t)
10585 (add-to-list 'rtn (org-match-string-no-properties 1)))
10586 (outline-next-heading))))
10588 (when include-specials
10589 (setq rtn (append org-special-properties rtn)))
10591 (when include-defaults
10592 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10594 (when include-columns
10595 (save-excursion
10596 (save-restriction
10597 (widen)
10598 (goto-char (point-min))
10599 (while (re-search-forward
10600 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10601 nil t)
10602 (setq cfmt (match-string 2) s 0)
10603 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10604 cfmt s)
10605 (setq s (match-end 0)
10606 p (match-string 1 cfmt))
10607 (unless (or (equal p "ITEM")
10608 (member p org-special-properties))
10609 (add-to-list 'rtn (match-string 1 cfmt))))))))
10611 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10613 (defun org-property-values (key)
10614 "Return a list of all values of property KEY."
10615 (save-excursion
10616 (save-restriction
10617 (widen)
10618 (goto-char (point-min))
10619 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10620 values)
10621 (while (re-search-forward re nil t)
10622 (add-to-list 'values (org-trim (match-string 1))))
10623 (delete "" values)))))
10625 (defun org-insert-property-drawer ()
10626 "Insert a property drawer into the current entry."
10627 (interactive)
10628 (org-back-to-heading t)
10629 (looking-at outline-regexp)
10630 (let ((indent (- (match-end 0)(match-beginning 0)))
10631 (beg (point))
10632 (re (concat "^[ \t]*" org-keyword-time-regexp))
10633 end hiddenp)
10634 (outline-next-heading)
10635 (setq end (point))
10636 (goto-char beg)
10637 (while (re-search-forward re end t))
10638 (setq hiddenp (org-invisible-p))
10639 (end-of-line 1)
10640 (and (equal (char-after) ?\n) (forward-char 1))
10641 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10642 (beginning-of-line 2))
10643 (org-skip-over-state-notes)
10644 (skip-chars-backward " \t\n\r")
10645 (if (eq (char-before) ?*) (forward-char 1))
10646 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10647 (beginning-of-line 0)
10648 (org-indent-to-column indent)
10649 (beginning-of-line 2)
10650 (org-indent-to-column indent)
10651 (beginning-of-line 0)
10652 (if hiddenp
10653 (save-excursion
10654 (org-back-to-heading t)
10655 (hide-entry))
10656 (org-flag-drawer t))))
10658 (defun org-set-property (property value)
10659 "In the current entry, set PROPERTY to VALUE.
10660 When called interactively, this will prompt for a property name, offering
10661 completion on existing and default properties. And then it will prompt
10662 for a value, offering completion either on allowed values (via an inherited
10663 xxx_ALL property) or on existing values in other instances of this property
10664 in the current file."
10665 (interactive
10666 (let* ((completion-ignore-case t)
10667 (keys (org-buffer-property-keys nil t t))
10668 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10669 (prop (if (member prop0 keys)
10670 prop0
10671 (or (cdr (assoc (downcase prop0)
10672 (mapcar (lambda (x) (cons (downcase x) x))
10673 keys)))
10674 prop0)))
10675 (cur (org-entry-get nil prop))
10676 (allowed (org-property-get-allowed-values nil prop 'table))
10677 (existing (mapcar 'list (org-property-values prop)))
10678 (val (if allowed
10679 (org-completing-read "Value: " allowed nil 'req-match)
10680 (org-completing-read
10681 (concat "Value" (if (and cur (string-match "\\S-" cur))
10682 (concat "[" cur "]") "")
10683 ": ")
10684 existing nil nil "" nil cur))))
10685 (list prop (if (equal val "") cur val))))
10686 (unless (equal (org-entry-get nil property) value)
10687 (org-entry-put nil property value)))
10689 (defun org-delete-property (property)
10690 "In the current entry, delete PROPERTY."
10691 (interactive
10692 (let* ((completion-ignore-case t)
10693 (prop (org-ido-completing-read
10694 "Property: " (org-entry-properties nil 'standard))))
10695 (list prop)))
10696 (message "Property %s %s" property
10697 (if (org-entry-delete nil property)
10698 "deleted"
10699 "was not present in the entry")))
10701 (defun org-delete-property-globally (property)
10702 "Remove PROPERTY globally, from all entries."
10703 (interactive
10704 (let* ((completion-ignore-case t)
10705 (prop (org-ido-completing-read
10706 "Globally remove property: "
10707 (mapcar 'list (org-buffer-property-keys)))))
10708 (list prop)))
10709 (save-excursion
10710 (save-restriction
10711 (widen)
10712 (goto-char (point-min))
10713 (let ((cnt 0))
10714 (while (re-search-forward
10715 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10716 nil t)
10717 (setq cnt (1+ cnt))
10718 (replace-match ""))
10719 (message "Property \"%s\" removed from %d entries" property cnt)))))
10721 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10723 (defun org-compute-property-at-point ()
10724 "Compute the property at point.
10725 This looks for an enclosing column format, extracts the operator and
10726 then applies it to the property in the column format's scope."
10727 (interactive)
10728 (unless (org-at-property-p)
10729 (error "Not at a property"))
10730 (let ((prop (org-match-string-no-properties 2)))
10731 (org-columns-get-format-and-top-level)
10732 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10733 (error "No operator defined for property %s" prop))
10734 (org-columns-compute prop)))
10736 (defun org-property-get-allowed-values (pom property &optional table)
10737 "Get allowed values for the property PROPERTY.
10738 When TABLE is non-nil, return an alist that can directly be used for
10739 completion."
10740 (let (vals)
10741 (cond
10742 ((equal property "TODO")
10743 (setq vals (org-with-point-at pom
10744 (append org-todo-keywords-1 '("")))))
10745 ((equal property "PRIORITY")
10746 (let ((n org-lowest-priority))
10747 (while (>= n org-highest-priority)
10748 (push (char-to-string n) vals)
10749 (setq n (1- n)))))
10750 ((member property org-special-properties))
10752 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10754 (when (and vals (string-match "\\S-" vals))
10755 (setq vals (car (read-from-string (concat "(" vals ")"))))
10756 (setq vals (mapcar (lambda (x)
10757 (cond ((stringp x) x)
10758 ((numberp x) (number-to-string x))
10759 ((symbolp x) (symbol-name x))
10760 (t "???")))
10761 vals)))))
10762 (if table (mapcar 'list vals) vals)))
10764 (defun org-property-previous-allowed-value (&optional previous)
10765 "Switch to the next allowed value for this property."
10766 (interactive)
10767 (org-property-next-allowed-value t))
10769 (defun org-property-next-allowed-value (&optional previous)
10770 "Switch to the next allowed value for this property."
10771 (interactive)
10772 (unless (org-at-property-p)
10773 (error "Not at a property"))
10774 (let* ((key (match-string 2))
10775 (value (match-string 3))
10776 (allowed (or (org-property-get-allowed-values (point) key)
10777 (and (member value '("[ ]" "[-]" "[X]"))
10778 '("[ ]" "[X]"))))
10779 nval)
10780 (unless allowed
10781 (error "Allowed values for this property have not been defined"))
10782 (if previous (setq allowed (reverse allowed)))
10783 (if (member value allowed)
10784 (setq nval (car (cdr (member value allowed)))))
10785 (setq nval (or nval (car allowed)))
10786 (if (equal nval value)
10787 (error "Only one allowed value for this property"))
10788 (org-at-property-p)
10789 (replace-match (concat " :" key ": " nval) t t)
10790 (org-indent-line-function)
10791 (beginning-of-line 1)
10792 (skip-chars-forward " \t")))
10794 (defun org-find-entry-with-id (ident)
10795 "Locate the entry that contains the ID property with exact value IDENT.
10796 IDENT can be a string, a symbol or a number, this function will search for
10797 the string representation of it.
10798 Return the position where this entry starts, or nil if there is no such entry."
10799 (interactive "sID: ")
10800 (let ((id (cond
10801 ((stringp ident) ident)
10802 ((symbol-name ident) (symbol-name ident))
10803 ((numberp ident) (number-to-string ident))
10804 (t (error "IDENT %s must be a string, symbol or number" ident))))
10805 (case-fold-search nil))
10806 (save-excursion
10807 (save-restriction
10808 (widen)
10809 (goto-char (point-min))
10810 (when (re-search-forward
10811 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10812 nil t)
10813 (org-back-to-heading)
10814 (point))))))
10816 ;;;; Timestamps
10818 (defvar org-last-changed-timestamp nil)
10819 (defvar org-last-inserted-timestamp nil
10820 "The last time stamp inserted with `org-insert-time-stamp'.")
10821 (defvar org-time-was-given) ; dynamically scoped parameter
10822 (defvar org-end-time-was-given) ; dynamically scoped parameter
10823 (defvar org-ts-what) ; dynamically scoped parameter
10825 (defun org-time-stamp (arg &optional inactive)
10826 "Prompt for a date/time and insert a time stamp.
10827 If the user specifies a time like HH:MM, or if this command is called
10828 with a prefix argument, the time stamp will contain date and time.
10829 Otherwise, only the date will be included. All parts of a date not
10830 specified by the user will be filled in from the current date/time.
10831 So if you press just return without typing anything, the time stamp
10832 will represent the current date/time. If there is already a timestamp
10833 at the cursor, it will be modified."
10834 (interactive "P")
10835 (let* ((ts nil)
10836 (default-time
10837 ;; Default time is either today, or, when entering a range,
10838 ;; the range start.
10839 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10840 (save-excursion
10841 (re-search-backward
10842 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10843 (- (point) 20) t)))
10844 (apply 'encode-time (org-parse-time-string (match-string 1)))
10845 (current-time)))
10846 (default-input (and ts (org-get-compact-tod ts)))
10847 org-time-was-given org-end-time-was-given time)
10848 (cond
10849 ((and (org-at-timestamp-p t)
10850 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10851 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10852 (insert "--")
10853 (setq time (let ((this-command this-command))
10854 (org-read-date arg 'totime nil nil
10855 default-time default-input)))
10856 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10857 ((org-at-timestamp-p t)
10858 (setq time (let ((this-command this-command))
10859 (org-read-date arg 'totime nil nil default-time default-input)))
10860 (when (org-at-timestamp-p t) ; just to get the match data
10861 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10862 (replace-match "")
10863 (setq org-last-changed-timestamp
10864 (org-insert-time-stamp
10865 time (or org-time-was-given arg)
10866 inactive nil nil (list org-end-time-was-given))))
10867 (message "Timestamp updated"))
10869 (setq time (let ((this-command this-command))
10870 (org-read-date arg 'totime nil nil default-time default-input)))
10871 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10872 nil nil (list org-end-time-was-given))))))
10874 ;; FIXME: can we use this for something else, like computing time differences?
10875 (defun org-get-compact-tod (s)
10876 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10877 (let* ((t1 (match-string 1 s))
10878 (h1 (string-to-number (match-string 2 s)))
10879 (m1 (string-to-number (match-string 3 s)))
10880 (t2 (and (match-end 4) (match-string 5 s)))
10881 (h2 (and t2 (string-to-number (match-string 6 s))))
10882 (m2 (and t2 (string-to-number (match-string 7 s))))
10883 dh dm)
10884 (if (not t2)
10886 (setq dh (- h2 h1) dm (- m2 m1))
10887 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10888 (concat t1 "+" (number-to-string dh)
10889 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10891 (defun org-time-stamp-inactive (&optional arg)
10892 "Insert an inactive time stamp.
10893 An inactive time stamp is enclosed in square brackets instead of angle
10894 brackets. It is inactive in the sense that it does not trigger agenda entries,
10895 does not link to the calendar and cannot be changed with the S-cursor keys.
10896 So these are more for recording a certain time/date."
10897 (interactive "P")
10898 (org-time-stamp arg 'inactive))
10900 (defvar org-date-ovl (org-make-overlay 1 1))
10901 (org-overlay-put org-date-ovl 'face 'org-warning)
10902 (org-detach-overlay org-date-ovl)
10904 (defvar org-ans1) ; dynamically scoped parameter
10905 (defvar org-ans2) ; dynamically scoped parameter
10907 (defvar org-plain-time-of-day-regexp) ; defined below
10909 (defvar org-overriding-default-time nil) ; dynamically scoped
10910 (defvar org-read-date-overlay nil)
10911 (defvar org-dcst nil) ; dynamically scoped
10913 (defun org-read-date (&optional with-time to-time from-string prompt
10914 default-time default-input)
10915 "Read a date, possibly a time, and make things smooth for the user.
10916 The prompt will suggest to enter an ISO date, but you can also enter anything
10917 which will at least partially be understood by `parse-time-string'.
10918 Unrecognized parts of the date will default to the current day, month, year,
10919 hour and minute. If this command is called to replace a timestamp at point,
10920 of to enter the second timestamp of a range, the default time is taken from the
10921 existing stamp. For example,
10922 3-2-5 --> 2003-02-05
10923 feb 15 --> currentyear-02-15
10924 sep 12 9 --> 2009-09-12
10925 12:45 --> today 12:45
10926 22 sept 0:34 --> currentyear-09-22 0:34
10927 12 --> currentyear-currentmonth-12
10928 Fri --> nearest Friday (today or later)
10929 etc.
10931 Furthermore you can specify a relative date by giving, as the *first* thing
10932 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10933 change in days weeks, months, years.
10934 With a single plus or minus, the date is relative to today. With a double
10935 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10936 +4d --> four days from today
10937 +4 --> same as above
10938 +2w --> two weeks from today
10939 ++5 --> five days from default date
10941 The function understands only English month and weekday abbreviations,
10942 but this can be configured with the variables `parse-time-months' and
10943 `parse-time-weekdays'.
10945 While prompting, a calendar is popped up - you can also select the
10946 date with the mouse (button 1). The calendar shows a period of three
10947 months. To scroll it to other months, use the keys `>' and `<'.
10948 If you don't like the calendar, turn it off with
10949 \(setq org-read-date-popup-calendar nil)
10951 With optional argument TO-TIME, the date will immediately be converted
10952 to an internal time.
10953 With an optional argument WITH-TIME, the prompt will suggest to also
10954 insert a time. Note that when WITH-TIME is not set, you can still
10955 enter a time, and this function will inform the calling routine about
10956 this change. The calling routine may then choose to change the format
10957 used to insert the time stamp into the buffer to include the time.
10958 With optional argument FROM-STRING, read from this string instead from
10959 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10960 the time/date that is used for everything that is not specified by the
10961 user."
10962 (require 'parse-time)
10963 (let* ((org-time-stamp-rounding-minutes
10964 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10965 (org-dcst org-display-custom-times)
10966 (ct (org-current-time))
10967 (def (or org-overriding-default-time default-time ct))
10968 (defdecode (decode-time def))
10969 (dummy (progn
10970 (when (< (nth 2 defdecode) org-extend-today-until)
10971 (setcar (nthcdr 2 defdecode) -1)
10972 (setcar (nthcdr 1 defdecode) 59)
10973 (setq def (apply 'encode-time defdecode)
10974 defdecode (decode-time def)))))
10975 (calendar-move-hook nil)
10976 (calendar-view-diary-initially-flag nil)
10977 (view-diary-entries-initially nil)
10978 (calendar-view-holidays-initially-flag nil)
10979 (view-calendar-holidays-initially nil)
10980 (timestr (format-time-string
10981 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10982 (prompt (concat (if prompt (concat prompt " ") "")
10983 (format "Date+time [%s]: " timestr)))
10984 ans (org-ans0 "") org-ans1 org-ans2 final)
10986 (cond
10987 (from-string (setq ans from-string))
10988 (org-read-date-popup-calendar
10989 (save-excursion
10990 (save-window-excursion
10991 (calendar)
10992 (calendar-forward-day (- (time-to-days def)
10993 (calendar-absolute-from-gregorian
10994 (calendar-current-date))))
10995 (org-eval-in-calendar nil t)
10996 (let* ((old-map (current-local-map))
10997 (map (copy-keymap calendar-mode-map))
10998 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10999 (org-defkey map (kbd "RET") 'org-calendar-select)
11000 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11001 'org-calendar-select-mouse)
11002 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11003 'org-calendar-select-mouse)
11004 (org-defkey minibuffer-local-map [(meta shift left)]
11005 (lambda () (interactive)
11006 (org-eval-in-calendar '(calendar-backward-month 1))))
11007 (org-defkey minibuffer-local-map [(meta shift right)]
11008 (lambda () (interactive)
11009 (org-eval-in-calendar '(calendar-forward-month 1))))
11010 (org-defkey minibuffer-local-map [(meta shift up)]
11011 (lambda () (interactive)
11012 (org-eval-in-calendar '(calendar-backward-year 1))))
11013 (org-defkey minibuffer-local-map [(meta shift down)]
11014 (lambda () (interactive)
11015 (org-eval-in-calendar '(calendar-forward-year 1))))
11016 (org-defkey minibuffer-local-map [(shift up)]
11017 (lambda () (interactive)
11018 (org-eval-in-calendar '(calendar-backward-week 1))))
11019 (org-defkey minibuffer-local-map [(shift down)]
11020 (lambda () (interactive)
11021 (org-eval-in-calendar '(calendar-forward-week 1))))
11022 (org-defkey minibuffer-local-map [(shift left)]
11023 (lambda () (interactive)
11024 (org-eval-in-calendar '(calendar-backward-day 1))))
11025 (org-defkey minibuffer-local-map [(shift right)]
11026 (lambda () (interactive)
11027 (org-eval-in-calendar '(calendar-forward-day 1))))
11028 (org-defkey minibuffer-local-map ">"
11029 (lambda () (interactive)
11030 (org-eval-in-calendar '(scroll-calendar-left 1))))
11031 (org-defkey minibuffer-local-map "<"
11032 (lambda () (interactive)
11033 (org-eval-in-calendar '(scroll-calendar-right 1))))
11034 (unwind-protect
11035 (progn
11036 (use-local-map map)
11037 (add-hook 'post-command-hook 'org-read-date-display)
11038 (setq org-ans0 (read-string prompt default-input nil nil))
11039 ;; org-ans0: from prompt
11040 ;; org-ans1: from mouse click
11041 ;; org-ans2: from calendar motion
11042 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11043 (remove-hook 'post-command-hook 'org-read-date-display)
11044 (use-local-map old-map)
11045 (when org-read-date-overlay
11046 (org-delete-overlay org-read-date-overlay)
11047 (setq org-read-date-overlay nil)))))))
11049 (t ; Naked prompt only
11050 (unwind-protect
11051 (setq ans (read-string prompt default-input nil timestr))
11052 (when org-read-date-overlay
11053 (org-delete-overlay org-read-date-overlay)
11054 (setq org-read-date-overlay nil)))))
11056 (setq final (org-read-date-analyze ans def defdecode))
11058 (if to-time
11059 (apply 'encode-time final)
11060 (if (and (boundp 'org-time-was-given) org-time-was-given)
11061 (format "%04d-%02d-%02d %02d:%02d"
11062 (nth 5 final) (nth 4 final) (nth 3 final)
11063 (nth 2 final) (nth 1 final))
11064 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11065 (defvar def)
11066 (defvar defdecode)
11067 (defvar with-time)
11068 (defun org-read-date-display ()
11069 "Display the current date prompt interpretation in the minibuffer."
11070 (when org-read-date-display-live
11071 (when org-read-date-overlay
11072 (org-delete-overlay org-read-date-overlay))
11073 (let ((p (point)))
11074 (end-of-line 1)
11075 (while (not (equal (buffer-substring
11076 (max (point-min) (- (point) 4)) (point))
11077 " "))
11078 (insert " "))
11079 (goto-char p))
11080 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11081 " " (or org-ans1 org-ans2)))
11082 (org-end-time-was-given nil)
11083 (f (org-read-date-analyze ans def defdecode))
11084 (fmts (if org-dcst
11085 org-time-stamp-custom-formats
11086 org-time-stamp-formats))
11087 (fmt (if (or with-time
11088 (and (boundp 'org-time-was-given) org-time-was-given))
11089 (cdr fmts)
11090 (car fmts)))
11091 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11092 (when (and org-end-time-was-given
11093 (string-match org-plain-time-of-day-regexp txt))
11094 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11095 org-end-time-was-given
11096 (substring txt (match-end 0)))))
11097 (setq org-read-date-overlay
11098 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11099 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11101 (defun org-read-date-analyze (ans def defdecode)
11102 "Analyse the combined answer of the date prompt."
11103 ;; FIXME: cleanup and comment
11104 (let (delta deltan deltaw deltadef year month day
11105 hour minute second wday pm h2 m2 tl wday1
11106 iso-year iso-weekday iso-week iso-year iso-date)
11108 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11109 (setq ans "+0"))
11111 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11112 (setq ans (replace-match "" t t ans)
11113 deltan (car delta)
11114 deltaw (nth 1 delta)
11115 deltadef (nth 2 delta)))
11117 ;; Check if there is an iso week date in there
11118 ;; If yes, sore the info and postpone interpreting it until the rest
11119 ;; of the parsing is done
11120 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11121 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11122 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11123 iso-week (string-to-number (match-string 2 ans)))
11124 (setq ans (replace-match "" t t ans)))
11126 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11127 (when (string-match
11128 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11129 (setq year (if (match-end 2)
11130 (string-to-number (match-string 2 ans))
11131 (string-to-number (format-time-string "%Y")))
11132 month (string-to-number (match-string 3 ans))
11133 day (string-to-number (match-string 4 ans)))
11134 (if (< year 100) (setq year (+ 2000 year)))
11135 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11136 t nil ans)))
11137 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11138 ;; If there is a time with am/pm, and *no* time without it, we convert
11139 ;; so that matching will be successful.
11140 (loop for i from 1 to 2 do ; twice, for end time as well
11141 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11142 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11143 (setq hour (string-to-number (match-string 1 ans))
11144 minute (if (match-end 3)
11145 (string-to-number (match-string 3 ans))
11147 pm (equal ?p
11148 (string-to-char (downcase (match-string 4 ans)))))
11149 (if (and (= hour 12) (not pm))
11150 (setq hour 0)
11151 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11152 (setq ans (replace-match (format "%02d:%02d" hour minute)
11153 t t ans))))
11155 ;; Check if a time range is given as a duration
11156 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11157 (setq hour (string-to-number (match-string 1 ans))
11158 h2 (+ hour (string-to-number (match-string 3 ans)))
11159 minute (string-to-number (match-string 2 ans))
11160 m2 (+ minute (if (match-end 5) (string-to-number
11161 (match-string 5 ans))0)))
11162 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11163 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11164 t t ans)))
11166 ;; Check if there is a time range
11167 (when (boundp 'org-end-time-was-given)
11168 (setq org-time-was-given nil)
11169 (when (and (string-match org-plain-time-of-day-regexp ans)
11170 (match-end 8))
11171 (setq org-end-time-was-given (match-string 8 ans))
11172 (setq ans (concat (substring ans 0 (match-beginning 7))
11173 (substring ans (match-end 7))))))
11175 (setq tl (parse-time-string ans)
11176 day (or (nth 3 tl) (nth 3 defdecode))
11177 month (or (nth 4 tl)
11178 (if (and org-read-date-prefer-future
11179 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11180 (1+ (nth 4 defdecode))
11181 (nth 4 defdecode)))
11182 year (or (nth 5 tl)
11183 (if (and org-read-date-prefer-future
11184 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11185 (1+ (nth 5 defdecode))
11186 (nth 5 defdecode)))
11187 hour (or (nth 2 tl) (nth 2 defdecode))
11188 minute (or (nth 1 tl) (nth 1 defdecode))
11189 second (or (nth 0 tl) 0)
11190 wday (nth 6 tl))
11192 ;; Special date definitions below
11193 (cond
11194 (iso-week
11195 ;; There was an iso week
11196 (setq year (or iso-year year)
11197 day (or iso-weekday wday 1)
11198 wday nil ; to make sure that the trigger below does not match
11199 iso-date (calendar-gregorian-from-absolute
11200 (calendar-absolute-from-iso
11201 (list iso-week day year))))
11202 ; FIXME: Should we also push ISO weeks into the future?
11203 ; (when (and org-read-date-prefer-future
11204 ; (not iso-year)
11205 ; (< (calendar-absolute-from-gregorian iso-date)
11206 ; (time-to-days (current-time))))
11207 ; (setq year (1+ year)
11208 ; iso-date (calendar-gregorian-from-absolute
11209 ; (calendar-absolute-from-iso
11210 ; (list iso-week day year)))))
11211 (setq month (car iso-date)
11212 year (nth 2 iso-date)
11213 day (nth 1 iso-date)))
11214 (deltan
11215 (unless deltadef
11216 (let ((now (decode-time (current-time))))
11217 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11218 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11219 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11220 ((equal deltaw "m") (setq month (+ month deltan)))
11221 ((equal deltaw "y") (setq year (+ year deltan)))))
11222 ((and wday (not (nth 3 tl)))
11223 ;; Weekday was given, but no day, so pick that day in the week
11224 ;; on or after the derived date.
11225 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11226 (unless (equal wday wday1)
11227 (setq day (+ day (% (- wday wday1 -7) 7))))))
11228 (if (and (boundp 'org-time-was-given)
11229 (nth 2 tl))
11230 (setq org-time-was-given t))
11231 (if (< year 100) (setq year (+ 2000 year)))
11232 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11233 (list second minute hour day month year)))
11235 (defvar parse-time-weekdays)
11237 (defun org-read-date-get-relative (s today default)
11238 "Check string S for special relative date string.
11239 TODAY and DEFAULT are internal times, for today and for a default.
11240 Return shift list (N what def-flag)
11241 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11242 N is the number of WHATs to shift.
11243 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11244 the DEFAULT date rather than TODAY."
11245 (when (and
11246 (string-match
11247 (concat
11248 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11249 "\\([0-9]+\\)?"
11250 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11251 "\\([ \t]\\|$\\)") s)
11252 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11253 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11254 (string-to-char (substring (match-string 1 s) -1))
11255 ?+))
11256 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11257 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11258 (what (if (match-end 3) (match-string 3 s) "d"))
11259 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11260 (date (if rel default today))
11261 (wday (nth 6 (decode-time date)))
11262 delta)
11263 (if wday1
11264 (progn
11265 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11266 (if (= dir ?-) (setq delta (- delta 7)))
11267 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11268 (list delta "d" rel))
11269 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11271 (defun org-eval-in-calendar (form &optional keepdate)
11272 "Eval FORM in the calendar window and return to current window.
11273 Also, store the cursor date in variable org-ans2."
11274 (let ((sw (selected-window)))
11275 (select-window (get-buffer-window "*Calendar*"))
11276 (eval form)
11277 (when (and (not keepdate) (calendar-cursor-to-date))
11278 (let* ((date (calendar-cursor-to-date))
11279 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11280 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11281 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11282 (select-window sw)))
11284 (defun org-calendar-select ()
11285 "Return to `org-read-date' with the date currently selected.
11286 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11287 (interactive)
11288 (when (calendar-cursor-to-date)
11289 (let* ((date (calendar-cursor-to-date))
11290 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11291 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11292 (if (active-minibuffer-window) (exit-minibuffer))))
11294 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11295 "Insert a date stamp for the date given by the internal TIME.
11296 WITH-HM means, use the stamp format that includes the time of the day.
11297 INACTIVE means use square brackets instead of angular ones, so that the
11298 stamp will not contribute to the agenda.
11299 PRE and POST are optional strings to be inserted before and after the
11300 stamp.
11301 The command returns the inserted time stamp."
11302 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11303 stamp)
11304 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11305 (insert-before-markers (or pre ""))
11306 (insert-before-markers (setq stamp (format-time-string fmt time)))
11307 (when (listp extra)
11308 (setq extra (car extra))
11309 (if (and (stringp extra)
11310 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11311 (setq extra (format "-%02d:%02d"
11312 (string-to-number (match-string 1 extra))
11313 (string-to-number (match-string 2 extra))))
11314 (setq extra nil)))
11315 (when extra
11316 (backward-char 1)
11317 (insert-before-markers extra)
11318 (forward-char 1))
11319 (insert-before-markers (or post ""))
11320 (setq org-last-inserted-timestamp stamp)))
11322 (defun org-toggle-time-stamp-overlays ()
11323 "Toggle the use of custom time stamp formats."
11324 (interactive)
11325 (setq org-display-custom-times (not org-display-custom-times))
11326 (unless org-display-custom-times
11327 (let ((p (point-min)) (bmp (buffer-modified-p)))
11328 (while (setq p (next-single-property-change p 'display))
11329 (if (and (get-text-property p 'display)
11330 (eq (get-text-property p 'face) 'org-date))
11331 (remove-text-properties
11332 p (setq p (next-single-property-change p 'display))
11333 '(display t))))
11334 (set-buffer-modified-p bmp)))
11335 (if (featurep 'xemacs)
11336 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11337 (org-restart-font-lock)
11338 (setq org-table-may-need-update t)
11339 (if org-display-custom-times
11340 (message "Time stamps are overlayed with custom format")
11341 (message "Time stamp overlays removed")))
11343 (defun org-display-custom-time (beg end)
11344 "Overlay modified time stamp format over timestamp between BEG and END."
11345 (let* ((ts (buffer-substring beg end))
11346 t1 w1 with-hm tf time str w2 (off 0))
11347 (save-match-data
11348 (setq t1 (org-parse-time-string ts t))
11349 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11350 (setq off (- (match-end 0) (match-beginning 0)))))
11351 (setq end (- end off))
11352 (setq w1 (- end beg)
11353 with-hm (and (nth 1 t1) (nth 2 t1))
11354 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11355 time (org-fix-decoded-time t1)
11356 str (org-add-props
11357 (format-time-string
11358 (substring tf 1 -1) (apply 'encode-time time))
11359 nil 'mouse-face 'highlight)
11360 w2 (length str))
11361 (if (not (= w2 w1))
11362 (add-text-properties (1+ beg) (+ 2 beg)
11363 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11364 (if (featurep 'xemacs)
11365 (progn
11366 (put-text-property beg end 'invisible t)
11367 (put-text-property beg end 'end-glyph (make-glyph str)))
11368 (put-text-property beg end 'display str))))
11370 (defun org-translate-time (string)
11371 "Translate all timestamps in STRING to custom format.
11372 But do this only if the variable `org-display-custom-times' is set."
11373 (when org-display-custom-times
11374 (save-match-data
11375 (let* ((start 0)
11376 (re org-ts-regexp-both)
11377 t1 with-hm inactive tf time str beg end)
11378 (while (setq start (string-match re string start))
11379 (setq beg (match-beginning 0)
11380 end (match-end 0)
11381 t1 (save-match-data
11382 (org-parse-time-string (substring string beg end) t))
11383 with-hm (and (nth 1 t1) (nth 2 t1))
11384 inactive (equal (substring string beg (1+ beg)) "[")
11385 tf (funcall (if with-hm 'cdr 'car)
11386 org-time-stamp-custom-formats)
11387 time (org-fix-decoded-time t1)
11388 str (format-time-string
11389 (concat
11390 (if inactive "[" "<") (substring tf 1 -1)
11391 (if inactive "]" ">"))
11392 (apply 'encode-time time))
11393 string (replace-match str t t string)
11394 start (+ start (length str)))))))
11395 string)
11397 (defun org-fix-decoded-time (time)
11398 "Set 0 instead of nil for the first 6 elements of time.
11399 Don't touch the rest."
11400 (let ((n 0))
11401 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11403 (defun org-days-to-time (timestamp-string)
11404 "Difference between TIMESTAMP-STRING and now in days."
11405 (- (time-to-days (org-time-string-to-time timestamp-string))
11406 (time-to-days (current-time))))
11408 (defun org-deadline-close (timestamp-string &optional ndays)
11409 "Is the time in TIMESTAMP-STRING close to the current date?"
11410 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11411 (and (< (org-days-to-time timestamp-string) ndays)
11412 (not (org-entry-is-done-p))))
11414 (defun org-get-wdays (ts)
11415 "Get the deadline lead time appropriate for timestring TS."
11416 (cond
11417 ((<= org-deadline-warning-days 0)
11418 ;; 0 or negative, enforce this value no matter what
11419 (- org-deadline-warning-days))
11420 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11421 ;; lead time is specified.
11422 (floor (* (string-to-number (match-string 1 ts))
11423 (cdr (assoc (match-string 2 ts)
11424 '(("d" . 1) ("w" . 7)
11425 ("m" . 30.4) ("y" . 365.25)))))))
11426 ;; go for the default.
11427 (t org-deadline-warning-days)))
11429 (defun org-calendar-select-mouse (ev)
11430 "Return to `org-read-date' with the date currently selected.
11431 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11432 (interactive "e")
11433 (mouse-set-point ev)
11434 (when (calendar-cursor-to-date)
11435 (let* ((date (calendar-cursor-to-date))
11436 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11437 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11438 (if (active-minibuffer-window) (exit-minibuffer))))
11440 (defun org-check-deadlines (ndays)
11441 "Check if there are any deadlines due or past due.
11442 A deadline is considered due if it happens within `org-deadline-warning-days'
11443 days from today's date. If the deadline appears in an entry marked DONE,
11444 it is not shown. The prefix arg NDAYS can be used to test that many
11445 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11446 (interactive "P")
11447 (let* ((org-warn-days
11448 (cond
11449 ((equal ndays '(4)) 100000)
11450 (ndays (prefix-numeric-value ndays))
11451 (t (abs org-deadline-warning-days))))
11452 (case-fold-search nil)
11453 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11454 (callback
11455 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11457 (message "%d deadlines past-due or due within %d days"
11458 (org-occur regexp nil callback)
11459 org-warn-days)))
11461 (defun org-check-before-date (date)
11462 "Check if there are deadlines or scheduled entries before DATE."
11463 (interactive (list (org-read-date)))
11464 (let ((case-fold-search nil)
11465 (regexp (concat "\\<\\(" org-deadline-string
11466 "\\|" org-scheduled-string
11467 "\\) *<\\([^>]+\\)>"))
11468 (callback
11469 (lambda () (time-less-p
11470 (org-time-string-to-time (match-string 2))
11471 (org-time-string-to-time date)))))
11472 (message "%d entries before %s"
11473 (org-occur regexp nil callback) date)))
11475 (defun org-evaluate-time-range (&optional to-buffer)
11476 "Evaluate a time range by computing the difference between start and end.
11477 Normally the result is just printed in the echo area, but with prefix arg
11478 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11479 If the time range is actually in a table, the result is inserted into the
11480 next column.
11481 For time difference computation, a year is assumed to be exactly 365
11482 days in order to avoid rounding problems."
11483 (interactive "P")
11485 (org-clock-update-time-maybe)
11486 (save-excursion
11487 (unless (org-at-date-range-p t)
11488 (goto-char (point-at-bol))
11489 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11490 (if (not (org-at-date-range-p t))
11491 (error "Not at a time-stamp range, and none found in current line")))
11492 (let* ((ts1 (match-string 1))
11493 (ts2 (match-string 2))
11494 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11495 (match-end (match-end 0))
11496 (time1 (org-time-string-to-time ts1))
11497 (time2 (org-time-string-to-time ts2))
11498 (t1 (time-to-seconds time1))
11499 (t2 (time-to-seconds time2))
11500 (diff (abs (- t2 t1)))
11501 (negative (< (- t2 t1) 0))
11502 ;; (ys (floor (* 365 24 60 60)))
11503 (ds (* 24 60 60))
11504 (hs (* 60 60))
11505 (fy "%dy %dd %02d:%02d")
11506 (fy1 "%dy %dd")
11507 (fd "%dd %02d:%02d")
11508 (fd1 "%dd")
11509 (fh "%02d:%02d")
11510 y d h m align)
11511 (if havetime
11512 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11514 d (floor (/ diff ds)) diff (mod diff ds)
11515 h (floor (/ diff hs)) diff (mod diff hs)
11516 m (floor (/ diff 60)))
11517 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11519 d (floor (+ (/ diff ds) 0.5))
11520 h 0 m 0))
11521 (if (not to-buffer)
11522 (message "%s" (org-make-tdiff-string y d h m))
11523 (if (org-at-table-p)
11524 (progn
11525 (goto-char match-end)
11526 (setq align t)
11527 (and (looking-at " *|") (goto-char (match-end 0))))
11528 (goto-char match-end))
11529 (if (looking-at
11530 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11531 (replace-match ""))
11532 (if negative (insert " -"))
11533 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11534 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11535 (insert " " (format fh h m))))
11536 (if align (org-table-align))
11537 (message "Time difference inserted")))))
11539 (defun org-make-tdiff-string (y d h m)
11540 (let ((fmt "")
11541 (l nil))
11542 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11543 l (push y l)))
11544 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11545 l (push d l)))
11546 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11547 l (push h l)))
11548 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11549 l (push m l)))
11550 (apply 'format fmt (nreverse l))))
11552 (defun org-time-string-to-time (s)
11553 (apply 'encode-time (org-parse-time-string s)))
11555 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11556 "Convert a time stamp to an absolute day number.
11557 If there is a specifyer for a cyclic time stamp, get the closest date to
11558 DAYNR.
11559 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11560 (cond
11561 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11562 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11563 daynr
11564 (+ daynr 1000)))
11565 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11566 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11567 (time-to-days (current-time))) (match-string 0 s)
11568 prefer show-all))
11569 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11571 (defun org-days-to-iso-week (days)
11572 "Return the iso week number."
11573 (require 'cal-iso)
11574 (car (calendar-iso-from-absolute days)))
11576 (defun org-small-year-to-year (year)
11577 "Convert 2-digit years into 4-digit years.
11578 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11579 The year 2000 cannot be abbreviated. Any year larger than 99
11580 is returned unchanged."
11581 (if (< year 38)
11582 (setq year (+ 2000 year))
11583 (if (< year 100)
11584 (setq year (+ 1900 year))))
11585 year)
11587 (defun org-time-from-absolute (d)
11588 "Return the time corresponding to date D.
11589 D may be an absolute day number, or a calendar-type list (month day year)."
11590 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11591 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11593 (defun org-calendar-holiday ()
11594 "List of holidays, for Diary display in Org-mode."
11595 (require 'holidays)
11596 (let ((hl (funcall
11597 (if (fboundp 'calendar-check-holidays)
11598 'calendar-check-holidays 'check-calendar-holidays) date)))
11599 (if hl (mapconcat 'identity hl "; "))))
11601 (defun org-diary-sexp-entry (sexp entry date)
11602 "Process a SEXP diary ENTRY for DATE."
11603 (require 'diary-lib)
11604 (let ((result (if calendar-debug-sexp
11605 (let ((stack-trace-on-error t))
11606 (eval (car (read-from-string sexp))))
11607 (condition-case nil
11608 (eval (car (read-from-string sexp)))
11609 (error
11610 (beep)
11611 (message "Bad sexp at line %d in %s: %s"
11612 (org-current-line)
11613 (buffer-file-name) sexp)
11614 (sleep-for 2))))))
11615 (cond ((stringp result) result)
11616 ((and (consp result)
11617 (stringp (cdr result))) (cdr result))
11618 (result entry)
11619 (t nil))))
11621 (defun org-diary-to-ical-string (frombuf)
11622 "Get iCalendar entries from diary entries in buffer FROMBUF.
11623 This uses the icalendar.el library."
11624 (let* ((tmpdir (if (featurep 'xemacs)
11625 (temp-directory)
11626 temporary-file-directory))
11627 (tmpfile (make-temp-name
11628 (expand-file-name "orgics" tmpdir)))
11629 buf rtn b e)
11630 (save-excursion
11631 (set-buffer frombuf)
11632 (icalendar-export-region (point-min) (point-max) tmpfile)
11633 (setq buf (find-buffer-visiting tmpfile))
11634 (set-buffer buf)
11635 (goto-char (point-min))
11636 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11637 (setq b (match-beginning 0)))
11638 (goto-char (point-max))
11639 (if (re-search-backward "^END:VEVENT" nil t)
11640 (setq e (match-end 0)))
11641 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11642 (kill-buffer buf)
11643 (delete-file tmpfile)
11644 rtn))
11646 (defun org-closest-date (start current change prefer show-all)
11647 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11648 When PREFER is `past' return a date that is either CURRENT or past.
11649 When PREFER is `future', return a date that is either CURRENT or future.
11650 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11651 ;; Make the proper lists from the dates
11652 (catch 'exit
11653 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11654 dn dw sday cday n1 n2 n0
11655 d m y y1 y2 date1 date2 nmonths nm ny m2)
11657 (setq start (org-date-to-gregorian start)
11658 current (org-date-to-gregorian
11659 (if show-all
11660 current
11661 (time-to-days (current-time))))
11662 sday (calendar-absolute-from-gregorian start)
11663 cday (calendar-absolute-from-gregorian current))
11665 (if (<= cday sday) (throw 'exit sday))
11667 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11668 (setq dn (string-to-number (match-string 1 change))
11669 dw (cdr (assoc (match-string 2 change) a1)))
11670 (error "Invalid change specifyer: %s" change))
11671 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11672 (cond
11673 ((eq dw 'day)
11674 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11675 n2 (+ n1 dn)))
11676 ((eq dw 'year)
11677 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11678 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11679 (setq date1 (list m d y1)
11680 n1 (calendar-absolute-from-gregorian date1)
11681 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11682 n2 (calendar-absolute-from-gregorian date2)))
11683 ((eq dw 'month)
11684 ;; approx number of month between the two dates
11685 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11686 ;; How often does dn fit in there?
11687 (setq d (nth 1 start) m (car start) y (nth 2 start)
11688 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11689 m (+ m nm)
11690 ny (floor (/ m 12))
11691 y (+ y ny)
11692 m (- m (* ny 12)))
11693 (while (> m 12) (setq m (- m 12) y (1+ y)))
11694 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11695 (setq m2 (+ m dn) y2 y)
11696 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11697 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11698 (while (<= n2 cday)
11699 (setq n1 n2 m m2 y y2)
11700 (setq m2 (+ m dn) y2 y)
11701 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11702 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11703 ;; Make sure n1 is the earlier date
11704 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11705 (if show-all
11706 (cond
11707 ((eq prefer 'past) n1)
11708 ((eq prefer 'future) (if (= cday n1) n1 n2))
11709 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11710 (cond
11711 ((eq prefer 'past) n1)
11712 ((eq prefer 'future) (if (= cday n1) n1 n2))
11713 (t (if (= cday n1) n1 n2)))))))
11715 (defun org-date-to-gregorian (date)
11716 "Turn any specification of DATE into a gregorian date for the calendar."
11717 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11718 ((and (listp date) (= (length date) 3)) date)
11719 ((stringp date)
11720 (setq date (org-parse-time-string date))
11721 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11722 ((listp date)
11723 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11725 (defun org-parse-time-string (s &optional nodefault)
11726 "Parse the standard Org-mode time string.
11727 This should be a lot faster than the normal `parse-time-string'.
11728 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11729 hour and minute fields will be nil if not given."
11730 (if (string-match org-ts-regexp0 s)
11731 (list 0
11732 (if (or (match-beginning 8) (not nodefault))
11733 (string-to-number (or (match-string 8 s) "0")))
11734 (if (or (match-beginning 7) (not nodefault))
11735 (string-to-number (or (match-string 7 s) "0")))
11736 (string-to-number (match-string 4 s))
11737 (string-to-number (match-string 3 s))
11738 (string-to-number (match-string 2 s))
11739 nil nil nil)
11740 (make-list 9 0)))
11742 (defun org-timestamp-up (&optional arg)
11743 "Increase the date item at the cursor by one.
11744 If the cursor is on the year, change the year. If it is on the month or
11745 the day, change that.
11746 With prefix ARG, change by that many units."
11747 (interactive "p")
11748 (org-timestamp-change (prefix-numeric-value arg)))
11750 (defun org-timestamp-down (&optional arg)
11751 "Decrease the date item at the cursor by one.
11752 If the cursor is on the year, change the year. If it is on the month or
11753 the day, change that.
11754 With prefix ARG, change by that many units."
11755 (interactive "p")
11756 (org-timestamp-change (- (prefix-numeric-value arg))))
11758 (defun org-timestamp-up-day (&optional arg)
11759 "Increase the date in the time stamp by one day.
11760 With prefix ARG, change that many days."
11761 (interactive "p")
11762 (if (and (not (org-at-timestamp-p t))
11763 (org-on-heading-p))
11764 (org-todo 'up)
11765 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11767 (defun org-timestamp-down-day (&optional arg)
11768 "Decrease the date in the time stamp by one day.
11769 With prefix ARG, change that many days."
11770 (interactive "p")
11771 (if (and (not (org-at-timestamp-p t))
11772 (org-on-heading-p))
11773 (org-todo 'down)
11774 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11776 (defun org-at-timestamp-p (&optional inactive-ok)
11777 "Determine if the cursor is in or at a timestamp."
11778 (interactive)
11779 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11780 (pos (point))
11781 (ans (or (looking-at tsr)
11782 (save-excursion
11783 (skip-chars-backward "^[<\n\r\t")
11784 (if (> (point) (point-min)) (backward-char 1))
11785 (and (looking-at tsr)
11786 (> (- (match-end 0) pos) -1))))))
11787 (and ans
11788 (boundp 'org-ts-what)
11789 (setq org-ts-what
11790 (cond
11791 ((= pos (match-beginning 0)) 'bracket)
11792 ((= pos (1- (match-end 0))) 'bracket)
11793 ((org-pos-in-match-range pos 2) 'year)
11794 ((org-pos-in-match-range pos 3) 'month)
11795 ((org-pos-in-match-range pos 7) 'hour)
11796 ((org-pos-in-match-range pos 8) 'minute)
11797 ((or (org-pos-in-match-range pos 4)
11798 (org-pos-in-match-range pos 5)) 'day)
11799 ((and (> pos (or (match-end 8) (match-end 5)))
11800 (< pos (match-end 0)))
11801 (- pos (or (match-end 8) (match-end 5))))
11802 (t 'day))))
11803 ans))
11805 (defun org-toggle-timestamp-type ()
11806 "Toggle the type (<active> or [inactive]) of a time stamp."
11807 (interactive)
11808 (when (org-at-timestamp-p t)
11809 (let ((beg (match-beginning 0)) (end (match-end 0))
11810 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11811 (save-excursion
11812 (goto-char beg)
11813 (while (re-search-forward "[][<>]" end t)
11814 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11815 t t)))
11816 (message "Timestamp is now %sactive"
11817 (if (equal (char-after beg) ?<) "" "in")))))
11819 (defun org-timestamp-change (n &optional what)
11820 "Change the date in the time stamp at point.
11821 The date will be changed by N times WHAT. WHAT can be `day', `month',
11822 `year', `minute', `second'. If WHAT is not given, the cursor position
11823 in the timestamp determines what will be changed."
11824 (let ((pos (point))
11825 with-hm inactive
11826 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11827 org-ts-what
11828 extra rem
11829 ts time time0)
11830 (if (not (org-at-timestamp-p t))
11831 (error "Not at a timestamp"))
11832 (if (and (not what) (eq org-ts-what 'bracket))
11833 (org-toggle-timestamp-type)
11834 (if (and (not what) (not (eq org-ts-what 'day))
11835 org-display-custom-times
11836 (get-text-property (point) 'display)
11837 (not (get-text-property (1- (point)) 'display)))
11838 (setq org-ts-what 'day))
11839 (setq org-ts-what (or what org-ts-what)
11840 inactive (= (char-after (match-beginning 0)) ?\[)
11841 ts (match-string 0))
11842 (replace-match "")
11843 (if (string-match
11844 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11846 (setq extra (match-string 1 ts)))
11847 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11848 (setq with-hm t))
11849 (setq time0 (org-parse-time-string ts))
11850 (when (and (eq org-ts-what 'minute)
11851 (eq current-prefix-arg nil))
11852 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11853 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11854 (setcar (cdr time0) (+ (nth 1 time0)
11855 (if (> n 0) (- rem) (- dm rem))))))
11856 (setq time
11857 (encode-time (or (car time0) 0)
11858 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11859 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11860 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11861 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11862 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11863 (nthcdr 6 time0)))
11864 (when (integerp org-ts-what)
11865 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11866 (if (eq what 'calendar)
11867 (let ((cal-date (org-get-date-from-calendar)))
11868 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11869 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11870 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11871 (setcar time0 (or (car time0) 0))
11872 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11873 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11874 (setq time (apply 'encode-time time0))))
11875 (setq org-last-changed-timestamp
11876 (org-insert-time-stamp time with-hm inactive nil nil extra))
11877 (org-clock-update-time-maybe)
11878 (goto-char pos)
11879 ;; Try to recenter the calendar window, if any
11880 (if (and org-calendar-follow-timestamp-change
11881 (get-buffer-window "*Calendar*" t)
11882 (memq org-ts-what '(day month year)))
11883 (org-recenter-calendar (time-to-days time))))))
11885 (defun org-modify-ts-extra (s pos n dm)
11886 "Change the different parts of the lead-time and repeat fields in timestamp."
11887 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11888 ng h m new rem)
11889 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11890 (cond
11891 ((or (org-pos-in-match-range pos 2)
11892 (org-pos-in-match-range pos 3))
11893 (setq m (string-to-number (match-string 3 s))
11894 h (string-to-number (match-string 2 s)))
11895 (if (org-pos-in-match-range pos 2)
11896 (setq h (+ h n))
11897 (setq n (* dm (org-no-warnings (signum n))))
11898 (when (not (= 0 (setq rem (% m dm))))
11899 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11900 (setq m (+ m n)))
11901 (if (< m 0) (setq m (+ m 60) h (1- h)))
11902 (if (> m 59) (setq m (- m 60) h (1+ h)))
11903 (setq h (min 24 (max 0 h)))
11904 (setq ng 1 new (format "-%02d:%02d" h m)))
11905 ((org-pos-in-match-range pos 6)
11906 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11907 ((org-pos-in-match-range pos 5)
11908 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11910 ((org-pos-in-match-range pos 9)
11911 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11912 ((org-pos-in-match-range pos 8)
11913 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11915 (when ng
11916 (setq s (concat
11917 (substring s 0 (match-beginning ng))
11919 (substring s (match-end ng))))))
11922 (defun org-recenter-calendar (date)
11923 "If the calendar is visible, recenter it to DATE."
11924 (let* ((win (selected-window))
11925 (cwin (get-buffer-window "*Calendar*" t))
11926 (calendar-move-hook nil))
11927 (when cwin
11928 (select-window cwin)
11929 (calendar-goto-date (if (listp date) date
11930 (calendar-gregorian-from-absolute date)))
11931 (select-window win))))
11933 (defun org-goto-calendar (&optional arg)
11934 "Go to the Emacs calendar at the current date.
11935 If there is a time stamp in the current line, go to that date.
11936 A prefix ARG can be used to force the current date."
11937 (interactive "P")
11938 (let ((tsr org-ts-regexp) diff
11939 (calendar-move-hook nil)
11940 (calendar-view-holidays-initially-flag nil)
11941 (view-calendar-holidays-initially nil)
11942 (calendar-view-diary-initially-flag nil)
11943 (view-diary-entries-initially nil))
11944 (if (or (org-at-timestamp-p)
11945 (save-excursion
11946 (beginning-of-line 1)
11947 (looking-at (concat ".*" tsr))))
11948 (let ((d1 (time-to-days (current-time)))
11949 (d2 (time-to-days
11950 (org-time-string-to-time (match-string 1)))))
11951 (setq diff (- d2 d1))))
11952 (calendar)
11953 (calendar-goto-today)
11954 (if (and diff (not arg)) (calendar-forward-day diff))))
11956 (defun org-get-date-from-calendar ()
11957 "Return a list (month day year) of date at point in calendar."
11958 (with-current-buffer "*Calendar*"
11959 (save-match-data
11960 (calendar-cursor-to-date))))
11962 (defun org-date-from-calendar ()
11963 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11964 If there is already a time stamp at the cursor position, update it."
11965 (interactive)
11966 (if (org-at-timestamp-p t)
11967 (org-timestamp-change 0 'calendar)
11968 (let ((cal-date (org-get-date-from-calendar)))
11969 (org-insert-time-stamp
11970 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11972 (defun org-minutes-to-hh:mm-string (m)
11973 "Compute H:MM from a number of minutes."
11974 (let ((h (/ m 60)))
11975 (setq m (- m (* 60 h)))
11976 (format org-time-clocksum-format h m)))
11978 (defun org-hh:mm-string-to-minutes (s)
11979 "Convert a string H:MM to a number of minutes."
11980 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11981 (+ (* (string-to-number (match-string 1 s)) 60)
11982 (string-to-number (match-string 2 s)))
11985 ;;;; Agenda files
11987 ;;;###autoload
11988 (defun org-iswitchb (&optional arg)
11989 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11990 With a prefix argument, restrict available to files.
11991 With two prefix arguments, restrict available buffers to agenda files.
11993 Due to some yet unresolved reason, the global function
11994 `iswitchb-mode' needs to be active for this function to work."
11995 (interactive "P")
11996 (require 'iswitchb)
11997 (let ((enabled iswitchb-mode) blist)
11998 (or enabled (iswitchb-mode 1))
11999 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12000 ((equal arg '(16)) (org-buffer-list 'agenda))
12001 (t (org-buffer-list))))
12002 (unwind-protect
12003 (let ((iswitchb-make-buflist-hook
12004 (lambda ()
12005 (setq iswitchb-temp-buflist
12006 (mapcar 'buffer-name blist)))))
12007 (switch-to-buffer
12008 (iswitchb-read-buffer
12009 "Switch-to: " nil t))
12010 (or enabled (iswitchb-mode -1))))))
12012 ;;;###autoload
12013 (defun org-ido-switchb (&optional arg)
12014 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12015 With a prefix argument, restrict available to files.
12016 With two prefix arguments, restrict available buffers to agenda files."
12017 (interactive "P")
12018 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12019 ((equal arg '(16)) (org-buffer-list 'agenda))
12020 (t (org-buffer-list)))))
12021 (switch-to-buffer
12022 (org-ido-completing-read "Org buffer: "
12023 (mapcar 'buffer-name blist)
12024 nil t))))
12026 (defun org-buffer-list (&optional predicate exclude-tmp)
12027 "Return a list of Org buffers.
12028 PREDICATE can be `export', `files' or `agenda'.
12030 export restrict the list to Export buffers.
12031 files restrict the list to buffers visiting Org files.
12032 agenda restrict the list to buffers visiting agenda files.
12034 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12035 (let* ((bfn nil)
12036 (agenda-files (and (eq predicate 'agenda)
12037 (mapcar 'file-truename (org-agenda-files t))))
12038 (filter
12039 (cond
12040 ((eq predicate 'files)
12041 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12042 ((eq predicate 'export)
12043 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12044 ((eq predicate 'agenda)
12045 (lambda (b)
12046 (with-current-buffer b
12047 (and (eq major-mode 'org-mode)
12048 (setq bfn (buffer-file-name b))
12049 (member (file-truename bfn) agenda-files)))))
12050 (t (lambda (b) (with-current-buffer b
12051 (or (eq major-mode 'org-mode)
12052 (string-match "\*Org .*Export"
12053 (buffer-name b)))))))))
12054 (delq nil
12055 (mapcar
12056 (lambda(b)
12057 (if (and (funcall filter b)
12058 (or (not exclude-tmp)
12059 (not (string-match "tmp" (buffer-name b)))))
12061 nil))
12062 (buffer-list)))))
12064 (defun org-agenda-files (&optional unrestricted archives)
12065 "Get the list of agenda files.
12066 Optional UNRESTRICTED means return the full list even if a restriction
12067 is currently in place.
12068 When ARCHIVES is t, include all archive files hat are really being
12069 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12070 `org-agenda-archives-mode' is t."
12071 (let ((files
12072 (cond
12073 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12074 ((stringp org-agenda-files) (org-read-agenda-file-list))
12075 ((listp org-agenda-files) org-agenda-files)
12076 (t (error "Invalid value of `org-agenda-files'")))))
12077 (setq files (apply 'append
12078 (mapcar (lambda (f)
12079 (if (file-directory-p f)
12080 (directory-files
12081 f t org-agenda-file-regexp)
12082 (list f)))
12083 files)))
12084 (when org-agenda-skip-unavailable-files
12085 (setq files (delq nil
12086 (mapcar (function
12087 (lambda (file)
12088 (and (file-readable-p file) file)))
12089 files))))
12090 (when (or (eq archives t)
12091 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12092 (setq files (org-add-archive-files files)))
12093 files))
12095 (defun org-edit-agenda-file-list ()
12096 "Edit the list of agenda files.
12097 Depending on setup, this either uses customize to edit the variable
12098 `org-agenda-files', or it visits the file that is holding the list. In the
12099 latter case, the buffer is set up in a way that saving it automatically kills
12100 the buffer and restores the previous window configuration."
12101 (interactive)
12102 (if (stringp org-agenda-files)
12103 (let ((cw (current-window-configuration)))
12104 (find-file org-agenda-files)
12105 (org-set-local 'org-window-configuration cw)
12106 (org-add-hook 'after-save-hook
12107 (lambda ()
12108 (set-window-configuration
12109 (prog1 org-window-configuration
12110 (kill-buffer (current-buffer))))
12111 (org-install-agenda-files-menu)
12112 (message "New agenda file list installed"))
12113 nil 'local)
12114 (message "%s" (substitute-command-keys
12115 "Edit list and finish with \\[save-buffer]")))
12116 (customize-variable 'org-agenda-files)))
12118 (defun org-store-new-agenda-file-list (list)
12119 "Set new value for the agenda file list and save it correctly."
12120 (if (stringp org-agenda-files)
12121 (let ((f org-agenda-files) b)
12122 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12123 (with-temp-file f
12124 (insert (mapconcat 'identity list "\n") "\n")))
12125 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12126 (setq org-agenda-files list)
12127 (customize-save-variable 'org-agenda-files org-agenda-files))))
12129 (defun org-read-agenda-file-list ()
12130 "Read the list of agenda files from a file."
12131 (when (file-directory-p org-agenda-files)
12132 (error "`org-agenda-files' cannot be a single directory"))
12133 (when (stringp org-agenda-files)
12134 (with-temp-buffer
12135 (insert-file-contents org-agenda-files)
12136 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12139 ;;;###autoload
12140 (defun org-cycle-agenda-files ()
12141 "Cycle through the files in `org-agenda-files'.
12142 If the current buffer visits an agenda file, find the next one in the list.
12143 If the current buffer does not, find the first agenda file."
12144 (interactive)
12145 (let* ((fs (org-agenda-files t))
12146 (files (append fs (list (car fs))))
12147 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12148 file)
12149 (unless files (error "No agenda files"))
12150 (catch 'exit
12151 (while (setq file (pop files))
12152 (if (equal (file-truename file) tcf)
12153 (when (car files)
12154 (find-file (car files))
12155 (throw 'exit t))))
12156 (find-file (car fs)))
12157 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12159 (defun org-agenda-file-to-front (&optional to-end)
12160 "Move/add the current file to the top of the agenda file list.
12161 If the file is not present in the list, it is added to the front. If it is
12162 present, it is moved there. With optional argument TO-END, add/move to the
12163 end of the list."
12164 (interactive "P")
12165 (let ((org-agenda-skip-unavailable-files nil)
12166 (file-alist (mapcar (lambda (x)
12167 (cons (file-truename x) x))
12168 (org-agenda-files t)))
12169 (ctf (file-truename buffer-file-name))
12170 x had)
12171 (setq x (assoc ctf file-alist) had x)
12173 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12174 (if to-end
12175 (setq file-alist (append (delq x file-alist) (list x)))
12176 (setq file-alist (cons x (delq x file-alist))))
12177 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12178 (org-install-agenda-files-menu)
12179 (message "File %s to %s of agenda file list"
12180 (if had "moved" "added") (if to-end "end" "front"))))
12182 (defun org-remove-file (&optional file)
12183 "Remove current file from the list of files in variable `org-agenda-files'.
12184 These are the files which are being checked for agenda entries.
12185 Optional argument FILE means, use this file instead of the current."
12186 (interactive)
12187 (let* ((org-agenda-skip-unavailable-files nil)
12188 (file (or file buffer-file-name))
12189 (true-file (file-truename file))
12190 (afile (abbreviate-file-name file))
12191 (files (delq nil (mapcar
12192 (lambda (x)
12193 (if (equal true-file
12194 (file-truename x))
12195 nil x))
12196 (org-agenda-files t)))))
12197 (if (not (= (length files) (length (org-agenda-files t))))
12198 (progn
12199 (org-store-new-agenda-file-list files)
12200 (org-install-agenda-files-menu)
12201 (message "Removed file: %s" afile))
12202 (message "File was not in list: %s (not removed)" afile))))
12204 (defun org-file-menu-entry (file)
12205 (vector file (list 'find-file file) t))
12207 (defun org-check-agenda-file (file)
12208 "Make sure FILE exists. If not, ask user what to do."
12209 (when (not (file-exists-p file))
12210 (message "non-existent file %s. [R]emove from list or [A]bort?"
12211 (abbreviate-file-name file))
12212 (let ((r (downcase (read-char-exclusive))))
12213 (cond
12214 ((equal r ?r)
12215 (org-remove-file file)
12216 (throw 'nextfile t))
12217 (t (error "Abort"))))))
12219 (defun org-get-agenda-file-buffer (file)
12220 "Get a buffer visiting FILE. If the buffer needs to be created, add
12221 it to the list of buffers which might be released later."
12222 (let ((buf (org-find-base-buffer-visiting file)))
12223 (if buf
12224 buf ; just return it
12225 ;; Make a new buffer and remember it
12226 (setq buf (find-file-noselect file))
12227 (if buf (push buf org-agenda-new-buffers))
12228 buf)))
12230 (defun org-release-buffers (blist)
12231 "Release all buffers in list, asking the user for confirmation when needed.
12232 When a buffer is unmodified, it is just killed. When modified, it is saved
12233 \(if the user agrees) and then killed."
12234 (let (buf file)
12235 (while (setq buf (pop blist))
12236 (setq file (buffer-file-name buf))
12237 (when (and (buffer-modified-p buf)
12238 file
12239 (y-or-n-p (format "Save file %s? " file)))
12240 (with-current-buffer buf (save-buffer)))
12241 (kill-buffer buf))))
12243 (defun org-prepare-agenda-buffers (files)
12244 "Create buffers for all agenda files, protect archived trees and comments."
12245 (interactive)
12246 (let ((pa '(:org-archived t))
12247 (pc '(:org-comment t))
12248 (pall '(:org-archived t :org-comment t))
12249 (inhibit-read-only t)
12250 (rea (concat ":" org-archive-tag ":"))
12251 bmp file re)
12252 (save-excursion
12253 (save-restriction
12254 (while (setq file (pop files))
12255 (if (bufferp file)
12256 (set-buffer file)
12257 (org-check-agenda-file file)
12258 (set-buffer (org-get-agenda-file-buffer file)))
12259 (widen)
12260 (setq bmp (buffer-modified-p))
12261 (org-refresh-category-properties)
12262 (setq org-todo-keywords-for-agenda
12263 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12264 (setq org-done-keywords-for-agenda
12265 (append org-done-keywords-for-agenda org-done-keywords))
12266 (setq org-todo-keyword-alist-for-agenda
12267 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12268 (setq org-tag-alist-for-agenda
12269 (append org-tag-alist-for-agenda org-tag-alist))
12271 (save-excursion
12272 (remove-text-properties (point-min) (point-max) pall)
12273 (when org-agenda-skip-archived-trees
12274 (goto-char (point-min))
12275 (while (re-search-forward rea nil t)
12276 (if (org-on-heading-p t)
12277 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12278 (goto-char (point-min))
12279 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12280 (while (re-search-forward re nil t)
12281 (add-text-properties
12282 (match-beginning 0) (org-end-of-subtree t) pc)))
12283 (set-buffer-modified-p bmp))))
12284 (setq org-todo-keyword-alist-for-agenda
12285 (org-uniquify org-todo-keyword-alist-for-agenda)
12286 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12288 ;;;; Embedded LaTeX
12290 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12291 "Keymap for the minor `org-cdlatex-mode'.")
12293 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12294 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12295 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12296 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12297 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12299 (defvar org-cdlatex-texmathp-advice-is-done nil
12300 "Flag remembering if we have applied the advice to texmathp already.")
12302 (define-minor-mode org-cdlatex-mode
12303 "Toggle the minor `org-cdlatex-mode'.
12304 This mode supports entering LaTeX environment and math in LaTeX fragments
12305 in Org-mode.
12306 \\{org-cdlatex-mode-map}"
12307 nil " OCDL" nil
12308 (when org-cdlatex-mode (require 'cdlatex))
12309 (unless org-cdlatex-texmathp-advice-is-done
12310 (setq org-cdlatex-texmathp-advice-is-done t)
12311 (defadvice texmathp (around org-math-always-on activate)
12312 "Always return t in org-mode buffers.
12313 This is because we want to insert math symbols without dollars even outside
12314 the LaTeX math segments. If Orgmode thinks that point is actually inside
12315 an embedded LaTeX fragment, let texmathp do its job.
12316 \\[org-cdlatex-mode-map]"
12317 (interactive)
12318 (let (p)
12319 (cond
12320 ((not (org-mode-p)) ad-do-it)
12321 ((eq this-command 'cdlatex-math-symbol)
12322 (setq ad-return-value t
12323 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12325 (let ((p (org-inside-LaTeX-fragment-p)))
12326 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12327 (setq ad-return-value t
12328 texmathp-why '("Org-mode embedded math" . 0))
12329 (if p ad-do-it)))))))))
12331 (defun turn-on-org-cdlatex ()
12332 "Unconditionally turn on `org-cdlatex-mode'."
12333 (org-cdlatex-mode 1))
12335 (defun org-inside-LaTeX-fragment-p ()
12336 "Test if point is inside a LaTeX fragment.
12337 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12338 sequence appearing also before point.
12339 Even though the matchers for math are configurable, this function assumes
12340 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12341 delimiters are skipped when they have been removed by customization.
12342 The return value is nil, or a cons cell with the delimiter and
12343 and the position of this delimiter.
12345 This function does a reasonably good job, but can locally be fooled by
12346 for example currency specifications. For example it will assume being in
12347 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12348 fragments that are properly closed, but during editing, we have to live
12349 with the uncertainty caused by missing closing delimiters. This function
12350 looks only before point, not after."
12351 (catch 'exit
12352 (let ((pos (point))
12353 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12354 (lim (progn
12355 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12356 (point)))
12357 dd-on str (start 0) m re)
12358 (goto-char pos)
12359 (when dodollar
12360 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12361 re (nth 1 (assoc "$" org-latex-regexps)))
12362 (while (string-match re str start)
12363 (cond
12364 ((= (match-end 0) (length str))
12365 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12366 ((= (match-end 0) (- (length str) 5))
12367 (throw 'exit nil))
12368 (t (setq start (match-end 0))))))
12369 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12370 (goto-char pos)
12371 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12372 (and (match-beginning 2) (throw 'exit nil))
12373 ;; count $$
12374 (while (re-search-backward "\\$\\$" lim t)
12375 (setq dd-on (not dd-on)))
12376 (goto-char pos)
12377 (if dd-on (cons "$$" m))))))
12380 (defun org-try-cdlatex-tab ()
12381 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12382 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12383 - inside a LaTeX fragment, or
12384 - after the first word in a line, where an abbreviation expansion could
12385 insert a LaTeX environment."
12386 (when org-cdlatex-mode
12387 (cond
12388 ((save-excursion
12389 (skip-chars-backward "a-zA-Z0-9*")
12390 (skip-chars-backward " \t")
12391 (bolp))
12392 (cdlatex-tab) t)
12393 ((org-inside-LaTeX-fragment-p)
12394 (cdlatex-tab) t)
12395 (t nil))))
12397 (defun org-cdlatex-underscore-caret (&optional arg)
12398 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12399 Revert to the normal definition outside of these fragments."
12400 (interactive "P")
12401 (if (org-inside-LaTeX-fragment-p)
12402 (call-interactively 'cdlatex-sub-superscript)
12403 (let (org-cdlatex-mode)
12404 (call-interactively (key-binding (vector last-input-event))))))
12406 (defun org-cdlatex-math-modify (&optional arg)
12407 "Execute `cdlatex-math-modify' in LaTeX fragments.
12408 Revert to the normal definition outside of these fragments."
12409 (interactive "P")
12410 (if (org-inside-LaTeX-fragment-p)
12411 (call-interactively 'cdlatex-math-modify)
12412 (let (org-cdlatex-mode)
12413 (call-interactively (key-binding (vector last-input-event))))))
12415 (defvar org-latex-fragment-image-overlays nil
12416 "List of overlays carrying the images of latex fragments.")
12417 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12419 (defun org-remove-latex-fragment-image-overlays ()
12420 "Remove all overlays with LaTeX fragment images in current buffer."
12421 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12422 (setq org-latex-fragment-image-overlays nil))
12424 (defun org-preview-latex-fragment (&optional subtree)
12425 "Preview the LaTeX fragment at point, or all locally or globally.
12426 If the cursor is in a LaTeX fragment, create the image and overlay
12427 it over the source code. If there is no fragment at point, display
12428 all fragments in the current text, from one headline to the next. With
12429 prefix SUBTREE, display all fragments in the current subtree. With a
12430 double prefix `C-u C-u', or when the cursor is before the first headline,
12431 display all fragments in the buffer.
12432 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12433 (interactive "P")
12434 (org-remove-latex-fragment-image-overlays)
12435 (save-excursion
12436 (save-restriction
12437 (let (beg end at msg)
12438 (cond
12439 ((or (equal subtree '(16))
12440 (not (save-excursion
12441 (re-search-backward (concat "^" outline-regexp) nil t))))
12442 (setq beg (point-min) end (point-max)
12443 msg "Creating images for buffer...%s"))
12444 ((equal subtree '(4))
12445 (org-back-to-heading)
12446 (setq beg (point) end (org-end-of-subtree t)
12447 msg "Creating images for subtree...%s"))
12449 (if (setq at (org-inside-LaTeX-fragment-p))
12450 (goto-char (max (point-min) (- (cdr at) 2)))
12451 (org-back-to-heading))
12452 (setq beg (point) end (progn (outline-next-heading) (point))
12453 msg (if at "Creating image...%s"
12454 "Creating images for entry...%s"))))
12455 (message msg "")
12456 (narrow-to-region beg end)
12457 (goto-char beg)
12458 (org-format-latex
12459 (concat "ltxpng/" (file-name-sans-extension
12460 (file-name-nondirectory
12461 buffer-file-name)))
12462 default-directory 'overlays msg at 'forbuffer)
12463 (message msg "done. Use `C-c C-c' to remove images.")))))
12465 (defvar org-latex-regexps
12466 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12467 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12468 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12469 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12470 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12471 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12472 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12473 "Regular expressions for matching embedded LaTeX.")
12475 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12476 "Replace LaTeX fragments with links to an image, and produce images."
12477 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12478 (let* ((prefixnodir (file-name-nondirectory prefix))
12479 (absprefix (expand-file-name prefix dir))
12480 (todir (file-name-directory absprefix))
12481 (opt org-format-latex-options)
12482 (matchers (plist-get opt :matchers))
12483 (re-list org-latex-regexps)
12484 (cnt 0) txt link beg end re e checkdir
12485 m n block linkfile movefile ov)
12486 ;; Check if there are old images files with this prefix, and remove them
12487 (when (file-directory-p todir)
12488 (mapc 'delete-file
12489 (directory-files
12490 todir 'full
12491 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12492 ;; Check the different regular expressions
12493 (while (setq e (pop re-list))
12494 (setq m (car e) re (nth 1 e) n (nth 2 e)
12495 block (if (nth 3 e) "\n\n" ""))
12496 (when (member m matchers)
12497 (goto-char (point-min))
12498 (while (re-search-forward re nil t)
12499 (when (or (not at) (equal (cdr at) (match-beginning n)))
12500 (setq txt (match-string n)
12501 beg (match-beginning n) end (match-end n)
12502 cnt (1+ cnt)
12503 linkfile (format "%s_%04d.png" prefix cnt)
12504 movefile (format "%s_%04d.png" absprefix cnt)
12505 link (concat block "[[file:" linkfile "]]" block))
12506 (if msg (message msg cnt))
12507 (goto-char beg)
12508 (unless checkdir ; make sure the directory exists
12509 (setq checkdir t)
12510 (or (file-directory-p todir) (make-directory todir)))
12511 (org-create-formula-image
12512 txt movefile opt forbuffer)
12513 (if overlays
12514 (progn
12515 (setq ov (org-make-overlay beg end))
12516 (if (featurep 'xemacs)
12517 (progn
12518 (org-overlay-put ov 'invisible t)
12519 (org-overlay-put
12520 ov 'end-glyph
12521 (make-glyph (vector 'png :file movefile))))
12522 (org-overlay-put
12523 ov 'display
12524 (list 'image :type 'png :file movefile :ascent 'center)))
12525 (push ov org-latex-fragment-image-overlays)
12526 (goto-char end))
12527 (delete-region beg end)
12528 (insert link))))))))
12530 ;; This function borrows from Ganesh Swami's latex2png.el
12531 (defun org-create-formula-image (string tofile options buffer)
12532 (let* ((tmpdir (if (featurep 'xemacs)
12533 (temp-directory)
12534 temporary-file-directory))
12535 (texfilebase (make-temp-name
12536 (expand-file-name "orgtex" tmpdir)))
12537 (texfile (concat texfilebase ".tex"))
12538 (dvifile (concat texfilebase ".dvi"))
12539 (pngfile (concat texfilebase ".png"))
12540 (fnh (if (featurep 'xemacs)
12541 (font-height (get-face-font 'default))
12542 (face-attribute 'default :height nil)))
12543 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12544 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12545 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12546 "Black"))
12547 (bg (or (plist-get options (if buffer :background :html-background))
12548 "Transparent")))
12549 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12550 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12551 (with-temp-file texfile
12552 (insert org-format-latex-header
12553 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12554 (let ((dir default-directory))
12555 (condition-case nil
12556 (progn
12557 (cd tmpdir)
12558 (call-process "latex" nil nil nil texfile))
12559 (error nil))
12560 (cd dir))
12561 (if (not (file-exists-p dvifile))
12562 (progn (message "Failed to create dvi file from %s" texfile) nil)
12563 (condition-case nil
12564 (call-process "dvipng" nil nil nil
12565 "-E" "-fg" fg "-bg" bg
12566 "-D" dpi
12567 ;;"-x" scale "-y" scale
12568 "-T" "tight"
12569 "-o" pngfile
12570 dvifile)
12571 (error nil))
12572 (if (not (file-exists-p pngfile))
12573 (progn (message "Failed to create png file from %s" texfile) nil)
12574 ;; Use the requested file name and clean up
12575 (copy-file pngfile tofile 'replace)
12576 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12577 (delete-file (concat texfilebase e)))
12578 pngfile))))
12580 (defun org-dvipng-color (attr)
12581 "Return an rgb color specification for dvipng."
12582 (apply 'format "rgb %s %s %s"
12583 (mapcar 'org-normalize-color
12584 (color-values (face-attribute 'default attr nil)))))
12586 (defun org-normalize-color (value)
12587 "Return string to be used as color value for an RGB component."
12588 (format "%g" (/ value 65535.0)))
12590 ;;;; Key bindings
12592 ;; Make `C-c C-x' a prefix key
12593 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12595 ;; TAB key with modifiers
12596 (org-defkey org-mode-map "\C-i" 'org-cycle)
12597 (org-defkey org-mode-map [(tab)] 'org-cycle)
12598 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12599 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12600 (org-defkey org-mode-map "\M-\t" 'org-complete)
12601 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12602 ;; The following line is necessary under Suse GNU/Linux
12603 (unless (featurep 'xemacs)
12604 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12605 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12606 (define-key org-mode-map [backtab] 'org-shifttab)
12608 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12609 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12610 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12612 ;; Cursor keys with modifiers
12613 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12614 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12615 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12616 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12618 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12619 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12620 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12621 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12623 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12624 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12625 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12626 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12628 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12629 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12631 ;;; Extra keys for tty access.
12632 ;; We only set them when really needed because otherwise the
12633 ;; menus don't show the simple keys
12635 (when (or org-use-extra-keys
12636 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12637 (not window-system))
12638 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12639 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12640 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12641 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12642 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12643 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12644 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12645 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12646 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12647 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12648 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12649 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12650 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12651 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12652 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12653 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12654 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12655 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12656 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12657 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12658 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12659 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12661 ;; All the other keys
12663 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12664 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12665 (if (boundp 'narrow-map)
12666 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12667 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12668 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12669 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12670 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12671 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12672 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12673 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12674 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12675 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12676 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12677 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12678 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12679 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12680 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12681 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12682 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12683 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12684 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12685 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12686 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12687 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12688 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12689 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12690 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12691 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12692 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12693 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12694 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12695 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12696 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12697 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12698 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12699 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12700 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12701 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12702 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12703 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12704 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12705 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12706 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12707 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12708 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12709 (org-defkey org-mode-map "\C-c^" 'org-sort)
12710 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12711 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12712 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12713 (org-defkey org-mode-map "\C-m" 'org-return)
12714 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12715 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12716 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12717 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12718 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12719 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12720 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12721 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12722 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12723 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12724 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12725 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12726 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12727 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12728 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12729 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12730 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12732 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12733 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12734 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12735 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12737 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12738 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12739 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12740 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12741 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12742 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12743 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12744 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12745 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12746 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12747 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12748 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12750 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12751 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12752 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12754 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12756 (when (featurep 'xemacs)
12757 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12759 (defvar org-table-auto-blank-field) ; defined in org-table.el
12760 (defun org-self-insert-command (N)
12761 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12762 If the cursor is in a table looking at whitespace, the whitespace is
12763 overwritten, and the table is not marked as requiring realignment."
12764 (interactive "p")
12765 (if (and (org-table-p)
12766 (progn
12767 ;; check if we blank the field, and if that triggers align
12768 (and (featurep 'org-table) org-table-auto-blank-field
12769 (member last-command
12770 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12771 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12772 ;; got extra space, this field does not determine column width
12773 (let (org-table-may-need-update) (org-table-blank-field))
12774 ;; no extra space, this field may determine column width
12775 (org-table-blank-field)))
12777 (eq N 1)
12778 (looking-at "[^|\n]* |"))
12779 (let (org-table-may-need-update)
12780 (goto-char (1- (match-end 0)))
12781 (delete-backward-char 1)
12782 (goto-char (match-beginning 0))
12783 (self-insert-command N))
12784 (setq org-table-may-need-update t)
12785 (self-insert-command N)
12786 (org-fix-tags-on-the-fly)))
12788 (defun org-fix-tags-on-the-fly ()
12789 (when (and (equal (char-after (point-at-bol)) ?*)
12790 (org-on-heading-p))
12791 (org-align-tags-here org-tags-column)))
12793 (defun org-delete-backward-char (N)
12794 "Like `delete-backward-char', insert whitespace at field end in tables.
12795 When deleting backwards, in tables this function will insert whitespace in
12796 front of the next \"|\" separator, to keep the table aligned. The table will
12797 still be marked for re-alignment if the field did fill the entire column,
12798 because, in this case the deletion might narrow the column."
12799 (interactive "p")
12800 (if (and (org-table-p)
12801 (eq N 1)
12802 (string-match "|" (buffer-substring (point-at-bol) (point)))
12803 (looking-at ".*?|"))
12804 (let ((pos (point))
12805 (noalign (looking-at "[^|\n\r]* |"))
12806 (c org-table-may-need-update))
12807 (backward-delete-char N)
12808 (skip-chars-forward "^|")
12809 (insert " ")
12810 (goto-char (1- pos))
12811 ;; noalign: if there were two spaces at the end, this field
12812 ;; does not determine the width of the column.
12813 (if noalign (setq org-table-may-need-update c)))
12814 (backward-delete-char N)
12815 (org-fix-tags-on-the-fly)))
12817 (defun org-delete-char (N)
12818 "Like `delete-char', but insert whitespace at field end in tables.
12819 When deleting characters, in tables this function will insert whitespace in
12820 front of the next \"|\" separator, to keep the table aligned. The table will
12821 still be marked for re-alignment if the field did fill the entire column,
12822 because, in this case the deletion might narrow the column."
12823 (interactive "p")
12824 (if (and (org-table-p)
12825 (not (bolp))
12826 (not (= (char-after) ?|))
12827 (eq N 1))
12828 (if (looking-at ".*?|")
12829 (let ((pos (point))
12830 (noalign (looking-at "[^|\n\r]* |"))
12831 (c org-table-may-need-update))
12832 (replace-match (concat
12833 (substring (match-string 0) 1 -1)
12834 " |"))
12835 (goto-char pos)
12836 ;; noalign: if there were two spaces at the end, this field
12837 ;; does not determine the width of the column.
12838 (if noalign (setq org-table-may-need-update c)))
12839 (delete-char N))
12840 (delete-char N)
12841 (org-fix-tags-on-the-fly)))
12843 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12844 (put 'org-self-insert-command 'delete-selection t)
12845 (put 'orgtbl-self-insert-command 'delete-selection t)
12846 (put 'org-delete-char 'delete-selection 'supersede)
12847 (put 'org-delete-backward-char 'delete-selection 'supersede)
12849 ;; Make `flyspell-mode' delay after some commands
12850 (put 'org-self-insert-command 'flyspell-delayed t)
12851 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12852 (put 'org-delete-char 'flyspell-delayed t)
12853 (put 'org-delete-backward-char 'flyspell-delayed t)
12855 ;; Make pabbrev-mode expand after org-mode commands
12856 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12857 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12859 ;; How to do this: Measure non-white length of current string
12860 ;; If equal to column width, we should realign.
12862 (defun org-remap (map &rest commands)
12863 "In MAP, remap the functions given in COMMANDS.
12864 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12865 (let (new old)
12866 (while commands
12867 (setq old (pop commands) new (pop commands))
12868 (if (fboundp 'command-remapping)
12869 (org-defkey map (vector 'remap old) new)
12870 (substitute-key-definition old new map global-map)))))
12872 (when (eq org-enable-table-editor 'optimized)
12873 ;; If the user wants maximum table support, we need to hijack
12874 ;; some standard editing functions
12875 (org-remap org-mode-map
12876 'self-insert-command 'org-self-insert-command
12877 'delete-char 'org-delete-char
12878 'delete-backward-char 'org-delete-backward-char)
12879 (org-defkey org-mode-map "|" 'org-force-self-insert))
12881 (defun org-shiftcursor-error ()
12882 "Throw an error because Shift-Cursor command was applied in wrong context."
12883 (error "This command is active in special context like tables, headlines or timestamps"))
12885 (defun org-shifttab (&optional arg)
12886 "Global visibility cycling or move to previous table field.
12887 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12888 on context.
12889 See the individual commands for more information."
12890 (interactive "P")
12891 (cond
12892 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12893 ((integerp arg)
12894 (message "Content view to level: %d" arg)
12895 (org-content (prefix-numeric-value arg))
12896 (setq org-cycle-global-status 'overview))
12897 (t (call-interactively 'org-global-cycle))))
12899 (defun org-shiftmetaleft ()
12900 "Promote subtree or delete table column.
12901 Calls `org-promote-subtree', `org-outdent-item',
12902 or `org-table-delete-column', depending on context.
12903 See the individual commands for more information."
12904 (interactive)
12905 (cond
12906 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12907 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12908 ((org-at-item-p) (call-interactively 'org-outdent-item))
12909 (t (org-shiftcursor-error))))
12911 (defun org-shiftmetaright ()
12912 "Demote subtree or insert table column.
12913 Calls `org-demote-subtree', `org-indent-item',
12914 or `org-table-insert-column', depending on context.
12915 See the individual commands for more information."
12916 (interactive)
12917 (cond
12918 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12919 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12920 ((org-at-item-p) (call-interactively 'org-indent-item))
12921 (t (org-shiftcursor-error))))
12923 (defun org-shiftmetaup (&optional arg)
12924 "Move subtree up or kill table row.
12925 Calls `org-move-subtree-up' or `org-table-kill-row' or
12926 `org-move-item-up' depending on context. See the individual commands
12927 for more information."
12928 (interactive "P")
12929 (cond
12930 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12931 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12932 ((org-at-item-p) (call-interactively 'org-move-item-up))
12933 (t (org-shiftcursor-error))))
12934 (defun org-shiftmetadown (&optional arg)
12935 "Move subtree down or insert table row.
12936 Calls `org-move-subtree-down' or `org-table-insert-row' or
12937 `org-move-item-down', depending on context. See the individual
12938 commands for more information."
12939 (interactive "P")
12940 (cond
12941 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12942 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12943 ((org-at-item-p) (call-interactively 'org-move-item-down))
12944 (t (org-shiftcursor-error))))
12946 (defun org-metaleft (&optional arg)
12947 "Promote heading or move table column to left.
12948 Calls `org-do-promote' or `org-table-move-column', depending on context.
12949 With no specific context, calls the Emacs default `backward-word'.
12950 See the individual commands for more information."
12951 (interactive "P")
12952 (cond
12953 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12954 ((or (org-on-heading-p) (org-region-active-p))
12955 (call-interactively 'org-do-promote))
12956 ((org-at-item-p) (call-interactively 'org-outdent-item))
12957 (t (call-interactively 'backward-word))))
12959 (defun org-metaright (&optional arg)
12960 "Demote subtree or move table column to right.
12961 Calls `org-do-demote' or `org-table-move-column', depending on context.
12962 With no specific context, calls the Emacs default `forward-word'.
12963 See the individual commands for more information."
12964 (interactive "P")
12965 (cond
12966 ((org-at-table-p) (call-interactively 'org-table-move-column))
12967 ((or (org-on-heading-p) (org-region-active-p))
12968 (call-interactively 'org-do-demote))
12969 ((org-at-item-p) (call-interactively 'org-indent-item))
12970 (t (call-interactively 'forward-word))))
12972 (defun org-metaup (&optional arg)
12973 "Move subtree up or move table row up.
12974 Calls `org-move-subtree-up' or `org-table-move-row' or
12975 `org-move-item-up', depending on context. See the individual commands
12976 for more information."
12977 (interactive "P")
12978 (cond
12979 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12980 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12981 ((org-at-item-p) (call-interactively 'org-move-item-up))
12982 (t (transpose-lines 1) (beginning-of-line -1))))
12984 (defun org-metadown (&optional arg)
12985 "Move subtree down or move table row down.
12986 Calls `org-move-subtree-down' or `org-table-move-row' or
12987 `org-move-item-down', depending on context. See the individual
12988 commands for more information."
12989 (interactive "P")
12990 (cond
12991 ((org-at-table-p) (call-interactively 'org-table-move-row))
12992 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12993 ((org-at-item-p) (call-interactively 'org-move-item-down))
12994 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12996 (defun org-shiftup (&optional arg)
12997 "Increase item in timestamp or increase priority of current headline.
12998 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12999 depending on context. See the individual commands for more information."
13000 (interactive "P")
13001 (cond
13002 ((org-at-timestamp-p t)
13003 (call-interactively (if org-edit-timestamp-down-means-later
13004 'org-timestamp-down 'org-timestamp-up)))
13005 ((org-on-heading-p) (call-interactively 'org-priority-up))
13006 ((org-at-item-p) (call-interactively 'org-previous-item))
13007 ((org-clocktable-try-shift 'up arg))
13008 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
13010 (defun org-shiftdown (&optional arg)
13011 "Decrease item in timestamp or decrease priority of current headline.
13012 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13013 depending on context. See the individual commands for more information."
13014 (interactive "P")
13015 (cond
13016 ((org-at-timestamp-p t)
13017 (call-interactively (if org-edit-timestamp-down-means-later
13018 'org-timestamp-up 'org-timestamp-down)))
13019 ((org-on-heading-p) (call-interactively 'org-priority-down))
13020 ((org-clocktable-try-shift 'down arg))
13021 (t (call-interactively 'org-next-item))))
13023 (defun org-shiftright (&optional arg)
13024 "Cycle the thing at point or in the current line, depending on context.
13025 Depending on context, this does one of the following:
13027 - switch a timestamp at point one day into the future
13028 - on a headline, switch to the next TODO keyword.
13029 - on an item, switch entire list to the next bullet type
13030 - on a property line, switch to the next allowed value
13031 - on a clocktable definition line, move time block into the future"
13032 (interactive "P")
13033 (cond
13034 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13035 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13036 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13037 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13038 ((org-clocktable-try-shift 'right arg))
13039 (t (org-shiftcursor-error))))
13041 (defun org-shiftleft (&optional arg)
13042 "Cycle the thing at point or in the current line, depending on context.
13043 Depending on context, this does one of the following:
13045 - switch a timestamp at point one day into the past
13046 - on a headline, switch to the previous TODO keyword.
13047 - on an item, switch entire list to the previous bullet type
13048 - on a property line, switch to the previous allowed value
13049 - on a clocktable definition line, move time block into the past"
13050 (interactive "P")
13051 (cond
13052 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13053 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13054 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13055 ((org-at-property-p)
13056 (call-interactively 'org-property-previous-allowed-value))
13057 ((org-clocktable-try-shift 'left arg))
13058 (t (org-shiftcursor-error))))
13060 (defun org-shiftcontrolright ()
13061 "Switch to next TODO set."
13062 (interactive)
13063 (cond
13064 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13065 (t (org-shiftcursor-error))))
13067 (defun org-shiftcontrolleft ()
13068 "Switch to previous TODO set."
13069 (interactive)
13070 (cond
13071 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13072 (t (org-shiftcursor-error))))
13074 (defun org-ctrl-c-ret ()
13075 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13076 (interactive)
13077 (cond
13078 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13079 (t (call-interactively 'org-insert-heading))))
13081 (defun org-copy-special ()
13082 "Copy region in table or copy current subtree.
13083 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13084 See the individual commands for more information."
13085 (interactive)
13086 (call-interactively
13087 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13089 (defun org-cut-special ()
13090 "Cut region in table or cut current subtree.
13091 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13092 See the individual commands for more information."
13093 (interactive)
13094 (call-interactively
13095 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13097 (defun org-paste-special (arg)
13098 "Paste rectangular region into table, or past subtree relative to level.
13099 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13100 See the individual commands for more information."
13101 (interactive "P")
13102 (if (org-at-table-p)
13103 (org-table-paste-rectangle)
13104 (org-paste-subtree arg)))
13106 (defun org-edit-special ()
13107 "Call a special editor for the stuff at point.
13108 When at a table, call the formula editor with `org-table-edit-formulas'.
13109 When at the first line of an src example, call `org-edit-src-code'.
13110 When in an #+include line, visit the include file. Otherwise call
13111 `ffap' to visit the file at point."
13112 (interactive)
13113 (cond
13114 ((org-at-table-p)
13115 (call-interactively 'org-table-edit-formulas))
13116 ((save-excursion
13117 (beginning-of-line 1)
13118 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13119 (find-file (org-trim (match-string 1))))
13120 ((org-edit-src-code))
13121 ((org-edit-fixed-width-region))
13122 (t (call-interactively 'ffap))))
13124 (defun org-ctrl-c-ctrl-c (&optional arg)
13125 "Set tags in headline, or update according to changed information at point.
13127 This command does many different things, depending on context:
13129 - If the cursor is in a headline, prompt for tags and insert them
13130 into the current line, aligned to `org-tags-column'. When called
13131 with prefix arg, realign all tags in the current buffer.
13133 - If the cursor is in one of the special #+KEYWORD lines, this
13134 triggers scanning the buffer for these lines and updating the
13135 information.
13137 - If the cursor is inside a table, realign the table. This command
13138 works even if the automatic table editor has been turned off.
13140 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13141 the entire table.
13143 - If the cursor is at a footnote reference or definition, jump to
13144 the corresponding definition or references, respectively.
13146 - If the cursor is a the beginning of a dynamic block, update it.
13148 - If the cursor is inside a table created by the table.el package,
13149 activate that table.
13151 - If the current buffer is a remember buffer, close note and file
13152 it. A prefix argument of 1 files to the default location
13153 without further interaction. A prefix argument of 2 files to
13154 the currently clocking task.
13156 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13157 links in this buffer.
13159 - If the cursor is on a numbered item in a plain list, renumber the
13160 ordered list.
13162 - If the cursor is on a checkbox, toggle it."
13163 (interactive "P")
13164 (let ((org-enable-table-editor t))
13165 (cond
13166 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13167 org-occur-highlights
13168 org-latex-fragment-image-overlays)
13169 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13170 (org-remove-occur-highlights)
13171 (org-remove-latex-fragment-image-overlays)
13172 (message "Temporary highlights/overlays removed from current buffer"))
13173 ((and (local-variable-p 'org-finish-function (current-buffer))
13174 (fboundp org-finish-function))
13175 (funcall org-finish-function))
13176 ((org-at-property-p)
13177 (call-interactively 'org-property-action))
13178 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13179 ((org-on-heading-p) (call-interactively 'org-set-tags))
13180 ((org-at-table.el-p)
13181 (require 'table)
13182 (beginning-of-line 1)
13183 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13184 (call-interactively 'table-recognize-table))
13185 ((org-at-table-p)
13186 (org-table-maybe-eval-formula)
13187 (if arg
13188 (call-interactively 'org-table-recalculate)
13189 (org-table-maybe-recalculate-line))
13190 (call-interactively 'org-table-align))
13191 ((or (org-footnote-at-reference-p)
13192 (org-footnote-at-definition-p))
13193 (call-interactively 'org-footnote-action))
13194 ((org-at-item-checkbox-p)
13195 (call-interactively 'org-toggle-checkbox))
13196 ((org-at-item-p)
13197 (call-interactively 'org-maybe-renumber-ordered-list))
13198 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13199 ;; Dynamic block
13200 (beginning-of-line 1)
13201 (save-excursion (org-update-dblock)))
13202 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13203 (cond
13204 ((equal (match-string 1) "TBLFM")
13205 ;; Recalculate the table before this line
13206 (save-excursion
13207 (beginning-of-line 1)
13208 (skip-chars-backward " \r\n\t")
13209 (if (org-at-table-p)
13210 (org-call-with-arg 'org-table-recalculate t))))
13212 ; (org-set-regexps-and-options)
13213 ; (org-restart-font-lock)
13214 (let ((org-inhibit-startup t)) (org-mode-restart))
13215 (message "Local setup has been refreshed"))))
13216 (t (error "C-c C-c can do nothing useful at this location.")))))
13218 (defun org-mode-restart ()
13219 "Restart Org-mode, to scan again for special lines.
13220 Also updates the keyword regular expressions."
13221 (interactive)
13222 (org-mode)
13223 (message "Org-mode restarted"))
13225 (defun org-kill-note-or-show-branches ()
13226 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13227 (interactive)
13228 (if (not org-finish-function)
13229 (call-interactively 'show-branches)
13230 (let ((org-note-abort t))
13231 (funcall org-finish-function))))
13233 (defun org-return (&optional indent)
13234 "Goto next table row or insert a newline.
13235 Calls `org-table-next-row' or `newline', depending on context.
13236 See the individual commands for more information."
13237 (interactive)
13238 (cond
13239 ((bobp) (if indent (newline-and-indent) (newline)))
13240 ((and (org-at-heading-p)
13241 (looking-at
13242 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13243 (org-show-entry)
13244 (end-of-line 1)
13245 (newline))
13246 ((org-at-table-p)
13247 (org-table-justify-field-maybe)
13248 (call-interactively 'org-table-next-row))
13249 (t (if indent (newline-and-indent) (newline)))))
13251 (defun org-return-indent ()
13252 "Goto next table row or insert a newline and indent.
13253 Calls `org-table-next-row' or `newline-and-indent', depending on
13254 context. See the individual commands for more information."
13255 (interactive)
13256 (org-return t))
13258 (defun org-ctrl-c-star ()
13259 "Compute table, or change heading status of lines.
13260 Calls `org-table-recalculate' or `org-toggle-region-headings',
13261 depending on context. This will also turn a plain list item or a normal
13262 line into a subheading."
13263 (interactive)
13264 (cond
13265 ((org-at-table-p)
13266 (call-interactively 'org-table-recalculate))
13267 ((org-region-active-p)
13268 ;; Convert all lines in region to list items
13269 (call-interactively 'org-toggle-region-headings))
13270 ((org-on-heading-p)
13271 (org-toggle-region-headings (point-at-bol)
13272 (min (1+ (point-at-eol)) (point-max))))
13273 ((org-at-item-p)
13274 ;; Convert to heading
13275 (let ((level (save-match-data
13276 (save-excursion
13277 (condition-case nil
13278 (progn
13279 (org-back-to-heading t)
13280 (funcall outline-level))
13281 (error 0))))))
13282 (replace-match
13283 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13284 (t (org-toggle-region-headings (point-at-bol)
13285 (min (1+ (point-at-eol)) (point-max))))))
13287 (defun org-ctrl-c-minus ()
13288 "Insert separator line in table or modify bullet status of line.
13289 Also turns a plain line or a region of lines into list items.
13290 Calls `org-table-insert-hline', `org-toggle-region-items', or
13291 `org-cycle-list-bullet', depending on context."
13292 (interactive)
13293 (cond
13294 ((org-at-table-p)
13295 (call-interactively 'org-table-insert-hline))
13296 ((org-on-heading-p)
13297 ;; Convert to item
13298 (save-excursion
13299 (beginning-of-line 1)
13300 (if (looking-at "\\*+ ")
13301 (replace-match
13302 (concat (make-string
13303 (- (match-end 0) (point) (if org-odd-levels-only 2 1)) ?\ )
13304 "- ")))))
13305 ((org-region-active-p)
13306 ;; Convert all lines in region to list items
13307 (call-interactively 'org-toggle-region-items))
13308 ((org-in-item-p)
13309 (call-interactively 'org-cycle-list-bullet))
13310 (t (org-toggle-region-items (point-at-bol)
13311 (min (1+ (point-at-eol)) (point-max))))))
13313 (defun org-toggle-region-items (beg end)
13314 "Convert all lines in region to list items.
13315 If the first line is already an item, convert all list items in the region
13316 to normal lines."
13317 (interactive "r")
13318 (let (l2 l)
13319 (save-excursion
13320 (goto-char end)
13321 (setq l2 (org-current-line))
13322 (goto-char beg)
13323 (beginning-of-line 1)
13324 (setq l (1- (org-current-line)))
13325 (if (org-at-item-p)
13326 ;; We already have items, de-itemize
13327 (while (< (setq l (1+ l)) l2)
13328 (when (org-at-item-p)
13329 (goto-char (match-beginning 2))
13330 (delete-region (match-beginning 2) (match-end 2))
13331 (and (looking-at "[ \t]+") (replace-match "")))
13332 (beginning-of-line 2))
13333 (while (< (setq l (1+ l)) l2)
13334 (unless (org-at-item-p)
13335 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13336 (replace-match "\\1- \\2")))
13337 (beginning-of-line 2))))))
13339 (defun org-toggle-region-headings (beg end)
13340 "Convert all lines in region to list items.
13341 If the first line is already an item, convert all list items in the region
13342 to normal lines."
13343 (interactive "r")
13344 (let (l2 l)
13345 (save-excursion
13346 (goto-char end)
13347 (setq l2 (org-current-line))
13348 (goto-char beg)
13349 (beginning-of-line 1)
13350 (setq l (1- (org-current-line)))
13351 (if (org-on-heading-p)
13352 ;; We already have headlines, de-star them
13353 (while (< (setq l (1+ l)) l2)
13354 (when (org-on-heading-p t)
13355 (and (looking-at outline-regexp) (replace-match "")))
13356 (beginning-of-line 2))
13357 (let* ((stars (save-excursion
13358 (re-search-backward org-complex-heading-regexp nil t)
13359 (or (match-string 1) "*")))
13360 (add-stars (if org-odd-levels-only "**" "*"))
13361 (rpl (concat stars add-stars " \\2")))
13362 (while (< (setq l (1+ l)) l2)
13363 (unless (org-on-heading-p)
13364 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13365 (replace-match rpl)))
13366 (beginning-of-line 2)))))))
13368 (defun org-meta-return (&optional arg)
13369 "Insert a new heading or wrap a region in a table.
13370 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13371 See the individual commands for more information."
13372 (interactive "P")
13373 (cond
13374 ((org-at-table-p)
13375 (call-interactively 'org-table-wrap-region))
13376 (t (call-interactively 'org-insert-heading))))
13378 ;;; Menu entries
13380 ;; Define the Org-mode menus
13381 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13382 '("Tbl"
13383 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13384 ["Next Field" org-cycle (org-at-table-p)]
13385 ["Previous Field" org-shifttab (org-at-table-p)]
13386 ["Next Row" org-return (org-at-table-p)]
13387 "--"
13388 ["Blank Field" org-table-blank-field (org-at-table-p)]
13389 ["Edit Field" org-table-edit-field (org-at-table-p)]
13390 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13391 "--"
13392 ("Column"
13393 ["Move Column Left" org-metaleft (org-at-table-p)]
13394 ["Move Column Right" org-metaright (org-at-table-p)]
13395 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13396 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13397 ("Row"
13398 ["Move Row Up" org-metaup (org-at-table-p)]
13399 ["Move Row Down" org-metadown (org-at-table-p)]
13400 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13401 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13402 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13403 "--"
13404 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13405 ("Rectangle"
13406 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13407 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13408 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13409 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13410 "--"
13411 ("Calculate"
13412 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13413 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13414 ["Edit Formulas" org-edit-special (org-at-table-p)]
13415 "--"
13416 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13417 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13418 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13419 "--"
13420 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13421 "--"
13422 ["Sum Column/Rectangle" org-table-sum
13423 (or (org-at-table-p) (org-region-active-p))]
13424 ["Which Column?" org-table-current-column (org-at-table-p)])
13425 ["Debug Formulas"
13426 org-table-toggle-formula-debugger
13427 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13428 ["Show Col/Row Numbers"
13429 org-table-toggle-coordinate-overlays
13430 :style toggle
13431 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13432 "--"
13433 ["Create" org-table-create (and (not (org-at-table-p))
13434 org-enable-table-editor)]
13435 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13436 ["Import from File" org-table-import (not (org-at-table-p))]
13437 ["Export to File" org-table-export (org-at-table-p)]
13438 "--"
13439 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13441 (easy-menu-define org-org-menu org-mode-map "Org menu"
13442 '("Org"
13443 ("Show/Hide"
13444 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13445 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13446 ["Sparse Tree..." org-sparse-tree t]
13447 ["Reveal Context" org-reveal t]
13448 ["Show All" show-all t]
13449 "--"
13450 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13451 "--"
13452 ["New Heading" org-insert-heading t]
13453 ("Navigate Headings"
13454 ["Up" outline-up-heading t]
13455 ["Next" outline-next-visible-heading t]
13456 ["Previous" outline-previous-visible-heading t]
13457 ["Next Same Level" outline-forward-same-level t]
13458 ["Previous Same Level" outline-backward-same-level t]
13459 "--"
13460 ["Jump" org-goto t])
13461 ("Edit Structure"
13462 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13463 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13464 "--"
13465 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13466 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13467 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13468 "--"
13469 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13470 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13471 ["Demote Heading" org-metaright (not (org-at-table-p))]
13472 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13473 "--"
13474 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13475 "--"
13476 ["Convert to odd levels" org-convert-to-odd-levels t]
13477 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13478 ("Editing"
13479 ["Emphasis..." org-emphasize t]
13480 ["Edit Source Example" org-edit-special t]
13481 "--"
13482 ["Footnote new/jump" org-footnote-action t]
13483 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13484 ("Archive"
13485 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13486 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13487 ; :active t :keys "C-u C-c C-x C-a"]
13488 ["Sparse trees open ARCHIVE trees"
13489 (setq org-sparse-tree-open-archived-trees
13490 (not org-sparse-tree-open-archived-trees))
13491 :style toggle :selected org-sparse-tree-open-archived-trees]
13492 ["Cycling opens ARCHIVE trees"
13493 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13494 :style toggle :selected org-cycle-open-archived-trees]
13495 "--"
13496 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13497 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13498 ; ["Check and Move Children" (org-archive-subtree '(4))
13499 ; :active t :keys "C-u C-c C-x C-s"]
13501 "--"
13502 ("TODO Lists"
13503 ["TODO/DONE/-" org-todo t]
13504 ("Select keyword"
13505 ["Next keyword" org-shiftright (org-on-heading-p)]
13506 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13507 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13508 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13509 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13510 ["Show TODO Tree" org-show-todo-tree t]
13511 ["Global TODO list" org-todo-list t]
13512 "--"
13513 ["Set Priority" org-priority t]
13514 ["Priority Up" org-shiftup t]
13515 ["Priority Down" org-shiftdown t])
13516 ("TAGS and Properties"
13517 ["Set Tags" org-set-tags-command t]
13518 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13519 "--"
13520 ["Set property" org-set-property t]
13521 ["Column view of properties" org-columns t]
13522 ["Insert Column View DBlock" org-insert-columns-dblock t])
13523 ("Dates and Scheduling"
13524 ["Timestamp" org-time-stamp t]
13525 ["Timestamp (inactive)" org-time-stamp-inactive t]
13526 ("Change Date"
13527 ["1 Day Later" org-shiftright t]
13528 ["1 Day Earlier" org-shiftleft t]
13529 ["1 ... Later" org-shiftup t]
13530 ["1 ... Earlier" org-shiftdown t])
13531 ["Compute Time Range" org-evaluate-time-range t]
13532 ["Schedule Item" org-schedule t]
13533 ["Deadline" org-deadline t]
13534 "--"
13535 ["Custom time format" org-toggle-time-stamp-overlays
13536 :style radio :selected org-display-custom-times]
13537 "--"
13538 ["Goto Calendar" org-goto-calendar t]
13539 ["Date from Calendar" org-date-from-calendar t]
13540 "--"
13541 ["Start/restart timer" org-timer-start t]
13542 ["Insert timer string" org-timer t]
13543 ["Insert timer item" org-timer-item t])
13544 ("Logging work"
13545 ["Clock in" org-clock-in t]
13546 ["Clock out" org-clock-out t]
13547 ["Clock cancel" org-clock-cancel t]
13548 ["Goto running clock" org-clock-goto t]
13549 ["Display times" org-clock-display t]
13550 ["Create clock table" org-clock-report t]
13551 "--"
13552 ["Record DONE time"
13553 (progn (setq org-log-done (not org-log-done))
13554 (message "Switching to %s will %s record a timestamp"
13555 (car org-done-keywords)
13556 (if org-log-done "automatically" "not")))
13557 :style toggle :selected org-log-done])
13558 "--"
13559 ["Agenda Command..." org-agenda t]
13560 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13561 ("File List for Agenda")
13562 ("Special views current file"
13563 ["TODO Tree" org-show-todo-tree t]
13564 ["Check Deadlines" org-check-deadlines t]
13565 ["Timeline" org-timeline t]
13566 ["Tags Tree" org-tags-sparse-tree t])
13567 "--"
13568 ("Hyperlinks"
13569 ["Store Link (Global)" org-store-link t]
13570 ["Insert Link" org-insert-link t]
13571 ["Follow Link" org-open-at-point t]
13572 "--"
13573 ["Next link" org-next-link t]
13574 ["Previous link" org-previous-link t]
13575 "--"
13576 ["Descriptive Links"
13577 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13578 :style radio
13579 :selected (member '(org-link) buffer-invisibility-spec)]
13580 ["Literal Links"
13581 (progn
13582 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13583 :style radio
13584 :selected (not (member '(org-link) buffer-invisibility-spec))])
13585 "--"
13586 ["Export/Publish..." org-export t]
13587 ("LaTeX"
13588 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13589 :selected org-cdlatex-mode]
13590 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13591 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13592 ["Modify math symbol" org-cdlatex-math-modify
13593 (org-inside-LaTeX-fragment-p)]
13594 ["Export LaTeX fragments as images"
13595 (if (featurep 'org-exp)
13596 (setq org-export-with-LaTeX-fragments
13597 (not org-export-with-LaTeX-fragments))
13598 (require 'org-exp))
13599 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13600 org-export-with-LaTeX-fragments)])
13601 "--"
13602 ("Documentation"
13603 ["Show Version" org-version t]
13604 ["Info Documentation" org-info t])
13605 ("Customize"
13606 ["Browse Org Group" org-customize t]
13607 "--"
13608 ["Expand This Menu" org-create-customize-menu
13609 (fboundp 'customize-menu-create)])
13610 "--"
13611 ["Refresh setup" org-mode-restart t]
13614 (defun org-info (&optional node)
13615 "Read documentation for Org-mode in the info system.
13616 With optional NODE, go directly to that node."
13617 (interactive)
13618 (info (format "(org)%s" (or node ""))))
13620 (defun org-install-agenda-files-menu ()
13621 (let ((bl (buffer-list)))
13622 (save-excursion
13623 (while bl
13624 (set-buffer (pop bl))
13625 (if (org-mode-p) (setq bl nil)))
13626 (when (org-mode-p)
13627 (easy-menu-change
13628 '("Org") "File List for Agenda"
13629 (append
13630 (list
13631 ["Edit File List" (org-edit-agenda-file-list) t]
13632 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13633 ["Remove Current File from List" org-remove-file t]
13634 ["Cycle through agenda files" org-cycle-agenda-files t]
13635 ["Occur in all agenda files" org-occur-in-agenda-files t]
13636 "--")
13637 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13639 ;;;; Documentation
13641 ;;;###autoload
13642 (defun org-require-autoloaded-modules ()
13643 (interactive)
13644 (mapc 'require
13645 '(org-agenda org-archive org-clock org-colview
13646 org-exp org-id org-export-latex org-publish
13647 org-remember org-table)))
13649 ;;;###autoload
13650 (defun org-customize ()
13651 "Call the customize function with org as argument."
13652 (interactive)
13653 (org-load-modules-maybe)
13654 (org-require-autoloaded-modules)
13655 (customize-browse 'org))
13657 (defun org-create-customize-menu ()
13658 "Create a full customization menu for Org-mode, insert it into the menu."
13659 (interactive)
13660 (org-load-modules-maybe)
13661 (org-require-autoloaded-modules)
13662 (if (fboundp 'customize-menu-create)
13663 (progn
13664 (easy-menu-change
13665 '("Org") "Customize"
13666 `(["Browse Org group" org-customize t]
13667 "--"
13668 ,(customize-menu-create 'org)
13669 ["Set" Custom-set t]
13670 ["Save" Custom-save t]
13671 ["Reset to Current" Custom-reset-current t]
13672 ["Reset to Saved" Custom-reset-saved t]
13673 ["Reset to Standard Settings" Custom-reset-standard t]))
13674 (message "\"Org\"-menu now contains full customization menu"))
13675 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13677 ;;;; Miscellaneous stuff
13679 ;;; Generally useful functions
13681 (defun org-find-text-property-in-string (prop s)
13682 "Return the first non-nil value of property PROP in string S."
13683 (or (get-text-property 0 prop s)
13684 (get-text-property (or (next-single-property-change 0 prop s) 0)
13685 prop s)))
13687 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13688 "Display the given MESSAGE as a warning."
13689 (if (fboundp 'display-warning)
13690 (display-warning 'org message
13691 (if (featurep 'xemacs)
13692 'warning
13693 :warning))
13694 (let ((buf (get-buffer-create "*Org warnings*")))
13695 (with-current-buffer buf
13696 (goto-char (point-max))
13697 (insert "Warning (Org): " message)
13698 (unless (bolp)
13699 (newline)))
13700 (display-buffer buf)
13701 (sit-for 0))))
13703 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13704 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13705 (if (and marker (marker-buffer marker)
13706 (buffer-live-p (marker-buffer marker)))
13707 (progn
13708 (switch-to-buffer (marker-buffer marker))
13709 (if (or (> marker (point-max)) (< marker (point-min)))
13710 (widen))
13711 (goto-char marker)
13712 (org-show-context 'org-goto))
13713 (if bookmark
13714 (bookmark-jump bookmark)
13715 (error "Cannot find location"))))
13717 (defun org-quote-csv-field (s)
13718 "Quote field for inclusion in CSV material."
13719 (if (string-match "[\",]" s)
13720 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13723 (defun org-plist-delete (plist property)
13724 "Delete PROPERTY from PLIST.
13725 This is in contrast to merely setting it to 0."
13726 (let (p)
13727 (while plist
13728 (if (not (eq property (car plist)))
13729 (setq p (plist-put p (car plist) (nth 1 plist))))
13730 (setq plist (cddr plist)))
13733 (defun org-force-self-insert (N)
13734 "Needed to enforce self-insert under remapping."
13735 (interactive "p")
13736 (self-insert-command N))
13738 (defun org-string-width (s)
13739 "Compute width of string, ignoring invisible characters.
13740 This ignores character with invisibility property `org-link', and also
13741 characters with property `org-cwidth', because these will become invisible
13742 upon the next fontification round."
13743 (let (b l)
13744 (when (or (eq t buffer-invisibility-spec)
13745 (assq 'org-link buffer-invisibility-spec))
13746 (while (setq b (text-property-any 0 (length s)
13747 'invisible 'org-link s))
13748 (setq s (concat (substring s 0 b)
13749 (substring s (or (next-single-property-change
13750 b 'invisible s) (length s)))))))
13751 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13752 (setq s (concat (substring s 0 b)
13753 (substring s (or (next-single-property-change
13754 b 'org-cwidth s) (length s))))))
13755 (setq l (string-width s) b -1)
13756 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13757 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13760 (defun org-get-indentation (&optional line)
13761 "Get the indentation of the current line, interpreting tabs.
13762 When LINE is given, assume it represents a line and compute its indentation."
13763 (if line
13764 (if (string-match "^ *" (org-remove-tabs line))
13765 (match-end 0))
13766 (save-excursion
13767 (beginning-of-line 1)
13768 (skip-chars-forward " \t")
13769 (current-column))))
13771 (defun org-remove-tabs (s &optional width)
13772 "Replace tabulators in S with spaces.
13773 Assumes that s is a single line, starting in column 0."
13774 (setq width (or width tab-width))
13775 (while (string-match "\t" s)
13776 (setq s (replace-match
13777 (make-string
13778 (- (* width (/ (+ (match-beginning 0) width) width))
13779 (match-beginning 0)) ?\ )
13780 t t s)))
13783 (defun org-fix-indentation (line ind)
13784 "Fix indentation in LINE.
13785 IND is a cons cell with target and minimum indentation.
13786 If the current indentation in LINE is smaller than the minimum,
13787 leave it alone. If it is larger than ind, set it to the target."
13788 (let* ((l (org-remove-tabs line))
13789 (i (org-get-indentation l))
13790 (i1 (car ind)) (i2 (cdr ind)))
13791 (if (>= i i2) (setq l (substring line i2)))
13792 (if (> i1 0)
13793 (concat (make-string i1 ?\ ) l)
13794 l)))
13796 (defun org-base-buffer (buffer)
13797 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13798 (if (not buffer)
13799 buffer
13800 (or (buffer-base-buffer buffer)
13801 buffer)))
13803 (defun org-trim (s)
13804 "Remove whitespace at beginning and end of string."
13805 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13806 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13809 (defun org-wrap (string &optional width lines)
13810 "Wrap string to either a number of lines, or a width in characters.
13811 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13812 that costs. If there is a word longer than WIDTH, the text is actually
13813 wrapped to the length of that word.
13814 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13815 many lines, whatever width that takes.
13816 The return value is a list of lines, without newlines at the end."
13817 (let* ((words (org-split-string string "[ \t\n]+"))
13818 (maxword (apply 'max (mapcar 'org-string-width words)))
13819 w ll)
13820 (cond (width
13821 (org-do-wrap words (max maxword width)))
13822 (lines
13823 (setq w maxword)
13824 (setq ll (org-do-wrap words maxword))
13825 (if (<= (length ll) lines)
13827 (setq ll words)
13828 (while (> (length ll) lines)
13829 (setq w (1+ w))
13830 (setq ll (org-do-wrap words w)))
13831 ll))
13832 (t (error "Cannot wrap this")))))
13834 (defun org-do-wrap (words width)
13835 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13836 (let (lines line)
13837 (while words
13838 (setq line (pop words))
13839 (while (and words (< (+ (length line) (length (car words))) width))
13840 (setq line (concat line " " (pop words))))
13841 (setq lines (push line lines)))
13842 (nreverse lines)))
13844 (defun org-split-string (string &optional separators)
13845 "Splits STRING into substrings at SEPARATORS.
13846 No empty strings are returned if there are matches at the beginning
13847 and end of string."
13848 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13849 (start 0)
13850 notfirst
13851 (list nil))
13852 (while (and (string-match rexp string
13853 (if (and notfirst
13854 (= start (match-beginning 0))
13855 (< start (length string)))
13856 (1+ start) start))
13857 (< (match-beginning 0) (length string)))
13858 (setq notfirst t)
13859 (or (eq (match-beginning 0) 0)
13860 (and (eq (match-beginning 0) (match-end 0))
13861 (eq (match-beginning 0) start))
13862 (setq list
13863 (cons (substring string start (match-beginning 0))
13864 list)))
13865 (setq start (match-end 0)))
13866 (or (eq start (length string))
13867 (setq list
13868 (cons (substring string start)
13869 list)))
13870 (nreverse list)))
13872 (defun org-context ()
13873 "Return a list of contexts of the current cursor position.
13874 If several contexts apply, all are returned.
13875 Each context entry is a list with a symbol naming the context, and
13876 two positions indicating start and end of the context. Possible
13877 contexts are:
13879 :headline anywhere in a headline
13880 :headline-stars on the leading stars in a headline
13881 :todo-keyword on a TODO keyword (including DONE) in a headline
13882 :tags on the TAGS in a headline
13883 :priority on the priority cookie in a headline
13884 :item on the first line of a plain list item
13885 :item-bullet on the bullet/number of a plain list item
13886 :checkbox on the checkbox in a plain list item
13887 :table in an org-mode table
13888 :table-special on a special filed in a table
13889 :table-table in a table.el table
13890 :link on a hyperlink
13891 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13892 :target on a <<target>>
13893 :radio-target on a <<<radio-target>>>
13894 :latex-fragment on a LaTeX fragment
13895 :latex-preview on a LaTeX fragment with overlayed preview image
13897 This function expects the position to be visible because it uses font-lock
13898 faces as a help to recognize the following contexts: :table-special, :link,
13899 and :keyword."
13900 (let* ((f (get-text-property (point) 'face))
13901 (faces (if (listp f) f (list f)))
13902 (p (point)) clist o)
13903 ;; First the large context
13904 (cond
13905 ((org-on-heading-p t)
13906 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13907 (when (progn
13908 (beginning-of-line 1)
13909 (looking-at org-todo-line-tags-regexp))
13910 (push (org-point-in-group p 1 :headline-stars) clist)
13911 (push (org-point-in-group p 2 :todo-keyword) clist)
13912 (push (org-point-in-group p 4 :tags) clist))
13913 (goto-char p)
13914 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13915 (if (looking-at "\\[#[A-Z0-9]\\]")
13916 (push (org-point-in-group p 0 :priority) clist)))
13918 ((org-at-item-p)
13919 (push (org-point-in-group p 2 :item-bullet) clist)
13920 (push (list :item (point-at-bol)
13921 (save-excursion (org-end-of-item) (point)))
13922 clist)
13923 (and (org-at-item-checkbox-p)
13924 (push (org-point-in-group p 0 :checkbox) clist)))
13926 ((org-at-table-p)
13927 (push (list :table (org-table-begin) (org-table-end)) clist)
13928 (if (memq 'org-formula faces)
13929 (push (list :table-special
13930 (previous-single-property-change p 'face)
13931 (next-single-property-change p 'face)) clist)))
13932 ((org-at-table-p 'any)
13933 (push (list :table-table) clist)))
13934 (goto-char p)
13936 ;; Now the small context
13937 (cond
13938 ((org-at-timestamp-p)
13939 (push (org-point-in-group p 0 :timestamp) clist))
13940 ((memq 'org-link faces)
13941 (push (list :link
13942 (previous-single-property-change p 'face)
13943 (next-single-property-change p 'face)) clist))
13944 ((memq 'org-special-keyword faces)
13945 (push (list :keyword
13946 (previous-single-property-change p 'face)
13947 (next-single-property-change p 'face)) clist))
13948 ((org-on-target-p)
13949 (push (org-point-in-group p 0 :target) clist)
13950 (goto-char (1- (match-beginning 0)))
13951 (if (looking-at org-radio-target-regexp)
13952 (push (org-point-in-group p 0 :radio-target) clist))
13953 (goto-char p))
13954 ((setq o (car (delq nil
13955 (mapcar
13956 (lambda (x)
13957 (if (memq x org-latex-fragment-image-overlays) x))
13958 (org-overlays-at (point))))))
13959 (push (list :latex-fragment
13960 (org-overlay-start o) (org-overlay-end o)) clist)
13961 (push (list :latex-preview
13962 (org-overlay-start o) (org-overlay-end o)) clist))
13963 ((org-inside-LaTeX-fragment-p)
13964 ;; FIXME: positions wrong.
13965 (push (list :latex-fragment (point) (point)) clist)))
13967 (setq clist (nreverse (delq nil clist)))
13968 clist))
13970 ;; FIXME: Compare with at-regexp-p Do we need both?
13971 (defun org-in-regexp (re &optional nlines visually)
13972 "Check if point is inside a match of regexp.
13973 Normally only the current line is checked, but you can include NLINES extra
13974 lines both before and after point into the search.
13975 If VISUALLY is set, require that the cursor is not after the match but
13976 really on, so that the block visually is on the match."
13977 (catch 'exit
13978 (let ((pos (point))
13979 (eol (point-at-eol (+ 1 (or nlines 0))))
13980 (inc (if visually 1 0)))
13981 (save-excursion
13982 (beginning-of-line (- 1 (or nlines 0)))
13983 (while (re-search-forward re eol t)
13984 (if (and (<= (match-beginning 0) pos)
13985 (>= (+ inc (match-end 0)) pos))
13986 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13988 (defun org-at-regexp-p (regexp)
13989 "Is point inside a match of REGEXP in the current line?"
13990 (catch 'exit
13991 (save-excursion
13992 (let ((pos (point)) (end (point-at-eol)))
13993 (beginning-of-line 1)
13994 (while (re-search-forward regexp end t)
13995 (if (and (<= (match-beginning 0) pos)
13996 (>= (match-end 0) pos))
13997 (throw 'exit t)))
13998 nil))))
14000 (defun org-occur-in-agenda-files (regexp &optional nlines)
14001 "Call `multi-occur' with buffers for all agenda files."
14002 (interactive "sOrg-files matching: \np")
14003 (let* ((files (org-agenda-files))
14004 (tnames (mapcar 'file-truename files))
14005 (extra org-agenda-text-search-extra-files)
14007 (when (eq (car extra) 'agenda-archives)
14008 (setq extra (cdr extra))
14009 (setq files (org-add-archive-files files)))
14010 (while (setq f (pop extra))
14011 (unless (member (file-truename f) tnames)
14012 (add-to-list 'files f 'append)
14013 (add-to-list 'tnames (file-truename f) 'append)))
14014 (multi-occur
14015 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14016 regexp)))
14018 (if (boundp 'occur-mode-find-occurrence-hook)
14019 ;; Emacs 23
14020 (add-hook 'occur-mode-find-occurrence-hook
14021 (lambda ()
14022 (when (org-mode-p)
14023 (org-reveal))))
14024 ;; Emacs 22
14025 (defadvice occur-mode-goto-occurrence
14026 (after org-occur-reveal activate)
14027 (and (org-mode-p) (org-reveal)))
14028 (defadvice occur-mode-goto-occurrence-other-window
14029 (after org-occur-reveal activate)
14030 (and (org-mode-p) (org-reveal)))
14031 (defadvice occur-mode-display-occurrence
14032 (after org-occur-reveal activate)
14033 (when (org-mode-p)
14034 (let ((pos (occur-mode-find-occurrence)))
14035 (with-current-buffer (marker-buffer pos)
14036 (save-excursion
14037 (goto-char pos)
14038 (org-reveal)))))))
14040 (defun org-uniquify (list)
14041 "Remove duplicate elements from LIST."
14042 (let (res)
14043 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14044 res))
14046 (defun org-delete-all (elts list)
14047 "Remove all elements in ELTS from LIST."
14048 (while elts
14049 (setq list (delete (pop elts) list)))
14050 list)
14052 (defun org-back-over-empty-lines ()
14053 "Move backwards over whitespace, to the beginning of the first empty line.
14054 Returns the number of empty lines passed."
14055 (let ((pos (point)))
14056 (skip-chars-backward " \t\n\r")
14057 (beginning-of-line 2)
14058 (goto-char (min (point) pos))
14059 (count-lines (point) pos)))
14061 (defun org-skip-whitespace ()
14062 (skip-chars-forward " \t\n\r"))
14064 (defun org-point-in-group (point group &optional context)
14065 "Check if POINT is in match-group GROUP.
14066 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14067 match. If the match group does ot exist or point is not inside it,
14068 return nil."
14069 (and (match-beginning group)
14070 (>= point (match-beginning group))
14071 (<= point (match-end group))
14072 (if context
14073 (list context (match-beginning group) (match-end group))
14074 t)))
14076 (defun org-switch-to-buffer-other-window (&rest args)
14077 "Switch to buffer in a second window on the current frame.
14078 In particular, do not allow pop-up frames."
14079 (let (pop-up-frames special-display-buffer-names special-display-regexps
14080 special-display-function)
14081 (apply 'switch-to-buffer-other-window args)))
14083 (defun org-combine-plists (&rest plists)
14084 "Create a single property list from all plists in PLISTS.
14085 The process starts by copying the first list, and then setting properties
14086 from the other lists. Settings in the last list are the most significant
14087 ones and overrule settings in the other lists."
14088 (let ((rtn (copy-sequence (pop plists)))
14089 p v ls)
14090 (while plists
14091 (setq ls (pop plists))
14092 (while ls
14093 (setq p (pop ls) v (pop ls))
14094 (setq rtn (plist-put rtn p v))))
14095 rtn))
14097 (defun org-move-line-down (arg)
14098 "Move the current line down. With prefix argument, move it past ARG lines."
14099 (interactive "p")
14100 (let ((col (current-column))
14101 beg end pos)
14102 (beginning-of-line 1) (setq beg (point))
14103 (beginning-of-line 2) (setq end (point))
14104 (beginning-of-line (+ 1 arg))
14105 (setq pos (move-marker (make-marker) (point)))
14106 (insert (delete-and-extract-region beg end))
14107 (goto-char pos)
14108 (org-move-to-column col)))
14110 (defun org-move-line-up (arg)
14111 "Move the current line up. With prefix argument, move it past ARG lines."
14112 (interactive "p")
14113 (let ((col (current-column))
14114 beg end pos)
14115 (beginning-of-line 1) (setq beg (point))
14116 (beginning-of-line 2) (setq end (point))
14117 (beginning-of-line (- arg))
14118 (setq pos (move-marker (make-marker) (point)))
14119 (insert (delete-and-extract-region beg end))
14120 (goto-char pos)
14121 (org-move-to-column col)))
14123 (defun org-replace-escapes (string table)
14124 "Replace %-escapes in STRING with values in TABLE.
14125 TABLE is an association list with keys like \"%a\" and string values.
14126 The sequences in STRING may contain normal field width and padding information,
14127 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14128 so values can contain further %-escapes if they are define later in TABLE."
14129 (let ((case-fold-search nil)
14130 e re rpl)
14131 (while (setq e (pop table))
14132 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14133 (while (string-match re string)
14134 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14135 (cdr e)))
14136 (setq string (replace-match rpl t t string))))
14137 string))
14140 (defun org-sublist (list start end)
14141 "Return a section of LIST, from START to END.
14142 Counting starts at 1."
14143 (let (rtn (c start))
14144 (setq list (nthcdr (1- start) list))
14145 (while (and list (<= c end))
14146 (push (pop list) rtn)
14147 (setq c (1+ c)))
14148 (nreverse rtn)))
14150 (defun org-find-base-buffer-visiting (file)
14151 "Like `find-buffer-visiting' but alway return the base buffer and
14152 not an indirect buffer."
14153 (let ((buf (find-buffer-visiting file)))
14154 (if buf
14155 (or (buffer-base-buffer buf) buf)
14156 nil)))
14158 (defun org-image-file-name-regexp ()
14159 "Return regexp matching the file names of images."
14160 (if (fboundp 'image-file-name-regexp)
14161 (image-file-name-regexp)
14162 (let ((image-file-name-extensions
14163 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14164 "xbm" "xpm" "pbm" "pgm" "ppm")))
14165 (concat "\\."
14166 (regexp-opt (nconc (mapcar 'upcase
14167 image-file-name-extensions)
14168 image-file-name-extensions)
14170 "\\'"))))
14172 (defun org-file-image-p (file)
14173 "Return non-nil if FILE is an image."
14174 (save-match-data
14175 (string-match (org-image-file-name-regexp) file)))
14177 (defun org-get-cursor-date ()
14178 "Return the date at cursor in as a time.
14179 This works in the calendar and in the agenda, anywhere else it just
14180 returns the current time."
14181 (let (date day defd)
14182 (cond
14183 ((eq major-mode 'calendar-mode)
14184 (setq date (calendar-cursor-to-date)
14185 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14186 ((eq major-mode 'org-agenda-mode)
14187 (setq day (get-text-property (point) 'day))
14188 (if day
14189 (setq date (calendar-gregorian-from-absolute day)
14190 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14191 (nth 2 date))))))
14192 (or defd (current-time))))
14194 (defvar org-agenda-action-marker (make-marker)
14195 "Marker pointing to the entry for the next agenda action.")
14197 (defun org-mark-entry-for-agenda-action ()
14198 "Mark the current entry as target of an agenda action.
14199 Agenda actions are actions executed from the agenda with the key `k',
14200 which make use of the date at the cursor."
14201 (interactive)
14202 (move-marker org-agenda-action-marker
14203 (save-excursion (org-back-to-heading t) (point))
14204 (current-buffer))
14205 (message
14206 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14208 ;;; Paragraph filling stuff.
14209 ;; We want this to be just right, so use the full arsenal.
14211 (defun org-indent-line-function ()
14212 "Indent line like previous, but further if previous was headline or item."
14213 (interactive)
14214 (let* ((pos (point))
14215 (itemp (org-at-item-p))
14216 column bpos bcol tpos tcol bullet btype bullet-type)
14217 ;; Find the previous relevant line
14218 (beginning-of-line 1)
14219 (cond
14220 ((looking-at "#") (setq column 0))
14221 ((looking-at "\\*+ ") (setq column 0))
14223 (beginning-of-line 0)
14224 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14225 (beginning-of-line 0))
14226 (cond
14227 ((looking-at "\\*+[ \t]+")
14228 (if (not org-adapt-indentation)
14229 (setq column 0)
14230 (goto-char (match-end 0))
14231 (setq column (current-column))))
14232 ((org-in-item-p)
14233 (org-beginning-of-item)
14234 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14235 (setq bpos (match-beginning 1) tpos (match-end 0)
14236 bcol (progn (goto-char bpos) (current-column))
14237 tcol (progn (goto-char tpos) (current-column))
14238 bullet (match-string 1)
14239 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14240 (if (> tcol (+ bcol org-description-max-indent))
14241 (setq tcol (+ bcol 5)))
14242 (if (not itemp)
14243 (setq column tcol)
14244 (goto-char pos)
14245 (beginning-of-line 1)
14246 (if (looking-at "\\S-")
14247 (progn
14248 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14249 (setq bullet (match-string 1)
14250 btype (if (string-match "[0-9]" bullet) "n" bullet))
14251 (setq column (if (equal btype bullet-type) bcol tcol)))
14252 (setq column (org-get-indentation)))))
14253 (t (setq column (org-get-indentation))))))
14254 (goto-char pos)
14255 (if (<= (current-column) (current-indentation))
14256 (org-indent-line-to column)
14257 (save-excursion (org-indent-line-to column)))
14258 (setq column (current-column))
14259 (beginning-of-line 1)
14260 (if (looking-at
14261 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14262 (replace-match (concat "\\1" (format org-property-format
14263 (match-string 2) (match-string 3)))
14264 t nil))
14265 (org-move-to-column column)))
14267 (defun org-set-autofill-regexps ()
14268 (interactive)
14269 ;; In the paragraph separator we include headlines, because filling
14270 ;; text in a line directly attached to a headline would otherwise
14271 ;; fill the headline as well.
14272 (org-set-local 'comment-start-skip "^#+[ \t]*")
14273 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14274 ;; The paragraph starter includes hand-formatted lists.
14275 (org-set-local 'paragraph-start
14276 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14277 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14278 ;; But only if the user has not turned off tables or fixed-width regions
14279 (org-set-local
14280 'auto-fill-inhibit-regexp
14281 (concat "\\*+ \\|#\\+"
14282 "\\|[ \t]*" org-keyword-time-regexp
14283 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14284 (concat
14285 "\\|[ \t]*["
14286 (if org-enable-table-editor "|" "")
14287 (if org-enable-fixed-width-editor ":" "")
14288 "]"))))
14289 ;; We use our own fill-paragraph function, to make sure that tables
14290 ;; and fixed-width regions are not wrapped. That function will pass
14291 ;; through to `fill-paragraph' when appropriate.
14292 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14293 ; Adaptive filling: To get full control, first make sure that
14294 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14295 (org-set-local 'adaptive-fill-regexp "\000")
14296 (org-set-local 'adaptive-fill-function
14297 'org-adaptive-fill-function)
14298 (org-set-local
14299 'align-mode-rules-list
14300 '((org-in-buffer-settings
14301 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14302 (modes . '(org-mode))))))
14304 (defun org-fill-paragraph (&optional justify)
14305 "Re-align a table, pass through to fill-paragraph if no table."
14306 (let ((table-p (org-at-table-p))
14307 (table.el-p (org-at-table.el-p)))
14308 (cond ((and (equal (char-after (point-at-bol)) ?*)
14309 (save-excursion (goto-char (point-at-bol))
14310 (looking-at outline-regexp)))
14311 t) ; skip headlines
14312 (table.el-p t) ; skip table.el tables
14313 (table-p (org-table-align) t) ; align org-mode tables
14314 (t nil)))) ; call paragraph-fill
14316 ;; For reference, this is the default value of adaptive-fill-regexp
14317 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14319 (defun org-adaptive-fill-function ()
14320 "Return a fill prefix for org-mode files.
14321 In particular, this makes sure hanging paragraphs for hand-formatted lists
14322 work correctly."
14323 (cond ((looking-at "#[ \t]+")
14324 (match-string 0))
14325 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14326 (save-excursion
14327 (if (> (match-end 1) (+ (match-beginning 1)
14328 org-description-max-indent))
14329 (goto-char (+ (match-beginning 1) 5))
14330 (goto-char (match-end 0)))
14331 (make-string (current-column) ?\ )))
14332 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14333 (save-excursion
14334 (goto-char (match-end 0))
14335 (make-string (current-column) ?\ )))
14336 (t nil)))
14338 ;;; Other stuff.
14340 (defun org-toggle-fixed-width-section (arg)
14341 "Toggle the fixed-width export.
14342 If there is no active region, the QUOTE keyword at the current headline is
14343 inserted or removed. When present, it causes the text between this headline
14344 and the next to be exported as fixed-width text, and unmodified.
14345 If there is an active region, this command adds or removes a colon as the
14346 first character of this line. If the first character of a line is a colon,
14347 this line is also exported in fixed-width font."
14348 (interactive "P")
14349 (let* ((cc 0)
14350 (regionp (org-region-active-p))
14351 (beg (if regionp (region-beginning) (point)))
14352 (end (if regionp (region-end)))
14353 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14354 (case-fold-search nil)
14355 (re "[ \t]*\\(:\\)")
14356 off)
14357 (if regionp
14358 (save-excursion
14359 (goto-char beg)
14360 (setq cc (current-column))
14361 (beginning-of-line 1)
14362 (setq off (looking-at re))
14363 (while (> nlines 0)
14364 (setq nlines (1- nlines))
14365 (beginning-of-line 1)
14366 (cond
14367 (arg
14368 (org-move-to-column cc t)
14369 (insert ":\n")
14370 (forward-line -1))
14371 ((and off (looking-at re))
14372 (replace-match "" t t nil 1))
14373 ((not off) (org-move-to-column cc t) (insert ":")))
14374 (forward-line 1)))
14375 (save-excursion
14376 (org-back-to-heading)
14377 (if (looking-at (concat outline-regexp
14378 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14379 (replace-match "" t t nil 1)
14380 (if (looking-at outline-regexp)
14381 (progn
14382 (goto-char (match-end 0))
14383 (insert org-quote-string " "))))))))
14385 ;;;; Functions extending outline functionality
14387 (defun org-beginning-of-line (&optional arg)
14388 "Go to the beginning of the current line. If that is invisible, continue
14389 to a visible line beginning. This makes the function of C-a more intuitive.
14390 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14391 first attempt, and only move to after the tags when the cursor is already
14392 beyond the end of the headline."
14393 (interactive "P")
14394 (let ((pos (point)) refpos)
14395 (beginning-of-line 1)
14396 (if (bobp)
14398 (backward-char 1)
14399 (if (org-invisible-p)
14400 (while (and (not (bobp)) (org-invisible-p))
14401 (backward-char 1)
14402 (beginning-of-line 1))
14403 (forward-char 1)))
14404 (when org-special-ctrl-a/e
14405 (cond
14406 ((and (looking-at org-complex-heading-regexp)
14407 (= (char-after (match-end 1)) ?\ ))
14408 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14409 (point-at-eol)))
14410 (goto-char
14411 (if (eq org-special-ctrl-a/e t)
14412 (cond ((> pos refpos) refpos)
14413 ((= pos (point)) refpos)
14414 (t (point)))
14415 (cond ((> pos (point)) (point))
14416 ((not (eq last-command this-command)) (point))
14417 (t refpos)))))
14418 ((org-at-item-p)
14419 (goto-char
14420 (if (eq org-special-ctrl-a/e t)
14421 (cond ((> pos (match-end 4)) (match-end 4))
14422 ((= pos (point)) (match-end 4))
14423 (t (point)))
14424 (cond ((> pos (point)) (point))
14425 ((not (eq last-command this-command)) (point))
14426 (t (match-end 4))))))))
14427 (org-no-warnings
14428 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14430 (defun org-end-of-line (&optional arg)
14431 "Go to the end of the line.
14432 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14433 first attempt, and only move to after the tags when the cursor is already
14434 beyond the end of the headline."
14435 (interactive "P")
14436 (if (or (not org-special-ctrl-a/e)
14437 (not (org-on-heading-p)))
14438 (end-of-line arg)
14439 (let ((pos (point)))
14440 (beginning-of-line 1)
14441 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14442 (if (eq org-special-ctrl-a/e t)
14443 (if (or (< pos (match-beginning 1))
14444 (= pos (match-end 0)))
14445 (goto-char (match-beginning 1))
14446 (goto-char (match-end 0)))
14447 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14448 (goto-char (match-end 0))
14449 (goto-char (match-beginning 1))))
14450 (end-of-line arg))))
14451 (org-no-warnings
14452 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14455 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14456 (define-key org-mode-map "\C-e" 'org-end-of-line)
14458 (defun org-kill-line (&optional arg)
14459 "Kill line, to tags or end of line."
14460 (interactive "P")
14461 (cond
14462 ((or (not org-special-ctrl-k)
14463 (bolp)
14464 (not (org-on-heading-p)))
14465 (call-interactively 'kill-line))
14466 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14467 (kill-region (point) (match-beginning 1))
14468 (org-set-tags nil t))
14469 (t (kill-region (point) (point-at-eol)))))
14471 (define-key org-mode-map "\C-k" 'org-kill-line)
14473 (defun org-yank (&optional arg)
14474 "Yank. If the kill is a subtree, treat it specially.
14475 This command will look at the current kill and check if is a single
14476 subtree, or a series of subtrees[1]. If it passes the test, and if the
14477 cursor is at the beginning of a line or after the stars of a currently
14478 empty headline, then the yank is handled specially. How exactly depends
14479 on the value of the following variables, both set by default.
14481 org-yank-folded-subtrees
14482 When set, the subtree(s) will be folded after insertion, but only
14483 if doing so would now swallow text after the yanked text.
14485 org-yank-adjusted-subtrees
14486 When set, the subtree will be promoted or demoted in order to
14487 fit into the local outline tree structure, which means that the level
14488 will be adjusted so that it becomes the smaller one of the two
14489 *visible* surrounding headings.
14491 Any prefix to this command will cause `yank' to be called directly with
14492 no special treatment. In particular, a simple `C-u' prefix will just
14493 plainly yank the text as it is.
14495 \[1] Basically, the test checks if the first non-white line is a heading
14496 and if there are no other headings with fewer stars."
14497 (interactive "P")
14498 (setq this-command 'yank)
14499 (if arg
14500 (call-interactively 'yank)
14501 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14502 (and (org-kill-is-subtree-p)
14503 (or (bolp)
14504 (and (looking-at "[ \t]*$")
14505 (string-match
14506 "\\`\\*+\\'"
14507 (buffer-substring (point-at-bol) (point)))))))
14508 swallowp)
14509 (cond
14510 ((and subtreep org-yank-folded-subtrees)
14511 (let ((beg (point))
14512 end)
14513 (if (and subtreep org-yank-adjusted-subtrees)
14514 (org-paste-subtree nil nil 'for-yank)
14515 (call-interactively 'yank))
14516 (setq end (point))
14517 (goto-char beg)
14518 (when (and (bolp) subtreep
14519 (not (setq swallowp
14520 (org-yank-folding-would-swallow-text beg end))))
14521 (or (looking-at outline-regexp)
14522 (re-search-forward (concat "^" outline-regexp) end t))
14523 (while (and (< (point) end) (looking-at outline-regexp))
14524 (hide-subtree)
14525 (org-cycle-show-empty-lines 'folded)
14526 (condition-case nil
14527 (outline-forward-same-level 1)
14528 (error (goto-char end)))))
14529 (when swallowp
14530 (message
14531 "Yanked text not folded because that would swallow text"))
14532 (goto-char end)
14533 (skip-chars-forward " \t\n\r")
14534 (beginning-of-line 1)
14535 (push-mark beg 'nomsg)))
14536 ((and subtreep org-yank-adjusted-subtrees)
14537 (let ((beg (point-at-bol)))
14538 (org-paste-subtree nil nil 'for-yank)
14539 (push-mark beg 'nomsg)))
14541 (call-interactively 'yank))))))
14543 (defun org-yank-folding-would-swallow-text (beg end)
14544 "Would hide-subtree at BEG swallow any text after END?"
14545 (let (level)
14546 (save-excursion
14547 (goto-char beg)
14548 (when (or (looking-at outline-regexp)
14549 (re-search-forward (concat "^" outline-regexp) end t))
14550 (setq level (org-outline-level)))
14551 (goto-char end)
14552 (skip-chars-forward " \t\r\n\v\f")
14553 (if (or (eobp)
14554 (and (bolp) (looking-at org-outline-regexp)
14555 (<= (org-outline-level) level)))
14556 nil ; Nothing would be swallowed
14557 t)))) ; something would swallow
14559 (define-key org-mode-map "\C-y" 'org-yank)
14561 (defun org-invisible-p ()
14562 "Check if point is at a character currently not visible."
14563 ;; Early versions of noutline don't have `outline-invisible-p'.
14564 (if (fboundp 'outline-invisible-p)
14565 (outline-invisible-p)
14566 (get-char-property (point) 'invisible)))
14568 (defun org-invisible-p2 ()
14569 "Check if point is at a character currently not visible."
14570 (save-excursion
14571 (if (and (eolp) (not (bobp))) (backward-char 1))
14572 ;; Early versions of noutline don't have `outline-invisible-p'.
14573 (if (fboundp 'outline-invisible-p)
14574 (outline-invisible-p)
14575 (get-char-property (point) 'invisible))))
14577 (defun org-back-to-heading (&optional invisible-ok)
14578 "Call `outline-back-to-heading', but provide a better error message."
14579 (condition-case nil
14580 (outline-back-to-heading invisible-ok)
14581 (error (error "Before first headline at position %d in buffer %s"
14582 (point) (current-buffer)))))
14584 (defun org-before-first-heading-p ()
14585 "Before first heading?"
14586 (save-excursion
14587 (null (re-search-backward "^\\*+ " nil t))))
14589 (defalias 'org-on-heading-p 'outline-on-heading-p)
14590 (defalias 'org-at-heading-p 'outline-on-heading-p)
14591 (defun org-at-heading-or-item-p ()
14592 (or (org-on-heading-p) (org-at-item-p)))
14594 (defun org-on-target-p ()
14595 (or (org-in-regexp org-radio-target-regexp)
14596 (org-in-regexp org-target-regexp)))
14598 (defun org-up-heading-all (arg)
14599 "Move to the heading line of which the present line is a subheading.
14600 This function considers both visible and invisible heading lines.
14601 With argument, move up ARG levels."
14602 (if (fboundp 'outline-up-heading-all)
14603 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14604 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14606 (defun org-up-heading-safe ()
14607 "Move to the heading line of which the present line is a subheading.
14608 This version will not throw an error. It will return the level of the
14609 headline found, or nil if no higher level is found."
14610 (let (start-level re)
14611 (org-back-to-heading t)
14612 (setq start-level (funcall outline-level))
14613 (if (equal start-level 1)
14615 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14616 (if (re-search-backward re nil t)
14617 (funcall outline-level)))))
14619 (defun org-first-sibling-p ()
14620 "Is this heading the first child of its parents?"
14621 (interactive)
14622 (let ((re (concat "^" outline-regexp))
14623 level l)
14624 (unless (org-at-heading-p t)
14625 (error "Not at a heading"))
14626 (setq level (funcall outline-level))
14627 (save-excursion
14628 (if (not (re-search-backward re nil t))
14630 (setq l (funcall outline-level))
14631 (< l level)))))
14633 (defun org-goto-sibling (&optional previous)
14634 "Goto the next sibling, even if it is invisible.
14635 When PREVIOUS is set, go to the previous sibling instead. Returns t
14636 when a sibling was found. When none is found, return nil and don't
14637 move point."
14638 (let ((fun (if previous 're-search-backward 're-search-forward))
14639 (pos (point))
14640 (re (concat "^" outline-regexp))
14641 level l)
14642 (when (condition-case nil (org-back-to-heading t) (error nil))
14643 (setq level (funcall outline-level))
14644 (catch 'exit
14645 (or previous (forward-char 1))
14646 (while (funcall fun re nil t)
14647 (setq l (funcall outline-level))
14648 (when (< l level) (goto-char pos) (throw 'exit nil))
14649 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14650 (goto-char pos)
14651 nil))))
14653 (defun org-show-siblings ()
14654 "Show all siblings of the current headline."
14655 (save-excursion
14656 (while (org-goto-sibling) (org-flag-heading nil)))
14657 (save-excursion
14658 (while (org-goto-sibling 'previous)
14659 (org-flag-heading nil))))
14661 (defun org-show-hidden-entry ()
14662 "Show an entry where even the heading is hidden."
14663 (save-excursion
14664 (org-show-entry)))
14666 (defun org-flag-heading (flag &optional entry)
14667 "Flag the current heading. FLAG non-nil means make invisible.
14668 When ENTRY is non-nil, show the entire entry."
14669 (save-excursion
14670 (org-back-to-heading t)
14671 ;; Check if we should show the entire entry
14672 (if entry
14673 (progn
14674 (org-show-entry)
14675 (save-excursion
14676 (and (outline-next-heading)
14677 (org-flag-heading nil))))
14678 (outline-flag-region (max (point-min) (1- (point)))
14679 (save-excursion (outline-end-of-heading) (point))
14680 flag))))
14682 (defun org-forward-same-level (arg)
14683 "Move forward to the ARG'th subheading at same level as this one.
14684 Stop at the first and last subheadings of a superior heading.
14685 This is like outline-forward-same-level, but invisible headings are ok."
14686 (interactive "p")
14687 (org-back-to-heading t)
14688 (while (> arg 0)
14689 (let ((point-to-move-to (save-excursion
14690 (org-get-next-sibling))))
14691 (if point-to-move-to
14692 (progn
14693 (goto-char point-to-move-to)
14694 (setq arg (1- arg)))
14695 (progn
14696 (setq arg 0)
14697 (error "No following same-level heading"))))))
14699 (defun org-get-next-sibling ()
14700 "Move to next heading of the same level, and return point.
14701 If there is no such heading, return nil.
14702 This is like outline-next-sibling, but invisible headings are ok."
14703 (let ((level (funcall outline-level)))
14704 (outline-next-heading)
14705 (while (and (not (eobp)) (> (funcall outline-level) level))
14706 (outline-next-heading))
14707 (if (or (eobp) (< (funcall outline-level) level))
14709 (point))))
14711 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14712 ;; This is an exact copy of the original function, but it uses
14713 ;; `org-back-to-heading', to make it work also in invisible
14714 ;; trees. And is uses an invisible-OK argument.
14715 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14716 (org-back-to-heading invisible-OK)
14717 (let ((first t)
14718 (level (funcall outline-level)))
14719 (while (and (not (eobp))
14720 (or first (> (funcall outline-level) level)))
14721 (setq first nil)
14722 (outline-next-heading))
14723 (unless to-heading
14724 (if (memq (preceding-char) '(?\n ?\^M))
14725 (progn
14726 ;; Go to end of line before heading
14727 (forward-char -1)
14728 (if (memq (preceding-char) '(?\n ?\^M))
14729 ;; leave blank line before heading
14730 (forward-char -1))))))
14731 (point))
14733 (defun org-show-subtree ()
14734 "Show everything after this heading at deeper levels."
14735 (outline-flag-region
14736 (point)
14737 (save-excursion
14738 (outline-end-of-subtree) (outline-next-heading) (point))
14739 nil))
14741 (defun org-show-entry ()
14742 "Show the body directly following this heading.
14743 Show the heading too, if it is currently invisible."
14744 (interactive)
14745 (save-excursion
14746 (condition-case nil
14747 (progn
14748 (org-back-to-heading t)
14749 (outline-flag-region
14750 (max (point-min) (1- (point)))
14751 (save-excursion
14752 (re-search-forward
14753 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14754 (or (match-beginning 1) (point-max)))
14755 nil))
14756 (error nil))))
14758 (defun org-make-options-regexp (kwds)
14759 "Make a regular expression for keyword lines."
14760 (concat
14762 "#?[ \t]*\\+\\("
14763 (mapconcat 'regexp-quote kwds "\\|")
14764 "\\):[ \t]*"
14765 "\\(.+\\)"))
14767 ;; Make isearch reveal the necessary context
14768 (defun org-isearch-end ()
14769 "Reveal context after isearch exits."
14770 (when isearch-success ; only if search was successful
14771 (if (featurep 'xemacs)
14772 ;; Under XEmacs, the hook is run in the correct place,
14773 ;; we directly show the context.
14774 (org-show-context 'isearch)
14775 ;; In Emacs the hook runs *before* restoring the overlays.
14776 ;; So we have to use a one-time post-command-hook to do this.
14777 ;; (Emacs 22 has a special variable, see function `org-mode')
14778 (unless (and (boundp 'isearch-mode-end-hook-quit)
14779 isearch-mode-end-hook-quit)
14780 ;; Only when the isearch was not quitted.
14781 (org-add-hook 'post-command-hook 'org-isearch-post-command
14782 'append 'local)))))
14784 (defun org-isearch-post-command ()
14785 "Remove self from hook, and show context."
14786 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14787 (org-show-context 'isearch))
14790 ;;;; Integration with and fixes for other packages
14792 ;;; Imenu support
14794 (defvar org-imenu-markers nil
14795 "All markers currently used by Imenu.")
14796 (make-variable-buffer-local 'org-imenu-markers)
14798 (defun org-imenu-new-marker (&optional pos)
14799 "Return a new marker for use by Imenu, and remember the marker."
14800 (let ((m (make-marker)))
14801 (move-marker m (or pos (point)))
14802 (push m org-imenu-markers)
14805 (defun org-imenu-get-tree ()
14806 "Produce the index for Imenu."
14807 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14808 (setq org-imenu-markers nil)
14809 (let* ((n org-imenu-depth)
14810 (re (concat "^" outline-regexp))
14811 (subs (make-vector (1+ n) nil))
14812 (last-level 0)
14813 m tree level head)
14814 (save-excursion
14815 (save-restriction
14816 (widen)
14817 (goto-char (point-max))
14818 (while (re-search-backward re nil t)
14819 (setq level (org-reduced-level (funcall outline-level)))
14820 (when (<= level n)
14821 (looking-at org-complex-heading-regexp)
14822 (setq head (org-link-display-format
14823 (org-match-string-no-properties 4))
14824 m (org-imenu-new-marker))
14825 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14826 (if (>= level last-level)
14827 (push (cons head m) (aref subs level))
14828 (push (cons head (aref subs (1+ level))) (aref subs level))
14829 (loop for i from (1+ level) to n do (aset subs i nil)))
14830 (setq last-level level)))))
14831 (aref subs 1)))
14833 (eval-after-load "imenu"
14834 '(progn
14835 (add-hook 'imenu-after-jump-hook
14836 (lambda ()
14837 (if (eq major-mode 'org-mode)
14838 (org-show-context 'org-goto))))))
14840 (defun org-link-display-format (link)
14841 "Replace a link with either the description, or the link target
14842 if no description is present"
14843 (save-match-data
14844 (if (string-match org-bracket-link-analytic-regexp link)
14845 (replace-match (or (match-string 5 link)
14846 (concat (match-string 1 link)
14847 (match-string 3 link)))
14848 nil nil link)
14849 link)))
14851 ;; Speedbar support
14853 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14854 "Overlay marking the agenda restriction line in speedbar.")
14855 (org-overlay-put org-speedbar-restriction-lock-overlay
14856 'face 'org-agenda-restriction-lock)
14857 (org-overlay-put org-speedbar-restriction-lock-overlay
14858 'help-echo "Agendas are currently limited to this item.")
14859 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14861 (defun org-speedbar-set-agenda-restriction ()
14862 "Restrict future agenda commands to the location at point in speedbar.
14863 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14864 (interactive)
14865 (require 'org-agenda)
14866 (let (p m tp np dir txt w)
14867 (cond
14868 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14869 'org-imenu t))
14870 (setq m (get-text-property p 'org-imenu-marker))
14871 (save-excursion
14872 (save-restriction
14873 (set-buffer (marker-buffer m))
14874 (goto-char m)
14875 (org-agenda-set-restriction-lock 'subtree))))
14876 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14877 'speedbar-function 'speedbar-find-file))
14878 (setq tp (previous-single-property-change
14879 (1+ p) 'speedbar-function)
14880 np (next-single-property-change
14881 tp 'speedbar-function)
14882 dir (speedbar-line-directory)
14883 txt (buffer-substring-no-properties (or tp (point-min))
14884 (or np (point-max))))
14885 (save-excursion
14886 (save-restriction
14887 (set-buffer (find-file-noselect
14888 (let ((default-directory dir))
14889 (expand-file-name txt))))
14890 (unless (org-mode-p)
14891 (error "Cannot restrict to non-Org-mode file"))
14892 (org-agenda-set-restriction-lock 'file))))
14893 (t (error "Don't know how to restrict Org-mode's agenda")))
14894 (org-move-overlay org-speedbar-restriction-lock-overlay
14895 (point-at-bol) (point-at-eol))
14896 (setq current-prefix-arg nil)
14897 (org-agenda-maybe-redo)))
14899 (eval-after-load "speedbar"
14900 '(progn
14901 (speedbar-add-supported-extension ".org")
14902 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14903 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14904 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14905 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14906 (add-hook 'speedbar-visiting-tag-hook
14907 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14910 ;;; Fixes and Hacks for problems with other packages
14912 ;; Make flyspell not check words in links, to not mess up our keymap
14913 (defun org-mode-flyspell-verify ()
14914 "Don't let flyspell put overlays at active buttons."
14915 (not (get-text-property (point) 'keymap)))
14917 ;; Make `bookmark-jump' show the jump location if it was hidden.
14918 (eval-after-load "bookmark"
14919 '(if (boundp 'bookmark-after-jump-hook)
14920 ;; We can use the hook
14921 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14922 ;; Hook not available, use advice
14923 (defadvice bookmark-jump (after org-make-visible activate)
14924 "Make the position visible."
14925 (org-bookmark-jump-unhide))))
14927 ;; Make sure saveplace show the location if it was hidden
14928 (eval-after-load "saveplace"
14929 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14930 "Make the position visible."
14931 (org-bookmark-jump-unhide)))
14933 (defun org-bookmark-jump-unhide ()
14934 "Unhide the current position, to show the bookmark location."
14935 (and (org-mode-p)
14936 (or (org-invisible-p)
14937 (save-excursion (goto-char (max (point-min) (1- (point))))
14938 (org-invisible-p)))
14939 (org-show-context 'bookmark-jump)))
14941 ;; Make session.el ignore our circular variable
14942 (eval-after-load "session"
14943 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14945 ;;;; Experimental code
14947 (defun org-closed-in-range ()
14948 "Sparse tree of items closed in a certain time range.
14949 Still experimental, may disappear in the future."
14950 (interactive)
14951 ;; Get the time interval from the user.
14952 (let* ((time1 (time-to-seconds
14953 (org-read-date nil 'to-time nil "Starting date: ")))
14954 (time2 (time-to-seconds
14955 (org-read-date nil 'to-time nil "End date:")))
14956 ;; callback function
14957 (callback (lambda ()
14958 (let ((time
14959 (time-to-seconds
14960 (apply 'encode-time
14961 (org-parse-time-string
14962 (match-string 1))))))
14963 ;; check if time in interval
14964 (and (>= time time1) (<= time time2))))))
14965 ;; make tree, check each match with the callback
14966 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14969 ;;;; Finish up
14971 (provide 'org)
14973 (run-hooks 'org-load-hook)
14975 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14977 ;;; org.el ends here