Shift-selection: More tweaking
[org-mode.git] / lisp / org.el
blob921362f913bdb69e1e238347f1bbe67f3776a1ab
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
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.19b
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-footnote)
93 ;;;; Customization variables
95 ;;; Version
97 (defconst org-version "6.19b"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (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)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
171 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
172 (const :tag " mew Links to Mew folders/messages" org-mew)
173 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
174 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
175 (const :tag " vm: Links to VM folders/messages" org-vm)
176 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
177 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
178 (const :tag " mouse: Additional mouse support" org-mouse)
180 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
181 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
182 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
183 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
184 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
185 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
186 (const :tag "C eval: Include command output as text" org-eval)
187 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
188 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
189 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
190 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
191 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
192 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
193 (const :tag "C mtags: Support for muse-like tags" org-mtags)
194 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
195 (const :tag "C registry: A registry for Org links" org-registry)
196 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
197 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
198 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
199 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
200 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
202 (defcustom org-support-shift-select nil
203 "Non-nil means, make shift-cursor commands select text when possible.
205 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
206 selecting a region, or enlarge thusly started regions. In Org-mode,
207 in special contexts, these same keys are used for other purposes, important
208 enough to compete with shift selection. Org tries to balance these needs
209 by supporting `shift-select-mode' outside these special contexts, under
210 control of this variable.
212 The default of this variable is nil, to avoid confusing behavior.
213 When this variable is t and the cursor is not in a special context,
214 Org-mode will support shift-selection for making and enlarging regions.
216 Shift-cursor keys then still have special meanings at the following
217 locations:
218 - on a headline, changing TODO state (left/right) and priority (up/down)
219 - on a time stamp, changing the time
220 - in a property definition line, switching between allowed values
221 - in the BEGIN line of a clock table (changing the time block).
223 If you set this variable to the symbol `always', then the keys
224 will not be special in headlines and property lines, to make shift
225 selection work there as well. If this is what you want, you can use the
226 following alternative commands: `C-c C-t' and `C-c ,' to change TODO
227 state and priority, `C-u C-u C-c C-t' can be used to switch TODO sets,
228 and properties can be edited by hand or in column view.
230 However, when the cursor is on a timestamp, shift-cursor commands
231 will still edit the time stamp - this is just too good to give up.
233 XEmacs user should have this variable set to nil, because shift-select-mode
234 is Emacs 23 only."
235 :group 'org
236 :type '(choice
237 (const :tag "Not at all" nil)
238 (const :tag "When context allows" t)
239 (const :tag "Everywhere except timestamps" always)))
241 (defgroup org-startup nil
242 "Options concerning startup of Org-mode."
243 :tag "Org Startup"
244 :group 'org)
246 (defcustom org-startup-folded t
247 "Non-nil means, entering Org-mode will switch to OVERVIEW.
248 This can also be configured on a per-file basis by adding one of
249 the following lines anywhere in the buffer:
251 #+STARTUP: fold
252 #+STARTUP: nofold
253 #+STARTUP: content"
254 :group 'org-startup
255 :type '(choice
256 (const :tag "nofold: show all" nil)
257 (const :tag "fold: overview" t)
258 (const :tag "content: all headlines" content)))
260 (defcustom org-startup-truncated t
261 "Non-nil means, entering Org-mode will set `truncate-lines'.
262 This is useful since some lines containing links can be very long and
263 uninteresting. Also tables look terrible when wrapped."
264 :group 'org-startup
265 :type 'boolean)
267 (defcustom org-startup-align-all-tables nil
268 "Non-nil means, align all tables when visiting a file.
269 This is useful when the column width in tables is forced with <N> cookies
270 in table fields. Such tables will look correct only after the first re-align.
271 This can also be configured on a per-file basis by adding one of
272 the following lines anywhere in the buffer:
273 #+STARTUP: align
274 #+STARTUP: noalign"
275 :group 'org-startup
276 :type 'boolean)
278 (defcustom org-insert-mode-line-in-empty-file nil
279 "Non-nil means insert the first line setting Org-mode in empty files.
280 When the function `org-mode' is called interactively in an empty file, this
281 normally means that the file name does not automatically trigger Org-mode.
282 To ensure that the file will always be in Org-mode in the future, a
283 line enforcing Org-mode will be inserted into the buffer, if this option
284 has been set."
285 :group 'org-startup
286 :type 'boolean)
288 (defcustom org-replace-disputed-keys nil
289 "Non-nil means use alternative key bindings for some keys.
290 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
291 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
292 If you want to use Org-mode together with one of these other modes,
293 or more generally if you would like to move some Org-mode commands to
294 other keys, set this variable and configure the keys with the variable
295 `org-disputed-keys'.
297 This option is only relevant at load-time of Org-mode, and must be set
298 *before* org.el is loaded. Changing it requires a restart of Emacs to
299 become effective."
300 :group 'org-startup
301 :type 'boolean)
303 (defcustom org-use-extra-keys nil
304 "Non-nil means use extra key sequence definitions for certain
305 commands. This happens automatically if you run XEmacs or if
306 window-system is nil. This variable lets you do the same
307 manually. You must set it before loading org.
309 Example: on Carbon Emacs 22 running graphically, with an external
310 keyboard on a Powerbook, the default way of setting M-left might
311 not work for either Alt or ESC. Setting this variable will make
312 it work for ESC."
313 :group 'org-startup
314 :type 'boolean)
316 (if (fboundp 'defvaralias)
317 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
319 (defcustom org-disputed-keys
320 '(([(shift up)] . [(meta p)])
321 ([(shift down)] . [(meta n)])
322 ([(shift left)] . [(meta -)])
323 ([(shift right)] . [(meta +)])
324 ([(control shift right)] . [(meta shift +)])
325 ([(control shift left)] . [(meta shift -)]))
326 "Keys for which Org-mode and other modes compete.
327 This is an alist, cars are the default keys, second element specifies
328 the alternative to use when `org-replace-disputed-keys' is t.
330 Keys can be specified in any syntax supported by `define-key'.
331 The value of this option takes effect only at Org-mode's startup,
332 therefore you'll have to restart Emacs to apply it after changing."
333 :group 'org-startup
334 :type 'alist)
336 (defun org-key (key)
337 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
338 Or return the original if not disputed."
339 (if org-replace-disputed-keys
340 (let* ((nkey (key-description key))
341 (x (org-find-if (lambda (x)
342 (equal (key-description (car x)) nkey))
343 org-disputed-keys)))
344 (if x (cdr x) key))
345 key))
347 (defun org-find-if (predicate seq)
348 (catch 'exit
349 (while seq
350 (if (funcall predicate (car seq))
351 (throw 'exit (car seq))
352 (pop seq)))))
354 (defun org-defkey (keymap key def)
355 "Define a key, possibly translated, as returned by `org-key'."
356 (define-key keymap (org-key key) def))
358 (defcustom org-ellipsis nil
359 "The ellipsis to use in the Org-mode outline.
360 When nil, just use the standard three dots. When a string, use that instead,
361 When a face, use the standard 3 dots, but with the specified face.
362 The change affects only Org-mode (which will then use its own display table).
363 Changing this requires executing `M-x org-mode' in a buffer to become
364 effective."
365 :group 'org-startup
366 :type '(choice (const :tag "Default" nil)
367 (face :tag "Face" :value org-warning)
368 (string :tag "String" :value "...#")))
370 (defvar org-display-table nil
371 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
373 (defgroup org-keywords nil
374 "Keywords in Org-mode."
375 :tag "Org Keywords"
376 :group 'org)
378 (defcustom org-deadline-string "DEADLINE:"
379 "String to mark deadline entries.
380 A deadline is this string, followed by a time stamp. Should be a word,
381 terminated by a colon. You can insert a schedule keyword and
382 a timestamp with \\[org-deadline].
383 Changes become only effective after restarting Emacs."
384 :group 'org-keywords
385 :type 'string)
387 (defcustom org-scheduled-string "SCHEDULED:"
388 "String to mark scheduled TODO entries.
389 A schedule is this string, followed by a time stamp. Should be a word,
390 terminated by a colon. You can insert a schedule keyword and
391 a timestamp with \\[org-schedule].
392 Changes become only effective after restarting Emacs."
393 :group 'org-keywords
394 :type 'string)
396 (defcustom org-closed-string "CLOSED:"
397 "String used as the prefix for timestamps logging closing a TODO entry."
398 :group 'org-keywords
399 :type 'string)
401 (defcustom org-clock-string "CLOCK:"
402 "String used as prefix for timestamps clocking work hours on an item."
403 :group 'org-keywords
404 :type 'string)
406 (defcustom org-comment-string "COMMENT"
407 "Entries starting with this keyword will never be exported.
408 An entry can be toggled between COMMENT and normal with
409 \\[org-toggle-comment].
410 Changes become only effective after restarting Emacs."
411 :group 'org-keywords
412 :type 'string)
414 (defcustom org-quote-string "QUOTE"
415 "Entries starting with this keyword will be exported in fixed-width font.
416 Quoting applies only to the text in the entry following the headline, and does
417 not extend beyond the next headline, even if that is lower level.
418 An entry can be toggled between QUOTE and normal with
419 \\[org-toggle-fixed-width-section]."
420 :group 'org-keywords
421 :type 'string)
423 (defconst org-repeat-re
424 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
425 "Regular expression for specifying repeated events.
426 After a match, group 1 contains the repeat expression.")
428 (defgroup org-structure nil
429 "Options concerning the general structure of Org-mode files."
430 :tag "Org Structure"
431 :group 'org)
433 (defgroup org-reveal-location nil
434 "Options about how to make context of a location visible."
435 :tag "Org Reveal Location"
436 :group 'org-structure)
438 (defconst org-context-choice
439 '(choice
440 (const :tag "Always" t)
441 (const :tag "Never" nil)
442 (repeat :greedy t :tag "Individual contexts"
443 (cons
444 (choice :tag "Context"
445 (const agenda)
446 (const org-goto)
447 (const occur-tree)
448 (const tags-tree)
449 (const link-search)
450 (const mark-goto)
451 (const bookmark-jump)
452 (const isearch)
453 (const default))
454 (boolean))))
455 "Contexts for the reveal options.")
457 (defcustom org-show-hierarchy-above '((default . t))
458 "Non-nil means, show full hierarchy when revealing a location.
459 Org-mode often shows locations in an org-mode file which might have
460 been invisible before. When this is set, the hierarchy of headings
461 above the exposed location is shown.
462 Turning this off for example for sparse trees makes them very compact.
463 Instead of t, this can also be an alist specifying this option for different
464 contexts. Valid contexts are
465 agenda when exposing an entry from the agenda
466 org-goto when using the command `org-goto' on key C-c C-j
467 occur-tree when using the command `org-occur' on key C-c /
468 tags-tree when constructing a sparse tree based on tags matches
469 link-search when exposing search matches associated with a link
470 mark-goto when exposing the jump goal of a mark
471 bookmark-jump when exposing a bookmark location
472 isearch when exiting from an incremental search
473 default default for all contexts not set explicitly"
474 :group 'org-reveal-location
475 :type org-context-choice)
477 (defcustom org-show-following-heading '((default . nil))
478 "Non-nil means, show following heading when revealing a location.
479 Org-mode often shows locations in an org-mode file which might have
480 been invisible before. When this is set, the heading following the
481 match is shown.
482 Turning this off for example for sparse trees makes them very compact,
483 but makes it harder to edit the location of the match. In such a case,
484 use the command \\[org-reveal] to show more context.
485 Instead of t, this can also be an alist specifying this option for different
486 contexts. See `org-show-hierarchy-above' for valid contexts."
487 :group 'org-reveal-location
488 :type org-context-choice)
490 (defcustom org-show-siblings '((default . nil) (isearch t))
491 "Non-nil means, show all sibling heading when revealing a location.
492 Org-mode often shows locations in an org-mode file which might have
493 been invisible before. When this is set, the sibling of the current entry
494 heading are all made visible. If `org-show-hierarchy-above' is t,
495 the same happens on each level of the hierarchy above the current entry.
497 By default this is on for the isearch context, off for all other contexts.
498 Turning this off for example for sparse trees makes them very compact,
499 but makes it harder to edit the location of the match. In such a case,
500 use the command \\[org-reveal] to show more context.
501 Instead of t, this can also be an alist specifying this option for different
502 contexts. See `org-show-hierarchy-above' for valid contexts."
503 :group 'org-reveal-location
504 :type org-context-choice)
506 (defcustom org-show-entry-below '((default . nil))
507 "Non-nil means, show the entry below a headline when revealing a location.
508 Org-mode often shows locations in an org-mode file which might have
509 been invisible before. When this is set, the text below the headline that is
510 exposed is also shown.
512 By default this is off for all contexts.
513 Instead of t, this can also be an alist specifying this option for different
514 contexts. See `org-show-hierarchy-above' for valid contexts."
515 :group 'org-reveal-location
516 :type org-context-choice)
518 (defcustom org-indirect-buffer-display 'other-window
519 "How should indirect tree buffers be displayed?
520 This applies to indirect buffers created with the commands
521 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
522 Valid values are:
523 current-window Display in the current window
524 other-window Just display in another window.
525 dedicated-frame Create one new frame, and re-use it each time.
526 new-frame Make a new frame each time. Note that in this case
527 previously-made indirect buffers are kept, and you need to
528 kill these buffers yourself."
529 :group 'org-structure
530 :group 'org-agenda-windows
531 :type '(choice
532 (const :tag "In current window" current-window)
533 (const :tag "In current frame, other window" other-window)
534 (const :tag "Each time a new frame" new-frame)
535 (const :tag "One dedicated frame" dedicated-frame)))
537 (defgroup org-cycle nil
538 "Options concerning visibility cycling in Org-mode."
539 :tag "Org Cycle"
540 :group 'org-structure)
542 (defcustom org-drawers '("PROPERTIES" "CLOCK")
543 "Names of drawers. Drawers are not opened by cycling on the headline above.
544 Drawers only open with a TAB on the drawer line itself. A drawer looks like
545 this:
546 :DRAWERNAME:
547 .....
548 :END:
549 The drawer \"PROPERTIES\" is special for capturing properties through
550 the property API.
552 Drawers can be defined on the per-file basis with a line like:
554 #+DRAWERS: HIDDEN STATE PROPERTIES"
555 :group 'org-structure
556 :type '(repeat (string :tag "Drawer Name")))
558 (defcustom org-cycle-global-at-bob nil
559 "Cycle globally if cursor is at beginning of buffer and not at a headline.
560 This makes it possible to do global cycling without having to use S-TAB or
561 C-u TAB. For this special case to work, the first line of the buffer
562 must not be a headline - it may be empty ot some other text. When used in
563 this way, `org-cycle-hook' is disables temporarily, to make sure the
564 cursor stays at the beginning of the buffer.
565 When this option is nil, don't do anything special at the beginning
566 of the buffer."
567 :group 'org-cycle
568 :type 'boolean)
570 (defcustom org-cycle-emulate-tab t
571 "Where should `org-cycle' emulate TAB.
572 nil Never
573 white Only in completely white lines
574 whitestart Only at the beginning of lines, before the first non-white char
575 t Everywhere except in headlines
576 exc-hl-bol Everywhere except at the start of a headline
577 If TAB is used in a place where it does not emulate TAB, the current subtree
578 visibility is cycled."
579 :group 'org-cycle
580 :type '(choice (const :tag "Never" nil)
581 (const :tag "Only in completely white lines" white)
582 (const :tag "Before first char in a line" whitestart)
583 (const :tag "Everywhere except in headlines" t)
584 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
587 (defcustom org-cycle-separator-lines 2
588 "Number of empty lines needed to keep an empty line between collapsed trees.
589 If you leave an empty line between the end of a subtree and the following
590 headline, this empty line is hidden when the subtree is folded.
591 Org-mode will leave (exactly) one empty line visible if the number of
592 empty lines is equal or larger to the number given in this variable.
593 So the default 2 means, at least 2 empty lines after the end of a subtree
594 are needed to produce free space between a collapsed subtree and the
595 following headline.
597 Special case: when 0, never leave empty lines in collapsed view."
598 :group 'org-cycle
599 :type 'integer)
600 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
602 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
603 org-cycle-hide-drawers
604 org-cycle-show-empty-lines
605 org-optimize-window-after-visibility-change)
606 "Hook that is run after `org-cycle' has changed the buffer visibility.
607 The function(s) in this hook must accept a single argument which indicates
608 the new state that was set by the most recent `org-cycle' command. The
609 argument is a symbol. After a global state change, it can have the values
610 `overview', `content', or `all'. After a local state change, it can have
611 the values `folded', `children', or `subtree'."
612 :group 'org-cycle
613 :type 'hook)
615 (defgroup org-edit-structure nil
616 "Options concerning structure editing in Org-mode."
617 :tag "Org Edit Structure"
618 :group 'org-structure)
620 (defcustom org-odd-levels-only nil
621 "Non-nil means, skip even levels and only use odd levels for the outline.
622 This has the effect that two stars are being added/taken away in
623 promotion/demotion commands. It also influences how levels are
624 handled by the exporters.
625 Changing it requires restart of `font-lock-mode' to become effective
626 for fontification also in regions already fontified.
627 You may also set this on a per-file basis by adding one of the following
628 lines to the buffer:
630 #+STARTUP: odd
631 #+STARTUP: oddeven"
632 :group 'org-edit-structure
633 :group 'org-font-lock
634 :type 'boolean)
636 (defcustom org-adapt-indentation t
637 "Non-nil means, adapt indentation when promoting and demoting.
638 When this is set and the *entire* text in an entry is indented, the
639 indentation is increased by one space in a demotion command, and
640 decreased by one in a promotion command. If any line in the entry
641 body starts at column 0, indentation is not changed at all."
642 :group 'org-edit-structure
643 :type 'boolean)
645 (defcustom org-special-ctrl-a/e nil
646 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
647 When t, `C-a' will bring back the cursor to the beginning of the
648 headline text, i.e. after the stars and after a possible TODO keyword.
649 In an item, this will be the position after the bullet.
650 When the cursor is already at that position, another `C-a' will bring
651 it to the beginning of the line.
652 `C-e' will jump to the end of the headline, ignoring the presence of tags
653 in the headline. A second `C-e' will then jump to the true end of the
654 line, after any tags.
655 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
656 and only a directly following, identical keypress will bring the cursor
657 to the special positions."
658 :group 'org-edit-structure
659 :type '(choice
660 (const :tag "off" nil)
661 (const :tag "after bullet first" t)
662 (const :tag "border first" reversed)))
664 (if (fboundp 'defvaralias)
665 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
667 (defcustom org-special-ctrl-k nil
668 "Non-nil means `C-k' will behave specially in headlines.
669 When nil, `C-k' will call the default `kill-line' command.
670 When t, the following will happen while the cursor is in the headline:
672 - When the cursor is at the beginning of a headline, kill the entire
673 line and possible the folded subtree below the line.
674 - When in the middle of the headline text, kill the headline up to the tags.
675 - When after the headline text, kill the tags."
676 :group 'org-edit-structure
677 :type 'boolean)
679 (defcustom org-yank-folded-subtrees t
680 "Non-nil means, when yanking subtrees, fold them.
681 If the kill is a single subtree, or a sequence of subtrees, i.e. if
682 it starts with a heading and all other headings in it are either children
683 or siblings, then fold all the subtrees. However, do this only if no
684 text after the yank would be swallowed into a folded tree by this action."
685 :group 'org-edit-structure
686 :type 'boolean)
688 (defcustom org-yank-adjusted-subtrees t
689 "Non-nil means, when yanking subtrees, adjust the level.
690 With this setting, `org-paste-subtree' is used to insert the subtree, see
691 this function for details."
692 :group 'org-edit-structure
693 :type 'boolean)
695 (defcustom org-M-RET-may-split-line '((default . t))
696 "Non-nil means, M-RET will split the line at the cursor position.
697 When nil, it will go to the end of the line before making a
698 new line.
699 You may also set this option in a different way for different
700 contexts. Valid contexts are:
702 headline when creating a new headline
703 item when creating a new item
704 table in a table field
705 default the value to be used for all contexts not explicitly
706 customized"
707 :group 'org-structure
708 :group 'org-table
709 :type '(choice
710 (const :tag "Always" t)
711 (const :tag "Never" nil)
712 (repeat :greedy t :tag "Individual contexts"
713 (cons
714 (choice :tag "Context"
715 (const headline)
716 (const item)
717 (const table)
718 (const default))
719 (boolean)))))
722 (defcustom org-insert-heading-respect-content nil
723 "Non-nil means, insert new headings after the current subtree.
724 When nil, the new heading is created directly after the current line.
725 The commands \\[org-insert-heading-respect-content] and
726 \\[org-insert-todo-heading-respect-content] turn this variable on
727 for the duration of the command."
728 :group 'org-structure
729 :type 'boolean)
731 (defcustom org-blank-before-new-entry '((heading . auto)
732 (plain-list-item . auto))
733 "Should `org-insert-heading' leave a blank line before new heading/item?
734 The value is an alist, with `heading' and `plain-list-item' as car,
735 and a boolean flag as cdr."
736 :group 'org-edit-structure
737 :type '(list
738 (cons (const heading)
739 (choice (const :tag "Never" nil)
740 (const :tag "Always" t)
741 (const :tag "Auto" auto)))
742 (cons (const plain-list-item)
743 (choice (const :tag "Never" nil)
744 (const :tag "Always" t)
745 (const :tag "Auto" auto)))))
747 (defcustom org-insert-heading-hook nil
748 "Hook being run after inserting a new heading."
749 :group 'org-edit-structure
750 :type 'hook)
752 (defcustom org-enable-fixed-width-editor t
753 "Non-nil means, lines starting with \":\" are treated as fixed-width.
754 This currently only means, they are never auto-wrapped.
755 When nil, such lines will be treated like ordinary lines.
756 See also the QUOTE keyword."
757 :group 'org-edit-structure
758 :type 'boolean)
760 (defcustom org-edit-src-region-extra nil
761 "Additional regexps to identify regions for editing with `org-edit-src-code'.
762 For examples see the function `org-edit-src-find-region-and-lang'.
763 The regular expression identifying the begin marker should end with a newline,
764 and the regexp marking the end line should start with a newline, to make sure
765 there are kept outside the narrowed region."
766 :group 'org-edit-structure
767 :type '(repeat
768 (list
769 (regexp :tag "begin regexp")
770 (regexp :tag "end regexp")
771 (choice :tag "language"
772 (string :tag "specify")
773 (integer :tag "from match group")
774 (const :tag "from `lang' element")
775 (const :tag "from `style' element")))))
777 (defcustom org-coderef-label-format "(ref:%s)"
778 "The default coderef format.
779 This format string will be used to search for coderef labels in literal
780 examples (EXAMPLE and SRC blocks). The format can be overwritten
781 an individual literal example with the -f option, like
783 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
785 #+END_SRC
787 If you want to use this for HTML export, make sure that the format does
788 not introduce special font-locking, and avoid the HTML special
789 characters `<', `>', and `&'. The reason for this restriction is that
790 the labels are searched for only after htmlize has done its job."
791 :group 'org-edit-structure ; FIXME this is not in the right group
792 :type 'string)
794 (defcustom org-edit-fixed-width-region-mode 'artist-mode
795 "The mode that should be used to edit fixed-width regions.
796 These are the regions where each line starts with a colon."
797 :group 'org-edit-structure
798 :type '(choice
799 (const artist-mode)
800 (const picture-mode)
801 (const fundamental-mode)
802 (function :tag "Other (specify)")))
804 (defcustom org-goto-auto-isearch t
805 "Non-nil means, typing characters in org-goto starts incremental search."
806 :group 'org-edit-structure
807 :type 'boolean)
809 (defgroup org-sparse-trees nil
810 "Options concerning sparse trees in Org-mode."
811 :tag "Org Sparse Trees"
812 :group 'org-structure)
814 (defcustom org-highlight-sparse-tree-matches t
815 "Non-nil means, highlight all matches that define a sparse tree.
816 The highlights will automatically disappear the next time the buffer is
817 changed by an edit command."
818 :group 'org-sparse-trees
819 :type 'boolean)
821 (defcustom org-remove-highlights-with-change t
822 "Non-nil means, any change to the buffer will remove temporary highlights.
823 Such highlights are created by `org-occur' and `org-clock-display'.
824 When nil, `C-c C-c needs to be used to get rid of the highlights.
825 The highlights created by `org-preview-latex-fragment' always need
826 `C-c C-c' to be removed."
827 :group 'org-sparse-trees
828 :group 'org-time
829 :type 'boolean)
832 (defcustom org-occur-hook '(org-first-headline-recenter)
833 "Hook that is run after `org-occur' has constructed a sparse tree.
834 This can be used to recenter the window to show as much of the structure
835 as possible."
836 :group 'org-sparse-trees
837 :type 'hook)
839 (defgroup org-imenu-and-speedbar nil
840 "Options concerning imenu and speedbar in Org-mode."
841 :tag "Org Imenu and Speedbar"
842 :group 'org-structure)
844 (defcustom org-imenu-depth 2
845 "The maximum level for Imenu access to Org-mode headlines.
846 This also applied for speedbar access."
847 :group 'org-imenu-and-speedbar
848 :type 'number)
850 (defgroup org-table nil
851 "Options concerning tables in Org-mode."
852 :tag "Org Table"
853 :group 'org)
855 (defcustom org-enable-table-editor 'optimized
856 "Non-nil means, lines starting with \"|\" are handled by the table editor.
857 When nil, such lines will be treated like ordinary lines.
859 When equal to the symbol `optimized', the table editor will be optimized to
860 do the following:
861 - Automatic overwrite mode in front of whitespace in table fields.
862 This makes the structure of the table stay in tact as long as the edited
863 field does not exceed the column width.
864 - Minimize the number of realigns. Normally, the table is aligned each time
865 TAB or RET are pressed to move to another field. With optimization this
866 happens only if changes to a field might have changed the column width.
867 Optimization requires replacing the functions `self-insert-command',
868 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
869 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
870 very good at guessing when a re-align will be necessary, but you can always
871 force one with \\[org-ctrl-c-ctrl-c].
873 If you would like to use the optimized version in Org-mode, but the
874 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
876 This variable can be used to turn on and off the table editor during a session,
877 but in order to toggle optimization, a restart is required.
879 See also the variable `org-table-auto-blank-field'."
880 :group 'org-table
881 :type '(choice
882 (const :tag "off" nil)
883 (const :tag "on" t)
884 (const :tag "on, optimized" optimized)))
886 (defcustom org-table-tab-recognizes-table.el t
887 "Non-nil means, TAB will automatically notice a table.el table.
888 When it sees such a table, it moves point into it and - if necessary -
889 calls `table-recognize-table'."
890 :group 'org-table-editing
891 :type 'boolean)
893 (defgroup org-link nil
894 "Options concerning links in Org-mode."
895 :tag "Org Link"
896 :group 'org)
898 (defvar org-link-abbrev-alist-local nil
899 "Buffer-local version of `org-link-abbrev-alist', which see.
900 The value of this is taken from the #+LINK lines.")
901 (make-variable-buffer-local 'org-link-abbrev-alist-local)
903 (defcustom org-link-abbrev-alist nil
904 "Alist of link abbreviations.
905 The car of each element is a string, to be replaced at the start of a link.
906 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
907 links in Org-mode buffers can have an optional tag after a double colon, e.g.
909 [[linkkey:tag][description]]
911 If REPLACE is a string, the tag will simply be appended to create the link.
912 If the string contains \"%s\", the tag will be inserted there. Alternatively,
913 the placeholder \"%h\" will cause a url-encoded version of the tag to
914 be inserted at that point (see the function `url-hexify-string').
916 REPLACE may also be a function that will be called with the tag as the
917 only argument to create the link, which should be returned as a string.
919 See the manual for examples."
920 :group 'org-link
921 :type '(repeat
922 (cons
923 (string :tag "Protocol")
924 (choice
925 (string :tag "Format")
926 (function)))))
928 (defcustom org-descriptive-links t
929 "Non-nil means, hide link part and only show description of bracket links.
930 Bracket links are like [[link][description]]. This variable sets the initial
931 state in new org-mode buffers. The setting can then be toggled on a
932 per-buffer basis from the Org->Hyperlinks menu."
933 :group 'org-link
934 :type 'boolean)
936 (defcustom org-link-file-path-type 'adaptive
937 "How the path name in file links should be stored.
938 Valid values are:
940 relative Relative to the current directory, i.e. the directory of the file
941 into which the link is being inserted.
942 absolute Absolute path, if possible with ~ for home directory.
943 noabbrev Absolute path, no abbreviation of home directory.
944 adaptive Use relative path for files in the current directory and sub-
945 directories of it. For other files, use an absolute path."
946 :group 'org-link
947 :type '(choice
948 (const relative)
949 (const absolute)
950 (const noabbrev)
951 (const adaptive)))
953 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
954 "Types of links that should be activated in Org-mode files.
955 This is a list of symbols, each leading to the activation of a certain link
956 type. In principle, it does not hurt to turn on most link types - there may
957 be a small gain when turning off unused link types. The types are:
959 bracket The recommended [[link][description]] or [[link]] links with hiding.
960 angular Links in angular brackets that may contain whitespace like
961 <bbdb:Carsten Dominik>.
962 plain Plain links in normal text, no whitespace, like http://google.com.
963 radio Text that is matched by a radio target, see manual for details.
964 tag Tag settings in a headline (link to tag search).
965 date Time stamps (link to calendar).
966 footnote Footnote labels.
968 Changing this variable requires a restart of Emacs to become effective."
969 :group 'org-link
970 :type '(set :greedy t
971 (const :tag "Double bracket links (new style)" bracket)
972 (const :tag "Angular bracket links (old style)" angular)
973 (const :tag "Plain text links" plain)
974 (const :tag "Radio target matches" radio)
975 (const :tag "Tags" tag)
976 (const :tag "Timestamps" date)
977 (const :tag "Footnotes" footnote)))
979 (defcustom org-make-link-description-function nil
980 "Function to use to generate link descriptions from links. If
981 nil the link location will be used. This function must take two
982 parameters; the first is the link and the second the description
983 org-insert-link has generated, and should return the description
984 to use."
985 :group 'org-link
986 :type 'function)
988 (defgroup org-link-store nil
989 "Options concerning storing links in Org-mode."
990 :tag "Org Store Link"
991 :group 'org-link)
993 (defcustom org-email-link-description-format "Email %c: %.30s"
994 "Format of the description part of a link to an email or usenet message.
995 The following %-escapes will be replaced by corresponding information:
997 %F full \"From\" field
998 %f name, taken from \"From\" field, address if no name
999 %T full \"To\" field
1000 %t first name in \"To\" field, address if no name
1001 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1002 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1003 %s subject
1004 %m message-id.
1006 You may use normal field width specification between the % and the letter.
1007 This is for example useful to limit the length of the subject.
1009 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1010 :group 'org-link-store
1011 :type 'string)
1013 (defcustom org-from-is-user-regexp
1014 (let (r1 r2)
1015 (when (and user-mail-address (not (string= user-mail-address "")))
1016 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1017 (when (and user-full-name (not (string= user-full-name "")))
1018 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1019 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1020 "Regexp matched against the \"From:\" header of an email or usenet message.
1021 It should match if the message is from the user him/herself."
1022 :group 'org-link-store
1023 :type 'regexp)
1025 (defcustom org-link-to-org-use-id 'create-if-interactive
1026 "Non-nil means, storing a link to an Org file will use entry IDs.
1028 Note that before this variable is even considered, org-id must be loaded,
1029 to please customize `org-modules' and turn it on.
1031 The variable can have the following values:
1033 t Create an ID if needed to make a link to the current entry.
1035 create-if-interactive
1036 If `org-store-link' is called directly (interactively, as a user
1037 command), do create an ID to support the link. But when doing the
1038 job for remember, only use the ID if it already exists. The
1039 purpose of this setting is to avoid proliferation of unwanted
1040 IDs, just because you happen to be in an Org file when you
1041 call `org-remember' that automatically and preemptively
1042 creates a link. If you do want to get an ID link in a remember
1043 template to an entry not having an ID, create it first by
1044 explicitly creating a link to it, using `C-c C-l' first.
1046 use-existing
1047 Use existing ID, do not create one.
1049 nil Never use an ID to make a link, instead link using a text search for
1050 the headline text."
1051 :group 'org-link-store
1052 :type '(choice
1053 (const :tag "Create ID to make link" t)
1054 (const :tag "Create if string link interactively"
1055 'create-if-interactive)
1056 (const :tag "Only use existing" 'use-existing)
1057 (const :tag "Do not use ID to create link" nil)))
1059 (defcustom org-context-in-file-links t
1060 "Non-nil means, file links from `org-store-link' contain context.
1061 A search string will be added to the file name with :: as separator and
1062 used to find the context when the link is activated by the command
1063 `org-open-at-point'.
1064 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1065 negates this setting for the duration of the command."
1066 :group 'org-link-store
1067 :type 'boolean)
1069 (defcustom org-keep-stored-link-after-insertion nil
1070 "Non-nil means, keep link in list for entire session.
1072 The command `org-store-link' adds a link pointing to the current
1073 location to an internal list. These links accumulate during a session.
1074 The command `org-insert-link' can be used to insert links into any
1075 Org-mode file (offering completion for all stored links). When this
1076 option is nil, every link which has been inserted once using \\[org-insert-link]
1077 will be removed from the list, to make completing the unused links
1078 more efficient."
1079 :group 'org-link-store
1080 :type 'boolean)
1082 (defgroup org-link-follow nil
1083 "Options concerning following links in Org-mode."
1084 :tag "Org Follow Link"
1085 :group 'org-link)
1087 (defcustom org-link-translation-function nil
1088 "Function to translate links with different syntax to Org syntax.
1089 This can be used to translate links created for example by the Planner
1090 or emacs-wiki packages to Org syntax.
1091 The function must accept two parameters, a TYPE containing the link
1092 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1093 which is everything after the link protocol. It should return a cons
1094 with possibly modified values of type and path.
1095 Org contains a function for this, so if you set this variable to
1096 `org-translate-link-from-planner', you should be able follow many
1097 links created by planner."
1098 :group 'org-link-follow
1099 :type 'function)
1101 (defcustom org-follow-link-hook nil
1102 "Hook that is run after a link has been followed."
1103 :group 'org-link-follow
1104 :type 'hook)
1106 (defcustom org-tab-follows-link nil
1107 "Non-nil means, on links TAB will follow the link.
1108 Needs to be set before org.el is loaded."
1109 :group 'org-link-follow
1110 :type 'boolean)
1112 (defcustom org-return-follows-link nil
1113 "Non-nil means, on links RET will follow the link.
1114 Needs to be set before org.el is loaded."
1115 :group 'org-link-follow
1116 :type 'boolean)
1118 (defcustom org-mouse-1-follows-link
1119 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1120 "Non-nil means, mouse-1 on a link will follow the link.
1121 A longer mouse click will still set point. Does not work on XEmacs.
1122 Needs to be set before org.el is loaded."
1123 :group 'org-link-follow
1124 :type 'boolean)
1126 (defcustom org-mark-ring-length 4
1127 "Number of different positions to be recorded in the ring
1128 Changing this requires a restart of Emacs to work correctly."
1129 :group 'org-link-follow
1130 :type 'integer)
1132 (defcustom org-link-frame-setup
1133 '((vm . vm-visit-folder-other-frame)
1134 (gnus . gnus-other-frame)
1135 (file . find-file-other-window))
1136 "Setup the frame configuration for following links.
1137 When following a link with Emacs, it may often be useful to display
1138 this link in another window or frame. This variable can be used to
1139 set this up for the different types of links.
1140 For VM, use any of
1141 `vm-visit-folder'
1142 `vm-visit-folder-other-frame'
1143 For Gnus, use any of
1144 `gnus'
1145 `gnus-other-frame'
1146 `org-gnus-no-new-news'
1147 For FILE, use any of
1148 `find-file'
1149 `find-file-other-window'
1150 `find-file-other-frame'
1151 For the calendar, use the variable `calendar-setup'.
1152 For BBDB, it is currently only possible to display the matches in
1153 another window."
1154 :group 'org-link-follow
1155 :type '(list
1156 (cons (const vm)
1157 (choice
1158 (const vm-visit-folder)
1159 (const vm-visit-folder-other-window)
1160 (const vm-visit-folder-other-frame)))
1161 (cons (const gnus)
1162 (choice
1163 (const gnus)
1164 (const gnus-other-frame)
1165 (const org-gnus-no-new-news)))
1166 (cons (const file)
1167 (choice
1168 (const find-file)
1169 (const find-file-other-window)
1170 (const find-file-other-frame)))))
1172 (defcustom org-display-internal-link-with-indirect-buffer nil
1173 "Non-nil means, use indirect buffer to display infile links.
1174 Activating internal links (from one location in a file to another location
1175 in the same file) normally just jumps to the location. When the link is
1176 activated with a C-u prefix (or with mouse-3), the link is displayed in
1177 another window. When this option is set, the other window actually displays
1178 an indirect buffer clone of the current buffer, to avoid any visibility
1179 changes to the current buffer."
1180 :group 'org-link-follow
1181 :type 'boolean)
1183 (defcustom org-open-non-existing-files nil
1184 "Non-nil means, `org-open-file' will open non-existing files.
1185 When nil, an error will be generated."
1186 :group 'org-link-follow
1187 :type 'boolean)
1189 (defcustom org-open-directory-means-index-dot-org nil
1190 "Non-nil means, a link to a directory really means to index.org.
1191 When nil, following a directory link will run dired or open a finder/explorer
1192 window on that directory."
1193 :group 'org-link-follow
1194 :type 'boolean)
1196 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1197 "Function and arguments to call for following mailto links.
1198 This is a list with the first element being a lisp function, and the
1199 remaining elements being arguments to the function. In string arguments,
1200 %a will be replaced by the address, and %s will be replaced by the subject
1201 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1202 :group 'org-link-follow
1203 :type '(choice
1204 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1205 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1206 (const :tag "message-mail" (message-mail "%a" "%s"))
1207 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1209 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1210 "Non-nil means, ask for confirmation before executing shell links.
1211 Shell links can be dangerous: just think about a link
1213 [[shell:rm -rf ~/*][Google Search]]
1215 This link would show up in your Org-mode document as \"Google Search\",
1216 but really it would remove your entire home directory.
1217 Therefore we advise against setting this variable to nil.
1218 Just change it to `y-or-n-p' of you want to confirm with a
1219 single keystroke rather than having to type \"yes\"."
1220 :group 'org-link-follow
1221 :type '(choice
1222 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1223 (const :tag "with y-or-n (faster)" y-or-n-p)
1224 (const :tag "no confirmation (dangerous)" nil)))
1226 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1227 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1228 Elisp links can be dangerous: just think about a link
1230 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1232 This link would show up in your Org-mode document as \"Google Search\",
1233 but really it would remove your entire home directory.
1234 Therefore we advise against setting this variable to nil.
1235 Just change it to `y-or-n-p' of you want to confirm with a
1236 single keystroke rather than having to type \"yes\"."
1237 :group 'org-link-follow
1238 :type '(choice
1239 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1240 (const :tag "with y-or-n (faster)" y-or-n-p)
1241 (const :tag "no confirmation (dangerous)" nil)))
1243 (defconst org-file-apps-defaults-gnu
1244 '((remote . emacs)
1245 (system . mailcap)
1246 (t . mailcap))
1247 "Default file applications on a UNIX or GNU/Linux system.
1248 See `org-file-apps'.")
1250 (defconst org-file-apps-defaults-macosx
1251 '((remote . emacs)
1252 (t . "open %s")
1253 (system . "open %s")
1254 ("ps.gz" . "gv %s")
1255 ("eps.gz" . "gv %s")
1256 ("dvi" . "xdvi %s")
1257 ("fig" . "xfig %s"))
1258 "Default file applications on a MacOS X system.
1259 The system \"open\" is known as a default, but we use X11 applications
1260 for some files for which the OS does not have a good default.
1261 See `org-file-apps'.")
1263 (defconst org-file-apps-defaults-windowsnt
1264 (list
1265 '(remote . emacs)
1266 (cons t
1267 (list (if (featurep 'xemacs)
1268 'mswindows-shell-execute
1269 'w32-shell-execute)
1270 "open" 'file))
1271 (cons 'system
1272 (list (if (featurep 'xemacs)
1273 'mswindows-shell-execute
1274 'w32-shell-execute)
1275 "open" 'file)))
1276 "Default file applications on a Windows NT system.
1277 The system \"open\" is used for most files.
1278 See `org-file-apps'.")
1280 (defcustom org-file-apps
1282 (auto-mode . emacs)
1283 ("\\.x?html?\\'" . default)
1284 ("\\.pdf\\'" . default)
1286 "External applications for opening `file:path' items in a document.
1287 Org-mode uses system defaults for different file types, but
1288 you can use this variable to set the application for a given file
1289 extension. The entries in this list are cons cells where the car identifies
1290 files and the cdr the corresponding command. Possible values for the
1291 file identifier are
1292 \"regex\" Regular expression matched against the file name. For backward
1293 compatibility, this can also be a string with only alphanumeric
1294 characters, which is then interpreted as an extension.
1295 `directory' Matches a directory
1296 `remote' Matches a remote file, accessible through tramp or efs.
1297 Remote files most likely should be visited through Emacs
1298 because external applications cannot handle such paths.
1299 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1300 so all files Emacs knows how to handle. Using this with
1301 command `emacs' will open most files in Emacs. Beware that this
1302 will also open html files inside Emacs, unless you add
1303 (\"html\" . default) to the list as well.
1304 t Default for files not matched by any of the other options.
1305 `system' The system command to open files, like `open' on Windows
1306 and Mac OS X, and mailcap under GNU/Linux. This is the command
1307 that will be selected if you call `C-c C-o' with a double
1308 `C-u C-u' prefix.
1310 Possible values for the command are:
1311 `emacs' The file will be visited by the current Emacs process.
1312 `default' Use the default application for this file type, which is the
1313 association for t in the list, most likely in the system-specific
1314 part.
1315 This can be used to overrule an unwanted setting in the
1316 system-specific variable.
1317 `system' Use the system command for opening files, like \"open\".
1318 This command is specified by the entry whose car is `system'.
1319 Most likely, the system-specific version of this variable
1320 does define this command, but you can overrule/replace it
1321 here.
1322 string A command to be executed by a shell; %s will be replaced
1323 by the path to the file.
1324 sexp A Lisp form which will be evaluated. The file path will
1325 be available in the Lisp variable `file'.
1326 For more examples, see the system specific constants
1327 `org-file-apps-defaults-macosx'
1328 `org-file-apps-defaults-windowsnt'
1329 `org-file-apps-defaults-gnu'."
1330 :group 'org-link-follow
1331 :type '(repeat
1332 (cons (choice :value ""
1333 (string :tag "Extension")
1334 (const :tag "System command to open files" system)
1335 (const :tag "Default for unrecognized files" t)
1336 (const :tag "Remote file" remote)
1337 (const :tag "Links to a directory" directory)
1338 (const :tag "Any files that have Emacs modes"
1339 auto-mode))
1340 (choice :value ""
1341 (const :tag "Visit with Emacs" emacs)
1342 (const :tag "Use default" default)
1343 (const :tag "Use the system command" system)
1344 (string :tag "Command")
1345 (sexp :tag "Lisp form")))))
1347 (defgroup org-refile nil
1348 "Options concerning refiling entries in Org-mode."
1349 :tag "Org Refile"
1350 :group 'org)
1352 (defcustom org-directory "~/org"
1353 "Directory with org files.
1354 This directory will be used as default to prompt for org files.
1355 Used by the hooks for remember.el."
1356 :group 'org-refile
1357 :group 'org-remember
1358 :type 'directory)
1360 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1361 "Default target for storing notes.
1362 Used by the hooks for remember.el. This can be a string, or nil to mean
1363 the value of `remember-data-file'.
1364 You can set this on a per-template basis with the variable
1365 `org-remember-templates'."
1366 :group 'org-refile
1367 :group 'org-remember
1368 :type '(choice
1369 (const :tag "Default from remember-data-file" nil)
1370 file))
1372 (defcustom org-goto-interface 'outline
1373 "The default interface to be used for `org-goto'.
1374 Allowed values are:
1375 outline The interface shows an outline of the relevant file
1376 and the correct heading is found by moving through
1377 the outline or by searching with incremental search.
1378 outline-path-completion Headlines in the current buffer are offered via
1379 completion. This is the interface also used by
1380 the refile command."
1381 :group 'org-refile
1382 :type '(choice
1383 (const :tag "Outline" outline)
1384 (const :tag "Outline-path-completion" outline-path-completion)))
1386 (defcustom org-goto-max-level 5
1387 "Maximum level to be considered when running org-goto with refile interface."
1388 :group 'org-refile
1389 :type 'number)
1391 (defcustom org-reverse-note-order nil
1392 "Non-nil means, store new notes at the beginning of a file or entry.
1393 When nil, new notes will be filed to the end of a file or entry.
1394 This can also be a list with cons cells of regular expressions that
1395 are matched against file names, and values."
1396 :group 'org-remember
1397 :group 'org-refile
1398 :type '(choice
1399 (const :tag "Reverse always" t)
1400 (const :tag "Reverse never" nil)
1401 (repeat :tag "By file name regexp"
1402 (cons regexp boolean))))
1404 (defcustom org-refile-targets nil
1405 "Targets for refiling entries with \\[org-refile].
1406 This is list of cons cells. Each cell contains:
1407 - a specification of the files to be considered, either a list of files,
1408 or a symbol whose function or variable value will be used to retrieve
1409 a file name or a list of file names. If you use `org-agenda-files' for
1410 that, all agenda files will be scanned for targets. Nil means, consider
1411 headings in the current buffer.
1412 - A specification of how to select find candidate refile targets. This
1413 may be any of
1414 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1415 This tag has to be present in all target headlines, inheritance will
1416 not be considered.
1417 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1418 todo keyword.
1419 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1420 headlines that are refiling targets.
1421 - a cons cell (:level . N). Any headline of level N is considered a target.
1422 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1424 When this variable is nil, all top-level headlines in the current buffer
1425 are used, equivalent to the value `((nil . (:level . 1))'."
1426 :group 'org-refile
1427 :type '(repeat
1428 (cons
1429 (choice :value org-agenda-files
1430 (const :tag "All agenda files" org-agenda-files)
1431 (const :tag "Current buffer" nil)
1432 (function) (variable) (file))
1433 (choice :tag "Identify target headline by"
1434 (cons :tag "Specific tag" (const :value :tag) (string))
1435 (cons :tag "TODO keyword" (const :value :todo) (string))
1436 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1437 (cons :tag "Level number" (const :value :level) (integer))
1438 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1440 (defcustom org-refile-use-outline-path nil
1441 "Non-nil means, provide refile targets as paths.
1442 So a level 3 headline will be available as level1/level2/level3.
1443 When the value is `file', also include the file name (without directory)
1444 into the path. When `full-file-path', include the full file path."
1445 :group 'org-refile
1446 :type '(choice
1447 (const :tag "Not" nil)
1448 (const :tag "Yes" t)
1449 (const :tag "Start with file name" file)
1450 (const :tag "Start with full file path" full-file-path)))
1452 (defcustom org-outline-path-complete-in-steps t
1453 "Non-nil means, complete the outline path in hierarchical steps.
1454 When Org-mode uses the refile interface to select an outline path
1455 \(see variable `org-refile-use-outline-path'), the completion of
1456 the path can be done is a single go, or if can be done in steps down
1457 the headline hierarchy. Going in steps is probably the best if you
1458 do not use a special completion package like `ido' or `icicles'.
1459 However, when using these packages, going in one step can be very
1460 fast, while still showing the whole path to the entry."
1461 :group 'org-refile
1462 :type 'boolean)
1464 (defgroup org-todo nil
1465 "Options concerning TODO items in Org-mode."
1466 :tag "Org TODO"
1467 :group 'org)
1469 (defgroup org-progress nil
1470 "Options concerning Progress logging in Org-mode."
1471 :tag "Org Progress"
1472 :group 'org-time)
1474 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1475 "List of TODO entry keyword sequences and their interpretation.
1476 \\<org-mode-map>This is a list of sequences.
1478 Each sequence starts with a symbol, either `sequence' or `type',
1479 indicating if the keywords should be interpreted as a sequence of
1480 action steps, or as different types of TODO items. The first
1481 keywords are states requiring action - these states will select a headline
1482 for inclusion into the global TODO list Org-mode produces. If one of
1483 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1484 signify that no further action is necessary. If \"|\" is not found,
1485 the last keyword is treated as the only DONE state of the sequence.
1487 The command \\[org-todo] cycles an entry through these states, and one
1488 additional state where no keyword is present. For details about this
1489 cycling, see the manual.
1491 TODO keywords and interpretation can also be set on a per-file basis with
1492 the special #+SEQ_TODO and #+TYP_TODO lines.
1494 Each keyword can optionally specify a character for fast state selection
1495 \(in combination with the variable `org-use-fast-todo-selection')
1496 and specifiers for state change logging, using the same syntax
1497 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1498 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1499 indicates to record a time stamp each time this state is selected.
1501 Each keyword may also specify if a timestamp or a note should be
1502 recorded when entering or leaving the state, by adding additional
1503 characters in the parenthesis after the keyword. This looks like this:
1504 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1505 record only the time of the state change. With X and Y being either
1506 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1507 Y when leaving the state if and only if the *target* state does not
1508 define X. You may omit any of the fast-selection key or X or /Y,
1509 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1511 For backward compatibility, this variable may also be just a list
1512 of keywords - in this case the interpretation (sequence or type) will be
1513 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1514 :group 'org-todo
1515 :group 'org-keywords
1516 :type '(choice
1517 (repeat :tag "Old syntax, just keywords"
1518 (string :tag "Keyword"))
1519 (repeat :tag "New syntax"
1520 (cons
1521 (choice
1522 :tag "Interpretation"
1523 (const :tag "Sequence (cycling hits every state)" sequence)
1524 (const :tag "Type (cycling directly to DONE)" type))
1525 (repeat
1526 (string :tag "Keyword"))))))
1528 (defvar org-todo-keywords-1 nil
1529 "All TODO and DONE keywords active in a buffer.")
1530 (make-variable-buffer-local 'org-todo-keywords-1)
1531 (defvar org-todo-keywords-for-agenda nil)
1532 (defvar org-done-keywords-for-agenda nil)
1533 (defvar org-todo-keyword-alist-for-agenda nil)
1534 (defvar org-tag-alist-for-agenda nil)
1535 (defvar org-agenda-contributing-files nil)
1536 (defvar org-not-done-keywords nil)
1537 (make-variable-buffer-local 'org-not-done-keywords)
1538 (defvar org-done-keywords nil)
1539 (make-variable-buffer-local 'org-done-keywords)
1540 (defvar org-todo-heads nil)
1541 (make-variable-buffer-local 'org-todo-heads)
1542 (defvar org-todo-sets nil)
1543 (make-variable-buffer-local 'org-todo-sets)
1544 (defvar org-todo-log-states nil)
1545 (make-variable-buffer-local 'org-todo-log-states)
1546 (defvar org-todo-kwd-alist nil)
1547 (make-variable-buffer-local 'org-todo-kwd-alist)
1548 (defvar org-todo-key-alist nil)
1549 (make-variable-buffer-local 'org-todo-key-alist)
1550 (defvar org-todo-key-trigger nil)
1551 (make-variable-buffer-local 'org-todo-key-trigger)
1553 (defcustom org-todo-interpretation 'sequence
1554 "Controls how TODO keywords are interpreted.
1555 This variable is in principle obsolete and is only used for
1556 backward compatibility, if the interpretation of todo keywords is
1557 not given already in `org-todo-keywords'. See that variable for
1558 more information."
1559 :group 'org-todo
1560 :group 'org-keywords
1561 :type '(choice (const sequence)
1562 (const type)))
1564 (defcustom org-use-fast-todo-selection 'prefix
1565 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1566 This variable describes if and under what circumstances the cycling
1567 mechanism for TODO keywords will be replaced by a single-key, direct
1568 selection scheme.
1570 When nil, fast selection is never used.
1572 When the symbol `prefix', it will be used when `org-todo' is called with
1573 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1574 in an agenda buffer.
1576 When t, fast selection is used by default. In this case, the prefix
1577 argument forces cycling instead.
1579 In all cases, the special interface is only used if access keys have actually
1580 been assigned by the user, i.e. if keywords in the configuration are followed
1581 by a letter in parenthesis, like TODO(t)."
1582 :group 'org-todo
1583 :type '(choice
1584 (const :tag "Never" nil)
1585 (const :tag "By default" t)
1586 (const :tag "Only with C-u C-c C-t" prefix)))
1588 (defcustom org-provide-todo-statistics t
1589 "Non-nil means, update todo statistics after insert and toggle.
1590 When this is set, todo statistics is updated in the parent of the current
1591 entry each time a todo state is changed."
1592 :group 'org-todo
1593 :type 'boolean)
1595 (defcustom org-after-todo-state-change-hook nil
1596 "Hook which is run after the state of a TODO item was changed.
1597 The new state (a string with a TODO keyword, or nil) is available in the
1598 Lisp variable `state'."
1599 :group 'org-todo
1600 :type 'hook)
1602 (defcustom org-todo-state-tags-triggers nil
1603 "Tag changes that should be triggered by TODO state changes.
1604 This is a list. Each entry is
1606 (state-change (tag . flag) .......)
1608 State-change can be a string with a state, and empty string to indicate the
1609 state that has no TODO keyword, or it can be one of the symbols `todo'
1610 or `done', meaning any not-done or done state, respectively."
1611 :group 'org-todo
1612 :group 'org-tags
1613 :type '(repeat
1614 (cons (choice :tag "When changing to"
1615 (const :tag "Not-done state" todo)
1616 (const :tag "Done state" done)
1617 (string :tag "State"))
1618 (repeat
1619 (cons :tag "Tag action"
1620 (string :tag "Tag")
1621 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1623 (defcustom org-log-done nil
1624 "Information to record when a task moves to the DONE state.
1626 Possible values are:
1628 nil Don't add anything, just change the keyword
1629 time Add a time stamp to the task
1630 note Prompt a closing note and add it with template `org-log-note-headings'
1632 This option can also be set with on a per-file-basis with
1634 #+STARTUP: nologdone
1635 #+STARTUP: logdone
1636 #+STARTUP: lognotedone
1638 You can have local logging settings for a subtree by setting the LOGGING
1639 property to one or more of these keywords."
1640 :group 'org-todo
1641 :group 'org-progress
1642 :type '(choice
1643 (const :tag "No logging" nil)
1644 (const :tag "Record CLOSED timestamp" time)
1645 (const :tag "Record CLOSED timestamp with closing note." note)))
1647 ;; Normalize old uses of org-log-done.
1648 (cond
1649 ((eq org-log-done t) (setq org-log-done 'time))
1650 ((and (listp org-log-done) (memq 'done org-log-done))
1651 (setq org-log-done 'note)))
1653 (defcustom org-log-note-clock-out nil
1654 "Non-nil means, record a note when clocking out of an item.
1655 This can also be configured on a per-file basis by adding one of
1656 the following lines anywhere in the buffer:
1658 #+STARTUP: lognoteclock-out
1659 #+STARTUP: nolognoteclock-out"
1660 :group 'org-todo
1661 :group 'org-progress
1662 :type 'boolean)
1664 (defcustom org-log-done-with-time t
1665 "Non-nil means, the CLOSED time stamp will contain date and time.
1666 When nil, only the date will be recorded."
1667 :group 'org-progress
1668 :type 'boolean)
1670 (defcustom org-log-note-headings
1671 '((done . "CLOSING NOTE %t")
1672 (state . "State %-12s %t")
1673 (note . "Note taken on %t")
1674 (clock-out . ""))
1675 "Headings for notes added to entries.
1676 The value is an alist, with the car being a symbol indicating the note
1677 context, and the cdr is the heading to be used. The heading may also be the
1678 empty string.
1679 %t in the heading will be replaced by a time stamp.
1680 %s will be replaced by the new TODO state, in double quotes.
1681 %u will be replaced by the user name.
1682 %U will be replaced by the full user name."
1683 :group 'org-todo
1684 :group 'org-progress
1685 :type '(list :greedy t
1686 (cons (const :tag "Heading when closing an item" done) string)
1687 (cons (const :tag
1688 "Heading when changing todo state (todo sequence only)"
1689 state) string)
1690 (cons (const :tag "Heading when just taking a note" note) string)
1691 (cons (const :tag "Heading when clocking out" clock-out) string)))
1693 (unless (assq 'note org-log-note-headings)
1694 (push '(note . "%t") org-log-note-headings))
1696 (defcustom org-log-state-notes-insert-after-drawers nil
1697 "Non-nil means, insert state change notes after any drawers in entry.
1698 Only the drawers that *immediately* follow the headline and the
1699 deadline/scheduled line are skipped.
1700 When nil, insert notes right after the heading and perhaps the line
1701 with deadline/scheduling if present."
1702 :group 'org-todo
1703 :group 'org-progress
1704 :type 'boolean)
1706 (defcustom org-log-states-order-reversed t
1707 "Non-nil means, the latest state change note will be directly after heading.
1708 When nil, the notes will be orderer according to time."
1709 :group 'org-todo
1710 :group 'org-progress
1711 :type 'boolean)
1713 (defcustom org-log-repeat 'time
1714 "Non-nil means, record moving through the DONE state when triggering repeat.
1715 An auto-repeating tasks is immediately switched back to TODO when marked
1716 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1717 the TODO keyword definition, or recording a closing note by setting
1718 `org-log-done', there will be no record of the task moving through DONE.
1719 This variable forces taking a note anyway. Possible values are:
1721 nil Don't force a record
1722 time Record a time stamp
1723 note Record a note
1725 This option can also be set with on a per-file-basis with
1727 #+STARTUP: logrepeat
1728 #+STARTUP: lognoterepeat
1729 #+STARTUP: nologrepeat
1731 You can have local logging settings for a subtree by setting the LOGGING
1732 property to one or more of these keywords."
1733 :group 'org-todo
1734 :group 'org-progress
1735 :type '(choice
1736 (const :tag "Don't force a record" nil)
1737 (const :tag "Force recording the DONE state" time)
1738 (const :tag "Force recording a note with the DONE state" note)))
1741 (defgroup org-priorities nil
1742 "Priorities in Org-mode."
1743 :tag "Org Priorities"
1744 :group 'org-todo)
1746 (defcustom org-highest-priority ?A
1747 "The highest priority of TODO items. A character like ?A, ?B etc.
1748 Must have a smaller ASCII number than `org-lowest-priority'."
1749 :group 'org-priorities
1750 :type 'character)
1752 (defcustom org-lowest-priority ?C
1753 "The lowest priority of TODO items. A character like ?A, ?B etc.
1754 Must have a larger ASCII number than `org-highest-priority'."
1755 :group 'org-priorities
1756 :type 'character)
1758 (defcustom org-default-priority ?B
1759 "The default priority of TODO items.
1760 This is the priority an item get if no explicit priority is given."
1761 :group 'org-priorities
1762 :type 'character)
1764 (defcustom org-priority-start-cycle-with-default t
1765 "Non-nil means, start with default priority when starting to cycle.
1766 When this is nil, the first step in the cycle will be (depending on the
1767 command used) one higher or lower that the default priority."
1768 :group 'org-priorities
1769 :type 'boolean)
1771 (defgroup org-time nil
1772 "Options concerning time stamps and deadlines in Org-mode."
1773 :tag "Org Time"
1774 :group 'org)
1776 (defcustom org-insert-labeled-timestamps-at-point nil
1777 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1778 When nil, these labeled time stamps are forces into the second line of an
1779 entry, just after the headline. When scheduling from the global TODO list,
1780 the time stamp will always be forced into the second line."
1781 :group 'org-time
1782 :type 'boolean)
1784 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1785 "Formats for `format-time-string' which are used for time stamps.
1786 It is not recommended to change this constant.")
1788 (defcustom org-time-stamp-rounding-minutes '(0 5)
1789 "Number of minutes to round time stamps to.
1790 These are two values, the first applies when first creating a time stamp.
1791 The second applies when changing it with the commands `S-up' and `S-down'.
1792 When changing the time stamp, this means that it will change in steps
1793 of N minutes, as given by the second value.
1795 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1796 numbers should be factors of 60, so for example 5, 10, 15.
1798 When this is larger than 1, you can still force an exact time-stamp by using
1799 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1800 and by using a prefix arg to `S-up/down' to specify the exact number
1801 of minutes to shift."
1802 :group 'org-time
1803 :get '(lambda (var) ; Make sure all entries have 5 elements
1804 (if (integerp (default-value var))
1805 (list (default-value var) 5)
1806 (default-value var)))
1807 :type '(list
1808 (integer :tag "when inserting times")
1809 (integer :tag "when modifying times")))
1811 ;; Normalize old customizations of this variable.
1812 (when (integerp org-time-stamp-rounding-minutes)
1813 (setq org-time-stamp-rounding-minutes
1814 (list org-time-stamp-rounding-minutes
1815 org-time-stamp-rounding-minutes)))
1817 (defcustom org-display-custom-times nil
1818 "Non-nil means, overlay custom formats over all time stamps.
1819 The formats are defined through the variable `org-time-stamp-custom-formats'.
1820 To turn this on on a per-file basis, insert anywhere in the file:
1821 #+STARTUP: customtime"
1822 :group 'org-time
1823 :set 'set-default
1824 :type 'sexp)
1825 (make-variable-buffer-local 'org-display-custom-times)
1827 (defcustom org-time-stamp-custom-formats
1828 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1829 "Custom formats for time stamps. See `format-time-string' for the syntax.
1830 These are overlayed over the default ISO format if the variable
1831 `org-display-custom-times' is set. Time like %H:%M should be at the
1832 end of the second format."
1833 :group 'org-time
1834 :type 'sexp)
1836 (defun org-time-stamp-format (&optional long inactive)
1837 "Get the right format for a time string."
1838 (let ((f (if long (cdr org-time-stamp-formats)
1839 (car org-time-stamp-formats))))
1840 (if inactive
1841 (concat "[" (substring f 1 -1) "]")
1842 f)))
1844 (defcustom org-time-clocksum-format "%d:%02d"
1845 "The format string used when creating CLOCKSUM lines, or when
1846 org-mode generates a time duration."
1847 :group 'org-time
1848 :type 'string)
1850 (defcustom org-deadline-warning-days 14
1851 "No. of days before expiration during which a deadline becomes active.
1852 This variable governs the display in sparse trees and in the agenda.
1853 When 0 or negative, it means use this number (the absolute value of it)
1854 even if a deadline has a different individual lead time specified."
1855 :group 'org-time
1856 :group 'org-agenda-daily/weekly
1857 :type 'number)
1859 (defcustom org-read-date-prefer-future t
1860 "Non-nil means, assume future for incomplete date input from user.
1861 This affects the following situations:
1862 1. The user gives a day, but no month.
1863 For example, if today is the 15th, and you enter \"3\", Org-mode will
1864 read this as the third of *next* month. However, if you enter \"17\",
1865 it will be considered as *this* month.
1866 2. The user gives a month but not a year.
1867 For example, if it is april and you enter \"feb 2\", this will be read
1868 as feb 2, *next* year. \"May 5\", however, will be this year.
1870 Currently this does not work for ISO week specifications.
1872 When this option is nil, the current month and year will always be used
1873 as defaults."
1874 :group 'org-time
1875 :type 'boolean)
1877 (defcustom org-read-date-display-live t
1878 "Non-nil means, display current interpretation of date prompt live.
1879 This display will be in an overlay, in the minibuffer."
1880 :group 'org-time
1881 :type 'boolean)
1883 (defcustom org-read-date-popup-calendar t
1884 "Non-nil means, pop up a calendar when prompting for a date.
1885 In the calendar, the date can be selected with mouse-1. However, the
1886 minibuffer will also be active, and you can simply enter the date as well.
1887 When nil, only the minibuffer will be available."
1888 :group 'org-time
1889 :type 'boolean)
1890 (if (fboundp 'defvaralias)
1891 (defvaralias 'org-popup-calendar-for-date-prompt
1892 'org-read-date-popup-calendar))
1894 (defcustom org-extend-today-until 0
1895 "The hour when your day really ends. Must be an integer.
1896 This has influence for the following applications:
1897 - When switching the agenda to \"today\". It it is still earlier than
1898 the time given here, the day recognized as TODAY is actually yesterday.
1899 - When a date is read from the user and it is still before the time given
1900 here, the current date and time will be assumed to be yesterday, 23:59.
1901 Also, timestamps inserted in remember templates follow this rule.
1903 IMPORTANT: This is a feature whose implementation is and likely will
1904 remain incomplete. Really, it is only here because past midnight seems to
1905 be the favorite working time of John Wiegley :-)"
1906 :group 'org-time
1907 :type 'number)
1909 (defcustom org-edit-timestamp-down-means-later nil
1910 "Non-nil means, S-down will increase the time in a time stamp.
1911 When nil, S-up will increase."
1912 :group 'org-time
1913 :type 'boolean)
1915 (defcustom org-calendar-follow-timestamp-change t
1916 "Non-nil means, make the calendar window follow timestamp changes.
1917 When a timestamp is modified and the calendar window is visible, it will be
1918 moved to the new date."
1919 :group 'org-time
1920 :type 'boolean)
1922 (defgroup org-tags nil
1923 "Options concerning tags in Org-mode."
1924 :tag "Org Tags"
1925 :group 'org)
1927 (defcustom org-tag-alist nil
1928 "List of tags allowed in Org-mode files.
1929 When this list is nil, Org-mode will base TAG input on what is already in the
1930 buffer.
1931 The value of this variable is an alist, the car of each entry must be a
1932 keyword as a string, the cdr may be a character that is used to select
1933 that tag through the fast-tag-selection interface.
1934 See the manual for details."
1935 :group 'org-tags
1936 :type '(repeat
1937 (choice
1938 (cons (string :tag "Tag name")
1939 (character :tag "Access char"))
1940 (const :tag "Start radio group" (:startgroup))
1941 (const :tag "End radio group" (:endgroup)))))
1943 (defvar org-file-tags nil
1944 "List of tags that can be inherited by all entries in the file.
1945 The tags will be inherited if the variable `org-use-tag-inheritance'
1946 says they should be.
1947 This variable is populated from #+TAG lines.")
1949 (defcustom org-use-fast-tag-selection 'auto
1950 "Non-nil means, use fast tag selection scheme.
1951 This is a special interface to select and deselect tags with single keys.
1952 When nil, fast selection is never used.
1953 When the symbol `auto', fast selection is used if and only if selection
1954 characters for tags have been configured, either through the variable
1955 `org-tag-alist' or through a #+TAGS line in the buffer.
1956 When t, fast selection is always used and selection keys are assigned
1957 automatically if necessary."
1958 :group 'org-tags
1959 :type '(choice
1960 (const :tag "Always" t)
1961 (const :tag "Never" nil)
1962 (const :tag "When selection characters are configured" 'auto)))
1964 (defcustom org-fast-tag-selection-single-key nil
1965 "Non-nil means, fast tag selection exits after first change.
1966 When nil, you have to press RET to exit it.
1967 During fast tag selection, you can toggle this flag with `C-c'.
1968 This variable can also have the value `expert'. In this case, the window
1969 displaying the tags menu is not even shown, until you press C-c again."
1970 :group 'org-tags
1971 :type '(choice
1972 (const :tag "No" nil)
1973 (const :tag "Yes" t)
1974 (const :tag "Expert" expert)))
1976 (defvar org-fast-tag-selection-include-todo nil
1977 "Non-nil means, fast tags selection interface will also offer TODO states.
1978 This is an undocumented feature, you should not rely on it.")
1980 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1981 "The column to which tags should be indented in a headline.
1982 If this number is positive, it specifies the column. If it is negative,
1983 it means that the tags should be flushright to that column. For example,
1984 -80 works well for a normal 80 character screen."
1985 :group 'org-tags
1986 :type 'integer)
1988 (defcustom org-auto-align-tags t
1989 "Non-nil means, realign tags after pro/demotion of TODO state change.
1990 These operations change the length of a headline and therefore shift
1991 the tags around. With this options turned on, after each such operation
1992 the tags are again aligned to `org-tags-column'."
1993 :group 'org-tags
1994 :type 'boolean)
1996 (defcustom org-use-tag-inheritance t
1997 "Non-nil means, tags in levels apply also for sublevels.
1998 When nil, only the tags directly given in a specific line apply there.
1999 This may also be a list of tags that should be inherited, or a regexp that
2000 matches tags that should be inherited. Additional control is possible
2001 with the variable `org-tags-exclude-from-inheritance' which gives an
2002 explicit list of tags to be excluded from inheritance., even if the value of
2003 `org-use-tag-inheritance' would select it for inheritance.
2005 If this option is t, a match early-on in a tree can lead to a large
2006 number of matches in the subtree when constructing the agenda or creating
2007 a sparse tree. If you only want to see the first match in a tree during
2008 a search, check out the variable `org-tags-match-list-sublevels'."
2009 :group 'org-tags
2010 :type '(choice
2011 (const :tag "Not" nil)
2012 (const :tag "Always" t)
2013 (repeat :tag "Specific tags" (string :tag "Tag"))
2014 (regexp :tag "Tags matched by regexp")))
2016 (defcustom org-tags-exclude-from-inheritance nil
2017 "List of tags that should never be inherited.
2018 This is a way to exclude a few tags from inheritance. For way to do
2019 the opposite, to actively allow inheritance for selected tags,
2020 see the variable `org-use-tag-inheritance'."
2021 :group 'org-tags
2022 :type '(repeat (string :tag "Tag")))
2024 (defun org-tag-inherit-p (tag)
2025 "Check if TAG is one that should be inherited."
2026 (cond
2027 ((member tag org-tags-exclude-from-inheritance) nil)
2028 ((eq org-use-tag-inheritance t) t)
2029 ((not org-use-tag-inheritance) nil)
2030 ((stringp org-use-tag-inheritance)
2031 (string-match org-use-tag-inheritance tag))
2032 ((listp org-use-tag-inheritance)
2033 (member tag org-use-tag-inheritance))
2034 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2036 (defcustom org-tags-match-list-sublevels t
2037 "Non-nil means list also sublevels of headlines matching tag search.
2038 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2039 the sublevels of a headline matching a tag search often also match
2040 the same search. Listing all of them can create very long lists.
2041 Setting this variable to nil causes subtrees of a match to be skipped.
2042 This option is off by default, because inheritance in on. If you turn
2043 inheritance off, you very likely want to turn this option on.
2045 As a special case, if the tag search is restricted to TODO items, the
2046 value of this variable is ignored and sublevels are always checked, to
2047 make sure all corresponding TODO items find their way into the list.
2049 This variable is semi-obsolete and probably should always be true. It
2050 is better to limit inheritance to certain tags using the variables
2051 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2052 :group 'org-tags
2053 :type 'boolean)
2055 (defvar org-tags-history nil
2056 "History of minibuffer reads for tags.")
2057 (defvar org-last-tags-completion-table nil
2058 "The last used completion table for tags.")
2059 (defvar org-after-tags-change-hook nil
2060 "Hook that is run after the tags in a line have changed.")
2062 (defgroup org-properties nil
2063 "Options concerning properties in Org-mode."
2064 :tag "Org Properties"
2065 :group 'org)
2067 (defcustom org-property-format "%-10s %s"
2068 "How property key/value pairs should be formatted by `indent-line'.
2069 When `indent-line' hits a property definition, it will format the line
2070 according to this format, mainly to make sure that the values are
2071 lined-up with respect to each other."
2072 :group 'org-properties
2073 :type 'string)
2075 (defcustom org-use-property-inheritance nil
2076 "Non-nil means, properties apply also for sublevels.
2078 This setting is chiefly used during property searches. Turning it on can
2079 cause significant overhead when doing a search, which is why it is not
2080 on by default.
2082 When nil, only the properties directly given in the current entry count.
2083 When t, every property is inherited. The value may also be a list of
2084 properties that should have inheritance, or a regular expression matching
2085 properties that should be inherited.
2087 However, note that some special properties use inheritance under special
2088 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2089 and the properties ending in \"_ALL\" when they are used as descriptor
2090 for valid values of a property.
2092 Note for programmers:
2093 When querying an entry with `org-entry-get', you can control if inheritance
2094 should be used. By default, `org-entry-get' looks only at the local
2095 properties. You can request inheritance by setting the inherit argument
2096 to t (to force inheritance) or to `selective' (to respect the setting
2097 in this variable)."
2098 :group 'org-properties
2099 :type '(choice
2100 (const :tag "Not" nil)
2101 (const :tag "Always" t)
2102 (repeat :tag "Specific properties" (string :tag "Property"))
2103 (regexp :tag "Properties matched by regexp")))
2105 (defun org-property-inherit-p (property)
2106 "Check if PROPERTY is one that should be inherited."
2107 (cond
2108 ((eq org-use-property-inheritance t) t)
2109 ((not org-use-property-inheritance) nil)
2110 ((stringp org-use-property-inheritance)
2111 (string-match org-use-property-inheritance property))
2112 ((listp org-use-property-inheritance)
2113 (member property org-use-property-inheritance))
2114 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2116 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2117 "The default column format, if no other format has been defined.
2118 This variable can be set on the per-file basis by inserting a line
2120 #+COLUMNS: %25ITEM ....."
2121 :group 'org-properties
2122 :type 'string)
2124 (defcustom org-columns-ellipses ".."
2125 "The ellipses to be used when a field in column view is truncated.
2126 When this is the empty string, as many characters as possible are shown,
2127 but then there will be no visual indication that the field has been truncated.
2128 When this is a string of length N, the last N characters of a truncated
2129 field are replaced by this string. If the column is narrower than the
2130 ellipses string, only part of the ellipses string will be shown."
2131 :group 'org-properties
2132 :type 'string)
2134 (defcustom org-columns-modify-value-for-display-function nil
2135 "Function that modifies values for display in column view.
2136 For example, it can be used to cut out a certain part from a time stamp.
2137 The function must take 2 arguments:
2139 column-title The title of the column (*not* the property name)
2140 value The value that should be modified.
2142 The function should return the value that should be displayed,
2143 or nil if the normal value should be used."
2144 :group 'org-properties
2145 :type 'function)
2147 (defcustom org-effort-property "Effort"
2148 "The property that is being used to keep track of effort estimates.
2149 Effort estimates given in this property need to have the format H:MM."
2150 :group 'org-properties
2151 :group 'org-progress
2152 :type '(string :tag "Property"))
2154 (defconst org-global-properties-fixed
2155 '(("VISIBILITY_ALL" . "folded children content all"))
2156 "List of property/value pairs that can be inherited by any entry.
2157 These are fixed values, for the preset properties.")
2160 (defcustom org-global-properties nil
2161 "List of property/value pairs that can be inherited by any entry.
2162 You can set buffer-local values for the same purpose in the variable
2163 `org-file-properties' this by adding lines like
2165 #+PROPERTY: NAME VALUE"
2166 :group 'org-properties
2167 :type '(repeat
2168 (cons (string :tag "Property")
2169 (string :tag "Value"))))
2171 (defvar org-file-properties nil
2172 "List of property/value pairs that can be inherited by any entry.
2173 Valid for the current buffer.
2174 This variable is populated from #+PROPERTY lines.")
2175 (make-variable-buffer-local 'org-file-properties)
2177 (defgroup org-agenda nil
2178 "Options concerning agenda views in Org-mode."
2179 :tag "Org Agenda"
2180 :group 'org)
2182 (defvar org-category nil
2183 "Variable used by org files to set a category for agenda display.
2184 Such files should use a file variable to set it, for example
2186 # -*- mode: org; org-category: \"ELisp\"
2188 or contain a special line
2190 #+CATEGORY: ELisp
2192 If the file does not specify a category, then file's base name
2193 is used instead.")
2194 (make-variable-buffer-local 'org-category)
2195 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2197 (defcustom org-agenda-files nil
2198 "The files to be used for agenda display.
2199 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2200 \\[org-remove-file]. You can also use customize to edit the list.
2202 If an entry is a directory, all files in that directory that are matched by
2203 `org-agenda-file-regexp' will be part of the file list.
2205 If the value of the variable is not a list but a single file name, then
2206 the list of agenda files is actually stored and maintained in that file, one
2207 agenda file per line."
2208 :group 'org-agenda
2209 :type '(choice
2210 (repeat :tag "List of files and directories" file)
2211 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2213 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2214 "Regular expression to match files for `org-agenda-files'.
2215 If any element in the list in that variable contains a directory instead
2216 of a normal file, all files in that directory that are matched by this
2217 regular expression will be included."
2218 :group 'org-agenda
2219 :type 'regexp)
2221 (defcustom org-agenda-text-search-extra-files nil
2222 "List of extra files to be searched by text search commands.
2223 These files will be search in addition to the agenda files by the
2224 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2225 Note that these files will only be searched for text search commands,
2226 not for the other agenda views like todo lists, tag searches or the weekly
2227 agenda. This variable is intended to list notes and possibly archive files
2228 that should also be searched by these two commands.
2229 In fact, if the first element in the list is the symbol `agenda-archives',
2230 than all archive files of all agenda files will be added to the search
2231 scope."
2232 :group 'org-agenda
2233 :type '(set :greedy t
2234 (const :tag "Agenda Archives" agenda-archives)
2235 (repeat :inline t (file))))
2237 (if (fboundp 'defvaralias)
2238 (defvaralias 'org-agenda-multi-occur-extra-files
2239 'org-agenda-text-search-extra-files))
2241 (defcustom org-agenda-skip-unavailable-files nil
2242 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2243 A nil value means to remove them, after a query, from the list."
2244 :group 'org-agenda
2245 :type 'boolean)
2247 (defcustom org-calendar-to-agenda-key [?c]
2248 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2249 The command `org-calendar-goto-agenda' will be bound to this key. The
2250 default is the character `c' because then `c' can be used to switch back and
2251 forth between agenda and calendar."
2252 :group 'org-agenda
2253 :type 'sexp)
2255 (defcustom org-calendar-agenda-action-key [?k]
2256 "The key to be installed in `calendar-mode-map' for agenda-action.
2257 The command `org-agenda-action' will be bound to this key. The
2258 default is the character `k' because we use the same key in the agenda."
2259 :group 'org-agenda
2260 :type 'sexp)
2262 (eval-after-load "calendar"
2263 '(progn
2264 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2265 'org-calendar-goto-agenda)
2266 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2267 'org-agenda-action)))
2269 (defgroup org-latex nil
2270 "Options for embedding LaTeX code into Org-mode."
2271 :tag "Org LaTeX"
2272 :group 'org)
2274 (defcustom org-format-latex-options
2275 '(:foreground default :background default :scale 1.0
2276 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2277 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2278 "Options for creating images from LaTeX fragments.
2279 This is a property list with the following properties:
2280 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2281 `default' means use the foreground of the default face.
2282 :background the background color, or \"Transparent\".
2283 `default' means use the background of the default face.
2284 :scale a scaling factor for the size of the images.
2285 :html-foreground, :html-background, :html-scale
2286 the same numbers for HTML export.
2287 :matchers a list indicating which matchers should be used to
2288 find LaTeX fragments. Valid members of this list are:
2289 \"begin\" find environments
2290 \"$1\" find single characters surrounded by $.$
2291 \"$\" find math expressions surrounded by $...$
2292 \"$$\" find math expressions surrounded by $$....$$
2293 \"\\(\" find math expressions surrounded by \\(...\\)
2294 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2295 :group 'org-latex
2296 :type 'plist)
2298 (defcustom org-format-latex-header "\\documentclass{article}
2299 \\usepackage{fullpage} % do not remove
2300 \\usepackage{amssymb}
2301 \\usepackage[usenames]{color}
2302 \\usepackage{amsmath}
2303 \\usepackage{latexsym}
2304 \\usepackage[mathscr]{eucal}
2305 \\pagestyle{empty} % do not remove"
2306 "The document header used for processing LaTeX fragments."
2307 :group 'org-latex
2308 :type 'string)
2311 (defgroup org-font-lock nil
2312 "Font-lock settings for highlighting in Org-mode."
2313 :tag "Org Font Lock"
2314 :group 'org)
2316 (defcustom org-level-color-stars-only nil
2317 "Non-nil means fontify only the stars in each headline.
2318 When nil, the entire headline is fontified.
2319 Changing it requires restart of `font-lock-mode' to become effective
2320 also in regions already fontified."
2321 :group 'org-font-lock
2322 :type 'boolean)
2324 (defcustom org-hide-leading-stars nil
2325 "Non-nil means, hide the first N-1 stars in a headline.
2326 This works by using the face `org-hide' for these stars. This
2327 face is white for a light background, and black for a dark
2328 background. You may have to customize the face `org-hide' to
2329 make this work.
2330 Changing it requires restart of `font-lock-mode' to become effective
2331 also in regions already fontified.
2332 You may also set this on a per-file basis by adding one of the following
2333 lines to the buffer:
2335 #+STARTUP: hidestars
2336 #+STARTUP: showstars"
2337 :group 'org-font-lock
2338 :type 'boolean)
2340 (defcustom org-fontify-done-headline nil
2341 "Non-nil means, change the face of a headline if it is marked DONE.
2342 Normally, only the TODO/DONE keyword indicates the state of a headline.
2343 When this is non-nil, the headline after the keyword is set to the
2344 `org-headline-done' as an additional indication."
2345 :group 'org-font-lock
2346 :type 'boolean)
2348 (defcustom org-fontify-emphasized-text t
2349 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2350 Changing this variable requires a restart of Emacs to take effect."
2351 :group 'org-font-lock
2352 :type 'boolean)
2354 (defcustom org-highlight-latex-fragments-and-specials nil
2355 "Non-nil means, fontify what is treated specially by the exporters."
2356 :group 'org-font-lock
2357 :type 'boolean)
2359 (defcustom org-hide-emphasis-markers nil
2360 "Non-nil mean font-lock should hide the emphasis marker characters."
2361 :group 'org-font-lock
2362 :type 'boolean)
2364 (defvar org-emph-re nil
2365 "Regular expression for matching emphasis.")
2366 (defvar org-verbatim-re nil
2367 "Regular expression for matching verbatim text.")
2368 (defvar org-emphasis-regexp-components) ; defined just below
2369 (defvar org-emphasis-alist) ; defined just below
2370 (defun org-set-emph-re (var val)
2371 "Set variable and compute the emphasis regular expression."
2372 (set var val)
2373 (when (and (boundp 'org-emphasis-alist)
2374 (boundp 'org-emphasis-regexp-components)
2375 org-emphasis-alist org-emphasis-regexp-components)
2376 (let* ((e org-emphasis-regexp-components)
2377 (pre (car e))
2378 (post (nth 1 e))
2379 (border (nth 2 e))
2380 (body (nth 3 e))
2381 (nl (nth 4 e))
2382 (body1 (concat body "*?"))
2383 (markers (mapconcat 'car org-emphasis-alist ""))
2384 (vmarkers (mapconcat
2385 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2386 org-emphasis-alist "")))
2387 ;; make sure special characters appear at the right position in the class
2388 (if (string-match "\\^" markers)
2389 (setq markers (concat (replace-match "" t t markers) "^")))
2390 (if (string-match "-" markers)
2391 (setq markers (concat (replace-match "" t t markers) "-")))
2392 (if (string-match "\\^" vmarkers)
2393 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2394 (if (string-match "-" vmarkers)
2395 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2396 (if (> nl 0)
2397 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2398 (int-to-string nl) "\\}")))
2399 ;; Make the regexp
2400 (setq org-emph-re
2401 (concat "\\([" pre "]\\|^\\)"
2402 "\\("
2403 "\\([" markers "]\\)"
2404 "\\("
2405 "[^" border "]\\|"
2406 "[^" border "]"
2407 body1
2408 "[^" border "]"
2409 "\\)"
2410 "\\3\\)"
2411 "\\([" post "]\\|$\\)"))
2412 (setq org-verbatim-re
2413 (concat "\\([" pre "]\\|^\\)"
2414 "\\("
2415 "\\([" vmarkers "]\\)"
2416 "\\("
2417 "[^" border "]\\|"
2418 "[^" border "]"
2419 body1
2420 "[^" border "]"
2421 "\\)"
2422 "\\3\\)"
2423 "\\([" post "]\\|$\\)")))))
2425 (defcustom org-emphasis-regexp-components
2426 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2427 "Components used to build the regular expression for emphasis.
2428 This is a list with 6 entries. Terminology: In an emphasis string
2429 like \" *strong word* \", we call the initial space PREMATCH, the final
2430 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2431 and \"trong wor\" is the body. The different components in this variable
2432 specify what is allowed/forbidden in each part:
2434 pre Chars allowed as prematch. Beginning of line will be allowed too.
2435 post Chars allowed as postmatch. End of line will be allowed too.
2436 border The chars *forbidden* as border characters.
2437 body-regexp A regexp like \".\" to match a body character. Don't use
2438 non-shy groups here, and don't allow newline here.
2439 newline The maximum number of newlines allowed in an emphasis exp.
2441 Use customize to modify this, or restart Emacs after changing it."
2442 :group 'org-font-lock
2443 :set 'org-set-emph-re
2444 :type '(list
2445 (sexp :tag "Allowed chars in pre ")
2446 (sexp :tag "Allowed chars in post ")
2447 (sexp :tag "Forbidden chars in border ")
2448 (sexp :tag "Regexp for body ")
2449 (integer :tag "number of newlines allowed")
2450 (option (boolean :tag "Please ignore this button"))))
2452 (defcustom org-emphasis-alist
2453 `(("*" bold "<b>" "</b>")
2454 ("/" italic "<i>" "</i>")
2455 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2456 ("=" org-code "<code>" "</code>" verbatim)
2457 ("~" org-verbatim "<code>" "</code>" verbatim)
2458 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2459 "<del>" "</del>")
2461 "Special syntax for emphasized text.
2462 Text starting and ending with a special character will be emphasized, for
2463 example *bold*, _underlined_ and /italic/. This variable sets the marker
2464 characters, the face to be used by font-lock for highlighting in Org-mode
2465 Emacs buffers, and the HTML tags to be used for this.
2466 Use customize to modify this, or restart Emacs after changing it."
2467 :group 'org-font-lock
2468 :set 'org-set-emph-re
2469 :type '(repeat
2470 (list
2471 (string :tag "Marker character")
2472 (choice
2473 (face :tag "Font-lock-face")
2474 (plist :tag "Face property list"))
2475 (string :tag "HTML start tag")
2476 (string :tag "HTML end tag")
2477 (option (const verbatim)))))
2479 ;;; Miscellaneous options
2481 (defgroup org-completion nil
2482 "Completion in Org-mode."
2483 :tag "Org Completion"
2484 :group 'org)
2486 (defcustom org-completion-use-ido nil
2487 "Non-nil means, use ido completion wherever possible.
2488 Note that `ido-mode' must be active for this variable to be relevant.
2489 If you decide to turn this variable on, you might well want to turn off
2490 `org-outline-path-complete-in-steps'."
2491 :group 'org-completion
2492 :type 'boolean)
2494 (defcustom org-completion-fallback-command 'hippie-expand
2495 "The expansion command called by \\[org-complete] in normal context.
2496 Normal means, no org-mode-specific context."
2497 :group 'org-completion
2498 :type 'function)
2500 ;;; Functions and variables from ther packages
2501 ;; Declared here to avoid compiler warnings
2503 ;; XEmacs only
2504 (defvar outline-mode-menu-heading)
2505 (defvar outline-mode-menu-show)
2506 (defvar outline-mode-menu-hide)
2507 (defvar zmacs-regions) ; XEmacs regions
2509 ;; Emacs only
2510 (defvar mark-active)
2512 ;; Various packages
2513 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2514 (declare-function calendar-forward-day "cal-move" (arg))
2515 (declare-function calendar-goto-date "cal-move" (date))
2516 (declare-function calendar-goto-today "cal-move" ())
2517 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2518 (defvar calc-embedded-close-formula)
2519 (defvar calc-embedded-open-formula)
2520 (declare-function cdlatex-tab "ext:cdlatex" ())
2521 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2522 (defvar font-lock-unfontify-region-function)
2523 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2524 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2525 (defvar iswitchb-temp-buflist)
2526 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2527 (defvar org-agenda-tags-todo-honor-ignore-options)
2528 (declare-function org-agenda-skip "org-agenda" ())
2529 (declare-function org-format-agenda-item "org-agenda"
2530 (extra txt &optional category tags dotime noprefix remove-re))
2531 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2532 (declare-function org-agenda-change-all-lines "org-agenda"
2533 (newhead hdmarker &optional fixface just-this))
2534 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2535 (declare-function org-agenda-maybe-redo "org-agenda" ())
2536 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2537 (beg end))
2538 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2539 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2540 "org-agenda" (&optional end))
2542 (declare-function parse-time-string "parse-time" (string))
2543 (declare-function remember "remember" (&optional initial))
2544 (declare-function remember-buffer-desc "remember" ())
2545 (declare-function remember-finalize "remember" ())
2546 (defvar remember-save-after-remembering)
2547 (defvar remember-data-file)
2548 (defvar remember-register)
2549 (defvar remember-buffer)
2550 (defvar remember-handler-functions)
2551 (defvar remember-annotation-functions)
2552 (defvar texmathp-why)
2553 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2554 (declare-function table--at-cell-p "table" (position &optional object at-column))
2556 (defvar w3m-current-url)
2557 (defvar w3m-current-title)
2559 (defvar org-latex-regexps)
2561 ;;; Autoload and prepare some org modules
2563 ;; Some table stuff that needs to be defined here, because it is used
2564 ;; by the functions setting up org-mode or checking for table context.
2566 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2567 "Detects an org-type or table-type table.")
2568 (defconst org-table-line-regexp "^[ \t]*|"
2569 "Detects an org-type table line.")
2570 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2571 "Detects an org-type table line.")
2572 (defconst org-table-hline-regexp "^[ \t]*|-"
2573 "Detects an org-type table hline.")
2574 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2575 "Detects a table-type table hline.")
2576 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2577 "Searching from within a table (any type) this finds the first line
2578 outside the table.")
2580 ;; Autoload the functions in org-table.el that are needed by functions here.
2582 (eval-and-compile
2583 (org-autoload "org-table"
2584 '(org-table-align org-table-begin org-table-blank-field
2585 org-table-convert org-table-convert-region org-table-copy-down
2586 org-table-copy-region org-table-create
2587 org-table-create-or-convert-from-region
2588 org-table-create-with-table.el org-table-current-dline
2589 org-table-cut-region org-table-delete-column org-table-edit-field
2590 org-table-edit-formulas org-table-end org-table-eval-formula
2591 org-table-export org-table-field-info
2592 org-table-get-stored-formulas org-table-goto-column
2593 org-table-hline-and-move org-table-import org-table-insert-column
2594 org-table-insert-hline org-table-insert-row org-table-iterate
2595 org-table-justify-field-maybe org-table-kill-row
2596 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2597 org-table-move-column org-table-move-column-left
2598 org-table-move-column-right org-table-move-row
2599 org-table-move-row-down org-table-move-row-up
2600 org-table-next-field org-table-next-row org-table-paste-rectangle
2601 org-table-previous-field org-table-recalculate
2602 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2603 org-table-toggle-coordinate-overlays
2604 org-table-toggle-formula-debugger org-table-wrap-region
2605 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2607 (defun org-at-table-p (&optional table-type)
2608 "Return t if the cursor is inside an org-type table.
2609 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2610 (if org-enable-table-editor
2611 (save-excursion
2612 (beginning-of-line 1)
2613 (looking-at (if table-type org-table-any-line-regexp
2614 org-table-line-regexp)))
2615 nil))
2616 (defsubst org-table-p () (org-at-table-p))
2618 (defun org-at-table.el-p ()
2619 "Return t if and only if we are at a table.el table."
2620 (and (org-at-table-p 'any)
2621 (save-excursion
2622 (goto-char (org-table-begin 'any))
2623 (looking-at org-table1-hline-regexp))))
2624 (defun org-table-recognize-table.el ()
2625 "If there is a table.el table nearby, recognize it and move into it."
2626 (if org-table-tab-recognizes-table.el
2627 (if (org-at-table.el-p)
2628 (progn
2629 (beginning-of-line 1)
2630 (if (looking-at org-table-dataline-regexp)
2632 (if (looking-at org-table1-hline-regexp)
2633 (progn
2634 (beginning-of-line 2)
2635 (if (looking-at org-table-any-border-regexp)
2636 (beginning-of-line -1)))))
2637 (if (re-search-forward "|" (org-table-end t) t)
2638 (progn
2639 (require 'table)
2640 (if (table--at-cell-p (point))
2642 (message "recognizing table.el table...")
2643 (table-recognize-table)
2644 (message "recognizing table.el table...done")))
2645 (error "This should not happen..."))
2647 nil)
2648 nil))
2650 (defun org-at-table-hline-p ()
2651 "Return t if the cursor is inside a hline in a table."
2652 (if org-enable-table-editor
2653 (save-excursion
2654 (beginning-of-line 1)
2655 (looking-at org-table-hline-regexp))
2656 nil))
2658 (defvar org-table-clean-did-remove-column nil)
2660 (defun org-table-map-tables (function)
2661 "Apply FUNCTION to the start of all tables in the buffer."
2662 (save-excursion
2663 (save-restriction
2664 (widen)
2665 (goto-char (point-min))
2666 (while (re-search-forward org-table-any-line-regexp nil t)
2667 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2668 (beginning-of-line 1)
2669 (if (looking-at org-table-line-regexp)
2670 (save-excursion (funcall function)))
2671 (re-search-forward org-table-any-border-regexp nil 1))))
2672 (message "Mapping tables: done"))
2674 ;; Declare and autoload functions from org-exp.el
2676 (declare-function org-default-export-plist "org-exp")
2677 (declare-function org-infile-export-plist "org-exp")
2678 (declare-function org-get-current-options "org-exp")
2679 (eval-and-compile
2680 (org-autoload "org-exp"
2681 '(org-export org-export-as-ascii org-export-visible
2682 org-insert-export-options-template org-export-as-html-and-open
2683 org-export-as-html-batch org-export-as-html-to-buffer
2684 org-replace-region-by-html org-export-region-as-html
2685 org-export-as-html org-export-icalendar-this-file
2686 org-export-icalendar-all-agenda-files
2687 org-table-clean-before-export
2688 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2690 ;; Declare and autoload functions from org-agenda.el
2692 (eval-and-compile
2693 (org-autoload "org-agenda"
2694 '(org-agenda org-agenda-list org-search-view
2695 org-todo-list org-tags-view org-agenda-list-stuck-projects
2696 org-diary org-agenda-to-appt
2697 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2699 ;; Autoload org-remember
2701 (eval-and-compile
2702 (org-autoload "org-remember"
2703 '(org-remember-insinuate org-remember-annotation
2704 org-remember-apply-template org-remember org-remember-handler)))
2706 ;; Autoload org-clock.el
2709 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2710 (beg end))
2711 (declare-function org-clock-update-mode-line "org-clock" ())
2712 (defvar org-clock-start-time)
2713 (defvar org-clock-marker (make-marker)
2714 "Marker recording the last clock-in.")
2716 (eval-and-compile
2717 (org-autoload
2718 "org-clock"
2719 '(org-clock-in org-clock-out org-clock-cancel
2720 org-clock-goto org-clock-sum org-clock-display
2721 org-clock-remove-overlays org-clock-report
2722 org-clocktable-shift org-dblock-write:clocktable
2723 org-get-clocktable)))
2725 (defun org-clock-update-time-maybe ()
2726 "If this is a CLOCK line, update it and return t.
2727 Otherwise, return nil."
2728 (interactive)
2729 (save-excursion
2730 (beginning-of-line 1)
2731 (skip-chars-forward " \t")
2732 (when (looking-at org-clock-string)
2733 (let ((re (concat "[ \t]*" org-clock-string
2734 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2735 "\\([ \t]*=>.*\\)?\\)?"))
2736 ts te h m s neg)
2737 (cond
2738 ((not (looking-at re))
2739 nil)
2740 ((not (match-end 2))
2741 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2742 (> org-clock-marker (point))
2743 (<= org-clock-marker (point-at-eol)))
2744 ;; The clock is running here
2745 (setq org-clock-start-time
2746 (apply 'encode-time
2747 (org-parse-time-string (match-string 1))))
2748 (org-clock-update-mode-line)))
2750 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2751 (end-of-line 1)
2752 (setq ts (match-string 1)
2753 te (match-string 3))
2754 (setq s (- (time-to-seconds
2755 (apply 'encode-time (org-parse-time-string te)))
2756 (time-to-seconds
2757 (apply 'encode-time (org-parse-time-string ts))))
2758 neg (< s 0)
2759 s (abs s)
2760 h (floor (/ s 3600))
2761 s (- s (* 3600 h))
2762 m (floor (/ s 60))
2763 s (- s (* 60 s)))
2764 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2765 t))))))
2767 (defun org-check-running-clock ()
2768 "Check if the current buffer contains the running clock.
2769 If yes, offer to stop it and to save the buffer with the changes."
2770 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2771 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2772 (buffer-name))))
2773 (org-clock-out)
2774 (when (y-or-n-p "Save changed buffer?")
2775 (save-buffer))))
2777 (defun org-clocktable-try-shift (dir n)
2778 "Check if this line starts a clock table, if yes, shift the time block."
2779 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2780 (org-clocktable-shift dir n)))
2782 ;; Autoload org-timer.el
2784 ;(declare-function org-timer "org-timer")
2786 (eval-and-compile
2787 (org-autoload
2788 "org-timer"
2789 '(org-timer-start org-timer org-timer-item
2790 org-timer-change-times-in-region)))
2793 ;; Autoload archiving code
2794 ;; The stuff that is needed for cycling and tags has to be defined here.
2796 (defgroup org-archive nil
2797 "Options concerning archiving in Org-mode."
2798 :tag "Org Archive"
2799 :group 'org-structure)
2801 (defcustom org-archive-location "%s_archive::"
2802 "The location where subtrees should be archived.
2804 The value of this variable is a string, consisting of two parts,
2805 separated by a double-colon. The first part is a filename and
2806 the second part is a headline.
2808 When the filename is omitted, archiving happens in the same file.
2809 %s in the filename will be replaced by the current file
2810 name (without the directory part). Archiving to a different file
2811 is useful to keep archived entries from contributing to the
2812 Org-mode Agenda.
2814 The archived entries will be filed as subtrees of the specified
2815 headline. When the headline is omitted, the subtrees are simply
2816 filed away at the end of the file, as top-level entries. Also in
2817 the heading you can use %s to represent the file name, this can be
2818 useful when using the same archive for a number of different files.
2820 Here are a few examples:
2821 \"%s_archive::\"
2822 If the current file is Projects.org, archive in file
2823 Projects.org_archive, as top-level trees. This is the default.
2825 \"::* Archived Tasks\"
2826 Archive in the current file, under the top-level headline
2827 \"* Archived Tasks\".
2829 \"~/org/archive.org::\"
2830 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2832 \"~/org/archive.org::From %s\"
2833 Archive in file ~/org/archive.org (absolute path), und headlines
2834 \"From FILENAME\" where file name is the current file name.
2836 \"basement::** Finished Tasks\"
2837 Archive in file ./basement (relative path), as level 3 trees
2838 below the level 2 heading \"** Finished Tasks\".
2840 You may set this option on a per-file basis by adding to the buffer a
2841 line like
2843 #+ARCHIVE: basement::** Finished Tasks
2845 You may also define it locally for a subtree by setting an ARCHIVE property
2846 in the entry. If such a property is found in an entry, or anywhere up
2847 the hierarchy, it will be used."
2848 :group 'org-archive
2849 :type 'string)
2851 (defcustom org-archive-tag "ARCHIVE"
2852 "The tag that marks a subtree as archived.
2853 An archived subtree does not open during visibility cycling, and does
2854 not contribute to the agenda listings.
2855 After changing this, font-lock must be restarted in the relevant buffers to
2856 get the proper fontification."
2857 :group 'org-archive
2858 :group 'org-keywords
2859 :type 'string)
2861 (defcustom org-agenda-skip-archived-trees t
2862 "Non-nil means, the agenda will skip any items located in archived trees.
2863 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2864 variable is no longer recommended, you should leave it at the value t.
2865 Instead, use the key `v' to cycle the archives-mode in the agenda."
2866 :group 'org-archive
2867 :group 'org-agenda-skip
2868 :type 'boolean)
2870 (defcustom org-cycle-open-archived-trees nil
2871 "Non-nil means, `org-cycle' will open archived trees.
2872 An archived tree is a tree marked with the tag ARCHIVE.
2873 When nil, archived trees will stay folded. You can still open them with
2874 normal outline commands like `show-all', but not with the cycling commands."
2875 :group 'org-archive
2876 :group 'org-cycle
2877 :type 'boolean)
2879 (defcustom org-sparse-tree-open-archived-trees nil
2880 "Non-nil means sparse tree construction shows matches in archived trees.
2881 When nil, matches in these trees are highlighted, but the trees are kept in
2882 collapsed state."
2883 :group 'org-archive
2884 :group 'org-sparse-trees
2885 :type 'boolean)
2887 (defun org-cycle-hide-archived-subtrees (state)
2888 "Re-hide all archived subtrees after a visibility state change."
2889 (when (and (not org-cycle-open-archived-trees)
2890 (not (memq state '(overview folded))))
2891 (save-excursion
2892 (let* ((globalp (memq state '(contents all)))
2893 (beg (if globalp (point-min) (point)))
2894 (end (if globalp (point-max) (org-end-of-subtree t))))
2895 (org-hide-archived-subtrees beg end)
2896 (goto-char beg)
2897 (if (looking-at (concat ".*:" org-archive-tag ":"))
2898 (message "%s" (substitute-command-keys
2899 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2901 (defun org-force-cycle-archived ()
2902 "Cycle subtree even if it is archived."
2903 (interactive)
2904 (setq this-command 'org-cycle)
2905 (let ((org-cycle-open-archived-trees t))
2906 (call-interactively 'org-cycle)))
2908 (defun org-hide-archived-subtrees (beg end)
2909 "Re-hide all archived subtrees after a visibility state change."
2910 (save-excursion
2911 (let* ((re (concat ":" org-archive-tag ":")))
2912 (goto-char beg)
2913 (while (re-search-forward re end t)
2914 (and (org-on-heading-p) (hide-subtree))
2915 (org-end-of-subtree t)))))
2917 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2919 (eval-and-compile
2920 (org-autoload "org-archive"
2921 '(org-add-archive-files org-archive-subtree
2922 org-archive-to-archive-sibling org-toggle-archive-tag)))
2924 ;; Autoload Column View Code
2926 (declare-function org-columns-number-to-string "org-colview")
2927 (declare-function org-columns-get-format-and-top-level "org-colview")
2928 (declare-function org-columns-compute "org-colview")
2930 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2931 '(org-columns-number-to-string org-columns-get-format-and-top-level
2932 org-columns-compute org-agenda-columns org-columns-remove-overlays
2933 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2935 ;; Autoload ID code
2937 (declare-function org-id-store-link "org-id")
2938 (org-autoload "org-id"
2939 '(org-id-get-create org-id-new org-id-copy org-id-get
2940 org-id-get-with-outline-path-completion
2941 org-id-get-with-outline-drilling
2942 org-id-goto org-id-find org-id-store-link))
2944 ;;; Variables for pre-computed regular expressions, all buffer local
2946 (defvar org-drawer-regexp nil
2947 "Matches first line of a hidden block.")
2948 (make-variable-buffer-local 'org-drawer-regexp)
2949 (defvar org-todo-regexp nil
2950 "Matches any of the TODO state keywords.")
2951 (make-variable-buffer-local 'org-todo-regexp)
2952 (defvar org-not-done-regexp nil
2953 "Matches any of the TODO state keywords except the last one.")
2954 (make-variable-buffer-local 'org-not-done-regexp)
2955 (defvar org-todo-line-regexp nil
2956 "Matches a headline and puts TODO state into group 2 if present.")
2957 (make-variable-buffer-local 'org-todo-line-regexp)
2958 (defvar org-complex-heading-regexp nil
2959 "Matches a headline and puts everything into groups:
2960 group 1: the stars
2961 group 2: The todo keyword, maybe
2962 group 3: Priority cookie
2963 group 4: True headline
2964 group 5: Tags")
2965 (make-variable-buffer-local 'org-complex-heading-regexp)
2966 (defvar org-todo-line-tags-regexp nil
2967 "Matches a headline and puts TODO state into group 2 if present.
2968 Also put tags into group 4 if tags are present.")
2969 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2970 (defvar org-nl-done-regexp nil
2971 "Matches newline followed by a headline with the DONE keyword.")
2972 (make-variable-buffer-local 'org-nl-done-regexp)
2973 (defvar org-looking-at-done-regexp nil
2974 "Matches the DONE keyword a point.")
2975 (make-variable-buffer-local 'org-looking-at-done-regexp)
2976 (defvar org-ds-keyword-length 12
2977 "Maximum length of the Deadline and SCHEDULED keywords.")
2978 (make-variable-buffer-local 'org-ds-keyword-length)
2979 (defvar org-deadline-regexp nil
2980 "Matches the DEADLINE keyword.")
2981 (make-variable-buffer-local 'org-deadline-regexp)
2982 (defvar org-deadline-time-regexp nil
2983 "Matches the DEADLINE keyword together with a time stamp.")
2984 (make-variable-buffer-local 'org-deadline-time-regexp)
2985 (defvar org-deadline-line-regexp nil
2986 "Matches the DEADLINE keyword and the rest of the line.")
2987 (make-variable-buffer-local 'org-deadline-line-regexp)
2988 (defvar org-scheduled-regexp nil
2989 "Matches the SCHEDULED keyword.")
2990 (make-variable-buffer-local 'org-scheduled-regexp)
2991 (defvar org-scheduled-time-regexp nil
2992 "Matches the SCHEDULED keyword together with a time stamp.")
2993 (make-variable-buffer-local 'org-scheduled-time-regexp)
2994 (defvar org-closed-time-regexp nil
2995 "Matches the CLOSED keyword together with a time stamp.")
2996 (make-variable-buffer-local 'org-closed-time-regexp)
2998 (defvar org-keyword-time-regexp nil
2999 "Matches any of the 4 keywords, together with the time stamp.")
3000 (make-variable-buffer-local 'org-keyword-time-regexp)
3001 (defvar org-keyword-time-not-clock-regexp nil
3002 "Matches any of the 3 keywords, together with the time stamp.")
3003 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3004 (defvar org-maybe-keyword-time-regexp nil
3005 "Matches a timestamp, possibly preceeded by a keyword.")
3006 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3007 (defvar org-planning-or-clock-line-re nil
3008 "Matches a line with planning or clock info.")
3009 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3011 (defconst org-plain-time-of-day-regexp
3012 (concat
3013 "\\(\\<[012]?[0-9]"
3014 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3015 "\\(--?"
3016 "\\(\\<[012]?[0-9]"
3017 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3018 "\\)?")
3019 "Regular expression to match a plain time or time range.
3020 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3021 groups carry important information:
3022 0 the full match
3023 1 the first time, range or not
3024 8 the second time, if it is a range.")
3026 (defconst org-plain-time-extension-regexp
3027 (concat
3028 "\\(\\<[012]?[0-9]"
3029 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3030 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3031 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3032 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3033 groups carry important information:
3034 0 the full match
3035 7 hours of duration
3036 9 minutes of duration")
3038 (defconst org-stamp-time-of-day-regexp
3039 (concat
3040 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3041 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3042 "\\(--?"
3043 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3044 "Regular expression to match a timestamp time or time range.
3045 After a match, the following groups carry important information:
3046 0 the full match
3047 1 date plus weekday, for backreferencing to make sure both times on same day
3048 2 the first time, range or not
3049 4 the second time, if it is a range.")
3051 (defconst org-startup-options
3052 '(("fold" org-startup-folded t)
3053 ("overview" org-startup-folded t)
3054 ("nofold" org-startup-folded nil)
3055 ("showall" org-startup-folded nil)
3056 ("content" org-startup-folded content)
3057 ("hidestars" org-hide-leading-stars t)
3058 ("showstars" org-hide-leading-stars nil)
3059 ("odd" org-odd-levels-only t)
3060 ("oddeven" org-odd-levels-only nil)
3061 ("align" org-startup-align-all-tables t)
3062 ("noalign" org-startup-align-all-tables nil)
3063 ("customtime" org-display-custom-times t)
3064 ("logdone" org-log-done time)
3065 ("lognotedone" org-log-done note)
3066 ("nologdone" org-log-done nil)
3067 ("lognoteclock-out" org-log-note-clock-out t)
3068 ("nolognoteclock-out" org-log-note-clock-out nil)
3069 ("logrepeat" org-log-repeat state)
3070 ("lognoterepeat" org-log-repeat note)
3071 ("nologrepeat" org-log-repeat nil)
3072 ("fninline" org-footnote-define-inline t)
3073 ("nofninline" org-footnote-define-inline nil)
3074 ("fnlocal" org-footnote-section nil)
3075 ("fnauto" org-footnote-auto-label t)
3076 ("fnprompt" org-footnote-auto-label nil)
3077 ("fnconfirm" org-footnote-auto-label confirm)
3078 ("fnplain" org-footnote-auto-label plain)
3079 ("constcgs" constants-unit-system cgs)
3080 ("constSI" constants-unit-system SI))
3081 "Variable associated with STARTUP options for org-mode.
3082 Each element is a list of three items: The startup options as written
3083 in the #+STARTUP line, the corresponding variable, and the value to
3084 set this variable to if the option is found. An optional forth element PUSH
3085 means to push this value onto the list in the variable.")
3087 (defun org-set-regexps-and-options ()
3088 "Precompute regular expressions for current buffer."
3089 (when (org-mode-p)
3090 (org-set-local 'org-todo-kwd-alist nil)
3091 (org-set-local 'org-todo-key-alist nil)
3092 (org-set-local 'org-todo-key-trigger nil)
3093 (org-set-local 'org-todo-keywords-1 nil)
3094 (org-set-local 'org-done-keywords nil)
3095 (org-set-local 'org-todo-heads nil)
3096 (org-set-local 'org-todo-sets nil)
3097 (org-set-local 'org-todo-log-states nil)
3098 (org-set-local 'org-file-properties nil)
3099 (org-set-local 'org-file-tags nil)
3100 (let ((re (org-make-options-regexp
3101 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3102 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3103 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3104 (splitre "[ \t]+")
3105 kwds kws0 kwsa key log value cat arch tags const links hw dws
3106 tail sep kws1 prio props ftags drawers
3107 ext-setup-or-nil setup-contents (start 0))
3108 (save-excursion
3109 (save-restriction
3110 (widen)
3111 (goto-char (point-min))
3112 (while (or (and ext-setup-or-nil
3113 (string-match re ext-setup-or-nil start)
3114 (setq start (match-end 0)))
3115 (and (setq ext-setup-or-nil nil start 0)
3116 (re-search-forward re nil t)))
3117 (setq key (upcase (match-string 1 ext-setup-or-nil))
3118 value (org-match-string-no-properties 2 ext-setup-or-nil))
3119 (cond
3120 ((equal key "CATEGORY")
3121 (if (string-match "[ \t]+$" value)
3122 (setq value (replace-match "" t t value)))
3123 (setq cat value))
3124 ((member key '("SEQ_TODO" "TODO"))
3125 (push (cons 'sequence (org-split-string value splitre)) kwds))
3126 ((equal key "TYP_TODO")
3127 (push (cons 'type (org-split-string value splitre)) kwds))
3128 ((equal key "TAGS")
3129 (setq tags (append tags (org-split-string value splitre))))
3130 ((equal key "COLUMNS")
3131 (org-set-local 'org-columns-default-format value))
3132 ((equal key "LINK")
3133 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3134 (push (cons (match-string 1 value)
3135 (org-trim (match-string 2 value)))
3136 links)))
3137 ((equal key "PRIORITIES")
3138 (setq prio (org-split-string value " +")))
3139 ((equal key "PROPERTY")
3140 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3141 (push (cons (match-string 1 value) (match-string 2 value))
3142 props)))
3143 ((equal key "FILETAGS")
3144 (when (string-match "\\S-" value)
3145 (setq ftags
3146 (append
3147 ftags
3148 (apply 'append
3149 (mapcar (lambda (x) (org-split-string x ":"))
3150 (org-split-string value)))))))
3151 ((equal key "DRAWERS")
3152 (setq drawers (org-split-string value splitre)))
3153 ((equal key "CONSTANTS")
3154 (setq const (append const (org-split-string value splitre))))
3155 ((equal key "STARTUP")
3156 (let ((opts (org-split-string value splitre))
3157 l var val)
3158 (while (setq l (pop opts))
3159 (when (setq l (assoc l org-startup-options))
3160 (setq var (nth 1 l) val (nth 2 l))
3161 (if (not (nth 3 l))
3162 (set (make-local-variable var) val)
3163 (if (not (listp (symbol-value var)))
3164 (set (make-local-variable var) nil))
3165 (set (make-local-variable var) (symbol-value var))
3166 (add-to-list var val))))))
3167 ((equal key "ARCHIVE")
3168 (string-match " *$" value)
3169 (setq arch (replace-match "" t t value))
3170 (remove-text-properties 0 (length arch)
3171 '(face t fontified t) arch))
3172 ((equal key "SETUPFILE")
3173 (setq setup-contents (org-file-contents
3174 (expand-file-name
3175 (org-remove-double-quotes value))
3176 'noerror))
3177 (if (not ext-setup-or-nil)
3178 (setq ext-setup-or-nil setup-contents start 0)
3179 (setq ext-setup-or-nil
3180 (concat (substring ext-setup-or-nil 0 start)
3181 "\n" setup-contents "\n"
3182 (substring ext-setup-or-nil start)))))
3183 ))))
3184 (when cat
3185 (org-set-local 'org-category (intern cat))
3186 (push (cons "CATEGORY" cat) props))
3187 (when prio
3188 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3189 (setq prio (mapcar 'string-to-char prio))
3190 (org-set-local 'org-highest-priority (nth 0 prio))
3191 (org-set-local 'org-lowest-priority (nth 1 prio))
3192 (org-set-local 'org-default-priority (nth 2 prio)))
3193 (and props (org-set-local 'org-file-properties (nreverse props)))
3194 (and ftags (org-set-local 'org-file-tags ftags))
3195 (and drawers (org-set-local 'org-drawers drawers))
3196 (and arch (org-set-local 'org-archive-location arch))
3197 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3198 ;; Process the TODO keywords
3199 (unless kwds
3200 ;; Use the global values as if they had been given locally.
3201 (setq kwds (default-value 'org-todo-keywords))
3202 (if (stringp (car kwds))
3203 (setq kwds (list (cons org-todo-interpretation
3204 (default-value 'org-todo-keywords)))))
3205 (setq kwds (reverse kwds)))
3206 (setq kwds (nreverse kwds))
3207 (let (inter kws kw)
3208 (while (setq kws (pop kwds))
3209 (setq inter (pop kws) sep (member "|" kws)
3210 kws0 (delete "|" (copy-sequence kws))
3211 kwsa nil
3212 kws1 (mapcar
3213 (lambda (x)
3214 ;; 1 2
3215 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3216 (progn
3217 (setq kw (match-string 1 x)
3218 key (and (match-end 2) (match-string 2 x))
3219 log (org-extract-log-state-settings x))
3220 (push (cons kw (and key (string-to-char key))) kwsa)
3221 (and log (push log org-todo-log-states))
3223 (error "Invalid TODO keyword %s" x)))
3224 kws0)
3225 kwsa (if kwsa (append '((:startgroup))
3226 (nreverse kwsa)
3227 '((:endgroup))))
3228 hw (car kws1)
3229 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3230 tail (list inter hw (car dws) (org-last dws)))
3231 (add-to-list 'org-todo-heads hw 'append)
3232 (push kws1 org-todo-sets)
3233 (setq org-done-keywords (append org-done-keywords dws nil))
3234 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3235 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3236 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3237 (setq org-todo-sets (nreverse org-todo-sets)
3238 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3239 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3240 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3241 ;; Process the constants
3242 (when const
3243 (let (e cst)
3244 (while (setq e (pop const))
3245 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3246 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3247 (setq org-table-formula-constants-local cst)))
3249 ;; Process the tags.
3250 (when tags
3251 (let (e tgs)
3252 (while (setq e (pop tags))
3253 (cond
3254 ((equal e "{") (push '(:startgroup) tgs))
3255 ((equal e "}") (push '(:endgroup) tgs))
3256 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3257 (push (cons (match-string 1 e)
3258 (string-to-char (match-string 2 e)))
3259 tgs))
3260 (t (push (list e) tgs))))
3261 (org-set-local 'org-tag-alist nil)
3262 (while (setq e (pop tgs))
3263 (or (and (stringp (car e))
3264 (assoc (car e) org-tag-alist))
3265 (push e org-tag-alist)))))
3267 ;; Compute the regular expressions and other local variables
3268 (if (not org-done-keywords)
3269 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3270 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3271 (length org-scheduled-string)
3272 (length org-clock-string)
3273 (length org-closed-string)))
3274 org-drawer-regexp
3275 (concat "^[ \t]*:\\("
3276 (mapconcat 'regexp-quote org-drawers "\\|")
3277 "\\):[ \t]*$")
3278 org-not-done-keywords
3279 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3280 org-todo-regexp
3281 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3282 "\\|") "\\)\\>")
3283 org-not-done-regexp
3284 (concat "\\<\\("
3285 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3286 "\\)\\>")
3287 org-todo-line-regexp
3288 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3289 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3290 "\\)\\>\\)?[ \t]*\\(.*\\)")
3291 org-complex-heading-regexp
3292 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3293 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3294 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3295 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3296 org-nl-done-regexp
3297 (concat "\n\\*+[ \t]+"
3298 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3299 "\\)" "\\>")
3300 org-todo-line-tags-regexp
3301 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3302 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3303 (org-re
3304 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3305 org-looking-at-done-regexp
3306 (concat "^" "\\(?:"
3307 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3308 "\\>")
3309 org-deadline-regexp (concat "\\<" org-deadline-string)
3310 org-deadline-time-regexp
3311 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3312 org-deadline-line-regexp
3313 (concat "\\<\\(" org-deadline-string "\\).*")
3314 org-scheduled-regexp
3315 (concat "\\<" org-scheduled-string)
3316 org-scheduled-time-regexp
3317 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3318 org-closed-time-regexp
3319 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3320 org-keyword-time-regexp
3321 (concat "\\<\\(" org-scheduled-string
3322 "\\|" org-deadline-string
3323 "\\|" org-closed-string
3324 "\\|" org-clock-string "\\)"
3325 " *[[<]\\([^]>]+\\)[]>]")
3326 org-keyword-time-not-clock-regexp
3327 (concat "\\<\\(" org-scheduled-string
3328 "\\|" org-deadline-string
3329 "\\|" org-closed-string
3330 "\\)"
3331 " *[[<]\\([^]>]+\\)[]>]")
3332 org-maybe-keyword-time-regexp
3333 (concat "\\(\\<\\(" org-scheduled-string
3334 "\\|" org-deadline-string
3335 "\\|" org-closed-string
3336 "\\|" org-clock-string "\\)\\)?"
3337 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3338 org-planning-or-clock-line-re
3339 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3340 "\\|" org-deadline-string
3341 "\\|" org-closed-string "\\|" org-clock-string
3342 "\\)\\>\\)")
3344 (org-compute-latex-and-specials-regexp)
3345 (org-set-font-lock-defaults))))
3347 (defun org-file-contents (file &optional noerror)
3348 "Return the contents of FILE, as a string."
3349 (if (or (not file)
3350 (not (file-readable-p file)))
3351 (if noerror
3352 (progn
3353 (message "Cannot read file %s" file)
3354 (ding) (sit-for 2)
3356 (error "Cannot read file %s" file))
3357 (with-temp-buffer
3358 (insert-file-contents file)
3359 (buffer-string))))
3361 (defun org-extract-log-state-settings (x)
3362 "Extract the log state setting from a TODO keyword string.
3363 This will extract info from a string like \"WAIT(w@/!)\"."
3364 (let (kw key log1 log2)
3365 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3366 (setq kw (match-string 1 x)
3367 key (and (match-end 2) (match-string 2 x))
3368 log1 (and (match-end 3) (match-string 3 x))
3369 log2 (and (match-end 4) (match-string 4 x)))
3370 (and (or log1 log2)
3371 (list kw
3372 (and log1 (if (equal log1 "!") 'time 'note))
3373 (and log2 (if (equal log2 "!") 'time 'note)))))))
3375 (defun org-remove-keyword-keys (list)
3376 "Remove a pair of parenthesis at the end of each string in LIST."
3377 (mapcar (lambda (x)
3378 (if (string-match "(.*)$" x)
3379 (substring x 0 (match-beginning 0))
3381 list))
3383 ;; FIXME: this could be done much better, using second characters etc.
3384 (defun org-assign-fast-keys (alist)
3385 "Assign fast keys to a keyword-key alist.
3386 Respect keys that are already there."
3387 (let (new e k c c1 c2 (char ?a))
3388 (while (setq e (pop alist))
3389 (cond
3390 ((equal e '(:startgroup)) (push e new))
3391 ((equal e '(:endgroup)) (push e new))
3393 (setq k (car e) c2 nil)
3394 (if (cdr e)
3395 (setq c (cdr e))
3396 ;; automatically assign a character.
3397 (setq c1 (string-to-char
3398 (downcase (substring
3399 k (if (= (string-to-char k) ?@) 1 0)))))
3400 (if (or (rassoc c1 new) (rassoc c1 alist))
3401 (while (or (rassoc char new) (rassoc char alist))
3402 (setq char (1+ char)))
3403 (setq c2 c1))
3404 (setq c (or c2 char)))
3405 (push (cons k c) new))))
3406 (nreverse new)))
3408 ;;; Some variables used in various places
3410 (defvar org-window-configuration nil
3411 "Used in various places to store a window configuration.")
3412 (defvar org-finish-function nil
3413 "Function to be called when `C-c C-c' is used.
3414 This is for getting out of special buffers like remember.")
3417 ;; FIXME: Occasionally check by commenting these, to make sure
3418 ;; no other functions uses these, forgetting to let-bind them.
3419 (defvar entry)
3420 (defvar state)
3421 (defvar last-state)
3422 (defvar date)
3423 (defvar description)
3425 ;; Defined somewhere in this file, but used before definition.
3426 (defvar org-html-entities)
3427 (defvar org-struct-menu)
3428 (defvar org-org-menu)
3429 (defvar org-tbl-menu)
3430 (defvar org-agenda-keymap)
3432 ;;;; Define the Org-mode
3434 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3435 (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."))
3438 ;; We use a before-change function to check if a table might need
3439 ;; an update.
3440 (defvar org-table-may-need-update t
3441 "Indicates that a table might need an update.
3442 This variable is set by `org-before-change-function'.
3443 `org-table-align' sets it back to nil.")
3444 (defun org-before-change-function (beg end)
3445 "Every change indicates that a table might need an update."
3446 (setq org-table-may-need-update t))
3447 (defvar org-mode-map)
3448 (defvar org-mode-hook nil
3449 "Mode hook for Org-mode, run after the mode was turned on.")
3450 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3451 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3452 (defvar org-table-buffer-is-an nil)
3453 (defconst org-outline-regexp "\\*+ ")
3455 ;;;###autoload
3456 (define-derived-mode org-mode outline-mode "Org"
3457 "Outline-based notes management and organizer, alias
3458 \"Carsten's outline-mode for keeping track of everything.\"
3460 Org-mode develops organizational tasks around a NOTES file which
3461 contains information about projects as plain text. Org-mode is
3462 implemented on top of outline-mode, which is ideal to keep the content
3463 of large files well structured. It supports ToDo items, deadlines and
3464 time stamps, which magically appear in the diary listing of the Emacs
3465 calendar. Tables are easily created with a built-in table editor.
3466 Plain text URL-like links connect to websites, emails (VM), Usenet
3467 messages (Gnus), BBDB entries, and any files related to the project.
3468 For printing and sharing of notes, an Org-mode file (or a part of it)
3469 can be exported as a structured ASCII or HTML file.
3471 The following commands are available:
3473 \\{org-mode-map}"
3475 ;; Get rid of Outline menus, they are not needed
3476 ;; Need to do this here because define-derived-mode sets up
3477 ;; the keymap so late. Still, it is a waste to call this each time
3478 ;; we switch another buffer into org-mode.
3479 (if (featurep 'xemacs)
3480 (when (boundp 'outline-mode-menu-heading)
3481 ;; Assume this is Greg's port, it used easymenu
3482 (easy-menu-remove outline-mode-menu-heading)
3483 (easy-menu-remove outline-mode-menu-show)
3484 (easy-menu-remove outline-mode-menu-hide))
3485 (define-key org-mode-map [menu-bar headings] 'undefined)
3486 (define-key org-mode-map [menu-bar hide] 'undefined)
3487 (define-key org-mode-map [menu-bar show] 'undefined))
3489 (org-load-modules-maybe)
3490 (easy-menu-add org-org-menu)
3491 (easy-menu-add org-tbl-menu)
3492 (org-install-agenda-files-menu)
3493 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3494 (org-add-to-invisibility-spec '(org-cwidth))
3495 (when (featurep 'xemacs)
3496 (org-set-local 'line-move-ignore-invisible t))
3497 (org-set-local 'outline-regexp org-outline-regexp)
3498 (org-set-local 'outline-level 'org-outline-level)
3499 (when (and org-ellipsis
3500 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3501 (fboundp 'make-glyph-code))
3502 (unless org-display-table
3503 (setq org-display-table (make-display-table)))
3504 (set-display-table-slot
3505 org-display-table 4
3506 (vconcat (mapcar
3507 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3508 org-ellipsis)))
3509 (if (stringp org-ellipsis) org-ellipsis "..."))))
3510 (setq buffer-display-table org-display-table))
3511 (org-set-regexps-and-options)
3512 (when (and org-tag-faces (not org-tags-special-faces-re))
3513 ;; tag faces set outside customize.... force initialization.
3514 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3515 ;; Calc embedded
3516 (org-set-local 'calc-embedded-open-mode "# ")
3517 (modify-syntax-entry ?# "<")
3518 (modify-syntax-entry ?@ "w")
3519 (if org-startup-truncated (setq truncate-lines t))
3520 (org-set-local 'font-lock-unfontify-region-function
3521 'org-unfontify-region)
3522 ;; Activate before-change-function
3523 (org-set-local 'org-table-may-need-update t)
3524 (org-add-hook 'before-change-functions 'org-before-change-function nil
3525 'local)
3526 ;; Check for running clock before killing a buffer
3527 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3528 ;; Paragraphs and auto-filling
3529 (org-set-autofill-regexps)
3530 (setq indent-line-function 'org-indent-line-function)
3531 (org-update-radio-target-regexp)
3533 ;; Comment characters
3534 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3535 (org-set-local 'comment-padding " ")
3537 ;; Align options lines
3538 (org-set-local
3539 'align-mode-rules-list
3540 '((org-in-buffer-settings
3541 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3542 (modes . '(org-mode)))))
3544 ;; Imenu
3545 (org-set-local 'imenu-create-index-function
3546 'org-imenu-get-tree)
3548 ;; Make isearch reveal context
3549 (if (or (featurep 'xemacs)
3550 (not (boundp 'outline-isearch-open-invisible-function)))
3551 ;; Emacs 21 and XEmacs make use of the hook
3552 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3553 ;; Emacs 22 deals with this through a special variable
3554 (org-set-local 'outline-isearch-open-invisible-function
3555 (lambda (&rest ignore) (org-show-context 'isearch))))
3557 ;; If empty file that did not turn on org-mode automatically, make it to.
3558 (if (and org-insert-mode-line-in-empty-file
3559 (interactive-p)
3560 (= (point-min) (point-max)))
3561 (insert "# -*- mode: org -*-\n\n"))
3563 (unless org-inhibit-startup
3564 (when org-startup-align-all-tables
3565 (let ((bmp (buffer-modified-p)))
3566 (org-table-map-tables 'org-table-align)
3567 (set-buffer-modified-p bmp)))
3568 (org-set-startup-visibility)))
3570 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3572 (defun org-current-time ()
3573 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3574 (if (> (car org-time-stamp-rounding-minutes) 1)
3575 (let ((r (car org-time-stamp-rounding-minutes))
3576 (time (decode-time)))
3577 (apply 'encode-time
3578 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3579 (nthcdr 2 time))))
3580 (current-time)))
3582 ;;;; Font-Lock stuff, including the activators
3584 (defvar org-mouse-map (make-sparse-keymap))
3585 (org-defkey org-mouse-map
3586 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3587 (org-defkey org-mouse-map
3588 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3589 (when org-mouse-1-follows-link
3590 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3591 (when org-tab-follows-link
3592 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3593 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3594 (when org-return-follows-link
3595 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3596 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3598 (require 'font-lock)
3600 (defconst org-non-link-chars "]\t\n\r<>")
3601 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3602 "shell" "elisp"))
3603 (defvar org-link-types-re nil
3604 "Matches a link that has a url-like prefix like \"http:\"")
3605 (defvar org-link-re-with-space nil
3606 "Matches a link with spaces, optional angular brackets around it.")
3607 (defvar org-link-re-with-space2 nil
3608 "Matches a link with spaces, optional angular brackets around it.")
3609 (defvar org-link-re-with-space3 nil
3610 "Matches a link with spaces, only for internal part in bracket links.")
3611 (defvar org-angle-link-re nil
3612 "Matches link with angular brackets, spaces are allowed.")
3613 (defvar org-plain-link-re nil
3614 "Matches plain link, without spaces.")
3615 (defvar org-bracket-link-regexp nil
3616 "Matches a link in double brackets.")
3617 (defvar org-bracket-link-analytic-regexp nil
3618 "Regular expression used to analyze links.
3619 Here is what the match groups contain after a match:
3620 1: http:
3621 2: http
3622 3: path
3623 4: [desc]
3624 5: desc")
3625 (defvar org-bracket-link-analytic-regexp++ nil
3626 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3627 (defvar org-any-link-re nil
3628 "Regular expression matching any link.")
3630 (defun org-make-link-regexps ()
3631 "Update the link regular expressions.
3632 This should be called after the variable `org-link-types' has changed."
3633 (setq org-link-types-re
3634 (concat
3635 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3636 org-link-re-with-space
3637 (concat
3638 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3639 "\\([^" org-non-link-chars " ]"
3640 "[^" org-non-link-chars "]*"
3641 "[^" org-non-link-chars " ]\\)>?")
3642 org-link-re-with-space2
3643 (concat
3644 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3645 "\\([^" org-non-link-chars " ]"
3646 "[^\t\n\r]*"
3647 "[^" org-non-link-chars " ]\\)>?")
3648 org-link-re-with-space3
3649 (concat
3650 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3651 "\\([^" org-non-link-chars " ]"
3652 "[^\t\n\r]*\\)")
3653 org-angle-link-re
3654 (concat
3655 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3656 "\\([^" org-non-link-chars " ]"
3657 "[^" org-non-link-chars "]*"
3658 "\\)>")
3659 org-plain-link-re
3660 (concat
3661 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3662 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3663 org-bracket-link-regexp
3664 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3665 org-bracket-link-analytic-regexp
3666 (concat
3667 "\\[\\["
3668 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3669 "\\([^]]+\\)"
3670 "\\]"
3671 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3672 "\\]")
3673 org-bracket-link-analytic-regexp++
3674 (concat
3675 "\\[\\["
3676 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3677 "\\([^]]+\\)"
3678 "\\]"
3679 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3680 "\\]")
3681 org-any-link-re
3682 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3683 org-angle-link-re "\\)\\|\\("
3684 org-plain-link-re "\\)")))
3686 (org-make-link-regexps)
3688 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3689 "Regular expression for fast time stamp matching.")
3690 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3691 "Regular expression for fast time stamp matching.")
3692 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3693 "Regular expression matching time strings for analysis.
3694 This one does not require the space after the date, so it can be used
3695 on a string that terminates immediately after the date.")
3696 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3697 "Regular expression matching time strings for analysis.")
3698 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3699 "Regular expression matching time stamps, with groups.")
3700 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3701 "Regular expression matching time stamps (also [..]), with groups.")
3702 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3703 "Regular expression matching a time stamp range.")
3704 (defconst org-tr-regexp-both
3705 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3706 "Regular expression matching a time stamp range.")
3707 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3708 org-ts-regexp "\\)?")
3709 "Regular expression matching a time stamp or time stamp range.")
3710 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3711 org-ts-regexp-both "\\)?")
3712 "Regular expression matching a time stamp or time stamp range.
3713 The time stamps may be either active or inactive.")
3715 (defvar org-emph-face nil)
3717 (defun org-do-emphasis-faces (limit)
3718 "Run through the buffer and add overlays to links."
3719 (let (rtn)
3720 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3721 (if (not (= (char-after (match-beginning 3))
3722 (char-after (match-beginning 4))))
3723 (progn
3724 (setq rtn t)
3725 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3726 'face
3727 (nth 1 (assoc (match-string 3)
3728 org-emphasis-alist)))
3729 (add-text-properties (match-beginning 2) (match-end 2)
3730 '(font-lock-multiline t))
3731 (when org-hide-emphasis-markers
3732 (add-text-properties (match-end 4) (match-beginning 5)
3733 '(invisible org-link))
3734 (add-text-properties (match-beginning 3) (match-end 3)
3735 '(invisible org-link)))))
3736 (backward-char 1))
3737 rtn))
3739 (defun org-emphasize (&optional char)
3740 "Insert or change an emphasis, i.e. a font like bold or italic.
3741 If there is an active region, change that region to a new emphasis.
3742 If there is no region, just insert the marker characters and position
3743 the cursor between them.
3744 CHAR should be either the marker character, or the first character of the
3745 HTML tag associated with that emphasis. If CHAR is a space, the means
3746 to remove the emphasis of the selected region.
3747 If char is not given (for example in an interactive call) it
3748 will be prompted for."
3749 (interactive)
3750 (let ((eal org-emphasis-alist) e det
3751 (erc org-emphasis-regexp-components)
3752 (prompt "")
3753 (string "") beg end move tag c s)
3754 (if (org-region-active-p)
3755 (setq beg (region-beginning) end (region-end)
3756 string (buffer-substring beg end))
3757 (setq move t))
3759 (while (setq e (pop eal))
3760 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3761 c (aref tag 0))
3762 (push (cons c (string-to-char (car e))) det)
3763 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3764 (substring tag 1)))))
3765 (setq det (nreverse det))
3766 (unless char
3767 (message "%s" (concat "Emphasis marker or tag:" prompt))
3768 (setq char (read-char-exclusive)))
3769 (setq char (or (cdr (assoc char det)) char))
3770 (if (equal char ?\ )
3771 (setq s "" move nil)
3772 (unless (assoc (char-to-string char) org-emphasis-alist)
3773 (error "No such emphasis marker: \"%c\"" char))
3774 (setq s (char-to-string char)))
3775 (while (and (> (length string) 1)
3776 (equal (substring string 0 1) (substring string -1))
3777 (assoc (substring string 0 1) org-emphasis-alist))
3778 (setq string (substring string 1 -1)))
3779 (setq string (concat s string s))
3780 (if beg (delete-region beg end))
3781 (unless (or (bolp)
3782 (string-match (concat "[" (nth 0 erc) "\n]")
3783 (char-to-string (char-before (point)))))
3784 (insert " "))
3785 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3786 (char-to-string (char-after (point))))
3787 (insert " ") (backward-char 1))
3788 (insert string)
3789 (and move (backward-char 1))))
3791 (defconst org-nonsticky-props
3792 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3795 (defun org-activate-plain-links (limit)
3796 "Run through the buffer and add overlays to links."
3797 (catch 'exit
3798 (let (f)
3799 (while (re-search-forward org-plain-link-re limit t)
3800 (setq f (get-text-property (match-beginning 0) 'face))
3801 (if (or (eq f 'org-tag)
3802 (and (listp f) (memq 'org-tag f)))
3804 (add-text-properties (match-beginning 0) (match-end 0)
3805 (list 'mouse-face 'highlight
3806 'rear-nonsticky org-nonsticky-props
3807 'keymap org-mouse-map
3809 (throw 'exit t))))))
3811 (defun org-activate-code (limit)
3812 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3813 (progn
3814 (remove-text-properties (match-beginning 0) (match-end 0)
3815 '(display t invisible t intangible t))
3816 t)))
3818 (defun org-activate-angle-links (limit)
3819 "Run through the buffer and add overlays to links."
3820 (if (re-search-forward org-angle-link-re limit t)
3821 (progn
3822 (add-text-properties (match-beginning 0) (match-end 0)
3823 (list 'mouse-face 'highlight
3824 'rear-nonsticky org-nonsticky-props
3825 'keymap org-mouse-map
3827 t)))
3829 (defun org-activate-footnote-links (limit)
3830 "Run through the buffer and add overlays to links."
3831 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3832 limit t)
3833 (progn
3834 (add-text-properties (match-beginning 2) (match-end 2)
3835 (list 'mouse-face 'highlight
3836 'rear-nonsticky org-nonsticky-props
3837 'keymap org-mouse-map
3838 'help-echo
3839 (if (= (point-at-bol) (match-beginning 2))
3840 "Footnote definition"
3841 "Footnote reference")
3843 t)))
3845 (defun org-activate-bracket-links (limit)
3846 "Run through the buffer and add overlays to bracketed links."
3847 (if (re-search-forward org-bracket-link-regexp limit t)
3848 (let* ((help (concat "LINK: "
3849 (org-match-string-no-properties 1)))
3850 ;; FIXME: above we should remove the escapes.
3851 ;; but that requires another match, protecting match data,
3852 ;; a lot of overhead for font-lock.
3853 (ip (org-maybe-intangible
3854 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3855 'keymap org-mouse-map 'mouse-face 'highlight
3856 'font-lock-multiline t 'help-echo help)))
3857 (vp (list 'rear-nonsticky org-nonsticky-props
3858 'keymap org-mouse-map 'mouse-face 'highlight
3859 ' font-lock-multiline t 'help-echo help)))
3860 ;; We need to remove the invisible property here. Table narrowing
3861 ;; may have made some of this invisible.
3862 (remove-text-properties (match-beginning 0) (match-end 0)
3863 '(invisible nil))
3864 (if (match-end 3)
3865 (progn
3866 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3867 (add-text-properties (match-beginning 3) (match-end 3) vp)
3868 (add-text-properties (match-end 3) (match-end 0) ip))
3869 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3870 (add-text-properties (match-beginning 1) (match-end 1) vp)
3871 (add-text-properties (match-end 1) (match-end 0) ip))
3872 t)))
3874 (defun org-activate-dates (limit)
3875 "Run through the buffer and add overlays to dates."
3876 (if (re-search-forward org-tsr-regexp-both limit t)
3877 (progn
3878 (add-text-properties (match-beginning 0) (match-end 0)
3879 (list 'mouse-face 'highlight
3880 'rear-nonsticky org-nonsticky-props
3881 'keymap org-mouse-map))
3882 (when org-display-custom-times
3883 (if (match-end 3)
3884 (org-display-custom-time (match-beginning 3) (match-end 3)))
3885 (org-display-custom-time (match-beginning 1) (match-end 1)))
3886 t)))
3888 (defvar org-target-link-regexp nil
3889 "Regular expression matching radio targets in plain text.")
3890 (make-variable-buffer-local 'org-target-link-regexp)
3891 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3892 "Regular expression matching a link target.")
3893 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3894 "Regular expression matching a radio target.")
3895 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3896 "Regular expression matching any target.")
3898 (defun org-activate-target-links (limit)
3899 "Run through the buffer and add overlays to target matches."
3900 (when org-target-link-regexp
3901 (let ((case-fold-search t))
3902 (if (re-search-forward org-target-link-regexp limit t)
3903 (progn
3904 (add-text-properties (match-beginning 0) (match-end 0)
3905 (list 'mouse-face 'highlight
3906 'rear-nonsticky org-nonsticky-props
3907 'keymap org-mouse-map
3908 'help-echo "Radio target link"
3909 'org-linked-text t))
3910 t)))))
3912 (defun org-update-radio-target-regexp ()
3913 "Find all radio targets in this file and update the regular expression."
3914 (interactive)
3915 (when (memq 'radio org-activate-links)
3916 (setq org-target-link-regexp
3917 (org-make-target-link-regexp (org-all-targets 'radio)))
3918 (org-restart-font-lock)))
3920 (defun org-hide-wide-columns (limit)
3921 (let (s e)
3922 (setq s (text-property-any (point) (or limit (point-max))
3923 'org-cwidth t))
3924 (when s
3925 (setq e (next-single-property-change s 'org-cwidth))
3926 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3927 (goto-char e)
3928 t)))
3930 (defvar org-latex-and-specials-regexp nil
3931 "Regular expression for highlighting export special stuff.")
3932 (defvar org-match-substring-regexp)
3933 (defvar org-match-substring-with-braces-regexp)
3934 (defvar org-export-html-special-string-regexps)
3936 (defun org-compute-latex-and-specials-regexp ()
3937 "Compute regular expression for stuff treated specially by exporters."
3938 (if (not org-highlight-latex-fragments-and-specials)
3939 (org-set-local 'org-latex-and-specials-regexp nil)
3940 (require 'org-exp)
3941 (let*
3942 ((matchers (plist-get org-format-latex-options :matchers))
3943 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3944 org-latex-regexps)))
3945 (options (org-combine-plists (org-default-export-plist)
3946 (org-infile-export-plist)))
3947 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3948 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3949 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3950 (org-export-html-expand (plist-get options :expand-quoted-html))
3951 (org-export-with-special-strings (plist-get options :special-strings))
3952 (re-sub
3953 (cond
3954 ((equal org-export-with-sub-superscripts '{})
3955 (list org-match-substring-with-braces-regexp))
3956 (org-export-with-sub-superscripts
3957 (list org-match-substring-regexp))
3958 (t nil)))
3959 (re-latex
3960 (if org-export-with-LaTeX-fragments
3961 (mapcar (lambda (x) (nth 1 x)) latexs)))
3962 (re-macros
3963 (if org-export-with-TeX-macros
3964 (list (concat "\\\\"
3965 (regexp-opt
3966 (append (mapcar 'car org-html-entities)
3967 (if (boundp 'org-latex-entities)
3968 org-latex-entities nil))
3969 'words))) ; FIXME
3971 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3972 (re-special (if org-export-with-special-strings
3973 (mapcar (lambda (x) (car x))
3974 org-export-html-special-string-regexps)))
3975 (re-rest
3976 (delq nil
3977 (list
3978 (if org-export-html-expand "@<[^>\n]+>")
3979 ))))
3980 (org-set-local
3981 'org-latex-and-specials-regexp
3982 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3983 re-rest) "\\|")))))
3985 (defun org-do-latex-and-special-faces (limit)
3986 "Run through the buffer and add overlays to links."
3987 (when org-latex-and-specials-regexp
3988 (let (rtn d)
3989 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3990 limit t))
3991 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3992 'face))
3993 '(org-code org-verbatim underline)))
3994 (progn
3995 (setq rtn t
3996 d (cond ((member (char-after (1+ (match-beginning 0)))
3997 '(?_ ?^)) 1)
3998 (t 0)))
3999 (font-lock-prepend-text-property
4000 (+ d (match-beginning 0)) (match-end 0)
4001 'face 'org-latex-and-export-specials)
4002 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4003 '(font-lock-multiline t)))))
4004 rtn)))
4006 (defun org-restart-font-lock ()
4007 "Restart font-lock-mode, to force refontification."
4008 (when (and (boundp 'font-lock-mode) font-lock-mode)
4009 (font-lock-mode -1)
4010 (font-lock-mode 1)))
4012 (defun org-all-targets (&optional radio)
4013 "Return a list of all targets in this file.
4014 With optional argument RADIO, only find radio targets."
4015 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4016 rtn)
4017 (save-excursion
4018 (goto-char (point-min))
4019 (while (re-search-forward re nil t)
4020 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4021 rtn)))
4023 (defun org-make-target-link-regexp (targets)
4024 "Make regular expression matching all strings in TARGETS.
4025 The regular expression finds the targets also if there is a line break
4026 between words."
4027 (and targets
4028 (concat
4029 "\\<\\("
4030 (mapconcat
4031 (lambda (x)
4032 (while (string-match " +" x)
4033 (setq x (replace-match "\\s-+" t t x)))
4035 targets
4036 "\\|")
4037 "\\)\\>")))
4039 (defun org-activate-tags (limit)
4040 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4041 (progn
4042 (add-text-properties (match-beginning 1) (match-end 1)
4043 (list 'mouse-face 'highlight
4044 'rear-nonsticky org-nonsticky-props
4045 'keymap org-mouse-map))
4046 t)))
4048 (defun org-outline-level ()
4049 (save-excursion
4050 (looking-at outline-regexp)
4051 (if (match-beginning 1)
4052 (+ (org-get-string-indentation (match-string 1)) 1000)
4053 (1- (- (match-end 0) (match-beginning 0))))))
4055 (defvar org-font-lock-keywords nil)
4057 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4058 "Regular expression matching a property line.")
4060 (defvar org-font-lock-hook nil
4061 "Functions to be called for special font lock stuff.")
4063 (defun org-font-lock-hook (limit)
4064 (run-hook-with-args 'org-font-lock-hook limit))
4066 (defun org-set-font-lock-defaults ()
4067 (let* ((em org-fontify-emphasized-text)
4068 (lk org-activate-links)
4069 (org-font-lock-extra-keywords
4070 (list
4071 ;; Call the hook
4072 '(org-font-lock-hook)
4073 ;; Headlines
4074 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4075 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4076 ;; Table lines
4077 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4078 (1 'org-table t))
4079 ;; Table internals
4080 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4081 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4082 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4083 ;; Drawers
4084 (list org-drawer-regexp '(0 'org-special-keyword t))
4085 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4086 ;; Properties
4087 (list org-property-re
4088 '(1 'org-special-keyword t)
4089 '(3 'org-property-value t))
4090 (if org-format-transports-properties-p
4091 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4092 ;; Links
4093 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4094 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4095 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4096 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4097 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4098 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4099 (if (memq 'footnote lk) '(org-activate-footnote-links
4100 (2 'org-footnote t)))
4101 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4102 '(org-hide-wide-columns (0 nil append))
4103 ;; TODO lines
4104 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4105 '(1 (org-get-todo-face 1) t))
4106 ;; DONE
4107 (if org-fontify-done-headline
4108 (list (concat "^[*]+ +\\<\\("
4109 (mapconcat 'regexp-quote org-done-keywords "\\|")
4110 "\\)\\(.*\\)")
4111 '(2 'org-headline-done t))
4112 nil)
4113 ;; Priorities
4114 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4115 ;; Tags
4116 '(org-font-lock-add-tag-faces)
4117 ;; Special keywords
4118 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4119 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4120 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4121 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4122 ;; Emphasis
4123 (if em
4124 (if (featurep 'xemacs)
4125 '(org-do-emphasis-faces (0 nil append))
4126 '(org-do-emphasis-faces)))
4127 ;; Checkboxes
4128 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4129 2 'bold prepend)
4130 (if org-provide-checkbox-statistics
4131 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4132 (0 (org-get-checkbox-statistics-face) t)))
4133 ;; Description list items
4134 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4135 2 'bold prepend)
4136 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4137 '(1 'org-archived prepend))
4138 ;; Specials
4139 '(org-do-latex-and-special-faces)
4140 ;; Code
4141 '(org-activate-code (1 'org-code t))
4142 ;; COMMENT
4143 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4144 "\\|" org-quote-string "\\)\\>")
4145 '(1 'org-special-keyword t))
4146 '("^#.*" (0 'font-lock-comment-face t))
4148 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4149 ;; Now set the full font-lock-keywords
4150 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4151 (org-set-local 'font-lock-defaults
4152 '(org-font-lock-keywords t nil nil backward-paragraph))
4153 (kill-local-variable 'font-lock-keywords) nil))
4155 (defvar org-m nil)
4156 (defvar org-l nil)
4157 (defvar org-f nil)
4158 (defun org-get-level-face (n)
4159 "Get the right face for match N in font-lock matching of headlines."
4160 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4161 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4162 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4163 (cond
4164 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4165 ((eq n 2) org-f)
4166 (t (if org-level-color-stars-only nil org-f))))
4168 (defun org-get-todo-face (kwd)
4169 "Get the right face for a TODO keyword KWD.
4170 If KWD is a number, get the corresponding match group."
4171 (if (numberp kwd) (setq kwd (match-string kwd)))
4172 (or (cdr (assoc kwd org-todo-keyword-faces))
4173 (and (member kwd org-done-keywords) 'org-done)
4174 'org-todo))
4176 (defun org-font-lock-add-tag-faces (limit)
4177 "Add the special tag faces."
4178 (when (and org-tag-faces org-tags-special-faces-re)
4179 (while (re-search-forward org-tags-special-faces-re limit t)
4180 (add-text-properties (match-beginning 1) (match-end 1)
4181 (list 'face (org-get-tag-face 1)
4182 'font-lock-fontified t))
4183 (backward-char 1))))
4185 (defun org-get-tag-face (kwd)
4186 "Get the right face for a TODO keyword KWD.
4187 If KWD is a number, get the corresponding match group."
4188 (if (numberp kwd) (setq kwd (match-string kwd)))
4189 (or (cdr (assoc kwd org-tag-faces))
4190 'org-tag))
4192 (defun org-unfontify-region (beg end &optional maybe_loudly)
4193 "Remove fontification and activation overlays from links."
4194 (font-lock-default-unfontify-region beg end)
4195 (let* ((buffer-undo-list t)
4196 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4197 (inhibit-modification-hooks t)
4198 deactivate-mark buffer-file-name buffer-file-truename)
4199 (remove-text-properties beg end
4200 '(mouse-face t keymap t org-linked-text t
4201 invisible t intangible t))))
4203 ;;;; Visibility cycling, including org-goto and indirect buffer
4205 ;;; Cycling
4207 (defvar org-cycle-global-status nil)
4208 (make-variable-buffer-local 'org-cycle-global-status)
4209 (defvar org-cycle-subtree-status nil)
4210 (make-variable-buffer-local 'org-cycle-subtree-status)
4212 ;;;###autoload
4213 (defun org-cycle (&optional arg)
4214 "Visibility cycling for Org-mode.
4216 - When this function is called with a prefix argument, rotate the entire
4217 buffer through 3 states (global cycling)
4218 1. OVERVIEW: Show only top-level headlines.
4219 2. CONTENTS: Show all headlines of all levels, but no body text.
4220 3. SHOW ALL: Show everything.
4221 When called with two C-u C-u prefixes, switch to the startup visibility,
4222 determined by the variable `org-startup-folded', and by any VISIBILITY
4223 properties in the buffer.
4224 When called with three C-u C-u C-u prefixed, show the entire buffer,
4225 including drawers.
4227 - When point is at the beginning of a headline, rotate the subtree started
4228 by this line through 3 different states (local cycling)
4229 1. FOLDED: Only the main headline is shown.
4230 2. CHILDREN: The main headline and the direct children are shown.
4231 From this state, you can move to one of the children
4232 and zoom in further.
4233 3. SUBTREE: Show the entire subtree, including body text.
4235 - When there is a numeric prefix, go up to a heading with level ARG, do
4236 a `show-subtree' and return to the previous cursor position. If ARG
4237 is negative, go up that many levels.
4239 - When point is not at the beginning of a headline, execute the global
4240 binding for TAB, which is re-indenting the line. See the option
4241 `org-cycle-emulate-tab' for details.
4243 - Special case: if point is at the beginning of the buffer and there is
4244 no headline in line 1, this function will act as if called with prefix arg.
4245 But only if also the variable `org-cycle-global-at-bob' is t."
4246 (interactive "P")
4247 (org-load-modules-maybe)
4248 (let* ((outline-regexp
4249 (if (and (org-mode-p) org-cycle-include-plain-lists)
4250 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4251 outline-regexp))
4252 (bob-special (and org-cycle-global-at-bob (bobp)
4253 (not (looking-at outline-regexp))))
4254 (org-cycle-hook
4255 (if bob-special
4256 (delq 'org-optimize-window-after-visibility-change
4257 (copy-sequence org-cycle-hook))
4258 org-cycle-hook))
4259 (pos (point)))
4261 (if (or bob-special (equal arg '(4)))
4262 ;; special case: use global cycling
4263 (setq arg t))
4265 (cond
4267 ((equal arg '(16))
4268 (org-set-startup-visibility)
4269 (message "Startup visibility, plus VISIBILITY properties"))
4271 ((equal arg '(64))
4272 (show-all)
4273 (message "Entire buffer visible, including drawers"))
4275 ((org-at-table-p 'any)
4276 ;; Enter the table or move to the next field in the table
4277 (or (org-table-recognize-table.el)
4278 (progn
4279 (if arg (org-table-edit-field t)
4280 (org-table-justify-field-maybe)
4281 (call-interactively 'org-table-next-field)))))
4283 ((eq arg t) ;; Global cycling
4285 (cond
4286 ((and (eq last-command this-command)
4287 (eq org-cycle-global-status 'overview))
4288 ;; We just created the overview - now do table of contents
4289 ;; This can be slow in very large buffers, so indicate action
4290 (message "CONTENTS...")
4291 (org-content)
4292 (message "CONTENTS...done")
4293 (setq org-cycle-global-status 'contents)
4294 (run-hook-with-args 'org-cycle-hook 'contents))
4296 ((and (eq last-command this-command)
4297 (eq org-cycle-global-status 'contents))
4298 ;; We just showed the table of contents - now show everything
4299 (show-all)
4300 (message "SHOW ALL")
4301 (setq org-cycle-global-status 'all)
4302 (run-hook-with-args 'org-cycle-hook 'all))
4305 ;; Default action: go to overview
4306 (org-overview)
4307 (message "OVERVIEW")
4308 (setq org-cycle-global-status 'overview)
4309 (run-hook-with-args 'org-cycle-hook 'overview))))
4311 ((and org-drawers org-drawer-regexp
4312 (save-excursion
4313 (beginning-of-line 1)
4314 (looking-at org-drawer-regexp)))
4315 ;; Toggle block visibility
4316 (org-flag-drawer
4317 (not (get-char-property (match-end 0) 'invisible))))
4319 ((integerp arg)
4320 ;; Show-subtree, ARG levels up from here.
4321 (save-excursion
4322 (org-back-to-heading)
4323 (outline-up-heading (if (< arg 0) (- arg)
4324 (- (funcall outline-level) arg)))
4325 (org-show-subtree)))
4327 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4328 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4329 ;; At a heading: rotate between three different views
4330 (org-back-to-heading)
4331 (let ((goal-column 0) eoh eol eos)
4332 ;; First, some boundaries
4333 (save-excursion
4334 (org-back-to-heading)
4335 (save-excursion
4336 (beginning-of-line 2)
4337 (while (and (not (eobp)) ;; this is like `next-line'
4338 (get-char-property (1- (point)) 'invisible))
4339 (beginning-of-line 2)) (setq eol (point)))
4340 (outline-end-of-heading) (setq eoh (point))
4341 (org-end-of-subtree t)
4342 (unless (eobp)
4343 (skip-chars-forward " \t\n")
4344 (beginning-of-line 1) ; in case this is an item
4346 (setq eos (1- (point))))
4347 ;; Find out what to do next and set `this-command'
4348 (cond
4349 ((= eos eoh)
4350 ;; Nothing is hidden behind this heading
4351 (message "EMPTY ENTRY")
4352 (setq org-cycle-subtree-status nil)
4353 (save-excursion
4354 (goto-char eos)
4355 (outline-next-heading)
4356 (if (org-invisible-p) (org-flag-heading nil))))
4357 ((or (>= eol eos)
4358 (not (string-match "\\S-" (buffer-substring eol eos))))
4359 ;; Entire subtree is hidden in one line: open it
4360 (org-show-entry)
4361 (show-children)
4362 (message "CHILDREN")
4363 (save-excursion
4364 (goto-char eos)
4365 (outline-next-heading)
4366 (if (org-invisible-p) (org-flag-heading nil)))
4367 (setq org-cycle-subtree-status 'children)
4368 (run-hook-with-args 'org-cycle-hook 'children))
4369 ((and (eq last-command this-command)
4370 (eq org-cycle-subtree-status 'children))
4371 ;; We just showed the children, now show everything.
4372 (org-show-subtree)
4373 (message "SUBTREE")
4374 (setq org-cycle-subtree-status 'subtree)
4375 (run-hook-with-args 'org-cycle-hook 'subtree))
4377 ;; Default action: hide the subtree.
4378 (hide-subtree)
4379 (message "FOLDED")
4380 (setq org-cycle-subtree-status 'folded)
4381 (run-hook-with-args 'org-cycle-hook 'folded)))))
4383 ;; TAB emulation and template completion
4384 (buffer-read-only (org-back-to-heading))
4386 ((org-try-structure-completion))
4388 ((org-try-cdlatex-tab))
4390 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4391 (or (not (bolp))
4392 (not (looking-at outline-regexp))))
4393 (call-interactively (global-key-binding "\t")))
4395 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4396 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4397 (or (and (eq org-cycle-emulate-tab 'white)
4398 (= (match-end 0) (point-at-eol)))
4399 (and (eq org-cycle-emulate-tab 'whitestart)
4400 (>= (match-end 0) pos))))
4402 (eq org-cycle-emulate-tab t))
4403 (call-interactively (global-key-binding "\t")))
4405 (t (save-excursion
4406 (org-back-to-heading)
4407 (org-cycle))))))
4409 ;;;###autoload
4410 (defun org-global-cycle (&optional arg)
4411 "Cycle the global visibility. For details see `org-cycle'.
4412 With C-u prefix arg, switch to startup visibility.
4413 With a numeric prefix, show all headlines up to that level."
4414 (interactive "P")
4415 (let ((org-cycle-include-plain-lists
4416 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4417 (cond
4418 ((integerp arg)
4419 (show-all)
4420 (hide-sublevels arg)
4421 (setq org-cycle-global-status 'contents))
4422 ((equal arg '(4))
4423 (org-set-startup-visibility)
4424 (message "Startup visibility, plus VISIBILITY properties."))
4426 (org-cycle '(4))))))
4428 (defun org-set-startup-visibility ()
4429 "Set the visibility required by startup options and properties."
4430 (cond
4431 ((eq org-startup-folded t)
4432 (org-cycle '(4)))
4433 ((eq org-startup-folded 'content)
4434 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4435 (org-cycle '(4)) (org-cycle '(4)))))
4436 (org-set-visibility-according-to-property 'no-cleanup)
4437 (org-cycle-hide-archived-subtrees 'all)
4438 (org-cycle-hide-drawers 'all)
4439 (org-cycle-show-empty-lines 'all))
4441 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4442 "Switch subtree visibilities according to :VISIBILITY: property."
4443 (interactive)
4444 (let (state)
4445 (save-excursion
4446 (goto-char (point-min))
4447 (while (re-search-forward
4448 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4449 nil t)
4450 (setq state (match-string 1))
4451 (save-excursion
4452 (org-back-to-heading t)
4453 (hide-subtree)
4454 (org-reveal)
4455 (cond
4456 ((equal state '("fold" "folded"))
4457 (hide-subtree))
4458 ((equal state "children")
4459 (org-show-hidden-entry)
4460 (show-children))
4461 ((equal state "content")
4462 (save-excursion
4463 (save-restriction
4464 (org-narrow-to-subtree)
4465 (org-content))))
4466 ((member state '("all" "showall"))
4467 (show-subtree)))))
4468 (unless no-cleanup
4469 (org-cycle-hide-archived-subtrees 'all)
4470 (org-cycle-hide-drawers 'all)
4471 (org-cycle-show-empty-lines 'all)))))
4473 (defun org-overview ()
4474 "Switch to overview mode, showing only top-level headlines.
4475 Really, this shows all headlines with level equal or greater than the level
4476 of the first headline in the buffer. This is important, because if the
4477 first headline is not level one, then (hide-sublevels 1) gives confusing
4478 results."
4479 (interactive)
4480 (let ((level (save-excursion
4481 (goto-char (point-min))
4482 (if (re-search-forward (concat "^" outline-regexp) nil t)
4483 (progn
4484 (goto-char (match-beginning 0))
4485 (funcall outline-level))))))
4486 (and level (hide-sublevels level))))
4488 (defun org-content (&optional arg)
4489 "Show all headlines in the buffer, like a table of contents.
4490 With numerical argument N, show content up to level N."
4491 (interactive "P")
4492 (save-excursion
4493 ;; Visit all headings and show their offspring
4494 (and (integerp arg) (org-overview))
4495 (goto-char (point-max))
4496 (catch 'exit
4497 (while (and (progn (condition-case nil
4498 (outline-previous-visible-heading 1)
4499 (error (goto-char (point-min))))
4501 (looking-at outline-regexp))
4502 (if (integerp arg)
4503 (show-children (1- arg))
4504 (show-branches))
4505 (if (bobp) (throw 'exit nil))))))
4508 (defun org-optimize-window-after-visibility-change (state)
4509 "Adjust the window after a change in outline visibility.
4510 This function is the default value of the hook `org-cycle-hook'."
4511 (when (get-buffer-window (current-buffer))
4512 (cond
4513 ; ((eq state 'overview) (org-first-headline-recenter 1))
4514 ; ((eq state 'overview) (org-beginning-of-line))
4515 ((eq state 'content) nil)
4516 ((eq state 'all) nil)
4517 ((eq state 'folded) nil)
4518 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4519 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4521 (defun org-compact-display-after-subtree-move ()
4522 "Show a compacter version of the tree of the entry's parent."
4523 (save-excursion
4524 (if (org-up-heading-safe)
4525 (progn
4526 (hide-subtree)
4527 (show-entry)
4528 (show-children)
4529 (org-cycle-show-empty-lines 'children)
4530 (org-cycle-hide-drawers 'children))
4531 (org-overview))))
4533 (defun org-cycle-show-empty-lines (state)
4534 "Show empty lines above all visible headlines.
4535 The region to be covered depends on STATE when called through
4536 `org-cycle-hook'. Lisp program can use t for STATE to get the
4537 entire buffer covered. Note that an empty line is only shown if there
4538 are at least `org-cycle-separator-lines' empty lines before the headline."
4539 (when (> org-cycle-separator-lines 0)
4540 (save-excursion
4541 (let* ((n org-cycle-separator-lines)
4542 (re (cond
4543 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4544 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4545 (t (let ((ns (number-to-string (- n 2))))
4546 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4547 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4548 beg end)
4549 (cond
4550 ((memq state '(overview contents t))
4551 (setq beg (point-min) end (point-max)))
4552 ((memq state '(children folded))
4553 (setq beg (point) end (progn (org-end-of-subtree t t)
4554 (beginning-of-line 2)
4555 (point)))))
4556 (when beg
4557 (goto-char beg)
4558 (while (re-search-forward re end t)
4559 (if (not (get-char-property (match-end 1) 'invisible))
4560 (outline-flag-region
4561 (match-beginning 1) (match-end 1) nil)))))))
4562 ;; Never hide empty lines at the end of the file.
4563 (save-excursion
4564 (goto-char (point-max))
4565 (outline-previous-heading)
4566 (outline-end-of-heading)
4567 (if (and (looking-at "[ \t\n]+")
4568 (= (match-end 0) (point-max)))
4569 (outline-flag-region (point) (match-end 0) nil))))
4571 (defun org-show-empty-lines-in-parent ()
4572 "Move to the parent and re-show empty lines before visible headlines."
4573 (save-excursion
4574 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4575 (org-cycle-show-empty-lines context))))
4577 (defun org-cycle-hide-drawers (state)
4578 "Re-hide all drawers after a visibility state change."
4579 (when (and (org-mode-p)
4580 (not (memq state '(overview folded))))
4581 (save-excursion
4582 (let* ((globalp (memq state '(contents all)))
4583 (beg (if globalp (point-min) (point)))
4584 (end (if globalp (point-max) (org-end-of-subtree t))))
4585 (goto-char beg)
4586 (while (re-search-forward org-drawer-regexp end t)
4587 (org-flag-drawer t))))))
4589 (defun org-flag-drawer (flag)
4590 (save-excursion
4591 (beginning-of-line 1)
4592 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4593 (let ((b (match-end 0))
4594 (outline-regexp org-outline-regexp))
4595 (if (re-search-forward
4596 "^[ \t]*:END:"
4597 (save-excursion (outline-next-heading) (point)) t)
4598 (outline-flag-region b (point-at-eol) flag)
4599 (error ":END: line missing"))))))
4601 (defun org-subtree-end-visible-p ()
4602 "Is the end of the current subtree visible?"
4603 (pos-visible-in-window-p
4604 (save-excursion (org-end-of-subtree t) (point))))
4606 (defun org-first-headline-recenter (&optional N)
4607 "Move cursor to the first headline and recenter the headline.
4608 Optional argument N means, put the headline into the Nth line of the window."
4609 (goto-char (point-min))
4610 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4611 (beginning-of-line)
4612 (recenter (prefix-numeric-value N))))
4614 ;;; Org-goto
4616 (defvar org-goto-window-configuration nil)
4617 (defvar org-goto-marker nil)
4618 (defvar org-goto-map
4619 (let ((map (make-sparse-keymap)))
4620 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4621 (while (setq cmd (pop cmds))
4622 (substitute-key-definition cmd cmd map global-map)))
4623 (suppress-keymap map)
4624 (org-defkey map "\C-m" 'org-goto-ret)
4625 (org-defkey map [(return)] 'org-goto-ret)
4626 (org-defkey map [(left)] 'org-goto-left)
4627 (org-defkey map [(right)] 'org-goto-right)
4628 (org-defkey map [(control ?g)] 'org-goto-quit)
4629 (org-defkey map "\C-i" 'org-cycle)
4630 (org-defkey map [(tab)] 'org-cycle)
4631 (org-defkey map [(down)] 'outline-next-visible-heading)
4632 (org-defkey map [(up)] 'outline-previous-visible-heading)
4633 (if org-goto-auto-isearch
4634 (if (fboundp 'define-key-after)
4635 (define-key-after map [t] 'org-goto-local-auto-isearch)
4636 nil)
4637 (org-defkey map "q" 'org-goto-quit)
4638 (org-defkey map "n" 'outline-next-visible-heading)
4639 (org-defkey map "p" 'outline-previous-visible-heading)
4640 (org-defkey map "f" 'outline-forward-same-level)
4641 (org-defkey map "b" 'outline-backward-same-level)
4642 (org-defkey map "u" 'outline-up-heading))
4643 (org-defkey map "/" 'org-occur)
4644 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4645 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4646 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4647 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4648 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4649 map))
4651 (defconst org-goto-help
4652 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4653 RET=jump to location [Q]uit and return to previous location
4654 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4656 (defvar org-goto-start-pos) ; dynamically scoped parameter
4658 ;; FIXME: Docstring doe not mention both interfaces
4659 (defun org-goto (&optional alternative-interface)
4660 "Look up a different location in the current file, keeping current visibility.
4662 When you want look-up or go to a different location in a document, the
4663 fastest way is often to fold the entire buffer and then dive into the tree.
4664 This method has the disadvantage, that the previous location will be folded,
4665 which may not be what you want.
4667 This command works around this by showing a copy of the current buffer
4668 in an indirect buffer, in overview mode. You can dive into the tree in
4669 that copy, use org-occur and incremental search to find a location.
4670 When pressing RET or `Q', the command returns to the original buffer in
4671 which the visibility is still unchanged. After RET is will also jump to
4672 the location selected in the indirect buffer and expose the
4673 the headline hierarchy above."
4674 (interactive "P")
4675 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4676 (org-refile-use-outline-path t)
4677 (interface
4678 (if (not alternative-interface)
4679 org-goto-interface
4680 (if (eq org-goto-interface 'outline)
4681 'outline-path-completion
4682 'outline)))
4683 (org-goto-start-pos (point))
4684 (selected-point
4685 (if (eq interface 'outline)
4686 (car (org-get-location (current-buffer) org-goto-help))
4687 (nth 3 (org-refile-get-location "Goto: ")))))
4688 (if selected-point
4689 (progn
4690 (org-mark-ring-push org-goto-start-pos)
4691 (goto-char selected-point)
4692 (if (or (org-invisible-p) (org-invisible-p2))
4693 (org-show-context 'org-goto)))
4694 (message "Quit"))))
4696 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4697 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4698 (defvar org-goto-local-auto-isearch-map) ; defined below
4700 (defun org-get-location (buf help)
4701 "Let the user select a location in the Org-mode buffer BUF.
4702 This function uses a recursive edit. It returns the selected position
4703 or nil."
4704 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4705 (isearch-hide-immediately nil)
4706 (isearch-search-fun-function
4707 (lambda () 'org-goto-local-search-headings))
4708 (org-goto-selected-point org-goto-exit-command))
4709 (save-excursion
4710 (save-window-excursion
4711 (delete-other-windows)
4712 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4713 (switch-to-buffer
4714 (condition-case nil
4715 (make-indirect-buffer (current-buffer) "*org-goto*")
4716 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4717 (with-output-to-temp-buffer "*Help*"
4718 (princ help))
4719 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4720 (setq buffer-read-only nil)
4721 (let ((org-startup-truncated t)
4722 (org-startup-folded nil)
4723 (org-startup-align-all-tables nil))
4724 (org-mode)
4725 (org-overview))
4726 (setq buffer-read-only t)
4727 (if (and (boundp 'org-goto-start-pos)
4728 (integer-or-marker-p org-goto-start-pos))
4729 (let ((org-show-hierarchy-above t)
4730 (org-show-siblings t)
4731 (org-show-following-heading t))
4732 (goto-char org-goto-start-pos)
4733 (and (org-invisible-p) (org-show-context)))
4734 (goto-char (point-min)))
4735 (org-beginning-of-line)
4736 (message "Select location and press RET")
4737 (use-local-map org-goto-map)
4738 (recursive-edit)
4740 (kill-buffer "*org-goto*")
4741 (cons org-goto-selected-point org-goto-exit-command)))
4743 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4744 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4745 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4746 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4748 (defun org-goto-local-search-headings (string bound noerror)
4749 "Search and make sure that any matches are in headlines."
4750 (catch 'return
4751 (while (if isearch-forward
4752 (search-forward string bound noerror)
4753 (search-backward string bound noerror))
4754 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4755 (and (member :headline context)
4756 (not (member :tags context))))
4757 (throw 'return (point))))))
4759 (defun org-goto-local-auto-isearch ()
4760 "Start isearch."
4761 (interactive)
4762 (goto-char (point-min))
4763 (let ((keys (this-command-keys)))
4764 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4765 (isearch-mode t)
4766 (isearch-process-search-char (string-to-char keys)))))
4768 (defun org-goto-ret (&optional arg)
4769 "Finish `org-goto' by going to the new location."
4770 (interactive "P")
4771 (setq org-goto-selected-point (point)
4772 org-goto-exit-command 'return)
4773 (throw 'exit nil))
4775 (defun org-goto-left ()
4776 "Finish `org-goto' by going to the new location."
4777 (interactive)
4778 (if (org-on-heading-p)
4779 (progn
4780 (beginning-of-line 1)
4781 (setq org-goto-selected-point (point)
4782 org-goto-exit-command 'left)
4783 (throw 'exit nil))
4784 (error "Not on a heading")))
4786 (defun org-goto-right ()
4787 "Finish `org-goto' by going to the new location."
4788 (interactive)
4789 (if (org-on-heading-p)
4790 (progn
4791 (setq org-goto-selected-point (point)
4792 org-goto-exit-command 'right)
4793 (throw 'exit nil))
4794 (error "Not on a heading")))
4796 (defun org-goto-quit ()
4797 "Finish `org-goto' without cursor motion."
4798 (interactive)
4799 (setq org-goto-selected-point nil)
4800 (setq org-goto-exit-command 'quit)
4801 (throw 'exit nil))
4803 ;;; Indirect buffer display of subtrees
4805 (defvar org-indirect-dedicated-frame nil
4806 "This is the frame being used for indirect tree display.")
4807 (defvar org-last-indirect-buffer nil)
4809 (defun org-tree-to-indirect-buffer (&optional arg)
4810 "Create indirect buffer and narrow it to current subtree.
4811 With numerical prefix ARG, go up to this level and then take that tree.
4812 If ARG is negative, go up that many levels.
4813 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4814 indirect buffer previously made with this command, to avoid proliferation of
4815 indirect buffers. However, when you call the command with a `C-u' prefix, or
4816 when `org-indirect-buffer-display' is `new-frame', the last buffer
4817 is kept so that you can work with several indirect buffers at the same time.
4818 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4819 requests that a new frame be made for the new buffer, so that the dedicated
4820 frame is not changed."
4821 (interactive "P")
4822 (let ((cbuf (current-buffer))
4823 (cwin (selected-window))
4824 (pos (point))
4825 beg end level heading ibuf)
4826 (save-excursion
4827 (org-back-to-heading t)
4828 (when (numberp arg)
4829 (setq level (org-outline-level))
4830 (if (< arg 0) (setq arg (+ level arg)))
4831 (while (> (setq level (org-outline-level)) arg)
4832 (outline-up-heading 1 t)))
4833 (setq beg (point)
4834 heading (org-get-heading))
4835 (org-end-of-subtree t) (setq end (point)))
4836 (if (and (buffer-live-p org-last-indirect-buffer)
4837 (not (eq org-indirect-buffer-display 'new-frame))
4838 (not arg))
4839 (kill-buffer org-last-indirect-buffer))
4840 (setq ibuf (org-get-indirect-buffer cbuf)
4841 org-last-indirect-buffer ibuf)
4842 (cond
4843 ((or (eq org-indirect-buffer-display 'new-frame)
4844 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4845 (select-frame (make-frame))
4846 (delete-other-windows)
4847 (switch-to-buffer ibuf)
4848 (org-set-frame-title heading))
4849 ((eq org-indirect-buffer-display 'dedicated-frame)
4850 (raise-frame
4851 (select-frame (or (and org-indirect-dedicated-frame
4852 (frame-live-p org-indirect-dedicated-frame)
4853 org-indirect-dedicated-frame)
4854 (setq org-indirect-dedicated-frame (make-frame)))))
4855 (delete-other-windows)
4856 (switch-to-buffer ibuf)
4857 (org-set-frame-title (concat "Indirect: " heading)))
4858 ((eq org-indirect-buffer-display 'current-window)
4859 (switch-to-buffer ibuf))
4860 ((eq org-indirect-buffer-display 'other-window)
4861 (pop-to-buffer ibuf))
4862 (t (error "Invalid value.")))
4863 (if (featurep 'xemacs)
4864 (save-excursion (org-mode) (turn-on-font-lock)))
4865 (narrow-to-region beg end)
4866 (show-all)
4867 (goto-char pos)
4868 (and (window-live-p cwin) (select-window cwin))))
4870 (defun org-get-indirect-buffer (&optional buffer)
4871 (setq buffer (or buffer (current-buffer)))
4872 (let ((n 1) (base (buffer-name buffer)) bname)
4873 (while (buffer-live-p
4874 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4875 (setq n (1+ n)))
4876 (condition-case nil
4877 (make-indirect-buffer buffer bname 'clone)
4878 (error (make-indirect-buffer buffer bname)))))
4880 (defun org-set-frame-title (title)
4881 "Set the title of the current frame to the string TITLE."
4882 ;; FIXME: how to name a single frame in XEmacs???
4883 (unless (featurep 'xemacs)
4884 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4886 ;;;; Structure editing
4888 ;;; Inserting headlines
4890 (defun org-previous-line-empty-p ()
4891 (save-excursion
4892 (and (not (bobp))
4893 (or (beginning-of-line 0) t)
4894 (save-match-data
4895 (looking-at "[ \t]*$")))))
4897 (defun org-insert-heading (&optional force-heading)
4898 "Insert a new heading or item with same depth at point.
4899 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4900 If point is at the beginning of a headline, insert a sibling before the
4901 current headline. If point is not at the beginning, do not split the line,
4902 but create the new headline after the current line."
4903 (interactive "P")
4904 (if (= (buffer-size) 0)
4905 (insert "\n* ")
4906 (when (or force-heading (not (org-insert-item)))
4907 (let* ((empty-line-p nil)
4908 (head (save-excursion
4909 (condition-case nil
4910 (progn
4911 (org-back-to-heading)
4912 (setq empty-line-p (org-previous-line-empty-p))
4913 (match-string 0))
4914 (error "*"))))
4915 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4916 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4917 pos hide-previous previous-pos)
4918 (cond
4919 ((and (org-on-heading-p) (bolp)
4920 (or (bobp)
4921 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4922 ;; insert before the current line
4923 (open-line (if blank 2 1)))
4924 ((and (bolp)
4925 (or (bobp)
4926 (save-excursion
4927 (backward-char 1) (not (org-invisible-p)))))
4928 ;; insert right here
4929 nil)
4931 ;; somewhere in the line
4932 (save-excursion
4933 (setq previous-pos (point-at-bol))
4934 (end-of-line)
4935 (setq hide-previous (org-invisible-p)))
4936 (and org-insert-heading-respect-content (org-show-subtree))
4937 (let ((split
4938 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4939 (save-excursion
4940 (let ((p (point)))
4941 (goto-char (point-at-bol))
4942 (and (looking-at org-complex-heading-regexp)
4943 (> p (match-beginning 4)))))))
4944 tags pos)
4945 (cond
4946 (org-insert-heading-respect-content
4947 (org-end-of-subtree nil t)
4948 (or (bolp) (newline))
4949 (or (org-previous-line-empty-p)
4950 (and blank (newline)))
4951 (open-line 1))
4952 ((org-on-heading-p)
4953 (when hide-previous
4954 (show-children)
4955 (org-show-entry))
4956 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4957 (setq tags (and (match-end 2) (match-string 2)))
4958 (and (match-end 1)
4959 (delete-region (match-beginning 1) (match-end 1)))
4960 (setq pos (point-at-bol))
4961 (or split (end-of-line 1))
4962 (delete-horizontal-space)
4963 (newline (if blank 2 1))
4964 (when tags
4965 (save-excursion
4966 (goto-char pos)
4967 (end-of-line 1)
4968 (insert " " tags)
4969 (org-set-tags nil 'align))))
4971 (or split (end-of-line 1))
4972 (newline (if blank 2 1)))))))
4973 (insert head) (just-one-space)
4974 (setq pos (point))
4975 (end-of-line 1)
4976 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4977 (when (and org-insert-heading-respect-content hide-previous)
4978 (save-excursion
4979 (goto-char previous-pos)
4980 (hide-subtree)))
4981 (run-hooks 'org-insert-heading-hook)))))
4983 (defun org-get-heading (&optional no-tags)
4984 "Return the heading of the current entry, without the stars."
4985 (save-excursion
4986 (org-back-to-heading t)
4987 (if (looking-at
4988 (if no-tags
4989 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4990 "\\*+[ \t]+\\([^\r\n]*\\)"))
4991 (match-string 1) "")))
4993 (defun org-heading-components ()
4994 "Return the components of the current heading.
4995 This is a list with the following elements:
4996 - the level as an integer
4997 - the reduced level, different if `org-odd-levels-only' is set.
4998 - the TODO keyword, or nil
4999 - the priority character, like ?A, or nil if no priority is given
5000 - the headline text itself, or the tags string if no headline text
5001 - the tags string, or nil."
5002 (save-excursion
5003 (org-back-to-heading t)
5004 (if (looking-at org-complex-heading-regexp)
5005 (list (length (match-string 1))
5006 (org-reduced-level (length (match-string 1)))
5007 (org-match-string-no-properties 2)
5008 (and (match-end 3) (aref (match-string 3) 2))
5009 (org-match-string-no-properties 4)
5010 (org-match-string-no-properties 5)))))
5012 (defun org-insert-heading-after-current ()
5013 "Insert a new heading with same level as current, after current subtree."
5014 (interactive)
5015 (org-back-to-heading)
5016 (org-insert-heading)
5017 (org-move-subtree-down)
5018 (end-of-line 1))
5020 (defun org-insert-heading-respect-content ()
5021 (interactive)
5022 (let ((org-insert-heading-respect-content t))
5023 (org-insert-heading t)))
5025 (defun org-insert-todo-heading-respect-content (&optional force-state)
5026 (interactive "P")
5027 (let ((org-insert-heading-respect-content t))
5028 (org-insert-todo-heading force-state t)))
5030 (defun org-insert-todo-heading (arg &optional force-heading)
5031 "Insert a new heading with the same level and TODO state as current heading.
5032 If the heading has no TODO state, or if the state is DONE, use the first
5033 state (TODO by default). Also with prefix arg, force first state."
5034 (interactive "P")
5035 (when (or force-heading (not (org-insert-item 'checkbox)))
5036 (org-insert-heading force-heading)
5037 (save-excursion
5038 (org-back-to-heading)
5039 (outline-previous-heading)
5040 (looking-at org-todo-line-regexp))
5041 (if (or arg
5042 (not (match-beginning 2))
5043 (member (match-string 2) org-done-keywords))
5044 (insert (car org-todo-keywords-1) " ")
5045 (insert (match-string 2) " "))
5046 (when org-provide-todo-statistics
5047 (org-update-parent-todo-statistics))))
5049 (defun org-insert-subheading (arg)
5050 "Insert a new subheading and demote it.
5051 Works for outline headings and for plain lists alike."
5052 (interactive "P")
5053 (org-insert-heading arg)
5054 (cond
5055 ((org-on-heading-p) (org-do-demote))
5056 ((org-at-item-p) (org-indent-item 1))))
5058 (defun org-insert-todo-subheading (arg)
5059 "Insert a new subheading with TODO keyword or checkbox and demote it.
5060 Works for outline headings and for plain lists alike."
5061 (interactive "P")
5062 (org-insert-todo-heading arg)
5063 (cond
5064 ((org-on-heading-p) (org-do-demote))
5065 ((org-at-item-p) (org-indent-item 1))))
5067 ;;; Promotion and Demotion
5069 (defun org-promote-subtree ()
5070 "Promote the entire subtree.
5071 See also `org-promote'."
5072 (interactive)
5073 (save-excursion
5074 (org-map-tree 'org-promote))
5075 (org-fix-position-after-promote))
5077 (defun org-demote-subtree ()
5078 "Demote the entire subtree. See `org-demote'.
5079 See also `org-promote'."
5080 (interactive)
5081 (save-excursion
5082 (org-map-tree 'org-demote))
5083 (org-fix-position-after-promote))
5086 (defun org-do-promote ()
5087 "Promote the current heading higher up the tree.
5088 If the region is active in `transient-mark-mode', promote all headings
5089 in the region."
5090 (interactive)
5091 (save-excursion
5092 (if (org-region-active-p)
5093 (org-map-region 'org-promote (region-beginning) (region-end))
5094 (org-promote)))
5095 (org-fix-position-after-promote))
5097 (defun org-do-demote ()
5098 "Demote the current heading lower down the tree.
5099 If the region is active in `transient-mark-mode', demote all headings
5100 in the region."
5101 (interactive)
5102 (save-excursion
5103 (if (org-region-active-p)
5104 (org-map-region 'org-demote (region-beginning) (region-end))
5105 (org-demote)))
5106 (org-fix-position-after-promote))
5108 (defun org-fix-position-after-promote ()
5109 "Make sure that after pro/demotion cursor position is right."
5110 (let ((pos (point)))
5111 (when (save-excursion
5112 (beginning-of-line 1)
5113 (looking-at org-todo-line-regexp)
5114 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5115 (cond ((eobp) (insert " "))
5116 ((eolp) (insert " "))
5117 ((equal (char-after) ?\ ) (forward-char 1))))))
5119 (defun org-reduced-level (l)
5120 "Compute the effective level of a heading.
5121 This takes into account the setting of `org-odd-levels-only'."
5122 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5124 (defun org-get-valid-level (level &optional change)
5125 "Rectify a level change under the influence of `org-odd-levels-only'
5126 LEVEL is a current level, CHANGE is by how much the level should be
5127 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5128 even level numbers will become the next higher odd number."
5129 (if org-odd-levels-only
5130 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5131 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5132 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5133 (max 1 (+ level change))))
5135 (if (boundp 'define-obsolete-function-alias)
5136 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5137 (define-obsolete-function-alias 'org-get-legal-level
5138 'org-get-valid-level)
5139 (define-obsolete-function-alias 'org-get-legal-level
5140 'org-get-valid-level "23.1")))
5142 (defun org-promote ()
5143 "Promote the current heading higher up the tree.
5144 If the region is active in `transient-mark-mode', promote all headings
5145 in the region."
5146 (org-back-to-heading t)
5147 (let* ((level (save-match-data (funcall outline-level)))
5148 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5149 (diff (abs (- level (length up-head) -1))))
5150 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5151 (replace-match up-head nil t)
5152 ;; Fixup tag positioning
5153 (and org-auto-align-tags (org-set-tags nil t))
5154 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5156 (defun org-demote ()
5157 "Demote the current heading lower down the tree.
5158 If the region is active in `transient-mark-mode', demote all headings
5159 in the region."
5160 (org-back-to-heading t)
5161 (let* ((level (save-match-data (funcall outline-level)))
5162 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5163 (diff (abs (- level (length down-head) -1))))
5164 (replace-match down-head nil t)
5165 ;; Fixup tag positioning
5166 (and org-auto-align-tags (org-set-tags nil t))
5167 (if org-adapt-indentation (org-fixup-indentation diff))))
5169 (defun org-map-tree (fun)
5170 "Call FUN for every heading underneath the current one."
5171 (org-back-to-heading)
5172 (let ((level (funcall outline-level)))
5173 (save-excursion
5174 (funcall fun)
5175 (while (and (progn
5176 (outline-next-heading)
5177 (> (funcall outline-level) level))
5178 (not (eobp)))
5179 (funcall fun)))))
5181 (defun org-map-region (fun beg end)
5182 "Call FUN for every heading between BEG and END."
5183 (let ((org-ignore-region t))
5184 (save-excursion
5185 (setq end (copy-marker end))
5186 (goto-char beg)
5187 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5188 (< (point) end))
5189 (funcall fun))
5190 (while (and (progn
5191 (outline-next-heading)
5192 (< (point) end))
5193 (not (eobp)))
5194 (funcall fun)))))
5196 (defun org-fixup-indentation (diff)
5197 "Change the indentation in the current entry by DIFF
5198 However, if any line in the current entry has no indentation, or if it
5199 would end up with no indentation after the change, nothing at all is done."
5200 (save-excursion
5201 (let ((end (save-excursion (outline-next-heading)
5202 (point-marker)))
5203 (prohibit (if (> diff 0)
5204 "^\\S-"
5205 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5206 col)
5207 (unless (save-excursion (end-of-line 1)
5208 (re-search-forward prohibit end t))
5209 (while (and (< (point) end)
5210 (re-search-forward "^[ \t]+" end t))
5211 (goto-char (match-end 0))
5212 (setq col (current-column))
5213 (if (< diff 0) (replace-match ""))
5214 (org-indent-to-column (+ diff col))))
5215 (move-marker end nil))))
5217 (defun org-convert-to-odd-levels ()
5218 "Convert an org-mode file with all levels allowed to one with odd levels.
5219 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5220 level 5 etc."
5221 (interactive)
5222 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5223 (let ((org-odd-levels-only nil) n)
5224 (save-excursion
5225 (goto-char (point-min))
5226 (while (re-search-forward "^\\*\\*+ " nil t)
5227 (setq n (- (length (match-string 0)) 2))
5228 (while (>= (setq n (1- n)) 0)
5229 (org-demote))
5230 (end-of-line 1))))))
5233 (defun org-convert-to-oddeven-levels ()
5234 "Convert an org-mode file with only odd levels to one with odd and even levels.
5235 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5236 section with an even level, conversion would destroy the structure of the file. An error
5237 is signaled in this case."
5238 (interactive)
5239 (goto-char (point-min))
5240 ;; First check if there are no even levels
5241 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5242 (org-show-context t)
5243 (error "Not all levels are odd in this file. Conversion not possible."))
5244 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5245 (let ((org-odd-levels-only nil) n)
5246 (save-excursion
5247 (goto-char (point-min))
5248 (while (re-search-forward "^\\*\\*+ " nil t)
5249 (setq n (/ (1- (length (match-string 0))) 2))
5250 (while (>= (setq n (1- n)) 0)
5251 (org-promote))
5252 (end-of-line 1))))))
5254 (defun org-tr-level (n)
5255 "Make N odd if required."
5256 (if org-odd-levels-only (1+ (/ n 2)) n))
5258 ;;; Vertical tree motion, cutting and pasting of subtrees
5260 (defun org-move-subtree-up (&optional arg)
5261 "Move the current subtree up past ARG headlines of the same level."
5262 (interactive "p")
5263 (org-move-subtree-down (- (prefix-numeric-value arg))))
5265 (defun org-move-subtree-down (&optional arg)
5266 "Move the current subtree down past ARG headlines of the same level."
5267 (interactive "p")
5268 (setq arg (prefix-numeric-value arg))
5269 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5270 'outline-get-last-sibling))
5271 (ins-point (make-marker))
5272 (cnt (abs arg))
5273 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5274 ;; Select the tree
5275 (org-back-to-heading)
5276 (setq beg0 (point))
5277 (save-excursion
5278 (setq ne-beg (org-back-over-empty-lines))
5279 (setq beg (point)))
5280 (save-match-data
5281 (save-excursion (outline-end-of-heading)
5282 (setq folded (org-invisible-p)))
5283 (outline-end-of-subtree))
5284 (outline-next-heading)
5285 (setq ne-end (org-back-over-empty-lines))
5286 (setq end (point))
5287 (goto-char beg0)
5288 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5289 ;; include less whitespace
5290 (save-excursion
5291 (goto-char beg)
5292 (forward-line (- ne-beg ne-end))
5293 (setq beg (point))))
5294 ;; Find insertion point, with error handling
5295 (while (> cnt 0)
5296 (or (and (funcall movfunc) (looking-at outline-regexp))
5297 (progn (goto-char beg0)
5298 (error "Cannot move past superior level or buffer limit")))
5299 (setq cnt (1- cnt)))
5300 (if (> arg 0)
5301 ;; Moving forward - still need to move over subtree
5302 (progn (org-end-of-subtree t t)
5303 (save-excursion
5304 (org-back-over-empty-lines)
5305 (or (bolp) (newline)))))
5306 (setq ne-ins (org-back-over-empty-lines))
5307 (move-marker ins-point (point))
5308 (setq txt (buffer-substring beg end))
5309 (org-save-markers-in-region beg end)
5310 (delete-region beg end)
5311 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5312 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5313 (let ((bbb (point)))
5314 (insert-before-markers txt)
5315 (org-reinstall-markers-in-region bbb)
5316 (move-marker ins-point bbb))
5317 (or (bolp) (insert "\n"))
5318 (setq ins-end (point))
5319 (goto-char ins-point)
5320 (org-skip-whitespace)
5321 (when (and (< arg 0)
5322 (org-first-sibling-p)
5323 (> ne-ins ne-beg))
5324 ;; Move whitespace back to beginning
5325 (save-excursion
5326 (goto-char ins-end)
5327 (let ((kill-whole-line t))
5328 (kill-line (- ne-ins ne-beg)) (point)))
5329 (insert (make-string (- ne-ins ne-beg) ?\n)))
5330 (move-marker ins-point nil)
5331 (org-compact-display-after-subtree-move)
5332 (org-show-empty-lines-in-parent)
5333 (unless folded
5334 (org-show-entry)
5335 (show-children)
5336 (org-cycle-hide-drawers 'children))))
5338 (defvar org-subtree-clip ""
5339 "Clipboard for cut and paste of subtrees.
5340 This is actually only a copy of the kill, because we use the normal kill
5341 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5343 (defvar org-subtree-clip-folded nil
5344 "Was the last copied subtree folded?
5345 This is used to fold the tree back after pasting.")
5347 (defun org-cut-subtree (&optional n)
5348 "Cut the current subtree into the clipboard.
5349 With prefix arg N, cut this many sequential subtrees.
5350 This is a short-hand for marking the subtree and then cutting it."
5351 (interactive "p")
5352 (org-copy-subtree n 'cut))
5354 (defun org-copy-subtree (&optional n cut force-store-markers)
5355 "Cut the current subtree into the clipboard.
5356 With prefix arg N, cut this many sequential subtrees.
5357 This is a short-hand for marking the subtree and then copying it.
5358 If CUT is non-nil, actually cut the subtree.
5359 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5360 of some markers in the region, even if CUT is non-nil. This is
5361 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5362 (interactive "p")
5363 (let (beg end folded (beg0 (point)))
5364 (if (interactive-p)
5365 (org-back-to-heading nil) ; take what looks like a subtree
5366 (org-back-to-heading t)) ; take what is really there
5367 (org-back-over-empty-lines)
5368 (setq beg (point))
5369 (skip-chars-forward " \t\r\n")
5370 (save-match-data
5371 (save-excursion (outline-end-of-heading)
5372 (setq folded (org-invisible-p)))
5373 (condition-case nil
5374 (outline-forward-same-level (1- n))
5375 (error nil))
5376 (org-end-of-subtree t t))
5377 (org-back-over-empty-lines)
5378 (setq end (point))
5379 (goto-char beg0)
5380 (when (> end beg)
5381 (setq org-subtree-clip-folded folded)
5382 (when (or cut force-store-markers)
5383 (org-save-markers-in-region beg end))
5384 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5385 (setq org-subtree-clip (current-kill 0))
5386 (message "%s: Subtree(s) with %d characters"
5387 (if cut "Cut" "Copied")
5388 (length org-subtree-clip)))))
5390 (defun org-paste-subtree (&optional level tree for-yank)
5391 "Paste the clipboard as a subtree, with modification of headline level.
5392 The entire subtree is promoted or demoted in order to match a new headline
5393 level.
5395 If the cursor is at the beginning of a headline, the same level as
5396 that headline is used to paste the tree
5398 If not, the new level is derived from the *visible* headings
5399 before and after the insertion point, and taken to be the inferior headline
5400 level of the two. So if the previous visible heading is level 3 and the
5401 next is level 4 (or vice versa), level 4 will be used for insertion.
5402 This makes sure that the subtree remains an independent subtree and does
5403 not swallow low level entries.
5405 You can also force a different level, either by using a numeric prefix
5406 argument, or by inserting the heading marker by hand. For example, if the
5407 cursor is after \"*****\", then the tree will be shifted to level 5.
5409 If optional TREE is given, use this text instead of the kill ring.
5411 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5412 move back over whitespace before inserting, and move point to the end of
5413 the inserted text when done."
5414 (interactive "P")
5415 (unless (org-kill-is-subtree-p tree)
5416 (error "%s"
5417 (substitute-command-keys
5418 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5419 (let* ((visp (not (org-invisible-p)))
5420 (txt (or tree (and kill-ring (current-kill 0))))
5421 (^re (concat "^\\(" outline-regexp "\\)"))
5422 (re (concat "\\(" outline-regexp "\\)"))
5423 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5425 (old-level (if (string-match ^re txt)
5426 (- (match-end 0) (match-beginning 0) 1)
5427 -1))
5428 (force-level (cond (level (prefix-numeric-value level))
5429 ((and (looking-at "[ \t]*$")
5430 (string-match
5431 ^re_ (buffer-substring
5432 (point-at-bol) (point))))
5433 (- (match-end 1) (match-beginning 1)))
5434 ((and (bolp)
5435 (looking-at org-outline-regexp))
5436 (- (match-end 0) (point) 1))
5437 (t nil)))
5438 (previous-level (save-excursion
5439 (condition-case nil
5440 (progn
5441 (outline-previous-visible-heading 1)
5442 (if (looking-at re)
5443 (- (match-end 0) (match-beginning 0) 1)
5445 (error 1))))
5446 (next-level (save-excursion
5447 (condition-case nil
5448 (progn
5449 (or (looking-at outline-regexp)
5450 (outline-next-visible-heading 1))
5451 (if (looking-at re)
5452 (- (match-end 0) (match-beginning 0) 1)
5454 (error 1))))
5455 (new-level (or force-level (max previous-level next-level)))
5456 (shift (if (or (= old-level -1)
5457 (= new-level -1)
5458 (= old-level new-level))
5460 (- new-level old-level)))
5461 (delta (if (> shift 0) -1 1))
5462 (func (if (> shift 0) 'org-demote 'org-promote))
5463 (org-odd-levels-only nil)
5464 beg end newend)
5465 ;; Remove the forced level indicator
5466 (if force-level
5467 (delete-region (point-at-bol) (point)))
5468 ;; Paste
5469 (beginning-of-line 1)
5470 (unless for-yank (org-back-over-empty-lines))
5471 (setq beg (point))
5472 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5473 (insert-before-markers txt)
5474 (unless (string-match "\n\\'" txt) (insert "\n"))
5475 (setq newend (point))
5476 (org-reinstall-markers-in-region beg)
5477 (setq end (point))
5478 (goto-char beg)
5479 (skip-chars-forward " \t\n\r")
5480 (setq beg (point))
5481 (if (and (org-invisible-p) visp)
5482 (save-excursion (outline-show-heading)))
5483 ;; Shift if necessary
5484 (unless (= shift 0)
5485 (save-restriction
5486 (narrow-to-region beg end)
5487 (while (not (= shift 0))
5488 (org-map-region func (point-min) (point-max))
5489 (setq shift (+ delta shift)))
5490 (goto-char (point-min))
5491 (setq newend (point-max))))
5492 (when (or (interactive-p) for-yank)
5493 (message "Clipboard pasted as level %d subtree" new-level))
5494 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5495 kill-ring
5496 (eq org-subtree-clip (current-kill 0))
5497 org-subtree-clip-folded)
5498 ;; The tree was folded before it was killed/copied
5499 (hide-subtree))
5500 (and for-yank (goto-char newend))))
5502 (defun org-kill-is-subtree-p (&optional txt)
5503 "Check if the current kill is an outline subtree, or a set of trees.
5504 Returns nil if kill does not start with a headline, or if the first
5505 headline level is not the largest headline level in the tree.
5506 So this will actually accept several entries of equal levels as well,
5507 which is OK for `org-paste-subtree'.
5508 If optional TXT is given, check this string instead of the current kill."
5509 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5510 (start-level (and kill
5511 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5512 org-outline-regexp "\\)")
5513 kill)
5514 (- (match-end 2) (match-beginning 2) 1)))
5515 (re (concat "^" org-outline-regexp))
5516 (start (1+ (or (match-beginning 2) -1))))
5517 (if (not start-level)
5518 (progn
5519 nil) ;; does not even start with a heading
5520 (catch 'exit
5521 (while (setq start (string-match re kill (1+ start)))
5522 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5523 (throw 'exit nil)))
5524 t))))
5526 (defvar org-markers-to-move nil
5527 "Markers that should be moved with a cut-and-paste operation.
5528 Those markers are stored together with their positions relative to
5529 the start of the region.")
5531 (defun org-save-markers-in-region (beg end)
5532 "Check markers in region.
5533 If these markers are between BEG and END, record their position relative
5534 to BEG, so that after moving the block of text, we can put the markers back
5535 into place.
5536 This function gets called just before an entry or tree gets cut from the
5537 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5538 called immediately, to move the markers with the entries."
5539 (setq org-markers-to-move nil)
5540 (when (featurep 'org-clock)
5541 (org-clock-save-markers-for-cut-and-paste beg end))
5542 (when (featurep 'org-agenda)
5543 (org-agenda-save-markers-for-cut-and-paste beg end)))
5545 (defun org-check-and-save-marker (marker beg end)
5546 "Check if MARKER is between BEG and END.
5547 If yes, remember the marker and the distance to BEG."
5548 (when (and (marker-buffer marker)
5549 (equal (marker-buffer marker) (current-buffer)))
5550 (if (and (>= marker beg) (< marker end))
5551 (push (cons marker (- marker beg)) org-markers-to-move))))
5553 (defun org-reinstall-markers-in-region (beg)
5554 "Move all remembered markers to their position relative to BEG."
5555 (mapc (lambda (x)
5556 (move-marker (car x) (+ beg (cdr x))))
5557 org-markers-to-move)
5558 (setq org-markers-to-move nil))
5560 (defun org-narrow-to-subtree ()
5561 "Narrow buffer to the current subtree."
5562 (interactive)
5563 (save-excursion
5564 (save-match-data
5565 (narrow-to-region
5566 (progn (org-back-to-heading) (point))
5567 (progn (org-end-of-subtree t) (point))))))
5570 ;;; Outline Sorting
5572 (defun org-sort (with-case)
5573 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5574 Optional argument WITH-CASE means sort case-sensitively."
5575 (interactive "P")
5576 (if (org-at-table-p)
5577 (org-call-with-arg 'org-table-sort-lines with-case)
5578 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5580 (defun org-sort-remove-invisible (s)
5581 (remove-text-properties 0 (length s) org-rm-props s)
5582 (while (string-match org-bracket-link-regexp s)
5583 (setq s (replace-match (if (match-end 2)
5584 (match-string 3 s)
5585 (match-string 1 s)) t t s)))
5588 (defvar org-priority-regexp) ; defined later in the file
5590 (defun org-sort-entries-or-items
5591 (&optional with-case sorting-type getkey-func compare-func property)
5592 "Sort entries on a certain level of an outline tree.
5593 If there is an active region, the entries in the region are sorted.
5594 Else, if the cursor is before the first entry, sort the top-level items.
5595 Else, the children of the entry at point are sorted.
5597 Sorting can be alphabetically, numerically, and by date/time as given by
5598 the first time stamp in the entry. The command prompts for the sorting
5599 type unless it has been given to the function through the SORTING-TYPE
5600 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5601 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5602 called with point at the beginning of the record. It must return either
5603 a string or a number that should serve as the sorting key for that record.
5605 Comparing entries ignores case by default. However, with an optional argument
5606 WITH-CASE, the sorting considers case as well."
5607 (interactive "P")
5608 (let ((case-func (if with-case 'identity 'downcase))
5609 start beg end stars re re2
5610 txt what tmp plain-list-p)
5611 ;; Find beginning and end of region to sort
5612 (cond
5613 ((org-region-active-p)
5614 ;; we will sort the region
5615 (setq end (region-end)
5616 what "region")
5617 (goto-char (region-beginning))
5618 (if (not (org-on-heading-p)) (outline-next-heading))
5619 (setq start (point)))
5620 ((org-at-item-p)
5621 ;; we will sort this plain list
5622 (org-beginning-of-item-list) (setq start (point))
5623 (org-end-of-item-list) (setq end (point))
5624 (goto-char start)
5625 (setq plain-list-p t
5626 what "plain list"))
5627 ((or (org-on-heading-p)
5628 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5629 ;; we will sort the children of the current headline
5630 (org-back-to-heading)
5631 (setq start (point)
5632 end (progn (org-end-of-subtree t t)
5633 (org-back-over-empty-lines)
5634 (point))
5635 what "children")
5636 (goto-char start)
5637 (show-subtree)
5638 (outline-next-heading))
5640 ;; we will sort the top-level entries in this file
5641 (goto-char (point-min))
5642 (or (org-on-heading-p) (outline-next-heading))
5643 (setq start (point) end (point-max) what "top-level")
5644 (goto-char start)
5645 (show-all)))
5647 (setq beg (point))
5648 (if (>= beg end) (error "Nothing to sort"))
5650 (unless plain-list-p
5651 (looking-at "\\(\\*+\\)")
5652 (setq stars (match-string 1)
5653 re (concat "^" (regexp-quote stars) " +")
5654 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5655 txt (buffer-substring beg end))
5656 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5657 (if (and (not (equal stars "*")) (string-match re2 txt))
5658 (error "Region to sort contains a level above the first entry")))
5660 (unless sorting-type
5661 (message
5662 (if plain-list-p
5663 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5664 "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:")
5665 what)
5666 (setq sorting-type (read-char-exclusive))
5668 (and (= (downcase sorting-type) ?f)
5669 (setq getkey-func
5670 (org-ido-completing-read "Sort using function: "
5671 obarray 'fboundp t nil nil))
5672 (setq getkey-func (intern getkey-func)))
5674 (and (= (downcase sorting-type) ?r)
5675 (setq property
5676 (org-ido-completing-read "Property: "
5677 (mapcar 'list (org-buffer-property-keys t))
5678 nil t))))
5680 (message "Sorting entries...")
5682 (save-restriction
5683 (narrow-to-region start end)
5685 (let ((dcst (downcase sorting-type))
5686 (now (current-time)))
5687 (sort-subr
5688 (/= dcst sorting-type)
5689 ;; This function moves to the beginning character of the "record" to
5690 ;; be sorted.
5691 (if plain-list-p
5692 (lambda nil
5693 (if (org-at-item-p) t (goto-char (point-max))))
5694 (lambda nil
5695 (if (re-search-forward re nil t)
5696 (goto-char (match-beginning 0))
5697 (goto-char (point-max)))))
5698 ;; This function moves to the last character of the "record" being
5699 ;; sorted.
5700 (if plain-list-p
5701 'org-end-of-item
5702 (lambda nil
5703 (save-match-data
5704 (condition-case nil
5705 (outline-forward-same-level 1)
5706 (error
5707 (goto-char (point-max)))))))
5709 ;; This function returns the value that gets sorted against.
5710 (if plain-list-p
5711 (lambda nil
5712 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5713 (cond
5714 ((= dcst ?n)
5715 (string-to-number (buffer-substring (match-end 0)
5716 (point-at-eol))))
5717 ((= dcst ?a)
5718 (buffer-substring (match-end 0) (point-at-eol)))
5719 ((= dcst ?t)
5720 (if (re-search-forward org-ts-regexp
5721 (point-at-eol) t)
5722 (org-time-string-to-time (match-string 0))
5723 now))
5724 ((= dcst ?f)
5725 (if getkey-func
5726 (progn
5727 (setq tmp (funcall getkey-func))
5728 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5729 tmp)
5730 (error "Invalid key function `%s'" getkey-func)))
5731 (t (error "Invalid sorting type `%c'" sorting-type)))))
5732 (lambda nil
5733 (cond
5734 ((= dcst ?n)
5735 (if (looking-at org-complex-heading-regexp)
5736 (string-to-number (match-string 4))
5737 nil))
5738 ((= dcst ?a)
5739 (if (looking-at org-complex-heading-regexp)
5740 (funcall case-func (match-string 4))
5741 nil))
5742 ((= dcst ?t)
5743 (if (re-search-forward org-ts-regexp
5744 (save-excursion
5745 (forward-line 2)
5746 (point)) t)
5747 (org-time-string-to-time (match-string 0))
5748 now))
5749 ((= dcst ?p)
5750 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5751 (string-to-char (match-string 2))
5752 org-default-priority))
5753 ((= dcst ?r)
5754 (or (org-entry-get nil property) ""))
5755 ((= dcst ?o)
5756 (if (looking-at org-complex-heading-regexp)
5757 (- 9999 (length (member (match-string 2)
5758 org-todo-keywords-1)))))
5759 ((= dcst ?f)
5760 (if getkey-func
5761 (progn
5762 (setq tmp (funcall getkey-func))
5763 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5764 tmp)
5765 (error "Invalid key function `%s'" getkey-func)))
5766 (t (error "Invalid sorting type `%c'" sorting-type)))))
5768 (cond
5769 ((= dcst ?a) 'string<)
5770 ((= dcst ?t) 'time-less-p)
5771 ((= dcst ?f) compare-func)
5772 (t nil)))))
5773 (message "Sorting entries...done")))
5775 (defun org-do-sort (table what &optional with-case sorting-type)
5776 "Sort TABLE of WHAT according to SORTING-TYPE.
5777 The user will be prompted for the SORTING-TYPE if the call to this
5778 function does not specify it. WHAT is only for the prompt, to indicate
5779 what is being sorted. The sorting key will be extracted from
5780 the car of the elements of the table.
5781 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5782 (unless sorting-type
5783 (message
5784 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5785 what)
5786 (setq sorting-type (read-char-exclusive)))
5787 (let ((dcst (downcase sorting-type))
5788 extractfun comparefun)
5789 ;; Define the appropriate functions
5790 (cond
5791 ((= dcst ?n)
5792 (setq extractfun 'string-to-number
5793 comparefun (if (= dcst sorting-type) '< '>)))
5794 ((= dcst ?a)
5795 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5796 (lambda(x) (downcase (org-sort-remove-invisible x))))
5797 comparefun (if (= dcst sorting-type)
5798 'string<
5799 (lambda (a b) (and (not (string< a b))
5800 (not (string= a b)))))))
5801 ((= dcst ?t)
5802 (setq extractfun
5803 (lambda (x)
5804 (if (string-match org-ts-regexp x)
5805 (time-to-seconds
5806 (org-time-string-to-time (match-string 0 x)))
5808 comparefun (if (= dcst sorting-type) '< '>)))
5809 (t (error "Invalid sorting type `%c'" sorting-type)))
5811 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5812 table)
5813 (lambda (a b) (funcall comparefun (car a) (car b))))))
5815 ;;; Editing source examples
5817 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5818 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5819 (defvar org-edit-src-force-single-line nil)
5820 (defvar org-edit-src-from-org-mode nil)
5821 (defvar org-edit-src-picture nil)
5823 (define-minor-mode org-exit-edit-mode
5824 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5826 (defun org-edit-src-code ()
5827 "Edit the source code example at point.
5828 An indirect buffer is created, and that buffer is then narrowed to the
5829 example at point and switched to the correct language mode. When done,
5830 exit by killing the buffer with \\[org-edit-src-exit]."
5831 (interactive)
5832 (let ((line (org-current-line))
5833 (case-fold-search t)
5834 (msg (substitute-command-keys
5835 "Edit, then exit with C-c ' (C-c and single quote)"))
5836 (info (org-edit-src-find-region-and-lang))
5837 (org-mode-p (eq major-mode 'org-mode))
5838 beg end lang lang-f single lfmt)
5839 (if (not info)
5841 (setq beg (nth 0 info)
5842 end (nth 1 info)
5843 lang (nth 2 info)
5844 single (nth 3 info)
5845 lfmt (nth 4 info)
5846 lang-f (intern (concat lang "-mode")))
5847 (unless (functionp lang-f)
5848 (error "No such language mode: %s" lang-f))
5849 (goto-line line)
5850 (if (get-buffer "*Org Edit Src Example*")
5851 (kill-buffer "*Org Edit Src Example*"))
5852 (switch-to-buffer (make-indirect-buffer (current-buffer)
5853 "*Org Edit Src Example*"))
5854 (narrow-to-region beg end)
5855 (remove-text-properties beg end '(display nil invisible nil
5856 intangible nil))
5857 (let ((org-inhibit-startup t))
5858 (funcall lang-f))
5859 (set (make-local-variable 'org-edit-src-force-single-line) single)
5860 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5861 (when lfmt
5862 (set (make-local-variable 'org-coderef-label-format) lfmt))
5863 (when org-mode-p
5864 (goto-char (point-min))
5865 (while (re-search-forward "^," nil t)
5866 (replace-match "")))
5867 (goto-line line)
5868 (org-exit-edit-mode)
5869 (org-set-local 'header-line-format msg)
5870 (message "%s" msg)
5871 t)))
5873 (defun org-edit-fixed-width-region ()
5874 "Edit the fixed-width ascii drawing at point.
5875 This must be a region where each line starts with a colon followed by
5876 a space character.
5877 An indirect buffer is created, and that buffer is then narrowed to the
5878 example at point and switched to artist-mode. When done,
5879 exit by killing the buffer with \\[org-edit-src-exit]."
5880 (interactive)
5881 (let ((line (org-current-line))
5882 (case-fold-search t)
5883 (msg (substitute-command-keys
5884 "Edit, then exit with C-c ' (C-c and single quote)"))
5885 (org-mode-p (eq major-mode 'org-mode))
5886 beg end)
5887 (beginning-of-line 1)
5888 (if (looking-at "[ \t]*[^:\n \t]")
5890 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5891 (setq beg (point) end beg)
5892 (save-excursion
5893 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5894 (setq beg (point-at-bol 2))
5895 (setq beg (point))))
5896 (save-excursion
5897 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5898 (setq end (1- (match-beginning 0)))
5899 (setq end (point))))
5900 (goto-line line))
5901 (if (get-buffer "*Org Edit Picture*")
5902 (kill-buffer "*Org Edit Picture*"))
5903 (switch-to-buffer (make-indirect-buffer (current-buffer)
5904 "*Org Edit Picture*"))
5905 (narrow-to-region beg end)
5906 (remove-text-properties beg end '(display nil invisible nil
5907 intangible nil))
5908 (when (fboundp 'font-lock-unfontify-region)
5909 (font-lock-unfontify-region (point-min) (point-max)))
5910 (cond
5911 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5912 (fundamental-mode)
5913 (artist-mode 1))
5914 (t (funcall org-edit-fixed-width-region-mode)))
5915 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5916 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5917 (set (make-local-variable 'org-edit-src-picture) t)
5918 (goto-char (point-min))
5919 (while (re-search-forward "^[ \t]*: ?" nil t)
5920 (replace-match ""))
5921 (goto-line line)
5922 (org-exit-edit-mode)
5923 (org-set-local 'header-line-format msg)
5924 (message "%s" msg)
5925 t)))
5928 (defun org-edit-src-find-region-and-lang ()
5929 "Find the region and language for a local edit.
5930 Return a list with beginning and end of the region, a string representing
5931 the language, a switch telling of the content should be in a single line."
5932 (let ((re-list
5933 (append
5934 org-edit-src-region-extra
5936 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5937 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5938 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5939 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5940 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5941 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5942 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5943 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5944 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5945 ("^#\\+html:" "\n" "html" single-line)
5946 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5947 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5948 ("^#\\+latex:" "\n" "latex" single-line)
5949 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5950 ("^#\\+ascii:" "\n" "ascii" single-line)
5952 (pos (point))
5953 re1 re2 single beg end lang lfmt match-re1)
5954 (catch 'exit
5955 (while (setq entry (pop re-list))
5956 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5957 single (nth 3 entry))
5958 (save-excursion
5959 (if (or (looking-at re1)
5960 (re-search-backward re1 nil t))
5961 (progn
5962 (setq match-re1 (match-string 0))
5963 (setq beg (match-end 0)
5964 lang (org-edit-src-get-lang lang)
5965 lfmt (org-edit-src-get-label-format match-re1))
5966 (if (and (re-search-forward re2 nil t)
5967 (>= (match-end 0) pos))
5968 (throw 'exit (list beg (match-beginning 0)
5969 lang single lfmt))))
5970 (if (or (looking-at re2)
5971 (re-search-forward re2 nil t))
5972 (progn
5973 (setq end (match-beginning 0))
5974 (if (and (re-search-backward re1 nil t)
5975 (<= (match-beginning 0) pos))
5976 (progn
5977 (setq lfmt (org-edit-src-get-label-format
5978 (match-string 0)))
5979 (throw 'exit
5980 (list (match-end 0) end
5981 (org-edit-src-get-lang lang)
5982 single lfmt))))))))))))
5984 (defun org-edit-src-get-lang (lang)
5985 "Extract the src language."
5986 (let ((m (match-string 0)))
5987 (cond
5988 ((stringp lang) lang)
5989 ((integerp lang) (match-string lang))
5990 ((and (eq lang 'lang)
5991 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5992 (match-string 1 m))
5993 ((and (eq lang 'style)
5994 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5995 (match-string 1 m))
5996 (t "fundamental"))))
5998 (defun org-edit-src-get-label-format (s)
5999 "Extract the label format."
6000 (save-match-data
6001 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6002 (match-string 1 s))))
6004 (defun org-edit-src-exit ()
6005 "Exit special edit and protect problematic lines."
6006 (interactive)
6007 (unless (buffer-base-buffer (current-buffer))
6008 (error "This is not an indirect buffer, something is wrong..."))
6009 (unless (> (point-min) 1)
6010 (error "This buffer is not narrowed, something is wrong..."))
6011 (goto-char (point-min))
6012 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6013 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6014 (when (org-bound-and-true-p org-edit-src-force-single-line)
6015 (goto-char (point-min))
6016 (while (re-search-forward "\n" nil t)
6017 (replace-match " "))
6018 (goto-char (point-min))
6019 (if (looking-at "\\s-*") (replace-match " "))
6020 (if (re-search-forward "\\s-+\\'" nil t)
6021 (replace-match "")))
6022 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6023 (goto-char (point-min))
6024 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6025 (replace-match ",\\1"))
6026 (when font-lock-mode
6027 (font-lock-unfontify-region (point-min) (point-max)))
6028 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6029 (when (org-bound-and-true-p org-edit-src-picture)
6030 (untabify (point-min) (point-max))
6031 (goto-char (point-min))
6032 (while (re-search-forward "^" nil t)
6033 (replace-match ": "))
6034 (when font-lock-mode
6035 (font-lock-unfontify-region (point-min) (point-max)))
6036 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6037 (kill-buffer (current-buffer))
6038 (and (org-mode-p) (org-restart-font-lock)))
6041 ;;; The orgstruct minor mode
6043 ;; Define a minor mode which can be used in other modes in order to
6044 ;; integrate the org-mode structure editing commands.
6046 ;; This is really a hack, because the org-mode structure commands use
6047 ;; keys which normally belong to the major mode. Here is how it
6048 ;; works: The minor mode defines all the keys necessary to operate the
6049 ;; structure commands, but wraps the commands into a function which
6050 ;; tests if the cursor is currently at a headline or a plain list
6051 ;; item. If that is the case, the structure command is used,
6052 ;; temporarily setting many Org-mode variables like regular
6053 ;; expressions for filling etc. However, when any of those keys is
6054 ;; used at a different location, function uses `key-binding' to look
6055 ;; up if the key has an associated command in another currently active
6056 ;; keymap (minor modes, major mode, global), and executes that
6057 ;; command. There might be problems if any of the keys is otherwise
6058 ;; used as a prefix key.
6060 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6061 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6062 ;; addresses this by checking explicitly for both bindings.
6064 (defvar orgstruct-mode-map (make-sparse-keymap)
6065 "Keymap for the minor `orgstruct-mode'.")
6067 (defvar org-local-vars nil
6068 "List of local variables, for use by `orgstruct-mode'")
6070 ;;;###autoload
6071 (define-minor-mode orgstruct-mode
6072 "Toggle the minor more `orgstruct-mode'.
6073 This mode is for using Org-mode structure commands in other modes.
6074 The following key behave as if Org-mode was active, if the cursor
6075 is on a headline, or on a plain list item (both in the definition
6076 of Org-mode).
6078 M-up Move entry/item up
6079 M-down Move entry/item down
6080 M-left Promote
6081 M-right Demote
6082 M-S-up Move entry/item up
6083 M-S-down Move entry/item down
6084 M-S-left Promote subtree
6085 M-S-right Demote subtree
6086 M-q Fill paragraph and items like in Org-mode
6087 C-c ^ Sort entries
6088 C-c - Cycle list bullet
6089 TAB Cycle item visibility
6090 M-RET Insert new heading/item
6091 S-M-RET Insert new TODO heading / Checkbox item
6092 C-c C-c Set tags / toggle checkbox"
6093 nil " OrgStruct" nil
6094 (org-load-modules-maybe)
6095 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6097 ;;;###autoload
6098 (defun turn-on-orgstruct ()
6099 "Unconditionally turn on `orgstruct-mode'."
6100 (orgstruct-mode 1))
6102 ;;;###autoload
6103 (defun turn-on-orgstruct++ ()
6104 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6105 In addition to setting orgstruct-mode, this also exports all indentation and
6106 autofilling variables from org-mode into the buffer. Note that turning
6107 off orgstruct-mode will *not* remove these additional settings."
6108 (orgstruct-mode 1)
6109 (let (var val)
6110 (mapc
6111 (lambda (x)
6112 (when (string-match
6113 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6114 (symbol-name (car x)))
6115 (setq var (car x) val (nth 1 x))
6116 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6117 org-local-vars)))
6119 (defun orgstruct-error ()
6120 "Error when there is no default binding for a structure key."
6121 (interactive)
6122 (error "This key has no function outside structure elements"))
6124 (defun orgstruct-setup ()
6125 "Setup orgstruct keymaps."
6126 (let ((nfunc 0)
6127 (bindings
6128 (list
6129 '([(meta up)] org-metaup)
6130 '([(meta down)] org-metadown)
6131 '([(meta left)] org-metaleft)
6132 '([(meta right)] org-metaright)
6133 '([(meta shift up)] org-shiftmetaup)
6134 '([(meta shift down)] org-shiftmetadown)
6135 '([(meta shift left)] org-shiftmetaleft)
6136 '([(meta shift right)] org-shiftmetaright)
6137 '([(shift up)] org-shiftup)
6138 '([(shift down)] org-shiftdown)
6139 '([(shift left)] org-shiftleft)
6140 '([(shift right)] org-shiftright)
6141 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6142 '("\M-q" fill-paragraph)
6143 '("\C-c^" org-sort)
6144 '("\C-c-" org-cycle-list-bullet)))
6145 elt key fun cmd)
6146 (while (setq elt (pop bindings))
6147 (setq nfunc (1+ nfunc))
6148 (setq key (org-key (car elt))
6149 fun (nth 1 elt)
6150 cmd (orgstruct-make-binding fun nfunc key))
6151 (org-defkey orgstruct-mode-map key cmd))
6153 ;; Special treatment needed for TAB and RET
6154 (org-defkey orgstruct-mode-map [(tab)]
6155 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6156 (org-defkey orgstruct-mode-map "\C-i"
6157 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6159 (org-defkey orgstruct-mode-map "\M-\C-m"
6160 (orgstruct-make-binding 'org-insert-heading 105
6161 "\M-\C-m" [(meta return)]))
6162 (org-defkey orgstruct-mode-map [(meta return)]
6163 (orgstruct-make-binding 'org-insert-heading 106
6164 [(meta return)] "\M-\C-m"))
6166 (org-defkey orgstruct-mode-map [(shift meta return)]
6167 (orgstruct-make-binding 'org-insert-todo-heading 107
6168 [(meta return)] "\M-\C-m"))
6170 (unless org-local-vars
6171 (setq org-local-vars (org-get-local-variables)))
6175 (defun orgstruct-make-binding (fun n &rest keys)
6176 "Create a function for binding in the structure minor mode.
6177 FUN is the command to call inside a table. N is used to create a unique
6178 command name. KEYS are keys that should be checked in for a command
6179 to execute outside of tables."
6180 (eval
6181 (list 'defun
6182 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6183 '(arg)
6184 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6185 "Outside of structure, run the binding of `"
6186 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6187 "'.")
6188 '(interactive "p")
6189 (list 'if
6190 '(org-context-p 'headline 'item)
6191 (list 'org-run-like-in-org-mode (list 'quote fun))
6192 (list 'let '(orgstruct-mode)
6193 (list 'call-interactively
6194 (append '(or)
6195 (mapcar (lambda (k)
6196 (list 'key-binding k))
6197 keys)
6198 '('orgstruct-error))))))))
6200 (defun org-context-p (&rest contexts)
6201 "Check if local context is any of CONTEXTS.
6202 Possible values in the list of contexts are `table', `headline', and `item'."
6203 (let ((pos (point)))
6204 (goto-char (point-at-bol))
6205 (prog1 (or (and (memq 'table contexts)
6206 (looking-at "[ \t]*|"))
6207 (and (memq 'headline contexts)
6208 ;;????????? (looking-at "\\*+"))
6209 (looking-at outline-regexp))
6210 (and (memq 'item contexts)
6211 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6212 (goto-char pos))))
6214 (defun org-get-local-variables ()
6215 "Return a list of all local variables in an org-mode buffer."
6216 (let (varlist)
6217 (with-current-buffer (get-buffer-create "*Org tmp*")
6218 (erase-buffer)
6219 (org-mode)
6220 (setq varlist (buffer-local-variables)))
6221 (kill-buffer "*Org tmp*")
6222 (delq nil
6223 (mapcar
6224 (lambda (x)
6225 (setq x
6226 (if (symbolp x)
6227 (list x)
6228 (list (car x) (list 'quote (cdr x)))))
6229 (if (string-match
6230 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6231 (symbol-name (car x)))
6232 x nil))
6233 varlist))))
6235 ;;;###autoload
6236 (defun org-run-like-in-org-mode (cmd)
6237 (org-load-modules-maybe)
6238 (unless org-local-vars
6239 (setq org-local-vars (org-get-local-variables)))
6240 (eval (list 'let org-local-vars
6241 (list 'call-interactively (list 'quote cmd)))))
6243 ;;;; Archiving
6245 (defun org-get-category (&optional pos)
6246 "Get the category applying to position POS."
6247 (get-text-property (or pos (point)) 'org-category))
6249 (defun org-refresh-category-properties ()
6250 "Refresh category text properties in the buffer."
6251 (let ((def-cat (cond
6252 ((null org-category)
6253 (if buffer-file-name
6254 (file-name-sans-extension
6255 (file-name-nondirectory buffer-file-name))
6256 "???"))
6257 ((symbolp org-category) (symbol-name org-category))
6258 (t org-category)))
6259 beg end cat pos optionp)
6260 (org-unmodified
6261 (save-excursion
6262 (save-restriction
6263 (widen)
6264 (goto-char (point-min))
6265 (put-text-property (point) (point-max) 'org-category def-cat)
6266 (while (re-search-forward
6267 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6268 (setq pos (match-end 0)
6269 optionp (equal (char-after (match-beginning 0)) ?#)
6270 cat (org-trim (match-string 2)))
6271 (if optionp
6272 (setq beg (point-at-bol) end (point-max))
6273 (org-back-to-heading t)
6274 (setq beg (point) end (org-end-of-subtree t t)))
6275 (put-text-property beg end 'org-category cat)
6276 (goto-char pos)))))))
6279 ;;;; Link Stuff
6281 ;;; Link abbreviations
6283 (defun org-link-expand-abbrev (link)
6284 "Apply replacements as defined in `org-link-abbrev-alist."
6285 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6286 (let* ((key (match-string 1 link))
6287 (as (or (assoc key org-link-abbrev-alist-local)
6288 (assoc key org-link-abbrev-alist)))
6289 (tag (and (match-end 2) (match-string 3 link)))
6290 rpl)
6291 (if (not as)
6292 link
6293 (setq rpl (cdr as))
6294 (cond
6295 ((symbolp rpl) (funcall rpl tag))
6296 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6297 ((string-match "%h" rpl)
6298 (replace-match (url-hexify-string (or tag "")) t t rpl))
6299 (t (concat rpl tag)))))
6300 link))
6302 ;;; Storing and inserting links
6304 (defvar org-insert-link-history nil
6305 "Minibuffer history for links inserted with `org-insert-link'.")
6307 (defvar org-stored-links nil
6308 "Contains the links stored with `org-store-link'.")
6310 (defvar org-store-link-plist nil
6311 "Plist with info about the most recently link created with `org-store-link'.")
6313 (defvar org-link-protocols nil
6314 "Link protocols added to Org-mode using `org-add-link-type'.")
6316 (defvar org-store-link-functions nil
6317 "List of functions that are called to create and store a link.
6318 Each function will be called in turn until one returns a non-nil
6319 value. Each function should check if it is responsible for creating
6320 this link (for example by looking at the major mode).
6321 If not, it must exit and return nil.
6322 If yes, it should return a non-nil value after a calling
6323 `org-store-link-props' with a list of properties and values.
6324 Special properties are:
6326 :type The link prefix. like \"http\". This must be given.
6327 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6328 This is obligatory as well.
6329 :description Optional default description for the second pair
6330 of brackets in an Org-mode link. The user can still change
6331 this when inserting this link into an Org-mode buffer.
6333 In addition to these, any additional properties can be specified
6334 and then used in remember templates.")
6336 (defun org-add-link-type (type &optional follow export)
6337 "Add TYPE to the list of `org-link-types'.
6338 Re-compute all regular expressions depending on `org-link-types'
6340 FOLLOW and EXPORT are two functions.
6342 FOLLOW should take the link path as the single argument and do whatever
6343 is necessary to follow the link, for example find a file or display
6344 a mail message.
6346 EXPORT should format the link path for export to one of the export formats.
6347 It should be a function accepting three arguments:
6349 path the path of the link, the text after the prefix (like \"http:\")
6350 desc the description of the link, if any, nil if there was no description
6351 format the export format, a symbol like `html' or `latex'.
6353 The function may use the FORMAT information to return different values
6354 depending on the format. The return value will be put literally into
6355 the exported file.
6356 Org-mode has a built-in default for exporting links. If you are happy with
6357 this default, there is no need to define an export function for the link
6358 type. For a simple example of an export function, see `org-bbdb.el'."
6359 (add-to-list 'org-link-types type t)
6360 (org-make-link-regexps)
6361 (if (assoc type org-link-protocols)
6362 (setcdr (assoc type org-link-protocols) (list follow export))
6363 (push (list type follow export) org-link-protocols)))
6365 ;;;###autoload
6366 (defun org-store-link (arg)
6367 "\\<org-mode-map>Store an org-link to the current location.
6368 This link is added to `org-stored-links' and can later be inserted
6369 into an org-buffer with \\[org-insert-link].
6371 For some link types, a prefix arg is interpreted:
6372 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6373 For file links, arg negates `org-context-in-file-links'."
6374 (interactive "P")
6375 (org-load-modules-maybe)
6376 (setq org-store-link-plist nil) ; reset
6377 (let (link cpltxt desc description search txt)
6378 (cond
6380 ((run-hook-with-args-until-success 'org-store-link-functions)
6381 (setq link (plist-get org-store-link-plist :link)
6382 desc (or (plist-get org-store-link-plist :description) link)))
6384 ((equal (buffer-name) "*Org Edit Src Example*")
6385 (let (label gc)
6386 (while (or (not label)
6387 (save-excursion
6388 (save-restriction
6389 (widen)
6390 (goto-char (point-min))
6391 (re-search-forward
6392 (regexp-quote (format org-coderef-label-format label))
6393 nil t))))
6394 (when label (message "Label exists already") (sit-for 2))
6395 (setq label (read-string "Code line label: " label)))
6396 (end-of-line 1)
6397 (setq link (format org-coderef-label-format label))
6398 (setq gc (- 79 (length link)))
6399 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6400 (insert link)
6401 (setq link (concat "(" label ")") desc nil)))
6403 ((eq major-mode 'calendar-mode)
6404 (let ((cd (calendar-cursor-to-date)))
6405 (setq link
6406 (format-time-string
6407 (car org-time-stamp-formats)
6408 (apply 'encode-time
6409 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6410 nil nil nil))))
6411 (org-store-link-props :type "calendar" :date cd)))
6413 ((eq major-mode 'w3-mode)
6414 (setq cpltxt (url-view-url t)
6415 link (org-make-link cpltxt))
6416 (org-store-link-props :type "w3" :url (url-view-url t)))
6418 ((eq major-mode 'w3m-mode)
6419 (setq cpltxt (or w3m-current-title w3m-current-url)
6420 link (org-make-link w3m-current-url))
6421 (org-store-link-props :type "w3m" :url (url-view-url t)))
6423 ((setq search (run-hook-with-args-until-success
6424 'org-create-file-search-functions))
6425 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6426 "::" search))
6427 (setq cpltxt (or description link)))
6429 ((eq major-mode 'image-mode)
6430 (setq cpltxt (concat "file:"
6431 (abbreviate-file-name buffer-file-name))
6432 link (org-make-link cpltxt))
6433 (org-store-link-props :type "image" :file buffer-file-name))
6435 ((eq major-mode 'dired-mode)
6436 ;; link to the file in the current line
6437 (setq cpltxt (concat "file:"
6438 (abbreviate-file-name
6439 (expand-file-name
6440 (dired-get-filename nil t))))
6441 link (org-make-link cpltxt)))
6443 ((and buffer-file-name (org-mode-p))
6444 (cond
6445 ((org-in-regexp "<<\\(.*?\\)>>")
6446 (setq cpltxt
6447 (concat "file:"
6448 (abbreviate-file-name buffer-file-name)
6449 "::" (match-string 1))
6450 link (org-make-link cpltxt)))
6451 ((and (featurep 'org-id)
6452 (or (eq org-link-to-org-use-id t)
6453 (and (eq org-link-to-org-use-id 'create-if-interactive)
6454 (interactive-p))
6455 (and org-link-to-org-use-id
6456 (condition-case nil
6457 (org-entry-get nil "ID")
6458 (error nil)))))
6459 ;; We can make a link using the ID.
6460 (setq link (condition-case nil
6461 (prog1 (org-id-store-link)
6462 (setq desc (plist-get org-store-link-plist
6463 :description)))
6464 (error
6465 ;; probably before first headline, link to file only
6466 (concat "file:"
6467 (abbreviate-file-name buffer-file-name))))))
6469 ;; Just link to current headline
6470 (setq cpltxt (concat "file:"
6471 (abbreviate-file-name buffer-file-name)))
6472 ;; Add a context search string
6473 (when (org-xor org-context-in-file-links arg)
6474 (setq txt (cond
6475 ((org-on-heading-p) nil)
6476 ((org-region-active-p)
6477 (buffer-substring (region-beginning) (region-end)))
6478 (t nil)))
6479 (when (or (null txt) (string-match "\\S-" txt))
6480 (setq cpltxt
6481 (concat cpltxt "::"
6482 (condition-case nil
6483 (org-make-org-heading-search-string txt)
6484 (error "")))
6485 desc "NONE")))
6486 (if (string-match "::\\'" cpltxt)
6487 (setq cpltxt (substring cpltxt 0 -2)))
6488 (setq link (org-make-link cpltxt)))))
6490 ((buffer-file-name (buffer-base-buffer))
6491 ;; Just link to this file here.
6492 (setq cpltxt (concat "file:"
6493 (abbreviate-file-name
6494 (buffer-file-name (buffer-base-buffer)))))
6495 ;; Add a context string
6496 (when (org-xor org-context-in-file-links arg)
6497 (setq txt (if (org-region-active-p)
6498 (buffer-substring (region-beginning) (region-end))
6499 (buffer-substring (point-at-bol) (point-at-eol))))
6500 ;; Only use search option if there is some text.
6501 (when (string-match "\\S-" txt)
6502 (setq cpltxt
6503 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6504 desc "NONE")))
6505 (setq link (org-make-link cpltxt)))
6507 ((interactive-p)
6508 (error "Cannot link to a buffer which is not visiting a file"))
6510 (t (setq link nil)))
6512 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6513 (setq link (or link cpltxt)
6514 desc (or desc cpltxt))
6515 (if (equal desc "NONE") (setq desc nil))
6517 (if (and (interactive-p) link)
6518 (progn
6519 (setq org-stored-links
6520 (cons (list link desc) org-stored-links))
6521 (message "Stored: %s" (or desc link)))
6522 (and link (org-make-link-string link desc)))))
6524 (defun org-store-link-props (&rest plist)
6525 "Store link properties, extract names and addresses."
6526 (let (x adr)
6527 (when (setq x (plist-get plist :from))
6528 (setq adr (mail-extract-address-components x))
6529 (setq plist (plist-put plist :fromname (car adr)))
6530 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6531 (when (setq x (plist-get plist :to))
6532 (setq adr (mail-extract-address-components x))
6533 (setq plist (plist-put plist :toname (car adr)))
6534 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6535 (let ((from (plist-get plist :from))
6536 (to (plist-get plist :to)))
6537 (when (and from to org-from-is-user-regexp)
6538 (setq plist
6539 (plist-put plist :fromto
6540 (if (string-match org-from-is-user-regexp from)
6541 (concat "to %t")
6542 (concat "from %f"))))))
6543 (setq org-store-link-plist plist))
6545 (defun org-add-link-props (&rest plist)
6546 "Add these properties to the link property list."
6547 (let (key value)
6548 (while plist
6549 (setq key (pop plist) value (pop plist))
6550 (setq org-store-link-plist
6551 (plist-put org-store-link-plist key value)))))
6553 (defun org-email-link-description (&optional fmt)
6554 "Return the description part of an email link.
6555 This takes information from `org-store-link-plist' and formats it
6556 according to FMT (default from `org-email-link-description-format')."
6557 (setq fmt (or fmt org-email-link-description-format))
6558 (let* ((p org-store-link-plist)
6559 (to (plist-get p :toaddress))
6560 (from (plist-get p :fromaddress))
6561 (table
6562 (list
6563 (cons "%c" (plist-get p :fromto))
6564 (cons "%F" (plist-get p :from))
6565 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6566 (cons "%T" (plist-get p :to))
6567 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6568 (cons "%s" (plist-get p :subject))
6569 (cons "%m" (plist-get p :message-id)))))
6570 (when (string-match "%c" fmt)
6571 ;; Check if the user wrote this message
6572 (if (and org-from-is-user-regexp from to
6573 (save-match-data (string-match org-from-is-user-regexp from)))
6574 (setq fmt (replace-match "to %t" t t fmt))
6575 (setq fmt (replace-match "from %f" t t fmt))))
6576 (org-replace-escapes fmt table)))
6578 (defun org-make-org-heading-search-string (&optional string heading)
6579 "Make search string for STRING or current headline."
6580 (interactive)
6581 (let ((s (or string (org-get-heading))))
6582 (unless (and string (not heading))
6583 ;; We are using a headline, clean up garbage in there.
6584 (if (string-match org-todo-regexp s)
6585 (setq s (replace-match "" t t s)))
6586 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6587 (setq s (replace-match "" t t s)))
6588 (setq s (org-trim s))
6589 (if (string-match (concat "^\\(" org-quote-string "\\|"
6590 org-comment-string "\\)") s)
6591 (setq s (replace-match "" t t s)))
6592 (while (string-match org-ts-regexp s)
6593 (setq s (replace-match "" t t s))))
6594 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6595 (setq s (replace-match " " t t s)))
6596 (or string (setq s (concat "*" s))) ; Add * for headlines
6597 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6599 (defun org-make-link (&rest strings)
6600 "Concatenate STRINGS."
6601 (apply 'concat strings))
6603 (defun org-make-link-string (link &optional description)
6604 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6605 (unless (string-match "\\S-" link)
6606 (error "Empty link"))
6607 (when (stringp description)
6608 ;; Remove brackets from the description, they are fatal.
6609 (while (string-match "\\[" description)
6610 (setq description (replace-match "{" t t description)))
6611 (while (string-match "\\]" description)
6612 (setq description (replace-match "}" t t description))))
6613 (when (equal (org-link-escape link) description)
6614 ;; No description needed, it is identical
6615 (setq description nil))
6616 (when (and (not description)
6617 (not (equal link (org-link-escape link))))
6618 (setq description (org-extract-attributes link)))
6619 (concat "[[" (org-link-escape link) "]"
6620 (if description (concat "[" description "]") "")
6621 "]"))
6623 (defconst org-link-escape-chars
6624 '((?\ . "%20")
6625 (?\[ . "%5B")
6626 (?\] . "%5D")
6627 (?\340 . "%E0") ; `a
6628 (?\342 . "%E2") ; ^a
6629 (?\347 . "%E7") ; ,c
6630 (?\350 . "%E8") ; `e
6631 (?\351 . "%E9") ; 'e
6632 (?\352 . "%EA") ; ^e
6633 (?\356 . "%EE") ; ^i
6634 (?\364 . "%F4") ; ^o
6635 (?\371 . "%F9") ; `u
6636 (?\373 . "%FB") ; ^u
6637 (?\; . "%3B")
6638 (?? . "%3F")
6639 (?= . "%3D")
6640 (?+ . "%2B")
6642 "Association list of escapes for some characters problematic in links.
6643 This is the list that is used for internal purposes.")
6645 (defconst org-link-escape-chars-browser
6646 '((?\ . "%20")) ; 32 for the SPC char
6647 "Association list of escapes for some characters problematic in links.
6648 This is the list that is used before handing over to the browser.")
6650 (defun org-link-escape (text &optional table)
6651 "Escape characters in TEXT that are problematic for links."
6652 (setq table (or table org-link-escape-chars))
6653 (when text
6654 (let ((re (mapconcat (lambda (x) (regexp-quote
6655 (char-to-string (car x))))
6656 table "\\|")))
6657 (while (string-match re text)
6658 (setq text
6659 (replace-match
6660 (cdr (assoc (string-to-char (match-string 0 text))
6661 table))
6662 t t text)))
6663 text)))
6665 (defun org-link-unescape (text &optional table)
6666 "Reverse the action of `org-link-escape'."
6667 (setq table (or table org-link-escape-chars))
6668 (when text
6669 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6670 table "\\|")))
6671 (while (string-match re text)
6672 (setq text
6673 (replace-match
6674 (char-to-string (car (rassoc (match-string 0 text) table)))
6675 t t text)))
6676 text)))
6678 (defun org-xor (a b)
6679 "Exclusive or."
6680 (if a (not b) b))
6682 (defun org-fixup-message-id-for-http (s)
6683 "Replace special characters in a message id, so it can be used in an http query."
6684 (while (string-match "<" s)
6685 (setq s (replace-match "%3C" t t s)))
6686 (while (string-match ">" s)
6687 (setq s (replace-match "%3E" t t s)))
6688 (while (string-match "@" s)
6689 (setq s (replace-match "%40" t t s)))
6692 ;;;###autoload
6693 (defun org-insert-link-global ()
6694 "Insert a link like Org-mode does.
6695 This command can be called in any mode to insert a link in Org-mode syntax."
6696 (interactive)
6697 (org-load-modules-maybe)
6698 (org-run-like-in-org-mode 'org-insert-link))
6700 (defun org-insert-link (&optional complete-file link-location)
6701 "Insert a link. At the prompt, enter the link.
6703 Completion can be used to insert any of the link protocol prefixes like
6704 http or ftp in use.
6706 The history can be used to select a link previously stored with
6707 `org-store-link'. When the empty string is entered (i.e. if you just
6708 press RET at the prompt), the link defaults to the most recently
6709 stored link. As SPC triggers completion in the minibuffer, you need to
6710 use M-SPC or C-q SPC to force the insertion of a space character.
6712 You will also be prompted for a description, and if one is given, it will
6713 be displayed in the buffer instead of the link.
6715 If there is already a link at point, this command will allow you to edit link
6716 and description parts.
6718 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6719 be selected using completion. The path to the file will be relative to the
6720 current directory if the file is in the current directory or a subdirectory.
6721 Otherwise, the link will be the absolute path as completed in the minibuffer
6722 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6723 option `org-link-file-path-type'.
6725 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6726 the current directory or below.
6728 With three \\[universal-argument] prefixes, negate the meaning of
6729 `org-keep-stored-link-after-insertion'.
6731 If `org-make-link-description-function' is non-nil, this function will be
6732 called with the link target, and the result will be the default
6733 link description.
6735 If the LINK-LOCATION parameter is non-nil, this value will be
6736 used as the link location instead of reading one interactively."
6737 (interactive "P")
6738 (let* ((wcf (current-window-configuration))
6739 (region (if (org-region-active-p)
6740 (buffer-substring (region-beginning) (region-end))))
6741 (remove (and region (list (region-beginning) (region-end))))
6742 (desc region)
6743 tmphist ; byte-compile incorrectly complains about this
6744 (link link-location)
6745 entry file)
6746 (cond
6747 (link-location) ; specified by arg, just use it.
6748 ((org-in-regexp org-bracket-link-regexp 1)
6749 ;; We do have a link at point, and we are going to edit it.
6750 (setq remove (list (match-beginning 0) (match-end 0)))
6751 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6752 (setq link (read-string "Link: "
6753 (org-link-unescape
6754 (org-match-string-no-properties 1)))))
6755 ((or (org-in-regexp org-angle-link-re)
6756 (org-in-regexp org-plain-link-re))
6757 ;; Convert to bracket link
6758 (setq remove (list (match-beginning 0) (match-end 0))
6759 link (read-string "Link: "
6760 (org-remove-angle-brackets (match-string 0)))))
6761 ((member complete-file '((4) (16)))
6762 ;; Completing read for file names.
6763 (setq file (read-file-name "File: "))
6764 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6765 (pwd1 (file-name-as-directory (abbreviate-file-name
6766 (expand-file-name ".")))))
6767 (cond
6768 ((equal complete-file '(16))
6769 (setq link (org-make-link
6770 "file:"
6771 (abbreviate-file-name (expand-file-name file)))))
6772 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6773 (setq link (org-make-link "file:" (match-string 1 file))))
6774 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6775 (expand-file-name file))
6776 (setq link (org-make-link
6777 "file:" (match-string 1 (expand-file-name file)))))
6778 (t (setq link (org-make-link "file:" file))))))
6780 ;; Read link, with completion for stored links.
6781 (with-output-to-temp-buffer "*Org Links*"
6782 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6783 (when org-stored-links
6784 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6785 (princ (mapconcat
6786 (lambda (x)
6787 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6788 (reverse org-stored-links) "\n"))))
6789 (let ((cw (selected-window)))
6790 (select-window (get-buffer-window "*Org Links*"))
6791 (setq truncate-lines t)
6792 (org-fit-window-to-buffer)
6793 (select-window cw))
6794 ;; Fake a link history, containing the stored links.
6795 (setq tmphist (append (mapcar 'car org-stored-links)
6796 org-insert-link-history))
6797 (unwind-protect
6798 (setq link
6799 (let ((org-completion-use-ido nil))
6800 (org-completing-read
6801 "Link: "
6802 (append
6803 (mapcar (lambda (x) (list (concat (car x) ":")))
6804 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6805 (mapcar (lambda (x) (list (concat x ":")))
6806 org-link-types))
6807 nil nil nil
6808 'tmphist
6809 (or (car (car org-stored-links))))))
6810 (set-window-configuration wcf)
6811 (kill-buffer "*Org Links*"))
6812 (setq entry (assoc link org-stored-links))
6813 (or entry (push link org-insert-link-history))
6814 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6815 (not org-keep-stored-link-after-insertion))
6816 (setq org-stored-links (delq (assoc link org-stored-links)
6817 org-stored-links)))
6818 (setq desc (or desc (nth 1 entry)))))
6820 (if (string-match org-plain-link-re link)
6821 ;; URL-like link, normalize the use of angular brackets.
6822 (setq link (org-make-link (org-remove-angle-brackets link))))
6824 ;; Check if we are linking to the current file with a search option
6825 ;; If yes, simplify the link by using only the search option.
6826 (when (and buffer-file-name
6827 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6828 (let* ((path (match-string 1 link))
6829 (case-fold-search nil)
6830 (search (match-string 2 link)))
6831 (save-match-data
6832 (if (equal (file-truename buffer-file-name) (file-truename path))
6833 ;; We are linking to this same file, with a search option
6834 (setq link search)))))
6836 ;; Check if we can/should use a relative path. If yes, simplify the link
6837 (when (string-match "^file:\\(.*\\)" link)
6838 (let* ((path (match-string 1 link))
6839 (origpath path)
6840 (case-fold-search nil))
6841 (cond
6842 ((or (eq org-link-file-path-type 'absolute)
6843 (equal complete-file '(16)))
6844 (setq path (abbreviate-file-name (expand-file-name path))))
6845 ((eq org-link-file-path-type 'noabbrev)
6846 (setq path (expand-file-name path)))
6847 ((eq org-link-file-path-type 'relative)
6848 (setq path (file-relative-name path)))
6850 (save-match-data
6851 (if (string-match (concat "^" (regexp-quote
6852 (file-name-as-directory
6853 (expand-file-name "."))))
6854 (expand-file-name path))
6855 ;; We are linking a file with relative path name.
6856 (setq path (substring (expand-file-name path)
6857 (match-end 0)))
6858 (setq path (abbreviate-file-name (expand-file-name path)))))))
6859 (setq link (concat "file:" path))
6860 (if (equal desc origpath)
6861 (setq desc path))))
6863 (if org-make-link-description-function
6864 (setq desc (funcall org-make-link-description-function link desc)))
6866 (setq desc (read-string "Description: " desc))
6867 (unless (string-match "\\S-" desc) (setq desc nil))
6868 (if remove (apply 'delete-region remove))
6869 (insert (org-make-link-string link desc))))
6871 (defun org-completing-read (&rest args)
6872 "Completing-read with SPACE being a normal character."
6873 (let ((minibuffer-local-completion-map
6874 (copy-keymap minibuffer-local-completion-map)))
6875 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6876 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6877 (apply 'org-ido-completing-read args)))
6879 (defun org-ido-completing-read (&rest args)
6880 "Completing-read using `ido-mode' speedups if available"
6881 (if (and org-completion-use-ido
6882 (fboundp 'ido-completing-read)
6883 (boundp 'ido-mode) ido-mode
6884 (listp (second args)))
6885 (apply 'ido-completing-read (concat (car args)) (cdr args))
6886 (apply 'completing-read args)))
6888 (defun org-extract-attributes (s)
6889 "Extract the attributes cookie from a string and set as text property."
6890 (let (a attr (start 0) key value)
6891 (save-match-data
6892 (when (string-match "{{\\([^}]+\\)}}$" s)
6893 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6894 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6895 (setq key (match-string 1 a) value (match-string 2 a)
6896 start (match-end 0)
6897 attr (plist-put attr (intern key) value))))
6898 (org-add-props s nil 'org-attr attr))
6901 (defun org-attributes-to-string (plist)
6902 "Format a property list into an HTML attribute list."
6903 (let ((s "") key value)
6904 (while plist
6905 (setq key (pop plist) value (pop plist))
6906 (and value
6907 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6910 ;;; Opening/following a link
6912 (defvar org-link-search-failed nil)
6914 (defun org-next-link ()
6915 "Move forward to the next link.
6916 If the link is in hidden text, expose it."
6917 (interactive)
6918 (when (and org-link-search-failed (eq this-command last-command))
6919 (goto-char (point-min))
6920 (message "Link search wrapped back to beginning of buffer"))
6921 (setq org-link-search-failed nil)
6922 (let* ((pos (point))
6923 (ct (org-context))
6924 (a (assoc :link ct)))
6925 (if a (goto-char (nth 2 a)))
6926 (if (re-search-forward org-any-link-re nil t)
6927 (progn
6928 (goto-char (match-beginning 0))
6929 (if (org-invisible-p) (org-show-context)))
6930 (goto-char pos)
6931 (setq org-link-search-failed t)
6932 (error "No further link found"))))
6934 (defun org-previous-link ()
6935 "Move backward to the previous link.
6936 If the link is in hidden text, expose it."
6937 (interactive)
6938 (when (and org-link-search-failed (eq this-command last-command))
6939 (goto-char (point-max))
6940 (message "Link search wrapped back to end of buffer"))
6941 (setq org-link-search-failed nil)
6942 (let* ((pos (point))
6943 (ct (org-context))
6944 (a (assoc :link ct)))
6945 (if a (goto-char (nth 1 a)))
6946 (if (re-search-backward org-any-link-re nil t)
6947 (progn
6948 (goto-char (match-beginning 0))
6949 (if (org-invisible-p) (org-show-context)))
6950 (goto-char pos)
6951 (setq org-link-search-failed t)
6952 (error "No further link found"))))
6954 (defun org-translate-link (s)
6955 "Translate a link string if a translation function has been defined."
6956 (if (and org-link-translation-function
6957 (fboundp org-link-translation-function)
6958 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6959 (progn
6960 (setq s (funcall org-link-translation-function
6961 (match-string 1) (match-string 2)))
6962 (concat (car s) ":" (cdr s)))
6965 (defun org-translate-link-from-planner (type path)
6966 "Translate a link from Emacs Planner syntax so that Org can follow it.
6967 This is still an experimental function, your mileage may vary."
6968 (cond
6969 ((member type '("http" "https" "news" "ftp"))
6970 ;; standard Internet links are the same.
6971 nil)
6972 ((and (equal type "irc") (string-match "^//" path))
6973 ;; Planner has two / at the beginning of an irc link, we have 1.
6974 ;; We should have zero, actually....
6975 (setq path (substring path 1)))
6976 ((and (equal type "lisp") (string-match "^/" path))
6977 ;; Planner has a slash, we do not.
6978 (setq type "elisp" path (substring path 1)))
6979 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6980 ;; A typical message link. Planner has the id after the fina slash,
6981 ;; we separate it with a hash mark
6982 (setq path (concat (match-string 1 path) "#"
6983 (org-remove-angle-brackets (match-string 2 path)))))
6985 (cons type path))
6987 (defun org-find-file-at-mouse (ev)
6988 "Open file link or URL at mouse."
6989 (interactive "e")
6990 (mouse-set-point ev)
6991 (org-open-at-point 'in-emacs))
6993 (defun org-open-at-mouse (ev)
6994 "Open file link or URL at mouse."
6995 (interactive "e")
6996 (mouse-set-point ev)
6997 (if (eq major-mode 'org-agenda-mode)
6998 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6999 (org-open-at-point))
7001 (defvar org-window-config-before-follow-link nil
7002 "The window configuration before following a link.
7003 This is saved in case the need arises to restore it.")
7005 (defvar org-open-link-marker (make-marker)
7006 "Marker pointing to the location where `org-open-at-point; was called.")
7008 ;;;###autoload
7009 (defun org-open-at-point-global ()
7010 "Follow a link like Org-mode does.
7011 This command can be called in any mode to follow a link that has
7012 Org-mode syntax."
7013 (interactive)
7014 (org-run-like-in-org-mode 'org-open-at-point))
7016 ;;;###autoload
7017 (defun org-open-link-from-string (s &optional arg)
7018 "Open a link in the string S, as if it was in Org-mode."
7019 (interactive "sLink: \nP")
7020 (with-temp-buffer
7021 (let ((org-inhibit-startup t))
7022 (org-mode)
7023 (insert s)
7024 (goto-char (point-min))
7025 (org-open-at-point arg))))
7027 (defun org-open-at-point (&optional in-emacs)
7028 "Open link at or after point.
7029 If there is no link at point, this function will search forward up to
7030 the end of the current subtree.
7031 Normally, files will be opened by an appropriate application. If the
7032 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7033 With a double prefix argument, try to open outside of Emacs, in the
7034 application the system uses for this file type."
7035 (interactive "P")
7036 (org-load-modules-maybe)
7037 (move-marker org-open-link-marker (point))
7038 (setq org-window-config-before-follow-link (current-window-configuration))
7039 (org-remove-occur-highlights nil nil t)
7040 (cond
7041 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7042 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7043 (org-footnote-action))
7045 (let (type path link line search (pos (point)))
7046 (catch 'match
7047 (save-excursion
7048 (skip-chars-forward "^]\n\r")
7049 (when (org-in-regexp org-bracket-link-regexp)
7050 (setq link (org-extract-attributes
7051 (org-link-unescape (org-match-string-no-properties 1))))
7052 (while (string-match " *\n *" link)
7053 (setq link (replace-match " " t t link)))
7054 (setq link (org-link-expand-abbrev link))
7055 (cond
7056 ((or (file-name-absolute-p link)
7057 (string-match "^\\.\\.?/" link))
7058 (setq type "file" path link))
7059 ((string-match org-link-re-with-space3 link)
7060 (setq type (match-string 1 link) path (match-string 2 link)))
7061 (t (setq type "thisfile" path link)))
7062 (throw 'match t)))
7064 (when (get-text-property (point) 'org-linked-text)
7065 (setq type "thisfile"
7066 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7067 (1+ (point)) (point))
7068 path (buffer-substring
7069 (previous-single-property-change pos 'org-linked-text)
7070 (next-single-property-change pos 'org-linked-text)))
7071 (throw 'match t))
7073 (save-excursion
7074 (when (or (org-in-regexp org-angle-link-re)
7075 (org-in-regexp org-plain-link-re))
7076 (setq type (match-string 1) path (match-string 2))
7077 (throw 'match t)))
7078 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7079 (setq type "tree-match"
7080 path (match-string 1))
7081 (throw 'match t))
7082 (save-excursion
7083 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7084 (setq type "tags"
7085 path (match-string 1))
7086 (while (string-match ":" path)
7087 (setq path (replace-match "+" t t path)))
7088 (throw 'match t))))
7089 (unless path
7090 (error "No link found"))
7091 ;; Remove any trailing spaces in path
7092 (if (string-match " +\\'" path)
7093 (setq path (replace-match "" t t path)))
7094 (if (and org-link-translation-function
7095 (fboundp org-link-translation-function))
7096 ;; Check if we need to translate the link
7097 (let ((tmp (funcall org-link-translation-function type path)))
7098 (setq type (car tmp) path (cdr tmp))))
7100 (cond
7102 ((assoc type org-link-protocols)
7103 (funcall (nth 1 (assoc type org-link-protocols)) path))
7105 ((equal type "mailto")
7106 (let ((cmd (car org-link-mailto-program))
7107 (args (cdr org-link-mailto-program)) args1
7108 (address path) (subject "") a)
7109 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7110 (setq address (match-string 1 path)
7111 subject (org-link-escape (match-string 2 path))))
7112 (while args
7113 (cond
7114 ((not (stringp (car args))) (push (pop args) args1))
7115 (t (setq a (pop args))
7116 (if (string-match "%a" a)
7117 (setq a (replace-match address t t a)))
7118 (if (string-match "%s" a)
7119 (setq a (replace-match subject t t a)))
7120 (push a args1))))
7121 (apply cmd (nreverse args1))))
7123 ((member type '("http" "https" "ftp" "news"))
7124 (browse-url (concat type ":" (org-link-escape
7125 path org-link-escape-chars-browser))))
7127 ((member type '("message"))
7128 (browse-url (concat type ":" path)))
7130 ((string= type "tags")
7131 (org-tags-view in-emacs path))
7132 ((string= type "thisfile")
7133 (if in-emacs
7134 (switch-to-buffer-other-window
7135 (org-get-buffer-for-internal-link (current-buffer)))
7136 (org-mark-ring-push))
7137 (let ((cmd `(org-link-search
7138 ,path
7139 ,(cond ((equal in-emacs '(4)) 'occur)
7140 ((equal in-emacs '(16)) 'org-occur)
7141 (t nil))
7142 ,pos)))
7143 (condition-case nil (eval cmd)
7144 (error (progn (widen) (eval cmd))))))
7146 ((string= type "tree-match")
7147 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7149 ((string= type "file")
7150 (if (string-match "::\\([0-9]+\\)\\'" path)
7151 (setq line (string-to-number (match-string 1 path))
7152 path (substring path 0 (match-beginning 0)))
7153 (if (string-match "::\\(.+\\)\\'" path)
7154 (setq search (match-string 1 path)
7155 path (substring path 0 (match-beginning 0)))))
7156 (if (string-match "[*?{]" (file-name-nondirectory path))
7157 (dired path)
7158 (org-open-file path in-emacs line search)))
7160 ((string= type "news")
7161 (require 'org-gnus)
7162 (org-gnus-follow-link path))
7164 ((string= type "shell")
7165 (let ((cmd path))
7166 (if (or (not org-confirm-shell-link-function)
7167 (funcall org-confirm-shell-link-function
7168 (format "Execute \"%s\" in shell? "
7169 (org-add-props cmd nil
7170 'face 'org-warning))))
7171 (progn
7172 (message "Executing %s" cmd)
7173 (shell-command cmd))
7174 (error "Abort"))))
7176 ((string= type "elisp")
7177 (let ((cmd path))
7178 (if (or (not org-confirm-elisp-link-function)
7179 (funcall org-confirm-elisp-link-function
7180 (format "Execute \"%s\" as elisp? "
7181 (org-add-props cmd nil
7182 'face 'org-warning))))
7183 (message "%s => %s" cmd
7184 (if (equal (string-to-char cmd) ?\()
7185 (eval (read cmd))
7186 (call-interactively (read cmd))))
7187 (error "Abort"))))
7190 (browse-url-at-point))))))
7191 (move-marker org-open-link-marker nil)
7192 (run-hook-with-args 'org-follow-link-hook))
7194 ;;;; Time estimates
7196 (defun org-get-effort (&optional pom)
7197 "Get the effort estimate for the current entry."
7198 (org-entry-get pom org-effort-property))
7200 ;;; File search
7202 (defvar org-create-file-search-functions nil
7203 "List of functions to construct the right search string for a file link.
7204 These functions are called in turn with point at the location to
7205 which the link should point.
7207 A function in the hook should first test if it would like to
7208 handle this file type, for example by checking the major-mode or
7209 the file extension. If it decides not to handle this file, it
7210 should just return nil to give other functions a chance. If it
7211 does handle the file, it must return the search string to be used
7212 when following the link. The search string will be part of the
7213 file link, given after a double colon, and `org-open-at-point'
7214 will automatically search for it. If special measures must be
7215 taken to make the search successful, another function should be
7216 added to the companion hook `org-execute-file-search-functions',
7217 which see.
7219 A function in this hook may also use `setq' to set the variable
7220 `description' to provide a suggestion for the descriptive text to
7221 be used for this link when it gets inserted into an Org-mode
7222 buffer with \\[org-insert-link].")
7224 (defvar org-execute-file-search-functions nil
7225 "List of functions to execute a file search triggered by a link.
7227 Functions added to this hook must accept a single argument, the
7228 search string that was part of the file link, the part after the
7229 double colon. The function must first check if it would like to
7230 handle this search, for example by checking the major-mode or the
7231 file extension. If it decides not to handle this search, it
7232 should just return nil to give other functions a chance. If it
7233 does handle the search, it must return a non-nil value to keep
7234 other functions from trying.
7236 Each function can access the current prefix argument through the
7237 variable `current-prefix-argument'. Note that a single prefix is
7238 used to force opening a link in Emacs, so it may be good to only
7239 use a numeric or double prefix to guide the search function.
7241 In case this is needed, a function in this hook can also restore
7242 the window configuration before `org-open-at-point' was called using:
7244 (set-window-configuration org-window-config-before-follow-link)")
7246 (defun org-link-search (s &optional type avoid-pos)
7247 "Search for a link search option.
7248 If S is surrounded by forward slashes, it is interpreted as a
7249 regular expression. In org-mode files, this will create an `org-occur'
7250 sparse tree. In ordinary files, `occur' will be used to list matches.
7251 If the current buffer is in `dired-mode', grep will be used to search
7252 in all files. If AVOID-POS is given, ignore matches near that position."
7253 (let ((case-fold-search t)
7254 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7255 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7256 (append '(("") (" ") ("\t") ("\n"))
7257 org-emphasis-alist)
7258 "\\|") "\\)"))
7259 (pos (point))
7260 (pre nil) (post nil)
7261 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7262 (cond
7263 ;; First check if there are any special
7264 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7265 ;; Now try the builtin stuff
7266 ((save-excursion
7267 (goto-char (point-min))
7268 (and
7269 (re-search-forward
7270 (concat "<<" (regexp-quote s0) ">>") nil t)
7271 (setq type 'dedicated
7272 pos (match-beginning 0))))
7273 ;; There is an exact target for this
7274 (goto-char pos))
7275 ((and (string-match "^(\\(.*\\))$" s0)
7276 (save-excursion
7277 (goto-char (point-min))
7278 (and
7279 (re-search-forward
7280 (concat "[^[]" (regexp-quote
7281 (format org-coderef-label-format
7282 (match-string 1 s0))))
7283 nil t)
7284 (setq type 'dedicated
7285 pos (1+ (match-beginning 0))))))
7286 ;; There is a coderef target for this
7287 (goto-char pos))
7288 ((string-match "^/\\(.*\\)/$" s)
7289 ;; A regular expression
7290 (cond
7291 ((org-mode-p)
7292 (org-occur (match-string 1 s)))
7293 ;;((eq major-mode 'dired-mode)
7294 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7295 (t (org-do-occur (match-string 1 s)))))
7297 ;; A normal search strings
7298 (when (equal (string-to-char s) ?*)
7299 ;; Anchor on headlines, post may include tags.
7300 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7301 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7302 s (substring s 1)))
7303 (remove-text-properties
7304 0 (length s)
7305 '(face nil mouse-face nil keymap nil fontified nil) s)
7306 ;; Make a series of regular expressions to find a match
7307 (setq words (org-split-string s "[ \n\r\t]+")
7309 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7310 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7311 "\\)" markers)
7312 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7313 re2a (concat "[ \t\r\n]" re2a_)
7314 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7315 re4 (concat "[^a-zA-Z_]" re4_)
7317 re1 (concat pre re2 post)
7318 re3 (concat pre (if pre re4_ re4) post)
7319 re5 (concat pre ".*" re4)
7320 re2 (concat pre re2)
7321 re2a (concat pre (if pre re2a_ re2a))
7322 re4 (concat pre (if pre re4_ re4))
7323 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7324 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7325 re5 "\\)"
7327 (cond
7328 ((eq type 'org-occur) (org-occur reall))
7329 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7330 (t (goto-char (point-min))
7331 (setq type 'fuzzy)
7332 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7333 (org-search-not-self 1 re1 nil t)
7334 (org-search-not-self 1 re2 nil t)
7335 (org-search-not-self 1 re2a nil t)
7336 (org-search-not-self 1 re3 nil t)
7337 (org-search-not-self 1 re4 nil t)
7338 (org-search-not-self 1 re5 nil t)
7340 (goto-char (match-beginning 1))
7341 (goto-char pos)
7342 (error "No match")))))
7344 ;; Normal string-search
7345 (goto-char (point-min))
7346 (if (search-forward s nil t)
7347 (goto-char (match-beginning 0))
7348 (error "No match"))))
7349 (and (org-mode-p) (org-show-context 'link-search))
7350 type))
7352 (defun org-search-not-self (group &rest args)
7353 "Execute `re-search-forward', but only accept matches that do not
7354 enclose the position of `org-open-link-marker'."
7355 (let ((m org-open-link-marker))
7356 (catch 'exit
7357 (while (apply 're-search-forward args)
7358 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7359 (goto-char (match-end group))
7360 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7361 (> (match-beginning 0) (marker-position m))
7362 (< (match-end 0) (marker-position m)))
7363 (save-match-data
7364 (or (not (org-in-regexp
7365 org-bracket-link-analytic-regexp 1))
7366 (not (match-end 4)) ; no description
7367 (and (<= (match-beginning 4) (point))
7368 (>= (match-end 4) (point))))))
7369 (throw 'exit (point))))))))
7371 (defun org-get-buffer-for-internal-link (buffer)
7372 "Return a buffer to be used for displaying the link target of internal links."
7373 (cond
7374 ((not org-display-internal-link-with-indirect-buffer)
7375 buffer)
7376 ((string-match "(Clone)$" (buffer-name buffer))
7377 (message "Buffer is already a clone, not making another one")
7378 ;; we also do not modify visibility in this case
7379 buffer)
7380 (t ; make a new indirect buffer for displaying the link
7381 (let* ((bn (buffer-name buffer))
7382 (ibn (concat bn "(Clone)"))
7383 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7384 (with-current-buffer ib (org-overview))
7385 ib))))
7387 (defun org-do-occur (regexp &optional cleanup)
7388 "Call the Emacs command `occur'.
7389 If CLEANUP is non-nil, remove the printout of the regular expression
7390 in the *Occur* buffer. This is useful if the regex is long and not useful
7391 to read."
7392 (occur regexp)
7393 (when cleanup
7394 (let ((cwin (selected-window)) win beg end)
7395 (when (setq win (get-buffer-window "*Occur*"))
7396 (select-window win))
7397 (goto-char (point-min))
7398 (when (re-search-forward "match[a-z]+" nil t)
7399 (setq beg (match-end 0))
7400 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7401 (setq end (1- (match-beginning 0)))))
7402 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7403 (goto-char (point-min))
7404 (select-window cwin))))
7406 ;;; The mark ring for links jumps
7408 (defvar org-mark-ring nil
7409 "Mark ring for positions before jumps in Org-mode.")
7410 (defvar org-mark-ring-last-goto nil
7411 "Last position in the mark ring used to go back.")
7412 ;; Fill and close the ring
7413 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7414 (loop for i from 1 to org-mark-ring-length do
7415 (push (make-marker) org-mark-ring))
7416 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7417 org-mark-ring)
7419 (defun org-mark-ring-push (&optional pos buffer)
7420 "Put the current position or POS into the mark ring and rotate it."
7421 (interactive)
7422 (setq pos (or pos (point)))
7423 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7424 (move-marker (car org-mark-ring)
7425 (or pos (point))
7426 (or buffer (current-buffer)))
7427 (message "%s"
7428 (substitute-command-keys
7429 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7431 (defun org-mark-ring-goto (&optional n)
7432 "Jump to the previous position in the mark ring.
7433 With prefix arg N, jump back that many stored positions. When
7434 called several times in succession, walk through the entire ring.
7435 Org-mode commands jumping to a different position in the current file,
7436 or to another Org-mode file, automatically push the old position
7437 onto the ring."
7438 (interactive "p")
7439 (let (p m)
7440 (if (eq last-command this-command)
7441 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7442 (setq p org-mark-ring))
7443 (setq org-mark-ring-last-goto p)
7444 (setq m (car p))
7445 (switch-to-buffer (marker-buffer m))
7446 (goto-char m)
7447 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7449 (defun org-remove-angle-brackets (s)
7450 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7451 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7453 (defun org-add-angle-brackets (s)
7454 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7455 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7457 (defun org-remove-double-quotes (s)
7458 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7459 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7462 ;;; Following specific links
7464 (defun org-follow-timestamp-link ()
7465 (cond
7466 ((org-at-date-range-p t)
7467 (let ((org-agenda-start-on-weekday)
7468 (t1 (match-string 1))
7469 (t2 (match-string 2)))
7470 (setq t1 (time-to-days (org-time-string-to-time t1))
7471 t2 (time-to-days (org-time-string-to-time t2)))
7472 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7473 ((org-at-timestamp-p t)
7474 (org-agenda-list nil (time-to-days (org-time-string-to-time
7475 (substring (match-string 1) 0 10)))
7477 (t (error "This should not happen"))))
7480 ;;; Following file links
7481 (defvar org-wait nil)
7482 (defun org-open-file (path &optional in-emacs line search)
7483 "Open the file at PATH.
7484 First, this expands any special file name abbreviations. Then the
7485 configuration variable `org-file-apps' is checked if it contains an
7486 entry for this file type, and if yes, the corresponding command is launched.
7488 If no application is found, Emacs simply visits the file.
7490 With optional prefix argument IN-EMACS, Emacs will visit the file.
7491 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7492 and o use an external application to visit the file.
7494 Optional LINE specifies a line to go to, optional SEARCH a string to
7495 search for. If LINE or SEARCH is given, the file will always be
7496 opened in Emacs.
7497 If the file does not exist, an error is thrown."
7498 (setq in-emacs (or in-emacs line search))
7499 (let* ((file (if (equal path "")
7500 buffer-file-name
7501 (substitute-in-file-name (expand-file-name path))))
7502 (apps (append org-file-apps (org-default-apps)))
7503 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7504 (dirp (if remp nil (file-directory-p file)))
7505 (file (if (and dirp org-open-directory-means-index-dot-org)
7506 (concat (file-name-as-directory file) "index.org")
7507 file))
7508 (a-m-a-p (assq 'auto-mode apps))
7509 (dfile (downcase file))
7510 (old-buffer (current-buffer))
7511 (old-pos (point))
7512 (old-mode major-mode)
7513 ext cmd)
7514 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7515 (setq ext (match-string 1 dfile))
7516 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7517 (setq ext (match-string 1 dfile))))
7518 (cond
7519 ((equal in-emacs '(16))
7520 (setq cmd (cdr (assoc 'system apps))))
7521 (in-emacs (setq cmd 'emacs))
7523 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7524 (and dirp (cdr (assoc 'directory apps)))
7525 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7526 'string-match)
7527 (cdr (assoc ext apps))
7528 (cdr (assoc t apps))))))
7529 (when (eq cmd 'system)
7530 (setq cmd (cdr (assoc 'system apps))))
7531 (when (eq cmd 'default)
7532 (setq cmd (cdr (assoc t apps))))
7533 (when (eq cmd 'mailcap)
7534 (require 'mailcap)
7535 (mailcap-parse-mailcaps)
7536 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7537 (command (mailcap-mime-info mime-type)))
7538 (if (stringp command)
7539 (setq cmd command)
7540 (setq cmd 'emacs))))
7541 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7542 (not (file-exists-p file))
7543 (not org-open-non-existing-files))
7544 (error "No such file: %s" file))
7545 (cond
7546 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7547 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7548 (while (string-match "['\"]%s['\"]" cmd)
7549 (setq cmd (replace-match "%s" t t cmd)))
7550 (while (string-match "%s" cmd)
7551 (setq cmd (replace-match
7552 (save-match-data
7553 (shell-quote-argument
7554 (convert-standard-filename file)))
7555 t t cmd)))
7556 (save-window-excursion
7557 (start-process-shell-command cmd nil cmd)
7558 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7560 ((or (stringp cmd)
7561 (eq cmd 'emacs))
7562 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7563 (widen)
7564 (if line (goto-line line)
7565 (if search (org-link-search search))))
7566 ((consp cmd)
7567 (let ((file (convert-standard-filename file)))
7568 (eval cmd)))
7569 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7570 (and (org-mode-p) (eq old-mode 'org-mode)
7571 (or (not (equal old-buffer (current-buffer)))
7572 (not (equal old-pos (point))))
7573 (org-mark-ring-push old-pos old-buffer))))
7575 (defun org-default-apps ()
7576 "Return the default applications for this operating system."
7577 (cond
7578 ((eq system-type 'darwin)
7579 org-file-apps-defaults-macosx)
7580 ((eq system-type 'windows-nt)
7581 org-file-apps-defaults-windowsnt)
7582 (t org-file-apps-defaults-gnu)))
7584 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7585 "Convert extensions to regular expressions in the cars of LIST.
7586 Also, weed out any non-string entries, because the return value is used
7587 only for regexp matching.
7588 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7589 point to the symbol `emacs', indicating that the file should
7590 be opened in Emacs."
7591 (append
7592 (delq nil
7593 (mapcar (lambda (x)
7594 (if (not (stringp (car x)))
7596 (if (string-match "\\W" (car x))
7598 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7599 list))
7600 (if add-auto-mode
7601 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7603 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7604 (defun org-file-remote-p (file)
7605 "Test whether FILE specifies a location on a remote system.
7606 Return non-nil if the location is indeed remote.
7608 For example, the filename \"/user@host:/foo\" specifies a location
7609 on the system \"/user@host:\"."
7610 (cond ((fboundp 'file-remote-p)
7611 (file-remote-p file))
7612 ((fboundp 'tramp-handle-file-remote-p)
7613 (tramp-handle-file-remote-p file))
7614 ((and (boundp 'ange-ftp-name-format)
7615 (string-match (car ange-ftp-name-format) file))
7617 (t nil)))
7620 ;;;; Refiling
7622 (defun org-get-org-file ()
7623 "Read a filename, with default directory `org-directory'."
7624 (let ((default (or org-default-notes-file remember-data-file)))
7625 (read-file-name (format "File name [%s]: " default)
7626 (file-name-as-directory org-directory)
7627 default)))
7629 (defun org-notes-order-reversed-p ()
7630 "Check if the current file should receive notes in reversed order."
7631 (cond
7632 ((not org-reverse-note-order) nil)
7633 ((eq t org-reverse-note-order) t)
7634 ((not (listp org-reverse-note-order)) nil)
7635 (t (catch 'exit
7636 (let ((all org-reverse-note-order)
7637 entry)
7638 (while (setq entry (pop all))
7639 (if (string-match (car entry) buffer-file-name)
7640 (throw 'exit (cdr entry))))
7641 nil)))))
7643 (defvar org-refile-target-table nil
7644 "The list of refile targets, created by `org-refile'.")
7646 (defvar org-agenda-new-buffers nil
7647 "Buffers created to visit agenda files.")
7649 (defun org-get-refile-targets (&optional default-buffer)
7650 "Produce a table with refile targets."
7651 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7652 targets txt re files f desc descre fast-path-p level)
7653 (message "Getting targets...")
7654 (with-current-buffer (or default-buffer (current-buffer))
7655 (while (setq entry (pop entries))
7656 (setq files (car entry) desc (cdr entry))
7657 (setq fast-path-p nil)
7658 (cond
7659 ((null files) (setq files (list (current-buffer))))
7660 ((eq files 'org-agenda-files)
7661 (setq files (org-agenda-files 'unrestricted)))
7662 ((and (symbolp files) (fboundp files))
7663 (setq files (funcall files)))
7664 ((and (symbolp files) (boundp files))
7665 (setq files (symbol-value files))))
7666 (if (stringp files) (setq files (list files)))
7667 (cond
7668 ((eq (car desc) :tag)
7669 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7670 ((eq (car desc) :todo)
7671 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7672 ((eq (car desc) :regexp)
7673 (setq descre (cdr desc)))
7674 ((eq (car desc) :level)
7675 (setq descre (concat "^\\*\\{" (number-to-string
7676 (if org-odd-levels-only
7677 (1- (* 2 (cdr desc)))
7678 (cdr desc)))
7679 "\\}[ \t]")))
7680 ((eq (car desc) :maxlevel)
7681 (setq fast-path-p t)
7682 (setq descre (concat "^\\*\\{1," (number-to-string
7683 (if org-odd-levels-only
7684 (1- (* 2 (cdr desc)))
7685 (cdr desc)))
7686 "\\}[ \t]")))
7687 (t (error "Bad refiling target description %s" desc)))
7688 (while (setq f (pop files))
7689 (save-excursion
7690 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7691 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7692 (setq f (expand-file-name f))
7693 (save-excursion
7694 (save-restriction
7695 (widen)
7696 (goto-char (point-min))
7697 (while (re-search-forward descre nil t)
7698 (goto-char (point-at-bol))
7699 (when (looking-at org-complex-heading-regexp)
7700 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7701 txt (org-link-display-format (match-string 4))
7702 re (concat "^" (regexp-quote
7703 (buffer-substring (match-beginning 1)
7704 (match-end 4)))))
7705 (if (match-end 5) (setq re (concat re "[ \t]+"
7706 (regexp-quote
7707 (match-string 5)))))
7708 (setq re (concat re "[ \t]*$"))
7709 (when org-refile-use-outline-path
7710 (setq txt (mapconcat 'org-protect-slash
7711 (append
7712 (if (eq org-refile-use-outline-path 'file)
7713 (list (file-name-nondirectory
7714 (buffer-file-name (buffer-base-buffer))))
7715 (if (eq org-refile-use-outline-path 'full-file-path)
7716 (list (buffer-file-name (buffer-base-buffer)))))
7717 (org-get-outline-path fast-path-p level txt)
7718 (list txt))
7719 "/")))
7720 (push (list txt f re (point)) targets))
7721 (goto-char (point-at-eol))))))))
7722 (message "Getting targets...done")
7723 (nreverse targets))))
7725 (defun org-protect-slash (s)
7726 (while (string-match "/" s)
7727 (setq s (replace-match "\\" t t s)))
7730 (defvar org-olpa (make-vector 20 nil))
7732 (defun org-get-outline-path (&optional fastp level heading)
7733 "Return the outline path to the current entry, as a list."
7734 (if fastp
7735 (progn
7736 (if (> level 19)
7737 (error "Outline path failure, more than 19 levels."))
7738 (loop for i from level upto 19 do
7739 (aset org-olpa i nil))
7740 (prog1
7741 (delq nil (append org-olpa nil))
7742 (aset org-olpa level heading)))
7743 (let (rtn)
7744 (save-excursion
7745 (while (org-up-heading-safe)
7746 (when (looking-at org-complex-heading-regexp)
7747 (push (org-match-string-no-properties 4) rtn)))
7748 rtn))))
7750 (defvar org-refile-history nil
7751 "History for refiling operations.")
7753 (defun org-refile (&optional goto default-buffer)
7754 "Move the entry at point to another heading.
7755 The list of target headings is compiled using the information in
7756 `org-refile-targets', which see. This list is created before each use
7757 and will therefore always be up-to-date.
7759 At the target location, the entry is filed as a subitem of the target heading.
7760 Depending on `org-reverse-note-order', the new subitem will either be the
7761 first or the last subitem.
7763 If there is an active region, all entries in that region will be moved.
7764 However, the region must fulfil the requirement that the first heading
7765 is the first one sets the top-level of the moved text - at most siblings
7766 below it are allowed.
7768 With prefix arg GOTO, the command will only visit the target location,
7769 not actually move anything.
7770 With a double prefix `C-u C-u', go to the location where the last refiling
7771 operation has put the subtree."
7772 (interactive "P")
7773 (let* ((cbuf (current-buffer))
7774 (regionp (org-region-active-p))
7775 (region-start (and regionp (region-beginning)))
7776 (region-end (and regionp (region-end)))
7777 (region-length (and regionp (- region-end region-start)))
7778 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7779 pos it nbuf file re level reversed)
7780 (when regionp (goto-char region-start)
7781 (unless (org-kill-is-subtree-p
7782 (buffer-substring region-start region-end))
7783 (error "The region is not a (sequence of) subtree(s)")))
7784 (if (equal goto '(16))
7785 (org-refile-goto-last-stored)
7786 (when (setq it (org-refile-get-location
7787 (if goto "Goto: " "Refile to: ") default-buffer))
7788 (setq file (nth 1 it)
7789 re (nth 2 it)
7790 pos (nth 3 it))
7791 (if (and (equal (buffer-file-name) file)
7792 (if regionp
7793 (and (>= pos region-start)
7794 (<= pos region-end))
7795 (and (>= pos (point))
7796 (< pos (save-excursion
7797 (org-end-of-subtree t t))))))
7798 (error "Cannot refile to position inside the tree or region"))
7800 (setq nbuf (or (find-buffer-visiting file)
7801 (find-file-noselect file)))
7802 (if goto
7803 (progn
7804 (switch-to-buffer nbuf)
7805 (goto-char pos)
7806 (org-show-context 'org-goto))
7807 (if regionp
7808 (progn
7809 (kill-new (buffer-substring region-start region-end))
7810 (org-save-markers-in-region region-start region-end))
7811 (org-copy-subtree 1 nil t))
7812 (save-excursion
7813 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7814 (find-file-noselect file))))
7815 (setq reversed (org-notes-order-reversed-p))
7816 (save-excursion
7817 (save-restriction
7818 (widen)
7819 (goto-char pos)
7820 (looking-at outline-regexp)
7821 (setq level (org-get-valid-level (funcall outline-level) 1))
7822 (goto-char
7823 (if reversed
7824 (or (outline-next-heading) (point-max))
7825 (or (save-excursion (outline-get-next-sibling))
7826 (org-end-of-subtree t t)
7827 (point-max))))
7828 (if (not (bolp)) (newline))
7829 (bookmark-set "org-refile-last-stored")
7830 (org-paste-subtree level))))
7831 (if regionp
7832 (delete-region (point) (+ (point) region-length))
7833 (org-cut-subtree))
7834 (setq org-markers-to-move nil)
7835 (message "Refiled to \"%s\"" (car it)))))))
7837 (defun org-refile-goto-last-stored ()
7838 "Go to the location where the last refile was stored."
7839 (interactive)
7840 (bookmark-jump "org-refile-last-stored")
7841 (message "This is the location of the last refile"))
7843 (defun org-refile-get-location (&optional prompt default-buffer)
7844 "Prompt the user for a refile location, using PROMPT."
7845 (let ((org-refile-targets org-refile-targets)
7846 (org-refile-use-outline-path org-refile-use-outline-path))
7847 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7848 (unless org-refile-target-table
7849 (error "No refile targets"))
7850 (let* ((cbuf (current-buffer))
7851 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7852 (cfunc (if (and org-refile-use-outline-path
7853 org-outline-path-complete-in-steps)
7854 'org-olpath-completing-read
7855 'org-ido-completing-read))
7856 (extra (if org-refile-use-outline-path "/" ""))
7857 (filename (and cfn (expand-file-name cfn)))
7858 (tbl (mapcar
7859 (lambda (x)
7860 (if (not (equal filename (nth 1 x)))
7861 (cons (concat (car x) extra " ("
7862 (file-name-nondirectory (nth 1 x)) ")")
7863 (cdr x))
7864 (cons (concat (car x) extra) (cdr x))))
7865 org-refile-target-table))
7866 (completion-ignore-case t))
7867 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7868 tbl)))
7870 (defun org-olpath-completing-read (prompt collection &rest args)
7871 "Read an outline path like a file name."
7872 (let ((thetable collection))
7873 (apply
7874 'org-ido-completing-read prompt
7875 (lambda (string predicate &optional flag)
7876 (let (rtn r f (l (length string)))
7877 (cond
7878 ((eq flag nil)
7879 ;; try completion
7880 (try-completion string thetable))
7881 ((eq flag t)
7882 ;; all-completions
7883 (setq rtn (all-completions string thetable predicate))
7884 (mapcar
7885 (lambda (x)
7886 (setq r (substring x l))
7887 (if (string-match " ([^)]*)$" x)
7888 (setq f (match-string 0 x))
7889 (setq f ""))
7890 (if (string-match "/" r)
7891 (concat string (substring r 0 (match-end 0)) f)
7893 rtn))
7894 ((eq flag 'lambda)
7895 ;; exact match?
7896 (assoc string thetable)))
7898 args)))
7900 ;;;; Dynamic blocks
7902 (defun org-find-dblock (name)
7903 "Find the first dynamic block with name NAME in the buffer.
7904 If not found, stay at current position and return nil."
7905 (let (pos)
7906 (save-excursion
7907 (goto-char (point-min))
7908 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7909 nil t)
7910 (match-beginning 0))))
7911 (if pos (goto-char pos))
7912 pos))
7914 (defconst org-dblock-start-re
7915 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7916 "Matches the startline of a dynamic block, with parameters.")
7918 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7919 "Matches the end of a dynamic block.")
7921 (defun org-create-dblock (plist)
7922 "Create a dynamic block section, with parameters taken from PLIST.
7923 PLIST must contain a :name entry which is used as name of the block."
7924 (unless (bolp) (newline))
7925 (let ((name (plist-get plist :name)))
7926 (insert "#+BEGIN: " name)
7927 (while plist
7928 (if (eq (car plist) :name)
7929 (setq plist (cddr plist))
7930 (insert " " (prin1-to-string (pop plist)))))
7931 (insert "\n\n#+END:\n")
7932 (beginning-of-line -2)))
7934 (defun org-prepare-dblock ()
7935 "Prepare dynamic block for refresh.
7936 This empties the block, puts the cursor at the insert position and returns
7937 the property list including an extra property :name with the block name."
7938 (unless (looking-at org-dblock-start-re)
7939 (error "Not at a dynamic block"))
7940 (let* ((begdel (1+ (match-end 0)))
7941 (name (org-no-properties (match-string 1)))
7942 (params (append (list :name name)
7943 (read (concat "(" (match-string 3) ")")))))
7944 (unless (re-search-forward org-dblock-end-re nil t)
7945 (error "Dynamic block not terminated"))
7946 (setq params
7947 (append params
7948 (list :content (buffer-substring
7949 begdel (match-beginning 0)))))
7950 (delete-region begdel (match-beginning 0))
7951 (goto-char begdel)
7952 (open-line 1)
7953 params))
7955 (defun org-map-dblocks (&optional command)
7956 "Apply COMMAND to all dynamic blocks in the current buffer.
7957 If COMMAND is not given, use `org-update-dblock'."
7958 (let ((cmd (or command 'org-update-dblock))
7959 pos)
7960 (save-excursion
7961 (goto-char (point-min))
7962 (while (re-search-forward org-dblock-start-re nil t)
7963 (goto-char (setq pos (match-beginning 0)))
7964 (condition-case nil
7965 (funcall cmd)
7966 (error (message "Error during update of dynamic block")))
7967 (goto-char pos)
7968 (unless (re-search-forward org-dblock-end-re nil t)
7969 (error "Dynamic block not terminated"))))))
7971 (defun org-dblock-update (&optional arg)
7972 "User command for updating dynamic blocks.
7973 Update the dynamic block at point. With prefix ARG, update all dynamic
7974 blocks in the buffer."
7975 (interactive "P")
7976 (if arg
7977 (org-update-all-dblocks)
7978 (or (looking-at org-dblock-start-re)
7979 (org-beginning-of-dblock))
7980 (org-update-dblock)))
7982 (defun org-update-dblock ()
7983 "Update the dynamic block at point
7984 This means to empty the block, parse for parameters and then call
7985 the correct writing function."
7986 (save-window-excursion
7987 (let* ((pos (point))
7988 (line (org-current-line))
7989 (params (org-prepare-dblock))
7990 (name (plist-get params :name))
7991 (cmd (intern (concat "org-dblock-write:" name))))
7992 (message "Updating dynamic block `%s' at line %d..." name line)
7993 (funcall cmd params)
7994 (message "Updating dynamic block `%s' at line %d...done" name line)
7995 (goto-char pos))))
7997 (defun org-beginning-of-dblock ()
7998 "Find the beginning of the dynamic block at point.
7999 Error if there is no such block at point."
8000 (let ((pos (point))
8001 beg)
8002 (end-of-line 1)
8003 (if (and (re-search-backward org-dblock-start-re nil t)
8004 (setq beg (match-beginning 0))
8005 (re-search-forward org-dblock-end-re nil t)
8006 (> (match-end 0) pos))
8007 (goto-char beg)
8008 (goto-char pos)
8009 (error "Not in a dynamic block"))))
8011 (defun org-update-all-dblocks ()
8012 "Update all dynamic blocks in the buffer.
8013 This function can be used in a hook."
8014 (when (org-mode-p)
8015 (org-map-dblocks 'org-update-dblock)))
8018 ;;;; Completion
8020 (defconst org-additional-option-like-keywords
8021 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8022 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8023 "BEGIN_EXAMPLE" "END_EXAMPLE"
8024 "BEGIN_QUOTE" "END_QUOTE"
8025 "BEGIN_VERSE" "END_VERSE"
8026 "BEGIN_SRC" "END_SRC"
8027 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8029 (defcustom org-structure-template-alist
8031 ("s" "#+begin_src ?\n\n#+end_src"
8032 "<src lang=\"?\">\n\n</src>")
8033 ("e" "#+begin_example\n?\n#+end_example"
8034 "<example>\n?\n</example>")
8035 ("q" "#+begin_quote\n?\n#+end_quote"
8036 "<quote>\n?\n</quote>")
8037 ("v" "#+begin_verse\n?\n#+end_verse"
8038 "<verse>\n?\n/verse>")
8039 ("l" "#+begin_latex\n?\n#+end_latex"
8040 "<literal style=\"latex\">\n?\n</literal>")
8041 ("L" "#+latex: "
8042 "<literal style=\"latex\">?</literal>")
8043 ("h" "#+begin_html\n?\n#+end_html"
8044 "<literal style=\"html\">\n?\n</literal>")
8045 ("H" "#+html: "
8046 "<literal style=\"html\">?</literal>")
8047 ("a" "#+begin_ascii\n?\n#+end_ascii")
8048 ("A" "#+ascii: ")
8049 ("i" "#+include %file ?"
8050 "<include file=%file markup=\"?\">")
8052 "Structure completion elements.
8053 This is a list of abbreviation keys and values. The value gets inserted
8054 it you type @samp{.} followed by the key and then the completion key,
8055 usually `M-TAB'. %file will be replaced by a file name after prompting
8056 for the file using completion.
8057 There are two templates for each key, the first uses the original Org syntax,
8058 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8059 the default when the /org-mtags.el/ module has been loaded. See also the
8060 variable `org-mtags-prefer-muse-templates'.
8061 This is an experimental feature, it is undecided if it is going to stay in."
8062 :group 'org-completion
8063 :type '(repeat
8064 (string :tag "Key")
8065 (string :tag "Template")
8066 (string :tag "Muse Template")))
8068 (defun org-try-structure-completion ()
8069 "Try to complete a structure template before point.
8070 This looks for strings like \"<e\" on an otherwise empty line and
8071 expands them."
8072 (let ((l (buffer-substring (point-at-bol) (point)))
8074 (when (and (looking-at "[ \t]*$")
8075 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8076 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8077 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8078 (match-beginning 1)) a)
8079 t)))
8081 (defun org-complete-expand-structure-template (start cell)
8082 "Expand a structure template."
8083 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8084 (rpl (nth (if musep 2 1) cell)))
8085 (delete-region start (point))
8086 (when (string-match "\\`#\\+" rpl)
8087 (cond
8088 ((bolp))
8089 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8090 (delete-region (point-at-bol) (point)))
8091 (t (newline))))
8092 (setq start (point))
8093 (if (string-match "%file" rpl)
8094 (setq rpl (replace-match
8095 (concat
8096 "\""
8097 (save-match-data
8098 (abbreviate-file-name (read-file-name "Include file: ")))
8099 "\"")
8100 t t rpl)))
8101 (insert rpl)
8102 (if (re-search-backward "\\?" start t) (delete-char 1))))
8105 (defun org-complete (&optional arg)
8106 "Perform completion on word at point.
8107 At the beginning of a headline, this completes TODO keywords as given in
8108 `org-todo-keywords'.
8109 If the current word is preceded by a backslash, completes the TeX symbols
8110 that are supported for HTML support.
8111 If the current word is preceded by \"#+\", completes special words for
8112 setting file options.
8113 In the line after \"#+STARTUP:, complete valid keywords.\"
8114 At all other locations, this simply calls the value of
8115 `org-completion-fallback-command'."
8116 (interactive "P")
8117 (org-without-partial-completion
8118 (catch 'exit
8119 (let* ((a nil)
8120 (end (point))
8121 (beg1 (save-excursion
8122 (skip-chars-backward (org-re "[:alnum:]_@"))
8123 (point)))
8124 (beg (save-excursion
8125 (skip-chars-backward "a-zA-Z0-9_:$")
8126 (point)))
8127 (confirm (lambda (x) (stringp (car x))))
8128 (searchhead (equal (char-before beg) ?*))
8129 (struct
8130 (when (and (member (char-before beg1) '(?. ?<))
8131 (setq a (assoc (buffer-substring beg1 (point))
8132 org-structure-template-alist)))
8133 (org-complete-expand-structure-template (1- beg1) a)
8134 (throw 'exit t)))
8135 (tag (and (equal (char-before beg1) ?:)
8136 (equal (char-after (point-at-bol)) ?*)))
8137 (prop (and (equal (char-before beg1) ?:)
8138 (not (equal (char-after (point-at-bol)) ?*))))
8139 (texp (equal (char-before beg) ?\\))
8140 (link (equal (char-before beg) ?\[))
8141 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8142 beg)
8143 "#+"))
8144 (startup (string-match "^#\\+STARTUP:.*"
8145 (buffer-substring (point-at-bol) (point))))
8146 (completion-ignore-case opt)
8147 (type nil)
8148 (tbl nil)
8149 (table (cond
8150 (opt
8151 (setq type :opt)
8152 (require 'org-exp)
8153 (append
8154 (mapcar
8155 (lambda (x)
8156 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8157 (cons (match-string 2 x) (match-string 1 x)))
8158 (org-split-string (org-get-current-options) "\n"))
8159 (mapcar 'list org-additional-option-like-keywords)))
8160 (startup
8161 (setq type :startup)
8162 org-startup-options)
8163 (link (append org-link-abbrev-alist-local
8164 org-link-abbrev-alist))
8165 (texp
8166 (setq type :tex)
8167 org-html-entities)
8168 ((string-match "\\`\\*+[ \t]+\\'"
8169 (buffer-substring (point-at-bol) beg))
8170 (setq type :todo)
8171 (mapcar 'list org-todo-keywords-1))
8172 (searchhead
8173 (setq type :searchhead)
8174 (save-excursion
8175 (goto-char (point-min))
8176 (while (re-search-forward org-todo-line-regexp nil t)
8177 (push (list
8178 (org-make-org-heading-search-string
8179 (match-string 3) t))
8180 tbl)))
8181 tbl)
8182 (tag (setq type :tag beg beg1)
8183 (or org-tag-alist (org-get-buffer-tags)))
8184 (prop (setq type :prop beg beg1)
8185 (mapcar 'list (org-buffer-property-keys nil t t)))
8186 (t (progn
8187 (call-interactively org-completion-fallback-command)
8188 (throw 'exit nil)))))
8189 (pattern (buffer-substring-no-properties beg end))
8190 (completion (try-completion pattern table confirm)))
8191 (cond ((eq completion t)
8192 (if (not (assoc (upcase pattern) table))
8193 (message "Already complete")
8194 (if (and (equal type :opt)
8195 (not (member (car (assoc (upcase pattern) table))
8196 org-additional-option-like-keywords)))
8197 (insert (substring (cdr (assoc (upcase pattern) table))
8198 (length pattern)))
8199 (if (memq type '(:tag :prop)) (insert ":")))))
8200 ((null completion)
8201 (message "Can't find completion for \"%s\"" pattern)
8202 (ding))
8203 ((not (string= pattern completion))
8204 (delete-region beg end)
8205 (if (string-match " +$" completion)
8206 (setq completion (replace-match "" t t completion)))
8207 (insert completion)
8208 (if (get-buffer-window "*Completions*")
8209 (delete-window (get-buffer-window "*Completions*")))
8210 (if (assoc completion table)
8211 (if (eq type :todo) (insert " ")
8212 (if (memq type '(:tag :prop)) (insert ":"))))
8213 (if (and (equal type :opt) (assoc completion table))
8214 (message "%s" (substitute-command-keys
8215 "Press \\[org-complete] again to insert example settings"))))
8217 (message "Making completion list...")
8218 (let ((list (sort (all-completions pattern table confirm)
8219 'string<)))
8220 (with-output-to-temp-buffer "*Completions*"
8221 (condition-case nil
8222 ;; Protection needed for XEmacs and emacs 21
8223 (display-completion-list list pattern)
8224 (error (display-completion-list list)))))
8225 (message "Making completion list...%s" "done")))))))
8227 ;;;; TODO, DEADLINE, Comments
8229 (defun org-toggle-comment ()
8230 "Change the COMMENT state of an entry."
8231 (interactive)
8232 (save-excursion
8233 (org-back-to-heading)
8234 (let (case-fold-search)
8235 (if (looking-at (concat outline-regexp
8236 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8237 (replace-match "" t t nil 1)
8238 (if (looking-at outline-regexp)
8239 (progn
8240 (goto-char (match-end 0))
8241 (insert org-comment-string " ")))))))
8243 (defvar org-last-todo-state-is-todo nil
8244 "This is non-nil when the last TODO state change led to a TODO state.
8245 If the last change removed the TODO tag or switched to DONE, then
8246 this is nil.")
8248 (defvar org-setting-tags nil) ; dynamically skipped
8250 (defun org-parse-local-options (string var)
8251 "Parse STRING for startup setting relevant for variable VAR."
8252 (let ((rtn (symbol-value var))
8253 e opts)
8254 (save-match-data
8255 (if (or (not string) (not (string-match "\\S-" string)))
8257 (setq opts (delq nil (mapcar (lambda (x)
8258 (setq e (assoc x org-startup-options))
8259 (if (eq (nth 1 e) var) e nil))
8260 (org-split-string string "[ \t]+"))))
8261 (if (not opts)
8263 (setq rtn nil)
8264 (while (setq e (pop opts))
8265 (if (not (nth 3 e))
8266 (setq rtn (nth 2 e))
8267 (if (not (listp rtn)) (setq rtn nil))
8268 (push (nth 2 e) rtn)))
8269 rtn)))))
8271 (defvar org-blocker-hook nil
8272 "Hook for functions that are allowed to block a state change.
8274 Each function gets as its single argument a property list, see
8275 `org-trigger-hook' for more information about this list.
8277 If any of the functions in this hook returns nil, the state change
8278 is blocked.")
8280 (defvar org-trigger-hook nil
8281 "Hook for functions that are triggered by a state change.
8283 Each function gets as its single argument a property list with at least
8284 the following elements:
8286 (:type type-of-change :position pos-at-entry-start
8287 :from old-state :to new-state)
8289 Depending on the type, more properties may be present.
8291 This mechanism is currently implemented for:
8293 TODO state changes
8294 ------------------
8295 :type todo-state-change
8296 :from previous state (keyword as a string), or nil
8297 :to new state (keyword as a string), or nil")
8299 (defvar org-agenda-headline-snapshot-before-repeat)
8300 (defun org-todo (&optional arg)
8301 "Change the TODO state of an item.
8302 The state of an item is given by a keyword at the start of the heading,
8303 like
8304 *** TODO Write paper
8305 *** DONE Call mom
8307 The different keywords are specified in the variable `org-todo-keywords'.
8308 By default the available states are \"TODO\" and \"DONE\".
8309 So for this example: when the item starts with TODO, it is changed to DONE.
8310 When it starts with DONE, the DONE is removed. And when neither TODO nor
8311 DONE are present, add TODO at the beginning of the heading.
8313 With C-u prefix arg, use completion to determine the new state.
8314 With numeric prefix arg, switch to that state.
8315 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8317 For calling through lisp, arg is also interpreted in the following way:
8318 'none -> empty state
8319 \"\"(empty string) -> switch to empty state
8320 'done -> switch to DONE
8321 'nextset -> switch to the next set of keywords
8322 'previousset -> switch to the previous set of keywords
8323 \"WAITING\" -> switch to the specified keyword, but only if it
8324 really is a member of `org-todo-keywords'."
8325 (interactive "P")
8326 (if (equal arg '(16)) (setq arg 'nextset))
8327 (save-excursion
8328 (catch 'exit
8329 (org-back-to-heading)
8330 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8331 (or (looking-at (concat " +" org-todo-regexp " *"))
8332 (looking-at " *"))
8333 (let* ((match-data (match-data))
8334 (startpos (point-at-bol))
8335 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8336 (org-log-done org-log-done)
8337 (org-log-repeat org-log-repeat)
8338 (org-todo-log-states org-todo-log-states)
8339 (this (match-string 1))
8340 (hl-pos (match-beginning 0))
8341 (head (org-get-todo-sequence-head this))
8342 (ass (assoc head org-todo-kwd-alist))
8343 (interpret (nth 1 ass))
8344 (done-word (nth 3 ass))
8345 (final-done-word (nth 4 ass))
8346 (last-state (or this ""))
8347 (completion-ignore-case t)
8348 (member (member this org-todo-keywords-1))
8349 (tail (cdr member))
8350 (state (cond
8351 ((and org-todo-key-trigger
8352 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8353 (and (not arg) org-use-fast-todo-selection
8354 (not (eq org-use-fast-todo-selection 'prefix)))))
8355 ;; Use fast selection
8356 (org-fast-todo-selection))
8357 ((and (equal arg '(4))
8358 (or (not org-use-fast-todo-selection)
8359 (not org-todo-key-trigger)))
8360 ;; Read a state with completion
8361 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8362 org-todo-keywords-1)
8363 nil t))
8364 ((eq arg 'right)
8365 (if this
8366 (if tail (car tail) nil)
8367 (car org-todo-keywords-1)))
8368 ((eq arg 'left)
8369 (if (equal member org-todo-keywords-1)
8371 (if this
8372 (nth (- (length org-todo-keywords-1) (length tail) 2)
8373 org-todo-keywords-1)
8374 (org-last org-todo-keywords-1))))
8375 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8376 (setq arg nil))) ; hack to fall back to cycling
8377 (arg
8378 ;; user or caller requests a specific state
8379 (cond
8380 ((equal arg "") nil)
8381 ((eq arg 'none) nil)
8382 ((eq arg 'done) (or done-word (car org-done-keywords)))
8383 ((eq arg 'nextset)
8384 (or (car (cdr (member head org-todo-heads)))
8385 (car org-todo-heads)))
8386 ((eq arg 'previousset)
8387 (let ((org-todo-heads (reverse org-todo-heads)))
8388 (or (car (cdr (member head org-todo-heads)))
8389 (car org-todo-heads))))
8390 ((car (member arg org-todo-keywords-1)))
8391 ((nth (1- (prefix-numeric-value arg))
8392 org-todo-keywords-1))))
8393 ((null member) (or head (car org-todo-keywords-1)))
8394 ((equal this final-done-word) nil) ;; -> make empty
8395 ((null tail) nil) ;; -> first entry
8396 ((eq interpret 'sequence)
8397 (car tail))
8398 ((memq interpret '(type priority))
8399 (if (eq this-command last-command)
8400 (car tail)
8401 (if (> (length tail) 0)
8402 (or done-word (car org-done-keywords))
8403 nil)))
8404 (t nil)))
8405 (next (if state (concat " " state " ") " "))
8406 (change-plist (list :type 'todo-state-change :from this :to state
8407 :position startpos))
8408 dolog now-done-p)
8409 (when org-blocker-hook
8410 (unless (save-excursion
8411 (save-match-data
8412 (run-hook-with-args-until-failure
8413 'org-blocker-hook change-plist)))
8414 (if (interactive-p)
8415 (error "TODO state change from %s to %s blocked" this state)
8416 ;; fail silently
8417 (message "TODO state change from %s to %s blocked" this state)
8418 (throw 'exit nil))))
8419 (store-match-data match-data)
8420 (replace-match next t t)
8421 (unless (pos-visible-in-window-p hl-pos)
8422 (message "TODO state changed to %s" (org-trim next)))
8423 (unless head
8424 (setq head (org-get-todo-sequence-head state)
8425 ass (assoc head org-todo-kwd-alist)
8426 interpret (nth 1 ass)
8427 done-word (nth 3 ass)
8428 final-done-word (nth 4 ass)))
8429 (when (memq arg '(nextset previousset))
8430 (message "Keyword-Set %d/%d: %s"
8431 (- (length org-todo-sets) -1
8432 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8433 (length org-todo-sets)
8434 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8435 (setq org-last-todo-state-is-todo
8436 (not (member state org-done-keywords)))
8437 (setq now-done-p (and (member state org-done-keywords)
8438 (not (member this org-done-keywords))))
8439 (and logging (org-local-logging logging))
8440 (when (and (or org-todo-log-states org-log-done)
8441 (not (memq arg '(nextset previousset))))
8442 ;; we need to look at recording a time and note
8443 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8444 (nth 2 (assoc this org-todo-log-states))))
8445 (when (and state
8446 (member state org-not-done-keywords)
8447 (not (member this org-not-done-keywords)))
8448 ;; This is now a todo state and was not one before
8449 ;; If there was a CLOSED time stamp, get rid of it.
8450 (org-add-planning-info nil nil 'closed))
8451 (when (and now-done-p org-log-done)
8452 ;; It is now done, and it was not done before
8453 (org-add-planning-info 'closed (org-current-time))
8454 (if (and (not dolog) (eq 'note org-log-done))
8455 (org-add-log-setup 'done state 'findpos 'note)))
8456 (when (and state dolog)
8457 ;; This is a non-nil state, and we need to log it
8458 (org-add-log-setup 'state state 'findpos dolog)))
8459 ;; Fixup tag positioning
8460 (org-todo-trigger-tag-changes state)
8461 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8462 (when org-provide-todo-statistics
8463 (org-update-parent-todo-statistics))
8464 (run-hooks 'org-after-todo-state-change-hook)
8465 (if (and arg (not (member state org-done-keywords)))
8466 (setq head (org-get-todo-sequence-head state)))
8467 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8468 ;; Do we need to trigger a repeat?
8469 (when now-done-p
8470 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8471 ;; This is for the agenda, take a snapshot of the headline.
8472 (save-match-data
8473 (setq org-agenda-headline-snapshot-before-repeat
8474 (org-get-heading))))
8475 (org-auto-repeat-maybe state))
8476 ;; Fixup cursor location if close to the keyword
8477 (if (and (outline-on-heading-p)
8478 (not (bolp))
8479 (save-excursion (beginning-of-line 1)
8480 (looking-at org-todo-line-regexp))
8481 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8482 (progn
8483 (goto-char (or (match-end 2) (match-end 1)))
8484 (just-one-space)))
8485 (when org-trigger-hook
8486 (save-excursion
8487 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8489 (defun org-update-parent-todo-statistics ()
8490 "Update any statistics cookie in the parent of the current headline."
8491 (interactive)
8492 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8493 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8494 (catch 'exit
8495 (save-excursion
8496 (setq level (org-up-heading-safe))
8497 (unless (and level
8498 (re-search-forward box-re (point-at-eol) t))
8499 (throw 'exit nil))
8500 (setq is-percent (match-end 2))
8501 (save-match-data
8502 (unless (outline-next-heading) (throw 'exit nil))
8503 (while (looking-at org-todo-line-regexp)
8504 (setq kwd (match-string 2))
8505 (and kwd (setq cnt-all (1+ cnt-all)))
8506 (and (member kwd org-done-keywords)
8507 (setq cnt-done (1+ cnt-done)))
8508 (condition-case nil
8509 (org-forward-same-level 1)
8510 (error (end-of-line 1)))))
8511 (replace-match
8512 (if is-percent
8513 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8514 (format "[%d/%d]" cnt-done cnt-all)))
8515 (run-hook-with-args 'org-after-todo-statistics-hook
8516 cnt-done (- cnt-all cnt-done))))))
8518 (defvar org-after-todo-statistics-hook nil
8519 "Hook that is called after a TODO statistics cookie has been updated.
8520 Each function is called with two arguments: the number of not-done entries
8521 and the number of done entries.
8523 For example, the following function, when added to this hook, will switch
8524 an entry to DONE when all children are done, and back to TODO when new
8525 entries are set to a TODO status. Note that this hook is only called
8526 when there is a statistics cookie in the headline!
8528 (defun org-summary-todo (n-done n-not-done)
8529 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8530 (let (org-log-done org-log-states) ; turn off logging
8531 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8534 (defun org-todo-trigger-tag-changes (state)
8535 "Apply the changes defined in `org-todo-state-tags-triggers'."
8536 (let ((l org-todo-state-tags-triggers)
8537 changes)
8538 (when (or (not state) (equal state ""))
8539 (setq changes (append changes (cdr (assoc "" l)))))
8540 (when (and (stringp state) (> (length state) 0))
8541 (setq changes (append changes (cdr (assoc state l)))))
8542 (when (member state org-not-done-keywords)
8543 (setq changes (append changes (cdr (assoc 'todo l)))))
8544 (when (member state org-done-keywords)
8545 (setq changes (append changes (cdr (assoc 'done l)))))
8546 (dolist (c changes)
8547 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8549 (defun org-local-logging (value)
8550 "Get logging settings from a property VALUE."
8551 (let* (words w a)
8552 ;; directly set the variables, they are already local.
8553 (setq org-log-done nil
8554 org-log-repeat nil
8555 org-todo-log-states nil)
8556 (setq words (org-split-string value))
8557 (while (setq w (pop words))
8558 (cond
8559 ((setq a (assoc w org-startup-options))
8560 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8561 (set (nth 1 a) (nth 2 a))))
8562 ((setq a (org-extract-log-state-settings w))
8563 (and (member (car a) org-todo-keywords-1)
8564 (push a org-todo-log-states)))))))
8566 (defun org-get-todo-sequence-head (kwd)
8567 "Return the head of the TODO sequence to which KWD belongs.
8568 If KWD is not set, check if there is a text property remembering the
8569 right sequence."
8570 (let (p)
8571 (cond
8572 ((not kwd)
8573 (or (get-text-property (point-at-bol) 'org-todo-head)
8574 (progn
8575 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8576 nil (point-at-eol)))
8577 (get-text-property p 'org-todo-head))))
8578 ((not (member kwd org-todo-keywords-1))
8579 (car org-todo-keywords-1))
8580 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8582 (defun org-fast-todo-selection ()
8583 "Fast TODO keyword selection with single keys.
8584 Returns the new TODO keyword, or nil if no state change should occur."
8585 (let* ((fulltable org-todo-key-alist)
8586 (done-keywords org-done-keywords) ;; needed for the faces.
8587 (maxlen (apply 'max (mapcar
8588 (lambda (x)
8589 (if (stringp (car x)) (string-width (car x)) 0))
8590 fulltable)))
8591 (expert nil)
8592 (fwidth (+ maxlen 3 1 3))
8593 (ncol (/ (- (window-width) 4) fwidth))
8594 tg cnt e c tbl
8595 groups ingroup)
8596 (save-window-excursion
8597 (if expert
8598 (set-buffer (get-buffer-create " *Org todo*"))
8599 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8600 (erase-buffer)
8601 (org-set-local 'org-done-keywords done-keywords)
8602 (setq tbl fulltable cnt 0)
8603 (while (setq e (pop tbl))
8604 (cond
8605 ((equal e '(:startgroup))
8606 (push '() groups) (setq ingroup t)
8607 (when (not (= cnt 0))
8608 (setq cnt 0)
8609 (insert "\n"))
8610 (insert "{ "))
8611 ((equal e '(:endgroup))
8612 (setq ingroup nil cnt 0)
8613 (insert "}\n"))
8615 (setq tg (car e) c (cdr e))
8616 (if ingroup (push tg (car groups)))
8617 (setq tg (org-add-props tg nil 'face
8618 (org-get-todo-face tg)))
8619 (if (and (= cnt 0) (not ingroup)) (insert " "))
8620 (insert "[" c "] " tg (make-string
8621 (- fwidth 4 (length tg)) ?\ ))
8622 (when (= (setq cnt (1+ cnt)) ncol)
8623 (insert "\n")
8624 (if ingroup (insert " "))
8625 (setq cnt 0)))))
8626 (insert "\n")
8627 (goto-char (point-min))
8628 (if (not expert) (org-fit-window-to-buffer))
8629 (message "[a-z..]:Set [SPC]:clear")
8630 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8631 (cond
8632 ((or (= c ?\C-g)
8633 (and (= c ?q) (not (rassoc c fulltable))))
8634 (setq quit-flag t))
8635 ((= c ?\ ) nil)
8636 ((setq e (rassoc c fulltable) tg (car e))
8638 (t (setq quit-flag t))))))
8640 (defun org-entry-is-todo-p ()
8641 (member (org-get-todo-state) org-not-done-keywords))
8643 (defun org-entry-is-done-p ()
8644 (member (org-get-todo-state) org-done-keywords))
8646 (defun org-get-todo-state ()
8647 (save-excursion
8648 (org-back-to-heading t)
8649 (and (looking-at org-todo-line-regexp)
8650 (match-end 2)
8651 (match-string 2))))
8653 (defun org-at-date-range-p (&optional inactive-ok)
8654 "Is the cursor inside a date range?"
8655 (interactive)
8656 (save-excursion
8657 (catch 'exit
8658 (let ((pos (point)))
8659 (skip-chars-backward "^[<\r\n")
8660 (skip-chars-backward "<[")
8661 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8662 (>= (match-end 0) pos)
8663 (throw 'exit t))
8664 (skip-chars-backward "^<[\r\n")
8665 (skip-chars-backward "<[")
8666 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8667 (>= (match-end 0) pos)
8668 (throw 'exit t)))
8669 nil)))
8671 (defun org-get-repeat ()
8672 "Check if there is a deadline/schedule with repeater in this entry."
8673 (save-match-data
8674 (save-excursion
8675 (org-back-to-heading t)
8676 (if (re-search-forward
8677 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8678 (match-string 1)))))
8680 (defvar org-last-changed-timestamp)
8681 (defvar org-last-inserted-timestamp)
8682 (defvar org-log-post-message)
8683 (defvar org-log-note-purpose)
8684 (defvar org-log-note-how)
8685 (defvar org-log-note-extra)
8686 (defun org-auto-repeat-maybe (done-word)
8687 "Check if the current headline contains a repeated deadline/schedule.
8688 If yes, set TODO state back to what it was and change the base date
8689 of repeating deadline/scheduled time stamps to new date.
8690 This function is run automatically after each state change to a DONE state."
8691 ;; last-state is dynamically scoped into this function
8692 (let* ((repeat (org-get-repeat))
8693 (aa (assoc last-state org-todo-kwd-alist))
8694 (interpret (nth 1 aa))
8695 (head (nth 2 aa))
8696 (whata '(("d" . day) ("m" . month) ("y" . year)))
8697 (msg "Entry repeats: ")
8698 (org-log-done nil)
8699 (org-todo-log-states nil)
8700 (nshiftmax 10) (nshift 0)
8701 re type n what ts time)
8702 (when repeat
8703 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8704 (org-todo (if (eq interpret 'type) last-state head))
8705 (when org-log-repeat
8706 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8707 (memq 'org-add-log-note post-command-hook))
8708 ;; OK, we are already setup for some record
8709 (if (eq org-log-repeat 'note)
8710 ;; make sure we take a note, not only a time stamp
8711 (setq org-log-note-how 'note))
8712 ;; Set up for taking a record
8713 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8714 'findpos org-log-repeat)))
8715 (org-back-to-heading t)
8716 (org-add-planning-info nil nil 'closed)
8717 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8718 org-deadline-time-regexp "\\)\\|\\("
8719 org-ts-regexp "\\)"))
8720 (while (re-search-forward
8721 re (save-excursion (outline-next-heading) (point)) t)
8722 (setq type (if (match-end 1) org-scheduled-string
8723 (if (match-end 3) org-deadline-string "Plain:"))
8724 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8725 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8726 (setq n (string-to-number (match-string 2 ts))
8727 what (match-string 3 ts))
8728 (if (equal what "w") (setq n (* n 7) what "d"))
8729 ;; Preparation, see if we need to modify the start date for the change
8730 (when (match-end 1)
8731 (setq time (save-match-data (org-time-string-to-time ts)))
8732 (cond
8733 ((equal (match-string 1 ts) ".")
8734 ;; Shift starting date to today
8735 (org-timestamp-change
8736 (- (time-to-days (current-time)) (time-to-days time))
8737 'day))
8738 ((equal (match-string 1 ts) "+")
8739 (while (or (= nshift 0)
8740 (<= (time-to-days time) (time-to-days (current-time))))
8741 (when (= (incf nshift) nshiftmax)
8742 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8743 (error "Abort")))
8744 (org-timestamp-change n (cdr (assoc what whata)))
8745 (org-at-timestamp-p t)
8746 (setq ts (match-string 1))
8747 (setq time (save-match-data (org-time-string-to-time ts))))
8748 (org-timestamp-change (- n) (cdr (assoc what whata)))
8749 ;; rematch, so that we have everything in place for the real shift
8750 (org-at-timestamp-p t)
8751 (setq ts (match-string 1))
8752 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8753 (org-timestamp-change n (cdr (assoc what whata)))
8754 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8755 (setq org-log-post-message msg)
8756 (message "%s" msg))))
8758 (defun org-show-todo-tree (arg)
8759 "Make a compact tree which shows all headlines marked with TODO.
8760 The tree will show the lines where the regexp matches, and all higher
8761 headlines above the match.
8762 With a \\[universal-argument] prefix, also show the DONE entries.
8763 With a numeric prefix N, construct a sparse tree for the Nth element
8764 of `org-todo-keywords-1'."
8765 (interactive "P")
8766 (let ((case-fold-search nil)
8767 (kwd-re
8768 (cond ((null arg) org-not-done-regexp)
8769 ((equal arg '(4))
8770 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8771 (mapcar 'list org-todo-keywords-1))))
8772 (concat "\\("
8773 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8774 "\\)\\>")))
8775 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8776 (regexp-quote (nth (1- (prefix-numeric-value arg))
8777 org-todo-keywords-1)))
8778 (t (error "Invalid prefix argument: %s" arg)))))
8779 (message "%d TODO entries found"
8780 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8782 (defun org-deadline (&optional remove time)
8783 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8784 With argument REMOVE, remove any deadline from the item.
8785 When TIME is set, it should be an internal time specification, and the
8786 scheduling will use the corresponding date."
8787 (interactive "P")
8788 (if remove
8789 (progn
8790 (org-remove-timestamp-with-keyword org-deadline-string)
8791 (message "Item no longer has a deadline."))
8792 (if (org-get-repeat)
8793 (error "Cannot change deadline on task with repeater, please do that by hand")
8794 (org-add-planning-info 'deadline time 'closed)
8795 (message "Deadline on %s" org-last-inserted-timestamp))))
8797 (defun org-schedule (&optional remove time)
8798 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8799 With argument REMOVE, remove any scheduling date from the item.
8800 When TIME is set, it should be an internal time specification, and the
8801 scheduling will use the corresponding date."
8802 (interactive "P")
8803 (if remove
8804 (progn
8805 (org-remove-timestamp-with-keyword org-scheduled-string)
8806 (message "Item is no longer scheduled."))
8807 (if (org-get-repeat)
8808 (error "Cannot reschedule task with repeater, please do that by hand")
8809 (org-add-planning-info 'scheduled time 'closed)
8810 (message "Scheduled to %s" org-last-inserted-timestamp))))
8812 (defun org-remove-timestamp-with-keyword (keyword)
8813 "Remove all time stamps with KEYWORD in the current entry."
8814 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8815 beg)
8816 (save-excursion
8817 (org-back-to-heading t)
8818 (setq beg (point))
8819 (org-end-of-subtree t t)
8820 (while (re-search-backward re beg t)
8821 (replace-match "")
8822 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8823 (equal (char-before) ?\ ))
8824 (backward-delete-char 1)
8825 (if (string-match "^[ \t]*$" (buffer-substring
8826 (point-at-bol) (point-at-eol)))
8827 (delete-region (point-at-bol)
8828 (min (point-max) (1+ (point-at-eol))))))))))
8830 (defun org-add-planning-info (what &optional time &rest remove)
8831 "Insert new timestamp with keyword in the line directly after the headline.
8832 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8833 If non is given, the user is prompted for a date.
8834 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8835 be removed."
8836 (interactive)
8837 (let (org-time-was-given org-end-time-was-given ts
8838 end default-time default-input)
8840 (when (and (not time) (memq what '(scheduled deadline)))
8841 ;; Try to get a default date/time from existing timestamp
8842 (save-excursion
8843 (org-back-to-heading t)
8844 (setq end (save-excursion (outline-next-heading) (point)))
8845 (when (re-search-forward (if (eq what 'scheduled)
8846 org-scheduled-time-regexp
8847 org-deadline-time-regexp)
8848 end t)
8849 (setq ts (match-string 1)
8850 default-time
8851 (apply 'encode-time (org-parse-time-string ts))
8852 default-input (and ts (org-get-compact-tod ts))))))
8853 (when what
8854 ;; If necessary, get the time from the user
8855 (setq time (or time (org-read-date nil 'to-time nil nil
8856 default-time default-input))))
8858 (when (and org-insert-labeled-timestamps-at-point
8859 (member what '(scheduled deadline)))
8860 (insert
8861 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8862 (org-insert-time-stamp time org-time-was-given
8863 nil nil nil (list org-end-time-was-given))
8864 (setq what nil))
8865 (save-excursion
8866 (save-restriction
8867 (let (col list elt ts buffer-invisibility-spec)
8868 (org-back-to-heading t)
8869 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8870 (goto-char (match-end 1))
8871 (setq col (current-column))
8872 (goto-char (match-end 0))
8873 (if (eobp) (insert "\n") (forward-char 1))
8874 (if (and (not (looking-at outline-regexp))
8875 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8876 "[^\r\n]*"))
8877 (not (equal (match-string 1) org-clock-string)))
8878 (narrow-to-region (match-beginning 0) (match-end 0))
8879 (insert-before-markers "\n")
8880 (backward-char 1)
8881 (narrow-to-region (point) (point))
8882 (and org-adapt-indentation (org-indent-to-column col)))
8883 ;; Check if we have to remove something.
8884 (setq list (cons what remove))
8885 (while list
8886 (setq elt (pop list))
8887 (goto-char (point-min))
8888 (when (or (and (eq elt 'scheduled)
8889 (re-search-forward org-scheduled-time-regexp nil t))
8890 (and (eq elt 'deadline)
8891 (re-search-forward org-deadline-time-regexp nil t))
8892 (and (eq elt 'closed)
8893 (re-search-forward org-closed-time-regexp nil t)))
8894 (replace-match "")
8895 (if (looking-at "--+<[^>]+>") (replace-match ""))
8896 (if (looking-at " +") (replace-match ""))))
8897 (goto-char (point-max))
8898 (when what
8899 (insert
8900 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8901 (cond ((eq what 'scheduled) org-scheduled-string)
8902 ((eq what 'deadline) org-deadline-string)
8903 ((eq what 'closed) org-closed-string))
8904 " ")
8905 (setq ts (org-insert-time-stamp
8906 time
8907 (or org-time-was-given
8908 (and (eq what 'closed) org-log-done-with-time))
8909 (eq what 'closed)
8910 nil nil (list org-end-time-was-given)))
8911 (end-of-line 1))
8912 (goto-char (point-min))
8913 (widen)
8914 (if (and (looking-at "[ \t]+\n")
8915 (equal (char-before) ?\n))
8916 (delete-region (1- (point)) (point-at-eol)))
8917 ts)))))
8919 (defvar org-log-note-marker (make-marker))
8920 (defvar org-log-note-purpose nil)
8921 (defvar org-log-note-state nil)
8922 (defvar org-log-note-how nil)
8923 (defvar org-log-note-extra nil)
8924 (defvar org-log-note-window-configuration nil)
8925 (defvar org-log-note-return-to (make-marker))
8926 (defvar org-log-post-message nil
8927 "Message to be displayed after a log note has been stored.
8928 The auto-repeater uses this.")
8930 (defun org-add-note ()
8931 "Add a note to the current entry.
8932 This is done in the same way as adding a state change note."
8933 (interactive)
8934 (org-add-log-setup 'note nil 'findpos nil))
8936 (defvar org-property-end-re)
8937 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8938 "Set up the post command hook to take a note.
8939 If this is about to TODO state change, the new state is expected in STATE.
8940 When FINDPOS is non-nil, find the correct position for the note in
8941 the current entry. If not, assume that it can be inserted at point.
8942 HOW is an indicator what kind of note should be created.
8943 EXTRA is additional text that will be inserted into the notes buffer."
8944 (save-restriction
8945 (save-excursion
8946 (when findpos
8947 (org-back-to-heading t)
8948 (narrow-to-region (point) (save-excursion
8949 (outline-next-heading) (point)))
8950 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8951 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8952 "[^\r\n]*\\)?"))
8953 (goto-char (match-end 0))
8954 (when (and org-log-state-notes-insert-after-drawers
8955 (save-excursion
8956 (forward-line) (looking-at org-drawer-regexp)))
8957 (progn (forward-line)
8958 (while (looking-at org-drawer-regexp)
8959 (goto-char (match-end 0))
8960 (re-search-forward org-property-end-re (point-max) t)
8961 (forward-line))
8962 (forward-line -1)))
8963 (unless org-log-states-order-reversed
8964 (and (= (char-after) ?\n) (forward-char 1))
8965 (org-skip-over-state-notes)
8966 (skip-chars-backward " \t\n\r")))
8967 (move-marker org-log-note-marker (point))
8968 (setq org-log-note-purpose purpose
8969 org-log-note-state state
8970 org-log-note-how how
8971 org-log-note-extra extra)
8972 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8974 (defun org-skip-over-state-notes ()
8975 "Skip past the list of State notes in an entry."
8976 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8977 (while (looking-at "[ \t]*- State")
8978 (condition-case nil
8979 (org-next-item)
8980 (error (org-end-of-item)))))
8982 (defun org-add-log-note (&optional purpose)
8983 "Pop up a window for taking a note, and add this note later at point."
8984 (remove-hook 'post-command-hook 'org-add-log-note)
8985 (setq org-log-note-window-configuration (current-window-configuration))
8986 (delete-other-windows)
8987 (move-marker org-log-note-return-to (point))
8988 (switch-to-buffer (marker-buffer org-log-note-marker))
8989 (goto-char org-log-note-marker)
8990 (org-switch-to-buffer-other-window "*Org Note*")
8991 (erase-buffer)
8992 (if (memq org-log-note-how '(time state))
8993 (let (current-prefix-arg) (org-store-log-note))
8994 (let ((org-inhibit-startup t)) (org-mode))
8995 (insert (format "# Insert note for %s.
8996 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8997 (cond
8998 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8999 ((eq org-log-note-purpose 'done) "closed todo item")
9000 ((eq org-log-note-purpose 'state)
9001 (format "state change to \"%s\"" org-log-note-state))
9002 ((eq org-log-note-purpose 'note)
9003 "this entry")
9004 (t (error "This should not happen")))))
9005 (if org-log-note-extra (insert org-log-note-extra))
9006 (org-set-local 'org-finish-function 'org-store-log-note)))
9008 (defvar org-note-abort nil) ; dynamically scoped
9009 (defun org-store-log-note ()
9010 "Finish taking a log note, and insert it to where it belongs."
9011 (let ((txt (buffer-string))
9012 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9013 lines ind)
9014 (kill-buffer (current-buffer))
9015 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9016 (setq txt (replace-match "" t t txt)))
9017 (if (string-match "\\s-+\\'" txt)
9018 (setq txt (replace-match "" t t txt)))
9019 (setq lines (org-split-string txt "\n"))
9020 (when (and note (string-match "\\S-" note))
9021 (setq note
9022 (org-replace-escapes
9023 note
9024 (list (cons "%u" (user-login-name))
9025 (cons "%U" user-full-name)
9026 (cons "%t" (format-time-string
9027 (org-time-stamp-format 'long 'inactive)
9028 (current-time)))
9029 (cons "%s" (if org-log-note-state
9030 (concat "\"" org-log-note-state "\"")
9031 "")))))
9032 (if lines (setq note (concat note " \\\\")))
9033 (push note lines))
9034 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9035 (when lines
9036 (save-excursion
9037 (set-buffer (marker-buffer org-log-note-marker))
9038 (save-excursion
9039 (goto-char org-log-note-marker)
9040 (move-marker org-log-note-marker nil)
9041 (end-of-line 1)
9042 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9043 (indent-relative nil)
9044 (insert "- " (pop lines))
9045 (org-indent-line-function)
9046 (beginning-of-line 1)
9047 (looking-at "[ \t]*")
9048 (setq ind (concat (match-string 0) " "))
9049 (end-of-line 1)
9050 (while lines (insert "\n" ind (pop lines)))))))
9051 (set-window-configuration org-log-note-window-configuration)
9052 (with-current-buffer (marker-buffer org-log-note-return-to)
9053 (goto-char org-log-note-return-to))
9054 (move-marker org-log-note-return-to nil)
9055 (and org-log-post-message (message "%s" org-log-post-message)))
9057 (defun org-sparse-tree (&optional arg)
9058 "Create a sparse tree, prompt for the details.
9059 This command can create sparse trees. You first need to select the type
9060 of match used to create the tree:
9062 t Show entries with a specific TODO keyword.
9063 T Show entries selected by a tags match.
9064 p Enter a property name and its value (both with completion on existing
9065 names/values) and show entries with that property.
9066 r Show entries matching a regular expression
9067 d Show deadlines due within `org-deadline-warning-days'."
9068 (interactive "P")
9069 (let (ans kwd value)
9070 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9071 (setq ans (read-char-exclusive))
9072 (cond
9073 ((equal ans ?d)
9074 (call-interactively 'org-check-deadlines))
9075 ((equal ans ?b)
9076 (call-interactively 'org-check-before-date))
9077 ((equal ans ?t)
9078 (org-show-todo-tree '(4)))
9079 ((equal ans ?T)
9080 (call-interactively 'org-tags-sparse-tree))
9081 ((member ans '(?p ?P))
9082 (setq kwd (org-ido-completing-read "Property: "
9083 (mapcar 'list (org-buffer-property-keys))))
9084 (setq value (org-ido-completing-read "Value: "
9085 (mapcar 'list (org-property-values kwd))))
9086 (unless (string-match "\\`{.*}\\'" value)
9087 (setq value (concat "\"" value "\"")))
9088 (org-tags-sparse-tree arg (concat kwd "=" value)))
9089 ((member ans '(?r ?R ?/))
9090 (call-interactively 'org-occur))
9091 (t (error "No such sparse tree command \"%c\"" ans)))))
9093 (defvar org-occur-highlights nil
9094 "List of overlays used for occur matches.")
9095 (make-variable-buffer-local 'org-occur-highlights)
9096 (defvar org-occur-parameters nil
9097 "Parameters of the active org-occur calls.
9098 This is a list, each call to org-occur pushes as cons cell,
9099 containing the regular expression and the callback, onto the list.
9100 The list can contain several entries if `org-occur' has been called
9101 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9102 will only contain one set of parameters. When the highlights are
9103 removed (for example with `C-c C-c', or with the next edit (depending
9104 on `org-remove-highlights-with-change'), this variable is emptied
9105 as well.")
9106 (make-variable-buffer-local 'org-occur-parameters)
9108 (defun org-occur (regexp &optional keep-previous callback)
9109 "Make a compact tree which shows all matches of REGEXP.
9110 The tree will show the lines where the regexp matches, and all higher
9111 headlines above the match. It will also show the heading after the match,
9112 to make sure editing the matching entry is easy.
9113 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9114 call to `org-occur' will be kept, to allow stacking of calls to this
9115 command.
9116 If CALLBACK is non-nil, it is a function which is called to confirm
9117 that the match should indeed be shown."
9118 (interactive "sRegexp: \nP")
9119 (unless keep-previous
9120 (org-remove-occur-highlights nil nil t))
9121 (push (cons regexp callback) org-occur-parameters)
9122 (let ((cnt 0))
9123 (save-excursion
9124 (goto-char (point-min))
9125 (if (or (not keep-previous) ; do not want to keep
9126 (not org-occur-highlights)) ; no previous matches
9127 ;; hide everything
9128 (org-overview))
9129 (while (re-search-forward regexp nil t)
9130 (when (or (not callback)
9131 (save-match-data (funcall callback)))
9132 (setq cnt (1+ cnt))
9133 (when org-highlight-sparse-tree-matches
9134 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9135 (org-show-context 'occur-tree))))
9136 (when org-remove-highlights-with-change
9137 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9138 nil 'local))
9139 (unless org-sparse-tree-open-archived-trees
9140 (org-hide-archived-subtrees (point-min) (point-max)))
9141 (run-hooks 'org-occur-hook)
9142 (if (interactive-p)
9143 (message "%d match(es) for regexp %s" cnt regexp))
9144 cnt))
9146 (defun org-show-context (&optional key)
9147 "Make sure point and context and visible.
9148 How much context is shown depends upon the variables
9149 `org-show-hierarchy-above', `org-show-following-heading'. and
9150 `org-show-siblings'."
9151 (let ((heading-p (org-on-heading-p t))
9152 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9153 (following-p (org-get-alist-option org-show-following-heading key))
9154 (entry-p (org-get-alist-option org-show-entry-below key))
9155 (siblings-p (org-get-alist-option org-show-siblings key)))
9156 (catch 'exit
9157 ;; Show heading or entry text
9158 (if (and heading-p (not entry-p))
9159 (org-flag-heading nil) ; only show the heading
9160 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9161 (org-show-hidden-entry))) ; show entire entry
9162 (when following-p
9163 ;; Show next sibling, or heading below text
9164 (save-excursion
9165 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9166 (org-flag-heading nil))))
9167 (when siblings-p (org-show-siblings))
9168 (when hierarchy-p
9169 ;; show all higher headings, possibly with siblings
9170 (save-excursion
9171 (while (and (condition-case nil
9172 (progn (org-up-heading-all 1) t)
9173 (error nil))
9174 (not (bobp)))
9175 (org-flag-heading nil)
9176 (when siblings-p (org-show-siblings))))))))
9178 (defun org-reveal (&optional siblings)
9179 "Show current entry, hierarchy above it, and the following headline.
9180 This can be used to show a consistent set of context around locations
9181 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9182 not t for the search context.
9184 With optional argument SIBLINGS, on each level of the hierarchy all
9185 siblings are shown. This repairs the tree structure to what it would
9186 look like when opened with hierarchical calls to `org-cycle'."
9187 (interactive "P")
9188 (let ((org-show-hierarchy-above t)
9189 (org-show-following-heading t)
9190 (org-show-siblings (if siblings t org-show-siblings)))
9191 (org-show-context nil)))
9193 (defun org-highlight-new-match (beg end)
9194 "Highlight from BEG to END and mark the highlight is an occur headline."
9195 (let ((ov (org-make-overlay beg end)))
9196 (org-overlay-put ov 'face 'secondary-selection)
9197 (push ov org-occur-highlights)))
9199 (defun org-remove-occur-highlights (&optional beg end noremove)
9200 "Remove the occur highlights from the buffer.
9201 BEG and END are ignored. If NOREMOVE is nil, remove this function
9202 from the `before-change-functions' in the current buffer."
9203 (interactive)
9204 (unless org-inhibit-highlight-removal
9205 (mapc 'org-delete-overlay org-occur-highlights)
9206 (setq org-occur-highlights nil)
9207 (setq org-occur-parameters nil)
9208 (unless noremove
9209 (remove-hook 'before-change-functions
9210 'org-remove-occur-highlights 'local))))
9212 ;;;; Priorities
9214 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9215 "Regular expression matching the priority indicator.")
9217 (defvar org-remove-priority-next-time nil)
9219 (defun org-priority-up ()
9220 "Increase the priority of the current item."
9221 (interactive)
9222 (org-priority 'up))
9224 (defun org-priority-down ()
9225 "Decrease the priority of the current item."
9226 (interactive)
9227 (org-priority 'down))
9229 (defun org-priority (&optional action)
9230 "Change the priority of an item by ARG.
9231 ACTION can be `set', `up', `down', or a character."
9232 (interactive)
9233 (setq action (or action 'set))
9234 (let (current new news have remove)
9235 (save-excursion
9236 (org-back-to-heading)
9237 (if (looking-at org-priority-regexp)
9238 (setq current (string-to-char (match-string 2))
9239 have t)
9240 (setq current org-default-priority))
9241 (cond
9242 ((or (eq action 'set)
9243 (if (featurep 'xemacs) (characterp action) (integerp action)))
9244 (if (not (eq action 'set))
9245 (setq new action)
9246 (message "Priority %c-%c, SPC to remove: "
9247 org-highest-priority org-lowest-priority)
9248 (setq new (read-char-exclusive)))
9249 (if (and (= (upcase org-highest-priority) org-highest-priority)
9250 (= (upcase org-lowest-priority) org-lowest-priority))
9251 (setq new (upcase new)))
9252 (cond ((equal new ?\ ) (setq remove t))
9253 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9254 (error "Priority must be between `%c' and `%c'"
9255 org-highest-priority org-lowest-priority))))
9256 ((eq action 'up)
9257 (if (and (not have) (eq last-command this-command))
9258 (setq new org-lowest-priority)
9259 (setq new (if (and org-priority-start-cycle-with-default (not have))
9260 org-default-priority (1- current)))))
9261 ((eq action 'down)
9262 (if (and (not have) (eq last-command this-command))
9263 (setq new org-highest-priority)
9264 (setq new (if (and org-priority-start-cycle-with-default (not have))
9265 org-default-priority (1+ current)))))
9266 (t (error "Invalid action")))
9267 (if (or (< (upcase new) org-highest-priority)
9268 (> (upcase new) org-lowest-priority))
9269 (setq remove t))
9270 (setq news (format "%c" new))
9271 (if have
9272 (if remove
9273 (replace-match "" t t nil 1)
9274 (replace-match news t t nil 2))
9275 (if remove
9276 (error "No priority cookie found in line")
9277 (looking-at org-todo-line-regexp)
9278 (if (match-end 2)
9279 (progn
9280 (goto-char (match-end 2))
9281 (insert " [#" news "]"))
9282 (goto-char (match-beginning 3))
9283 (insert "[#" news "] ")))))
9284 (org-preserve-lc (org-set-tags nil 'align))
9285 (if remove
9286 (message "Priority removed")
9287 (message "Priority of current item set to %s" news))))
9290 (defun org-get-priority (s)
9291 "Find priority cookie and return priority."
9292 (save-match-data
9293 (if (not (string-match org-priority-regexp s))
9294 (* 1000 (- org-lowest-priority org-default-priority))
9295 (* 1000 (- org-lowest-priority
9296 (string-to-char (match-string 2 s)))))))
9298 ;;;; Tags
9300 (defvar org-agenda-archives-mode)
9301 (defun org-scan-tags (action matcher &optional todo-only)
9302 "Scan headline tags with inheritance and produce output ACTION.
9304 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9305 or `agenda' to produce an entry list for an agenda view. It can also be
9306 a Lisp form or a function that should be called at each matched headline, in
9307 this case the return value is a list of all return values from these calls.
9309 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9310 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9311 only lines with a TODO keyword are included in the output."
9312 (require 'org-agenda)
9313 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9314 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9315 (org-re
9316 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9317 (props (list 'face 'default
9318 'done-face 'org-done
9319 'undone-face 'default
9320 'mouse-face 'highlight
9321 'org-not-done-regexp org-not-done-regexp
9322 'org-todo-regexp org-todo-regexp
9323 'keymap org-agenda-keymap
9324 'help-echo
9325 (format "mouse-2 or RET jump to org file %s"
9326 (abbreviate-file-name
9327 (or (buffer-file-name (buffer-base-buffer))
9328 (buffer-name (buffer-base-buffer)))))))
9329 (case-fold-search nil)
9330 lspos tags tags-list
9331 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9332 (llast 0) rtn rtn1 level category i txt
9333 todo marker entry priority)
9334 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9335 (setq action (list 'lambda nil action)))
9336 (save-excursion
9337 (goto-char (point-min))
9338 (when (eq action 'sparse-tree)
9339 (org-overview)
9340 (org-remove-occur-highlights))
9341 (while (re-search-forward re nil t)
9342 (catch :skip
9343 (setq todo (if (match-end 1) (match-string 2))
9344 tags (if (match-end 4) (match-string 4)))
9345 (goto-char (setq lspos (1+ (match-beginning 0))))
9346 (setq level (org-reduced-level (funcall outline-level))
9347 category (org-get-category))
9348 (setq i llast llast level)
9349 ;; remove tag lists from same and sublevels
9350 (while (>= i level)
9351 (when (setq entry (assoc i tags-alist))
9352 (setq tags-alist (delete entry tags-alist)))
9353 (setq i (1- i)))
9354 ;; add the next tags
9355 (when tags
9356 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9357 tags-alist
9358 (cons (cons level tags) tags-alist)))
9359 ;; compile tags for current headline
9360 (setq tags-list
9361 (if org-use-tag-inheritance
9362 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9363 tags))
9364 (when org-use-tag-inheritance
9365 (setcdr (car tags-alist)
9366 (mapcar (lambda (x)
9367 (setq x (copy-sequence x))
9368 (org-add-prop-inherited x))
9369 (cdar tags-alist))))
9370 (when (and tags org-use-tag-inheritance
9371 (not (eq t org-use-tag-inheritance)))
9372 ;; selective inheritance, remove uninherited ones
9373 (setcdr (car tags-alist)
9374 (org-remove-uniherited-tags (cdar tags-alist))))
9375 (when (and (or (not todo-only)
9376 (and (member todo org-not-done-keywords)
9377 (or (not org-agenda-tags-todo-honor-ignore-options)
9378 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9379 (let ((case-fold-search t)) (eval matcher))
9381 (not (member org-archive-tag tags-list))
9382 ;; we have an archive tag, should we use this anyway?
9383 (or (not org-agenda-skip-archived-trees)
9384 (and (eq action 'agenda) org-agenda-archives-mode))))
9385 (unless (eq action 'sparse-tree) (org-agenda-skip))
9387 ;; select this headline
9389 (cond
9390 ((eq action 'sparse-tree)
9391 (and org-highlight-sparse-tree-matches
9392 (org-get-heading) (match-end 0)
9393 (org-highlight-new-match
9394 (match-beginning 0) (match-beginning 1)))
9395 (org-show-context 'tags-tree))
9396 ((eq action 'agenda)
9397 (setq txt (org-format-agenda-item
9399 (concat
9400 (if org-tags-match-list-sublevels
9401 (make-string (1- level) ?.) "")
9402 (org-get-heading))
9403 category (org-get-tags-at))
9404 priority (org-get-priority txt))
9405 (goto-char lspos)
9406 (setq marker (org-agenda-new-marker))
9407 (org-add-props txt props
9408 'org-marker marker 'org-hd-marker marker 'org-category category
9409 'priority priority 'type "tagsmatch")
9410 (push txt rtn))
9411 ((functionp action)
9412 (save-excursion
9413 (setq rtn1 (funcall action))
9414 (push rtn1 rtn))
9415 (goto-char (point-at-eol)))
9416 (t (error "Invalid action")))
9418 ;; if we are to skip sublevels, jump to end of subtree
9419 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9420 (when (and (eq action 'sparse-tree)
9421 (not org-sparse-tree-open-archived-trees))
9422 (org-hide-archived-subtrees (point-min) (point-max)))
9423 (nreverse rtn)))
9425 (defun org-remove-uniherited-tags (tags)
9426 "Remove all tags that are not inherited from the list TAGS."
9427 (cond
9428 ((eq org-use-tag-inheritance t)
9429 (if org-tags-exclude-from-inheritance
9430 (org-delete-all org-tags-exclude-from-inheritance tags)
9431 tags))
9432 ((not org-use-tag-inheritance) nil)
9433 ((stringp org-use-tag-inheritance)
9434 (delq nil (mapcar
9435 (lambda (x)
9436 (if (and (string-match org-use-tag-inheritance x)
9437 (not (member x org-tags-exclude-from-inheritance)))
9438 x nil))
9439 tags)))
9440 ((listp org-use-tag-inheritance)
9441 (delq nil (mapcar
9442 (lambda (x)
9443 (if (member x org-use-tag-inheritance) x nil))
9444 tags)))))
9446 (defvar todo-only) ;; dynamically scoped
9448 (defun org-tags-sparse-tree (&optional todo-only match)
9449 "Create a sparse tree according to tags string MATCH.
9450 MATCH can contain positive and negative selection of tags, like
9451 \"+WORK+URGENT-WITHBOSS\".
9452 If optional argument TODO-ONLY is non-nil, only select lines that are
9453 also TODO lines."
9454 (interactive "P")
9455 (org-prepare-agenda-buffers (list (current-buffer)))
9456 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9458 (defvar org-cached-props nil)
9459 (defun org-cached-entry-get (pom property)
9460 (if (or (eq t org-use-property-inheritance)
9461 (and (stringp org-use-property-inheritance)
9462 (string-match org-use-property-inheritance property))
9463 (and (listp org-use-property-inheritance)
9464 (member property org-use-property-inheritance)))
9465 ;; Caching is not possible, check it directly
9466 (org-entry-get pom property 'inherit)
9467 ;; Get all properties, so that we can do complicated checks easily
9468 (cdr (assoc property (or org-cached-props
9469 (setq org-cached-props
9470 (org-entry-properties pom)))))))
9472 (defun org-global-tags-completion-table (&optional files)
9473 "Return the list of all tags in all agenda buffer/files."
9474 (save-excursion
9475 (org-uniquify
9476 (delq nil
9477 (apply 'append
9478 (mapcar
9479 (lambda (file)
9480 (set-buffer (find-file-noselect file))
9481 (append (org-get-buffer-tags)
9482 (mapcar (lambda (x) (if (stringp (car-safe x))
9483 (list (car-safe x)) nil))
9484 org-tag-alist)))
9485 (if (and files (car files))
9486 files
9487 (org-agenda-files))))))))
9489 (defun org-make-tags-matcher (match)
9490 "Create the TAGS//TODO matcher form for the selection string MATCH."
9491 ;; todo-only is scoped dynamically into this function, and the function
9492 ;; may change it if the matcher asks for it.
9493 (unless match
9494 ;; Get a new match request, with completion
9495 (let ((org-last-tags-completion-table
9496 (org-global-tags-completion-table)))
9497 (setq match (org-completing-read
9498 "Match: " 'org-tags-completion-function nil nil nil
9499 'org-tags-history))))
9501 ;; Parse the string and create a lisp form
9502 (let ((match0 match)
9503 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9504 minus tag mm
9505 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9506 orterms term orlist re-p str-p level-p level-op time-p
9507 prop-p pn pv po cat-p gv rest)
9508 (if (string-match "/+" match)
9509 ;; match contains also a todo-matching request
9510 (progn
9511 (setq tagsmatch (substring match 0 (match-beginning 0))
9512 todomatch (substring match (match-end 0)))
9513 (if (string-match "^!" todomatch)
9514 (setq todo-only t todomatch (substring todomatch 1)))
9515 (if (string-match "^\\s-*$" todomatch)
9516 (setq todomatch nil)))
9517 ;; only matching tags
9518 (setq tagsmatch match todomatch nil))
9520 ;; Make the tags matcher
9521 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9522 (setq tagsmatcher t)
9523 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9524 (while (setq term (pop orterms))
9525 (while (and (equal (substring term -1) "\\") orterms)
9526 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9527 (while (string-match re term)
9528 (setq rest (substring term (match-end 0))
9529 minus (and (match-end 1)
9530 (equal (match-string 1 term) "-"))
9531 tag (match-string 2 term)
9532 re-p (equal (string-to-char tag) ?{)
9533 level-p (match-end 4)
9534 prop-p (match-end 5)
9535 mm (cond
9536 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9537 (level-p
9538 (setq level-op (org-op-to-function (match-string 3 term)))
9539 `(,level-op level ,(string-to-number
9540 (match-string 4 term))))
9541 (prop-p
9542 (setq pn (match-string 5 term)
9543 po (match-string 6 term)
9544 pv (match-string 7 term)
9545 cat-p (equal pn "CATEGORY")
9546 re-p (equal (string-to-char pv) ?{)
9547 str-p (equal (string-to-char pv) ?\")
9548 time-p (save-match-data
9549 (string-match "^\"[[<].*[]>]\"$" pv))
9550 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9551 (if time-p (setq pv (org-matcher-time pv)))
9552 (setq po (org-op-to-function po (if time-p 'time str-p)))
9553 (cond
9554 ((equal pn "CATEGORY")
9555 (setq gv '(get-text-property (point) 'org-category)))
9556 ((equal pn "TODO")
9557 (setq gv 'todo))
9559 (setq gv `(org-cached-entry-get nil ,pn))))
9560 (if re-p
9561 (if (eq po 'org<>)
9562 `(not (string-match ,pv (or ,gv "")))
9563 `(string-match ,pv (or ,gv "")))
9564 (if str-p
9565 `(,po (or ,gv "") ,pv)
9566 `(,po (string-to-number (or ,gv ""))
9567 ,(string-to-number pv) ))))
9568 (t `(member ,(downcase tag) tags-list)))
9569 mm (if minus (list 'not mm) mm)
9570 term rest)
9571 (push mm tagsmatcher))
9572 (push (if (> (length tagsmatcher) 1)
9573 (cons 'and tagsmatcher)
9574 (car tagsmatcher))
9575 orlist)
9576 (setq tagsmatcher nil))
9577 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9578 (setq tagsmatcher
9579 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9580 ;; Make the todo matcher
9581 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9582 (setq todomatcher t)
9583 (setq orterms (org-split-string todomatch "|") orlist nil)
9584 (while (setq term (pop orterms))
9585 (while (string-match re term)
9586 (setq minus (and (match-end 1)
9587 (equal (match-string 1 term) "-"))
9588 kwd (match-string 2 term)
9589 re-p (equal (string-to-char kwd) ?{)
9590 term (substring term (match-end 0))
9591 mm (if re-p
9592 `(string-match ,(substring kwd 1 -1) todo)
9593 (list 'equal 'todo kwd))
9594 mm (if minus (list 'not mm) mm))
9595 (push mm todomatcher))
9596 (push (if (> (length todomatcher) 1)
9597 (cons 'and todomatcher)
9598 (car todomatcher))
9599 orlist)
9600 (setq todomatcher nil))
9601 (setq todomatcher (if (> (length orlist) 1)
9602 (cons 'or orlist) (car orlist))))
9604 ;; Return the string and lisp forms of the matcher
9605 (setq matcher (if todomatcher
9606 (list 'and tagsmatcher todomatcher)
9607 tagsmatcher))
9608 (cons match0 matcher)))
9610 (defun org-op-to-function (op &optional stringp)
9611 "Turn an operator into the appropriate function."
9612 (setq op
9613 (cond
9614 ((equal op "<" ) '(< string< org-time<))
9615 ((equal op ">" ) '(> org-string> org-time>))
9616 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9617 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9618 ((member op '("=" "==")) '(= string= org-time=))
9619 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9620 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9622 (defun org<> (a b) (not (= a b)))
9623 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9624 (defun org-string>= (a b) (not (string< a b)))
9625 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9626 (defun org-string<> (a b) (not (string= a b)))
9627 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9628 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9629 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9630 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9631 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9632 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9633 (defun org-2ft (s)
9634 "Convert S to a floating point time.
9635 If S is already a number, just return it. If it is a string, parse
9636 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9637 (cond
9638 ((numberp s) s)
9639 ((stringp s)
9640 (condition-case nil
9641 (float-time (apply 'encode-time (org-parse-time-string s)))
9642 (error 0.)))
9643 (t 0.)))
9645 (defun org-time-today ()
9646 "Time in seconds today at 0:00.
9647 Returns the float number of seconds since the beginning of the
9648 epoch to the beginning of today (00:00)."
9649 (float-time (apply 'encode-time
9650 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9652 (defun org-matcher-time (s)
9653 "Interpret a time comparison value."
9654 (save-match-data
9655 (cond
9656 ((string= s "<now>") (float-time))
9657 ((string= s "<today>") (org-time-today))
9658 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9659 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9660 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9661 (+ (org-time-today)
9662 (* (string-to-number (match-string 1 s))
9663 (cdr (assoc (match-string 2 s)
9664 '(("d" . 86400.0) ("w" . 604800.0)
9665 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9666 (t (org-2ft s)))))
9668 (defun org-match-any-p (re list)
9669 "Does re match any element of list?"
9670 (setq list (mapcar (lambda (x) (string-match re x)) list))
9671 (delq nil list))
9673 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9674 (defvar org-tags-overlay (org-make-overlay 1 1))
9675 (org-detach-overlay org-tags-overlay)
9677 (defun org-get-local-tags-at (&optional pos)
9678 "Get a list of tags defined in the current headline."
9679 (org-get-tags-at pos 'local))
9681 (defun org-get-local-tags ()
9682 "Get a list of tags defined in the current headline."
9683 (org-get-tags-at nil 'local))
9685 (defun org-get-tags-at (&optional pos local)
9686 "Get a list of all headline tags applicable at POS.
9687 POS defaults to point. If tags are inherited, the list contains
9688 the targets in the same sequence as the headlines appear, i.e.
9689 the tags of the current headline come last.
9690 When LOCAL is non-nil, only return tags from the current headline,
9691 ignore inherited ones."
9692 (interactive)
9693 (let (tags ltags lastpos parent)
9694 (save-excursion
9695 (save-restriction
9696 (widen)
9697 (goto-char (or pos (point)))
9698 (save-match-data
9699 (catch 'done
9700 (condition-case nil
9701 (progn
9702 (org-back-to-heading t)
9703 (while (not (equal lastpos (point)))
9704 (setq lastpos (point))
9705 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9706 (setq ltags (org-split-string
9707 (org-match-string-no-properties 1) ":"))
9708 (when parent
9709 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9710 (setq tags (append
9711 (if parent
9712 (org-remove-uniherited-tags ltags)
9713 ltags)
9714 tags)))
9715 (or org-use-tag-inheritance (throw 'done t))
9716 (if local (throw 'done t))
9717 (org-up-heading-all 1)
9718 (setq parent t)))
9719 (error nil)))))
9720 (append (org-remove-uniherited-tags org-file-tags) tags))))
9722 (defun org-add-prop-inherited (s)
9723 (add-text-properties 0 (length s) '(inherited t) s)
9726 (defun org-toggle-tag (tag &optional onoff)
9727 "Toggle the tag TAG for the current line.
9728 If ONOFF is `on' or `off', don't toggle but set to this state."
9729 (let (res current)
9730 (save-excursion
9731 (org-back-to-heading t)
9732 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9733 (point-at-eol) t)
9734 (progn
9735 (setq current (match-string 1))
9736 (replace-match ""))
9737 (setq current ""))
9738 (setq current (nreverse (org-split-string current ":")))
9739 (cond
9740 ((eq onoff 'on)
9741 (setq res t)
9742 (or (member tag current) (push tag current)))
9743 ((eq onoff 'off)
9744 (or (not (member tag current)) (setq current (delete tag current))))
9745 (t (if (member tag current)
9746 (setq current (delete tag current))
9747 (setq res t)
9748 (push tag current))))
9749 (end-of-line 1)
9750 (if current
9751 (progn
9752 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9753 (org-set-tags nil t))
9754 (delete-horizontal-space))
9755 (run-hooks 'org-after-tags-change-hook))
9756 res))
9758 (defun org-align-tags-here (to-col)
9759 ;; Assumes that this is a headline
9760 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9761 (beginning-of-line 1)
9762 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9763 (< pos (match-beginning 2)))
9764 (progn
9765 (setq tags-l (- (match-end 2) (match-beginning 2)))
9766 (goto-char (match-beginning 1))
9767 (insert " ")
9768 (delete-region (point) (1+ (match-beginning 2)))
9769 (setq ncol (max (1+ (current-column))
9770 (1+ col)
9771 (if (> to-col 0)
9772 to-col
9773 (- (abs to-col) tags-l))))
9774 (setq p (point))
9775 (insert (make-string (- ncol (current-column)) ?\ ))
9776 (setq ncol (current-column))
9777 (when indent-tabs-mode (tabify p (point-at-eol)))
9778 (org-move-to-column (min ncol col) t))
9779 (goto-char pos))))
9781 (defun org-set-tags-command (&optional arg just-align)
9782 "Call the set-tags command for the current entry."
9783 (interactive "P")
9784 (if (org-on-heading-p)
9785 (org-set-tags arg just-align)
9786 (save-excursion
9787 (org-back-to-heading t)
9788 (org-set-tags arg just-align))))
9790 (defun org-set-tags (&optional arg just-align)
9791 "Set the tags for the current headline.
9792 With prefix ARG, realign all tags in headings in the current buffer."
9793 (interactive "P")
9794 (let* ((re (concat "^" outline-regexp))
9795 (current (org-get-tags-string))
9796 (col (current-column))
9797 (org-setting-tags t)
9798 table current-tags inherited-tags ; computed below when needed
9799 tags p0 c0 c1 rpl)
9800 (if arg
9801 (save-excursion
9802 (goto-char (point-min))
9803 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9804 (while (re-search-forward re nil t)
9805 (org-set-tags nil t)
9806 (end-of-line 1)))
9807 (message "All tags realigned to column %d" org-tags-column))
9808 (if just-align
9809 (setq tags current)
9810 ;; Get a new set of tags from the user
9811 (save-excursion
9812 (setq table (or org-tag-alist (org-get-buffer-tags))
9813 org-last-tags-completion-table table
9814 current-tags (org-split-string current ":")
9815 inherited-tags (nreverse
9816 (nthcdr (length current-tags)
9817 (nreverse (org-get-tags-at))))
9818 tags
9819 (if (or (eq t org-use-fast-tag-selection)
9820 (and org-use-fast-tag-selection
9821 (delq nil (mapcar 'cdr table))))
9822 (org-fast-tag-selection
9823 current-tags inherited-tags table
9824 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9825 (let ((org-add-colon-after-tag-completion t))
9826 (org-trim
9827 (org-without-partial-completion
9828 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9829 nil nil current 'org-tags-history)))))))
9830 (while (string-match "[-+&]+" tags)
9831 ;; No boolean logic, just a list
9832 (setq tags (replace-match ":" t t tags))))
9834 (if (string-match "\\`[\t ]*\\'" tags)
9835 (setq tags "")
9836 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9837 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9839 ;; Insert new tags at the correct column
9840 (beginning-of-line 1)
9841 (cond
9842 ((and (equal current "") (equal tags "")))
9843 ((re-search-forward
9844 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9845 (point-at-eol) t)
9846 (if (equal tags "")
9847 (setq rpl "")
9848 (goto-char (match-beginning 0))
9849 (setq c0 (current-column) p0 (point)
9850 c1 (max (1+ c0) (if (> org-tags-column 0)
9851 org-tags-column
9852 (- (- org-tags-column) (length tags))))
9853 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9854 (replace-match rpl t t)
9855 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9856 tags)
9857 (t (error "Tags alignment failed")))
9858 (org-move-to-column col)
9859 (unless just-align
9860 (run-hooks 'org-after-tags-change-hook)))))
9862 (defun org-change-tag-in-region (beg end tag off)
9863 "Add or remove TAG for each entry in the region.
9864 This works in the agenda, and also in an org-mode buffer."
9865 (interactive
9866 (list (region-beginning) (region-end)
9867 (let ((org-last-tags-completion-table
9868 (if (org-mode-p)
9869 (org-get-buffer-tags)
9870 (org-global-tags-completion-table))))
9871 (org-ido-completing-read
9872 "Tag: " 'org-tags-completion-function nil nil nil
9873 'org-tags-history))
9874 (progn
9875 (message "[s]et or [r]emove? ")
9876 (equal (read-char-exclusive) ?r))))
9877 (if (fboundp 'deactivate-mark) (deactivate-mark))
9878 (let ((agendap (equal major-mode 'org-agenda-mode))
9879 l1 l2 m buf pos newhead (cnt 0))
9880 (goto-char end)
9881 (setq l2 (1- (org-current-line)))
9882 (goto-char beg)
9883 (setq l1 (org-current-line))
9884 (loop for l from l1 to l2 do
9885 (goto-line l)
9886 (setq m (get-text-property (point) 'org-hd-marker))
9887 (when (or (and (org-mode-p) (org-on-heading-p))
9888 (and agendap m))
9889 (setq buf (if agendap (marker-buffer m) (current-buffer))
9890 pos (if agendap m (point)))
9891 (with-current-buffer buf
9892 (save-excursion
9893 (save-restriction
9894 (goto-char pos)
9895 (setq cnt (1+ cnt))
9896 (org-toggle-tag tag (if off 'off 'on))
9897 (setq newhead (org-get-heading)))))
9898 (and agendap (org-agenda-change-all-lines newhead m))))
9899 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9901 (defun org-tags-completion-function (string predicate &optional flag)
9902 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9903 (confirm (lambda (x) (stringp (car x)))))
9904 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9905 (setq s1 (match-string 1 string)
9906 s2 (match-string 2 string))
9907 (setq s1 "" s2 string))
9908 (cond
9909 ((eq flag nil)
9910 ;; try completion
9911 (setq rtn (try-completion s2 ctable confirm))
9912 (if (stringp rtn)
9913 (setq rtn
9914 (concat s1 s2 (substring rtn (length s2))
9915 (if (and org-add-colon-after-tag-completion
9916 (assoc rtn ctable))
9917 ":" ""))))
9918 rtn)
9919 ((eq flag t)
9920 ;; all-completions
9921 (all-completions s2 ctable confirm)
9923 ((eq flag 'lambda)
9924 ;; exact match?
9925 (assoc s2 ctable)))
9928 (defun org-fast-tag-insert (kwd tags face &optional end)
9929 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9930 (insert (format "%-12s" (concat kwd ":"))
9931 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9932 (or end "")))
9934 (defun org-fast-tag-show-exit (flag)
9935 (save-excursion
9936 (goto-line 3)
9937 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9938 (replace-match ""))
9939 (when flag
9940 (end-of-line 1)
9941 (org-move-to-column (- (window-width) 19) t)
9942 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9944 (defun org-set-current-tags-overlay (current prefix)
9945 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9946 (if (featurep 'xemacs)
9947 (org-overlay-display org-tags-overlay (concat prefix s)
9948 'secondary-selection)
9949 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9950 (org-overlay-display org-tags-overlay (concat prefix s)))))
9952 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9953 "Fast tag selection with single keys.
9954 CURRENT is the current list of tags in the headline, INHERITED is the
9955 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9956 possibly with grouping information. TODO-TABLE is a similar table with
9957 TODO keywords, should these have keys assigned to them.
9958 If the keys are nil, a-z are automatically assigned.
9959 Returns the new tags string, or nil to not change the current settings."
9960 (let* ((fulltable (append table todo-table))
9961 (maxlen (apply 'max (mapcar
9962 (lambda (x)
9963 (if (stringp (car x)) (string-width (car x)) 0))
9964 fulltable)))
9965 (buf (current-buffer))
9966 (expert (eq org-fast-tag-selection-single-key 'expert))
9967 (buffer-tags nil)
9968 (fwidth (+ maxlen 3 1 3))
9969 (ncol (/ (- (window-width) 4) fwidth))
9970 (i-face 'org-done)
9971 (c-face 'org-todo)
9972 tg cnt e c char c1 c2 ntable tbl rtn
9973 ov-start ov-end ov-prefix
9974 (exit-after-next org-fast-tag-selection-single-key)
9975 (done-keywords org-done-keywords)
9976 groups ingroup)
9977 (save-excursion
9978 (beginning-of-line 1)
9979 (if (looking-at
9980 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9981 (setq ov-start (match-beginning 1)
9982 ov-end (match-end 1)
9983 ov-prefix "")
9984 (setq ov-start (1- (point-at-eol))
9985 ov-end (1+ ov-start))
9986 (skip-chars-forward "^\n\r")
9987 (setq ov-prefix
9988 (concat
9989 (buffer-substring (1- (point)) (point))
9990 (if (> (current-column) org-tags-column)
9992 (make-string (- org-tags-column (current-column)) ?\ ))))))
9993 (org-move-overlay org-tags-overlay ov-start ov-end)
9994 (save-window-excursion
9995 (if expert
9996 (set-buffer (get-buffer-create " *Org tags*"))
9997 (delete-other-windows)
9998 (split-window-vertically)
9999 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10000 (erase-buffer)
10001 (org-set-local 'org-done-keywords done-keywords)
10002 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10003 (org-fast-tag-insert "Current" current c-face "\n\n")
10004 (org-fast-tag-show-exit exit-after-next)
10005 (org-set-current-tags-overlay current ov-prefix)
10006 (setq tbl fulltable char ?a cnt 0)
10007 (while (setq e (pop tbl))
10008 (cond
10009 ((equal e '(:startgroup))
10010 (push '() groups) (setq ingroup t)
10011 (when (not (= cnt 0))
10012 (setq cnt 0)
10013 (insert "\n"))
10014 (insert "{ "))
10015 ((equal e '(:endgroup))
10016 (setq ingroup nil cnt 0)
10017 (insert "}\n"))
10019 (setq tg (car e) c2 nil)
10020 (if (cdr e)
10021 (setq c (cdr e))
10022 ;; automatically assign a character.
10023 (setq c1 (string-to-char
10024 (downcase (substring
10025 tg (if (= (string-to-char tg) ?@) 1 0)))))
10026 (if (or (rassoc c1 ntable) (rassoc c1 table))
10027 (while (or (rassoc char ntable) (rassoc char table))
10028 (setq char (1+ char)))
10029 (setq c2 c1))
10030 (setq c (or c2 char)))
10031 (if ingroup (push tg (car groups)))
10032 (setq tg (org-add-props tg nil 'face
10033 (cond
10034 ((not (assoc tg table))
10035 (org-get-todo-face tg))
10036 ((member tg current) c-face)
10037 ((member tg inherited) i-face)
10038 (t nil))))
10039 (if (and (= cnt 0) (not ingroup)) (insert " "))
10040 (insert "[" c "] " tg (make-string
10041 (- fwidth 4 (length tg)) ?\ ))
10042 (push (cons tg c) ntable)
10043 (when (= (setq cnt (1+ cnt)) ncol)
10044 (insert "\n")
10045 (if ingroup (insert " "))
10046 (setq cnt 0)))))
10047 (setq ntable (nreverse ntable))
10048 (insert "\n")
10049 (goto-char (point-min))
10050 (if (not expert) (org-fit-window-to-buffer))
10051 (setq rtn
10052 (catch 'exit
10053 (while t
10054 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10055 (if groups " [!] no groups" " [!]groups")
10056 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10057 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10058 (cond
10059 ((= c ?\r) (throw 'exit t))
10060 ((= c ?!)
10061 (setq groups (not groups))
10062 (goto-char (point-min))
10063 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10064 ((= c ?\C-c)
10065 (if (not expert)
10066 (org-fast-tag-show-exit
10067 (setq exit-after-next (not exit-after-next)))
10068 (setq expert nil)
10069 (delete-other-windows)
10070 (split-window-vertically)
10071 (org-switch-to-buffer-other-window " *Org tags*")
10072 (org-fit-window-to-buffer)))
10073 ((or (= c ?\C-g)
10074 (and (= c ?q) (not (rassoc c ntable))))
10075 (org-detach-overlay org-tags-overlay)
10076 (setq quit-flag t))
10077 ((= c ?\ )
10078 (setq current nil)
10079 (if exit-after-next (setq exit-after-next 'now)))
10080 ((= c ?\t)
10081 (condition-case nil
10082 (setq tg (org-ido-completing-read
10083 "Tag: "
10084 (or buffer-tags
10085 (with-current-buffer buf
10086 (org-get-buffer-tags)))))
10087 (quit (setq tg "")))
10088 (when (string-match "\\S-" tg)
10089 (add-to-list 'buffer-tags (list tg))
10090 (if (member tg current)
10091 (setq current (delete tg current))
10092 (push tg current)))
10093 (if exit-after-next (setq exit-after-next 'now)))
10094 ((setq e (rassoc c todo-table) tg (car e))
10095 (with-current-buffer buf
10096 (save-excursion (org-todo tg)))
10097 (if exit-after-next (setq exit-after-next 'now)))
10098 ((setq e (rassoc c ntable) tg (car e))
10099 (if (member tg current)
10100 (setq current (delete tg current))
10101 (loop for g in groups do
10102 (if (member tg g)
10103 (mapc (lambda (x)
10104 (setq current (delete x current)))
10105 g)))
10106 (push tg current))
10107 (if exit-after-next (setq exit-after-next 'now))))
10109 ;; Create a sorted list
10110 (setq current
10111 (sort current
10112 (lambda (a b)
10113 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10114 (if (eq exit-after-next 'now) (throw 'exit t))
10115 (goto-char (point-min))
10116 (beginning-of-line 2)
10117 (delete-region (point) (point-at-eol))
10118 (org-fast-tag-insert "Current" current c-face)
10119 (org-set-current-tags-overlay current ov-prefix)
10120 (while (re-search-forward
10121 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10122 (setq tg (match-string 1))
10123 (add-text-properties
10124 (match-beginning 1) (match-end 1)
10125 (list 'face
10126 (cond
10127 ((member tg current) c-face)
10128 ((member tg inherited) i-face)
10129 (t (get-text-property (match-beginning 1) 'face))))))
10130 (goto-char (point-min)))))
10131 (org-detach-overlay org-tags-overlay)
10132 (if rtn
10133 (mapconcat 'identity current ":")
10134 nil))))
10136 (defun org-get-tags-string ()
10137 "Get the TAGS string in the current headline."
10138 (unless (org-on-heading-p t)
10139 (error "Not on a heading"))
10140 (save-excursion
10141 (beginning-of-line 1)
10142 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10143 (org-match-string-no-properties 1)
10144 "")))
10146 (defun org-get-tags ()
10147 "Get the list of tags specified in the current headline."
10148 (org-split-string (org-get-tags-string) ":"))
10150 (defun org-get-buffer-tags ()
10151 "Get a table of all tags used in the buffer, for completion."
10152 (let (tags)
10153 (save-excursion
10154 (goto-char (point-min))
10155 (while (re-search-forward
10156 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10157 (when (equal (char-after (point-at-bol 0)) ?*)
10158 (mapc (lambda (x) (add-to-list 'tags x))
10159 (org-split-string (org-match-string-no-properties 1) ":")))))
10160 (mapcar 'list tags)))
10162 ;;;; The mapping API
10164 ;;;###autoload
10165 (defun org-map-entries (func &optional match scope &rest skip)
10166 "Call FUNC at each headline selected by MATCH in SCOPE.
10168 FUNC is a function or a lisp form. The function will be called without
10169 arguments, with the cursor positioned at the beginning of the headline.
10170 The return values of all calls to the function will be collected and
10171 returned as a list.
10173 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10174 Only headlines that are matched by this query will be considered during
10175 the iteration. When MATCH is nil or t, all headlines will be
10176 visited by the iteration.
10178 SCOPE determines the scope of this command. It can be any of:
10180 nil The current buffer, respecting the restriction if any
10181 tree The subtree started with the entry at point
10182 file The current buffer, without restriction
10183 file-with-archives
10184 The current buffer, and any archives associated with it
10185 agenda All agenda files
10186 agenda-with-archives
10187 All agenda files with any archive files associated with them
10188 \(file1 file2 ...)
10189 If this is a list, all files in the list will be scanned
10191 The remaining args are treated as settings for the skipping facilities of
10192 the scanner. The following items can be given here:
10194 archive skip trees with the archive tag.
10195 comment skip trees with the COMMENT keyword
10196 function or Emacs Lisp form:
10197 will be used as value for `org-agenda-skip-function', so whenever
10198 the the function returns t, FUNC will not be called for that
10199 entry and search will continue from the point where the
10200 function leaves it."
10201 (let* ((org-agenda-archives-mode nil) ; just to make sure
10202 (org-agenda-skip-archived-trees (memq 'archive skip))
10203 (org-agenda-skip-comment-trees (memq 'comment skip))
10204 (org-agenda-skip-function
10205 (car (org-delete-all '(comment archive) skip)))
10206 (org-tags-match-list-sublevels t)
10207 matcher file res
10208 org-todo-keywords-for-agenda
10209 org-done-keywords-for-agenda
10210 org-todo-keyword-alist-for-agenda
10211 org-tag-alist-for-agenda)
10213 (cond
10214 ((eq match t) (setq matcher t))
10215 ((eq match nil) (setq matcher t))
10216 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10218 (save-excursion
10219 (save-restriction
10220 (when (eq scope 'tree)
10221 (org-back-to-heading t)
10222 (org-narrow-to-subtree)
10223 (setq scope nil))
10225 (if (not scope)
10226 (progn
10227 (org-prepare-agenda-buffers
10228 (list (buffer-file-name (current-buffer))))
10229 (setq res (org-scan-tags func matcher)))
10230 ;; Get the right scope
10231 (cond
10232 ((and scope (listp scope) (symbolp (car scope)))
10233 (setq scope (eval scope)))
10234 ((eq scope 'agenda)
10235 (setq scope (org-agenda-files t)))
10236 ((eq scope 'agenda-with-archives)
10237 (setq scope (org-agenda-files t))
10238 (setq scope (org-add-archive-files scope)))
10239 ((eq scope 'file)
10240 (setq scope (list (buffer-file-name))))
10241 ((eq scope 'file-with-archives)
10242 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10243 (org-prepare-agenda-buffers scope)
10244 (while (setq file (pop scope))
10245 (with-current-buffer (org-find-base-buffer-visiting file)
10246 (save-excursion
10247 (save-restriction
10248 (widen)
10249 (goto-char (point-min))
10250 (setq res (append res (org-scan-tags func matcher))))))))))
10251 res))
10253 ;;;; Properties
10255 ;;; Setting and retrieving properties
10257 (defconst org-special-properties
10258 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10259 "TIMESTAMP" "TIMESTAMP_IA")
10260 "The special properties valid in Org-mode.
10262 These are properties that are not defined in the property drawer,
10263 but in some other way.")
10265 (defconst org-default-properties
10266 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10267 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10268 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10269 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10270 "Some properties that are used by Org-mode for various purposes.
10271 Being in this list makes sure that they are offered for completion.")
10273 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10274 "Regular expression matching the first line of a property drawer.")
10276 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10277 "Regular expression matching the first line of a property drawer.")
10279 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10280 "Regular expression matching the first line of a property drawer.")
10282 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10283 "Regular expression matching the first line of a property drawer.")
10285 (defconst org-property-drawer-re
10286 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10287 org-property-end-re "\\)\n?")
10288 "Matches an entire property drawer.")
10290 (defconst org-clock-drawer-re
10291 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10292 org-property-end-re "\\)\n?")
10293 "Matches an entire clock drawer.")
10295 (defun org-property-action ()
10296 "Do an action on properties."
10297 (interactive)
10298 (let (c)
10299 (org-at-property-p)
10300 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10301 (setq c (read-char-exclusive))
10302 (cond
10303 ((equal c ?s)
10304 (call-interactively 'org-set-property))
10305 ((equal c ?d)
10306 (call-interactively 'org-delete-property))
10307 ((equal c ?D)
10308 (call-interactively 'org-delete-property-globally))
10309 ((equal c ?c)
10310 (call-interactively 'org-compute-property-at-point))
10311 (t (error "No such property action %c" c)))))
10313 (defun org-at-property-p ()
10314 "Is the cursor in a property line?"
10315 ;; FIXME: Does not check if we are actually in the drawer.
10316 ;; FIXME: also returns true on any drawers.....
10317 ;; This is used by C-c C-c for property action.
10318 (save-excursion
10319 (beginning-of-line 1)
10320 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10322 (defun org-get-property-block (&optional beg end force)
10323 "Return the (beg . end) range of the body of the property drawer.
10324 BEG and END can be beginning and end of subtree, if not given
10325 they will be found.
10326 If the drawer does not exist and FORCE is non-nil, create the drawer."
10327 (catch 'exit
10328 (save-excursion
10329 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10330 (end (or end (progn (outline-next-heading) (point)))))
10331 (goto-char beg)
10332 (if (re-search-forward org-property-start-re end t)
10333 (setq beg (1+ (match-end 0)))
10334 (if force
10335 (save-excursion
10336 (org-insert-property-drawer)
10337 (setq end (progn (outline-next-heading) (point))))
10338 (throw 'exit nil))
10339 (goto-char beg)
10340 (if (re-search-forward org-property-start-re end t)
10341 (setq beg (1+ (match-end 0)))))
10342 (if (re-search-forward org-property-end-re end t)
10343 (setq end (match-beginning 0))
10344 (or force (throw 'exit nil))
10345 (goto-char beg)
10346 (setq end beg)
10347 (org-indent-line-function)
10348 (insert ":END:\n"))
10349 (cons beg end)))))
10351 (defun org-entry-properties (&optional pom which)
10352 "Get all properties of the entry at point-or-marker POM.
10353 This includes the TODO keyword, the tags, time strings for deadline,
10354 scheduled, and clocking, and any additional properties defined in the
10355 entry. The return value is an alist, keys may occur multiple times
10356 if the property key was used several times.
10357 POM may also be nil, in which case the current entry is used.
10358 If WHICH is nil or `all', get all properties. If WHICH is
10359 `special' or `standard', only get that subclass."
10360 (setq which (or which 'all))
10361 (org-with-point-at pom
10362 (let ((clockstr (substring org-clock-string 0 -1))
10363 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10364 beg end range props sum-props key value string clocksum)
10365 (save-excursion
10366 (when (condition-case nil
10367 (and (org-mode-p) (org-back-to-heading t))
10368 (error nil))
10369 (setq beg (point))
10370 (setq sum-props (get-text-property (point) 'org-summaries))
10371 (setq clocksum (get-text-property (point) :org-clock-minutes))
10372 (outline-next-heading)
10373 (setq end (point))
10374 (when (memq which '(all special))
10375 ;; Get the special properties, like TODO and tags
10376 (goto-char beg)
10377 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10378 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10379 (when (looking-at org-priority-regexp)
10380 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10381 (when (and (setq value (org-get-tags-string))
10382 (string-match "\\S-" value))
10383 (push (cons "TAGS" value) props))
10384 (when (setq value (org-get-tags-at))
10385 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10386 props))
10387 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10388 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10389 string (if (equal key clockstr)
10390 (org-no-properties
10391 (org-trim
10392 (buffer-substring
10393 (match-beginning 3) (goto-char (point-at-eol)))))
10394 (substring (org-match-string-no-properties 3) 1 -1)))
10395 (unless key
10396 (if (= (char-after (match-beginning 3)) ?\[)
10397 (setq key "TIMESTAMP_IA")
10398 (setq key "TIMESTAMP")))
10399 (when (or (equal key clockstr) (not (assoc key props)))
10400 (push (cons key string) props)))
10404 (when (memq which '(all standard))
10405 ;; Get the standard properties, like :PORP: ...
10406 (setq range (org-get-property-block beg end))
10407 (when range
10408 (goto-char (car range))
10409 (while (re-search-forward
10410 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10411 (cdr range) t)
10412 (setq key (org-match-string-no-properties 1)
10413 value (org-trim (or (org-match-string-no-properties 2) "")))
10414 (unless (member key excluded)
10415 (push (cons key (or value "")) props)))))
10416 (if clocksum
10417 (push (cons "CLOCKSUM"
10418 (org-columns-number-to-string (/ (float clocksum) 60.)
10419 'add_times))
10420 props))
10421 (unless (assoc "CATEGORY" props)
10422 (setq value (or (org-get-category)
10423 (progn (org-refresh-category-properties)
10424 (org-get-category))))
10425 (push (cons "CATEGORY" value) props))
10426 (append sum-props (nreverse props)))))))
10428 (defun org-entry-get (pom property &optional inherit)
10429 "Get value of PROPERTY for entry at point-or-marker POM.
10430 If INHERIT is non-nil and the entry does not have the property,
10431 then also check higher levels of the hierarchy.
10432 If INHERIT is the symbol `selective', use inheritance only if the setting
10433 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10434 If the property is present but empty, the return value is the empty string.
10435 If the property is not present at all, nil is returned."
10436 (org-with-point-at pom
10437 (if (and inherit (if (eq inherit 'selective)
10438 (org-property-inherit-p property)
10440 (org-entry-get-with-inheritance property)
10441 (if (member property org-special-properties)
10442 ;; We need a special property. Use brute force, get all properties.
10443 (cdr (assoc property (org-entry-properties nil 'special)))
10444 (let ((range (org-get-property-block)))
10445 (if (and range
10446 (goto-char (car range))
10447 (re-search-forward
10448 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10449 (cdr range) t))
10450 ;; Found the property, return it.
10451 (if (match-end 1)
10452 (org-match-string-no-properties 1)
10453 "")))))))
10455 (defun org-property-or-variable-value (var &optional inherit)
10456 "Check if there is a property fixing the value of VAR.
10457 If yes, return this value. If not, return the current value of the variable."
10458 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10459 (if (and prop (stringp prop) (string-match "\\S-" prop))
10460 (read prop)
10461 (symbol-value var))))
10463 (defun org-entry-delete (pom property)
10464 "Delete the property PROPERTY from entry at point-or-marker POM."
10465 (org-with-point-at pom
10466 (if (member property org-special-properties)
10467 nil ; cannot delete these properties.
10468 (let ((range (org-get-property-block)))
10469 (if (and range
10470 (goto-char (car range))
10471 (re-search-forward
10472 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10473 (cdr range) t))
10474 (progn
10475 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10477 nil)))))
10479 ;; Multi-values properties are properties that contain multiple values
10480 ;; These values are assumed to be single words, separated by whitespace.
10481 (defun org-entry-add-to-multivalued-property (pom property value)
10482 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10483 (let* ((old (org-entry-get pom property))
10484 (values (and old (org-split-string old "[ \t]"))))
10485 (setq value (org-entry-protect-space value))
10486 (unless (member value values)
10487 (setq values (cons value values))
10488 (org-entry-put pom property
10489 (mapconcat 'identity values " ")))))
10491 (defun org-entry-remove-from-multivalued-property (pom property value)
10492 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10493 (let* ((old (org-entry-get pom property))
10494 (values (and old (org-split-string old "[ \t]"))))
10495 (setq value (org-entry-protect-space value))
10496 (when (member value values)
10497 (setq values (delete value values))
10498 (org-entry-put pom property
10499 (mapconcat 'identity values " ")))))
10501 (defun org-entry-member-in-multivalued-property (pom property value)
10502 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10503 (let* ((old (org-entry-get pom property))
10504 (values (and old (org-split-string old "[ \t]"))))
10505 (setq value (org-entry-protect-space value))
10506 (member value values)))
10508 (defun org-entry-get-multivalued-property (pom property)
10509 "Return a list of values in a multivalued property."
10510 (let* ((value (org-entry-get pom property))
10511 (values (and value (org-split-string value "[ \t]"))))
10512 (mapcar 'org-entry-restore-space values)))
10514 (defun org-entry-put-multivalued-property (pom property &rest values)
10515 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10516 VALUES should be a list of strings. Spaces will be protected."
10517 (org-entry-put pom property
10518 (mapconcat 'org-entry-protect-space values " "))
10519 (let* ((value (org-entry-get pom property))
10520 (values (and value (org-split-string value "[ \t]"))))
10521 (mapcar 'org-entry-restore-space values)))
10523 (defun org-entry-protect-space (s)
10524 "Protect spaces and newline in string S."
10525 (while (string-match " " s)
10526 (setq s (replace-match "%20" t t s)))
10527 (while (string-match "\n" s)
10528 (setq s (replace-match "%0A" t t s)))
10531 (defun org-entry-restore-space (s)
10532 "Restore spaces and newline in string S."
10533 (while (string-match "%20" s)
10534 (setq s (replace-match " " t t s)))
10535 (while (string-match "%0A" s)
10536 (setq s (replace-match "\n" t t s)))
10539 (defvar org-entry-property-inherited-from (make-marker)
10540 "Marker pointing to the entry from where a property was inherited.
10541 Each call to `org-entry-get-with-inheritance' will set this marker to the
10542 location of the entry where the inheritance search matched. If there was
10543 no match, the marker will point nowhere.
10544 Note that also `org-entry-get' calls this function, if the INHERIT flag
10545 is set.")
10547 (defun org-entry-get-with-inheritance (property)
10548 "Get entry property, and search higher levels if not present."
10549 (move-marker org-entry-property-inherited-from nil)
10550 (let (tmp)
10551 (save-excursion
10552 (save-restriction
10553 (widen)
10554 (catch 'ex
10555 (while t
10556 (when (setq tmp (org-entry-get nil property))
10557 (org-back-to-heading t)
10558 (move-marker org-entry-property-inherited-from (point))
10559 (throw 'ex tmp))
10560 (or (org-up-heading-safe) (throw 'ex nil)))))
10561 (or tmp
10562 (cdr (assoc property org-file-properties))
10563 (cdr (assoc property org-global-properties))
10564 (cdr (assoc property org-global-properties-fixed))))))
10566 (defun org-entry-put (pom property value)
10567 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10568 (org-with-point-at pom
10569 (org-back-to-heading t)
10570 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10571 range)
10572 (cond
10573 ((equal property "TODO")
10574 (when (and (stringp value) (string-match "\\S-" value)
10575 (not (member value org-todo-keywords-1)))
10576 (error "\"%s\" is not a valid TODO state" value))
10577 (if (or (not value)
10578 (not (string-match "\\S-" value)))
10579 (setq value 'none))
10580 (org-todo value)
10581 (org-set-tags nil 'align))
10582 ((equal property "PRIORITY")
10583 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10584 (string-to-char value) ?\ ))
10585 (org-set-tags nil 'align))
10586 ((equal property "SCHEDULED")
10587 (if (re-search-forward org-scheduled-time-regexp end t)
10588 (cond
10589 ((eq value 'earlier) (org-timestamp-change -1 'day))
10590 ((eq value 'later) (org-timestamp-change 1 'day))
10591 (t (call-interactively 'org-schedule)))
10592 (call-interactively 'org-schedule)))
10593 ((equal property "DEADLINE")
10594 (if (re-search-forward org-deadline-time-regexp end t)
10595 (cond
10596 ((eq value 'earlier) (org-timestamp-change -1 'day))
10597 ((eq value 'later) (org-timestamp-change 1 'day))
10598 (t (call-interactively 'org-deadline)))
10599 (call-interactively 'org-deadline)))
10600 ((member property org-special-properties)
10601 (error "The %s property can not yet be set with `org-entry-put'"
10602 property))
10603 (t ; a non-special property
10604 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10605 (setq range (org-get-property-block beg end 'force))
10606 (goto-char (car range))
10607 (if (re-search-forward
10608 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10609 (progn
10610 (delete-region (match-beginning 1) (match-end 1))
10611 (goto-char (match-beginning 1)))
10612 (goto-char (cdr range))
10613 (insert "\n")
10614 (backward-char 1)
10615 (org-indent-line-function)
10616 (insert ":" property ":"))
10617 (and value (insert " " value))
10618 (org-indent-line-function)))))))
10620 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10621 "Get all property keys in the current buffer.
10622 With INCLUDE-SPECIALS, also list the special properties that reflect things
10623 like tags and TODO state.
10624 With INCLUDE-DEFAULTS, also include properties that has special meaning
10625 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10626 With INCLUDE-COLUMNS, also include property names given in COLUMN
10627 formats in the current buffer."
10628 (let (rtn range cfmt s p)
10629 (save-excursion
10630 (save-restriction
10631 (widen)
10632 (goto-char (point-min))
10633 (while (re-search-forward org-property-start-re nil t)
10634 (setq range (org-get-property-block))
10635 (goto-char (car range))
10636 (while (re-search-forward
10637 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10638 (cdr range) t)
10639 (add-to-list 'rtn (org-match-string-no-properties 1)))
10640 (outline-next-heading))))
10642 (when include-specials
10643 (setq rtn (append org-special-properties rtn)))
10645 (when include-defaults
10646 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10648 (when include-columns
10649 (save-excursion
10650 (save-restriction
10651 (widen)
10652 (goto-char (point-min))
10653 (while (re-search-forward
10654 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10655 nil t)
10656 (setq cfmt (match-string 2) s 0)
10657 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10658 cfmt s)
10659 (setq s (match-end 0)
10660 p (match-string 1 cfmt))
10661 (unless (or (equal p "ITEM")
10662 (member p org-special-properties))
10663 (add-to-list 'rtn (match-string 1 cfmt))))))))
10665 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10667 (defun org-property-values (key)
10668 "Return a list of all values of property KEY."
10669 (save-excursion
10670 (save-restriction
10671 (widen)
10672 (goto-char (point-min))
10673 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10674 values)
10675 (while (re-search-forward re nil t)
10676 (add-to-list 'values (org-trim (match-string 1))))
10677 (delete "" values)))))
10679 (defun org-insert-property-drawer ()
10680 "Insert a property drawer into the current entry."
10681 (interactive)
10682 (org-back-to-heading t)
10683 (looking-at outline-regexp)
10684 (let ((indent (- (match-end 0)(match-beginning 0)))
10685 (beg (point))
10686 (re (concat "^[ \t]*" org-keyword-time-regexp))
10687 end hiddenp)
10688 (outline-next-heading)
10689 (setq end (point))
10690 (goto-char beg)
10691 (while (re-search-forward re end t))
10692 (setq hiddenp (org-invisible-p))
10693 (end-of-line 1)
10694 (and (equal (char-after) ?\n) (forward-char 1))
10695 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10696 (beginning-of-line 2))
10697 (org-skip-over-state-notes)
10698 (skip-chars-backward " \t\n\r")
10699 (if (eq (char-before) ?*) (forward-char 1))
10700 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10701 (beginning-of-line 0)
10702 (org-indent-to-column indent)
10703 (beginning-of-line 2)
10704 (org-indent-to-column indent)
10705 (beginning-of-line 0)
10706 (if hiddenp
10707 (save-excursion
10708 (org-back-to-heading t)
10709 (hide-entry))
10710 (org-flag-drawer t))))
10712 (defun org-set-property (property value)
10713 "In the current entry, set PROPERTY to VALUE.
10714 When called interactively, this will prompt for a property name, offering
10715 completion on existing and default properties. And then it will prompt
10716 for a value, offering completion either on allowed values (via an inherited
10717 xxx_ALL property) or on existing values in other instances of this property
10718 in the current file."
10719 (interactive
10720 (let* ((completion-ignore-case t)
10721 (keys (org-buffer-property-keys nil t t))
10722 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10723 (prop (if (member prop0 keys)
10724 prop0
10725 (or (cdr (assoc (downcase prop0)
10726 (mapcar (lambda (x) (cons (downcase x) x))
10727 keys)))
10728 prop0)))
10729 (cur (org-entry-get nil prop))
10730 (allowed (org-property-get-allowed-values nil prop 'table))
10731 (existing (mapcar 'list (org-property-values prop)))
10732 (val (if allowed
10733 (org-completing-read "Value: " allowed nil 'req-match)
10734 (org-completing-read
10735 (concat "Value" (if (and cur (string-match "\\S-" cur))
10736 (concat "[" cur "]") "")
10737 ": ")
10738 existing nil nil "" nil cur))))
10739 (list prop (if (equal val "") cur val))))
10740 (unless (equal (org-entry-get nil property) value)
10741 (org-entry-put nil property value)))
10743 (defun org-delete-property (property)
10744 "In the current entry, delete PROPERTY."
10745 (interactive
10746 (let* ((completion-ignore-case t)
10747 (prop (org-ido-completing-read
10748 "Property: " (org-entry-properties nil 'standard))))
10749 (list prop)))
10750 (message "Property %s %s" property
10751 (if (org-entry-delete nil property)
10752 "deleted"
10753 "was not present in the entry")))
10755 (defun org-delete-property-globally (property)
10756 "Remove PROPERTY globally, from all entries."
10757 (interactive
10758 (let* ((completion-ignore-case t)
10759 (prop (org-ido-completing-read
10760 "Globally remove property: "
10761 (mapcar 'list (org-buffer-property-keys)))))
10762 (list prop)))
10763 (save-excursion
10764 (save-restriction
10765 (widen)
10766 (goto-char (point-min))
10767 (let ((cnt 0))
10768 (while (re-search-forward
10769 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10770 nil t)
10771 (setq cnt (1+ cnt))
10772 (replace-match ""))
10773 (message "Property \"%s\" removed from %d entries" property cnt)))))
10775 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10777 (defun org-compute-property-at-point ()
10778 "Compute the property at point.
10779 This looks for an enclosing column format, extracts the operator and
10780 then applies it to the property in the column format's scope."
10781 (interactive)
10782 (unless (org-at-property-p)
10783 (error "Not at a property"))
10784 (let ((prop (org-match-string-no-properties 2)))
10785 (org-columns-get-format-and-top-level)
10786 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10787 (error "No operator defined for property %s" prop))
10788 (org-columns-compute prop)))
10790 (defun org-property-get-allowed-values (pom property &optional table)
10791 "Get allowed values for the property PROPERTY.
10792 When TABLE is non-nil, return an alist that can directly be used for
10793 completion."
10794 (let (vals)
10795 (cond
10796 ((equal property "TODO")
10797 (setq vals (org-with-point-at pom
10798 (append org-todo-keywords-1 '("")))))
10799 ((equal property "PRIORITY")
10800 (let ((n org-lowest-priority))
10801 (while (>= n org-highest-priority)
10802 (push (char-to-string n) vals)
10803 (setq n (1- n)))))
10804 ((member property org-special-properties))
10806 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10808 (when (and vals (string-match "\\S-" vals))
10809 (setq vals (car (read-from-string (concat "(" vals ")"))))
10810 (setq vals (mapcar (lambda (x)
10811 (cond ((stringp x) x)
10812 ((numberp x) (number-to-string x))
10813 ((symbolp x) (symbol-name x))
10814 (t "???")))
10815 vals)))))
10816 (if table (mapcar 'list vals) vals)))
10818 (defun org-property-previous-allowed-value (&optional previous)
10819 "Switch to the next allowed value for this property."
10820 (interactive)
10821 (org-property-next-allowed-value t))
10823 (defun org-property-next-allowed-value (&optional previous)
10824 "Switch to the next allowed value for this property."
10825 (interactive)
10826 (unless (org-at-property-p)
10827 (error "Not at a property"))
10828 (let* ((key (match-string 2))
10829 (value (match-string 3))
10830 (allowed (or (org-property-get-allowed-values (point) key)
10831 (and (member value '("[ ]" "[-]" "[X]"))
10832 '("[ ]" "[X]"))))
10833 nval)
10834 (unless allowed
10835 (error "Allowed values for this property have not been defined"))
10836 (if previous (setq allowed (reverse allowed)))
10837 (if (member value allowed)
10838 (setq nval (car (cdr (member value allowed)))))
10839 (setq nval (or nval (car allowed)))
10840 (if (equal nval value)
10841 (error "Only one allowed value for this property"))
10842 (org-at-property-p)
10843 (replace-match (concat " :" key ": " nval) t t)
10844 (org-indent-line-function)
10845 (beginning-of-line 1)
10846 (skip-chars-forward " \t")))
10848 (defun org-find-entry-with-id (ident)
10849 "Locate the entry that contains the ID property with exact value IDENT.
10850 IDENT can be a string, a symbol or a number, this function will search for
10851 the string representation of it.
10852 Return the position where this entry starts, or nil if there is no such entry."
10853 (interactive "sID: ")
10854 (let ((id (cond
10855 ((stringp ident) ident)
10856 ((symbol-name ident) (symbol-name ident))
10857 ((numberp ident) (number-to-string ident))
10858 (t (error "IDENT %s must be a string, symbol or number" ident))))
10859 (case-fold-search nil))
10860 (save-excursion
10861 (save-restriction
10862 (widen)
10863 (goto-char (point-min))
10864 (when (re-search-forward
10865 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10866 nil t)
10867 (org-back-to-heading)
10868 (point))))))
10870 ;;;; Timestamps
10872 (defvar org-last-changed-timestamp nil)
10873 (defvar org-last-inserted-timestamp nil
10874 "The last time stamp inserted with `org-insert-time-stamp'.")
10875 (defvar org-time-was-given) ; dynamically scoped parameter
10876 (defvar org-end-time-was-given) ; dynamically scoped parameter
10877 (defvar org-ts-what) ; dynamically scoped parameter
10879 (defun org-time-stamp (arg &optional inactive)
10880 "Prompt for a date/time and insert a time stamp.
10881 If the user specifies a time like HH:MM, or if this command is called
10882 with a prefix argument, the time stamp will contain date and time.
10883 Otherwise, only the date will be included. All parts of a date not
10884 specified by the user will be filled in from the current date/time.
10885 So if you press just return without typing anything, the time stamp
10886 will represent the current date/time. If there is already a timestamp
10887 at the cursor, it will be modified."
10888 (interactive "P")
10889 (let* ((ts nil)
10890 (default-time
10891 ;; Default time is either today, or, when entering a range,
10892 ;; the range start.
10893 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10894 (save-excursion
10895 (re-search-backward
10896 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10897 (- (point) 20) t)))
10898 (apply 'encode-time (org-parse-time-string (match-string 1)))
10899 (current-time)))
10900 (default-input (and ts (org-get-compact-tod ts)))
10901 org-time-was-given org-end-time-was-given time)
10902 (cond
10903 ((and (org-at-timestamp-p t)
10904 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10905 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10906 (insert "--")
10907 (setq time (let ((this-command this-command))
10908 (org-read-date arg 'totime nil nil
10909 default-time default-input)))
10910 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10911 ((org-at-timestamp-p t)
10912 (setq time (let ((this-command this-command))
10913 (org-read-date arg 'totime nil nil default-time default-input)))
10914 (when (org-at-timestamp-p t) ; just to get the match data
10915 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10916 (replace-match "")
10917 (setq org-last-changed-timestamp
10918 (org-insert-time-stamp
10919 time (or org-time-was-given arg)
10920 inactive nil nil (list org-end-time-was-given))))
10921 (message "Timestamp updated"))
10923 (setq time (let ((this-command this-command))
10924 (org-read-date arg 'totime nil nil default-time default-input)))
10925 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10926 nil nil (list org-end-time-was-given))))))
10928 ;; FIXME: can we use this for something else, like computing time differences?
10929 (defun org-get-compact-tod (s)
10930 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10931 (let* ((t1 (match-string 1 s))
10932 (h1 (string-to-number (match-string 2 s)))
10933 (m1 (string-to-number (match-string 3 s)))
10934 (t2 (and (match-end 4) (match-string 5 s)))
10935 (h2 (and t2 (string-to-number (match-string 6 s))))
10936 (m2 (and t2 (string-to-number (match-string 7 s))))
10937 dh dm)
10938 (if (not t2)
10940 (setq dh (- h2 h1) dm (- m2 m1))
10941 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10942 (concat t1 "+" (number-to-string dh)
10943 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10945 (defun org-time-stamp-inactive (&optional arg)
10946 "Insert an inactive time stamp.
10947 An inactive time stamp is enclosed in square brackets instead of angle
10948 brackets. It is inactive in the sense that it does not trigger agenda entries,
10949 does not link to the calendar and cannot be changed with the S-cursor keys.
10950 So these are more for recording a certain time/date."
10951 (interactive "P")
10952 (org-time-stamp arg 'inactive))
10954 (defvar org-date-ovl (org-make-overlay 1 1))
10955 (org-overlay-put org-date-ovl 'face 'org-warning)
10956 (org-detach-overlay org-date-ovl)
10958 (defvar org-ans1) ; dynamically scoped parameter
10959 (defvar org-ans2) ; dynamically scoped parameter
10961 (defvar org-plain-time-of-day-regexp) ; defined below
10963 (defvar org-overriding-default-time nil) ; dynamically scoped
10964 (defvar org-read-date-overlay nil)
10965 (defvar org-dcst nil) ; dynamically scoped
10967 (defun org-read-date (&optional with-time to-time from-string prompt
10968 default-time default-input)
10969 "Read a date, possibly a time, and make things smooth for the user.
10970 The prompt will suggest to enter an ISO date, but you can also enter anything
10971 which will at least partially be understood by `parse-time-string'.
10972 Unrecognized parts of the date will default to the current day, month, year,
10973 hour and minute. If this command is called to replace a timestamp at point,
10974 of to enter the second timestamp of a range, the default time is taken from the
10975 existing stamp. For example,
10976 3-2-5 --> 2003-02-05
10977 feb 15 --> currentyear-02-15
10978 sep 12 9 --> 2009-09-12
10979 12:45 --> today 12:45
10980 22 sept 0:34 --> currentyear-09-22 0:34
10981 12 --> currentyear-currentmonth-12
10982 Fri --> nearest Friday (today or later)
10983 etc.
10985 Furthermore you can specify a relative date by giving, as the *first* thing
10986 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10987 change in days weeks, months, years.
10988 With a single plus or minus, the date is relative to today. With a double
10989 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10990 +4d --> four days from today
10991 +4 --> same as above
10992 +2w --> two weeks from today
10993 ++5 --> five days from default date
10995 The function understands only English month and weekday abbreviations,
10996 but this can be configured with the variables `parse-time-months' and
10997 `parse-time-weekdays'.
10999 While prompting, a calendar is popped up - you can also select the
11000 date with the mouse (button 1). The calendar shows a period of three
11001 months. To scroll it to other months, use the keys `>' and `<'.
11002 If you don't like the calendar, turn it off with
11003 \(setq org-read-date-popup-calendar nil)
11005 With optional argument TO-TIME, the date will immediately be converted
11006 to an internal time.
11007 With an optional argument WITH-TIME, the prompt will suggest to also
11008 insert a time. Note that when WITH-TIME is not set, you can still
11009 enter a time, and this function will inform the calling routine about
11010 this change. The calling routine may then choose to change the format
11011 used to insert the time stamp into the buffer to include the time.
11012 With optional argument FROM-STRING, read from this string instead from
11013 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11014 the time/date that is used for everything that is not specified by the
11015 user."
11016 (require 'parse-time)
11017 (let* ((org-time-stamp-rounding-minutes
11018 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11019 (org-dcst org-display-custom-times)
11020 (ct (org-current-time))
11021 (def (or org-overriding-default-time default-time ct))
11022 (defdecode (decode-time def))
11023 (dummy (progn
11024 (when (< (nth 2 defdecode) org-extend-today-until)
11025 (setcar (nthcdr 2 defdecode) -1)
11026 (setcar (nthcdr 1 defdecode) 59)
11027 (setq def (apply 'encode-time defdecode)
11028 defdecode (decode-time def)))))
11029 (calendar-move-hook nil)
11030 (calendar-view-diary-initially-flag nil)
11031 (view-diary-entries-initially nil)
11032 (calendar-view-holidays-initially-flag nil)
11033 (view-calendar-holidays-initially nil)
11034 (timestr (format-time-string
11035 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11036 (prompt (concat (if prompt (concat prompt " ") "")
11037 (format "Date+time [%s]: " timestr)))
11038 ans (org-ans0 "") org-ans1 org-ans2 final)
11040 (cond
11041 (from-string (setq ans from-string))
11042 (org-read-date-popup-calendar
11043 (save-excursion
11044 (save-window-excursion
11045 (calendar)
11046 (calendar-forward-day (- (time-to-days def)
11047 (calendar-absolute-from-gregorian
11048 (calendar-current-date))))
11049 (org-eval-in-calendar nil t)
11050 (let* ((old-map (current-local-map))
11051 (map (copy-keymap calendar-mode-map))
11052 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11053 (org-defkey map (kbd "RET") 'org-calendar-select)
11054 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11055 'org-calendar-select-mouse)
11056 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11057 'org-calendar-select-mouse)
11058 (org-defkey minibuffer-local-map [(meta shift left)]
11059 (lambda () (interactive)
11060 (org-eval-in-calendar '(calendar-backward-month 1))))
11061 (org-defkey minibuffer-local-map [(meta shift right)]
11062 (lambda () (interactive)
11063 (org-eval-in-calendar '(calendar-forward-month 1))))
11064 (org-defkey minibuffer-local-map [(meta shift up)]
11065 (lambda () (interactive)
11066 (org-eval-in-calendar '(calendar-backward-year 1))))
11067 (org-defkey minibuffer-local-map [(meta shift down)]
11068 (lambda () (interactive)
11069 (org-eval-in-calendar '(calendar-forward-year 1))))
11070 (org-defkey minibuffer-local-map [(shift up)]
11071 (lambda () (interactive)
11072 (org-eval-in-calendar '(calendar-backward-week 1))))
11073 (org-defkey minibuffer-local-map [(shift down)]
11074 (lambda () (interactive)
11075 (org-eval-in-calendar '(calendar-forward-week 1))))
11076 (org-defkey minibuffer-local-map [(shift left)]
11077 (lambda () (interactive)
11078 (org-eval-in-calendar '(calendar-backward-day 1))))
11079 (org-defkey minibuffer-local-map [(shift right)]
11080 (lambda () (interactive)
11081 (org-eval-in-calendar '(calendar-forward-day 1))))
11082 (org-defkey minibuffer-local-map ">"
11083 (lambda () (interactive)
11084 (org-eval-in-calendar '(scroll-calendar-left 1))))
11085 (org-defkey minibuffer-local-map "<"
11086 (lambda () (interactive)
11087 (org-eval-in-calendar '(scroll-calendar-right 1))))
11088 (unwind-protect
11089 (progn
11090 (use-local-map map)
11091 (add-hook 'post-command-hook 'org-read-date-display)
11092 (setq org-ans0 (read-string prompt default-input nil nil))
11093 ;; org-ans0: from prompt
11094 ;; org-ans1: from mouse click
11095 ;; org-ans2: from calendar motion
11096 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11097 (remove-hook 'post-command-hook 'org-read-date-display)
11098 (use-local-map old-map)
11099 (when org-read-date-overlay
11100 (org-delete-overlay org-read-date-overlay)
11101 (setq org-read-date-overlay nil)))))))
11103 (t ; Naked prompt only
11104 (unwind-protect
11105 (setq ans (read-string prompt default-input nil timestr))
11106 (when org-read-date-overlay
11107 (org-delete-overlay org-read-date-overlay)
11108 (setq org-read-date-overlay nil)))))
11110 (setq final (org-read-date-analyze ans def defdecode))
11112 (if to-time
11113 (apply 'encode-time final)
11114 (if (and (boundp 'org-time-was-given) org-time-was-given)
11115 (format "%04d-%02d-%02d %02d:%02d"
11116 (nth 5 final) (nth 4 final) (nth 3 final)
11117 (nth 2 final) (nth 1 final))
11118 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11119 (defvar def)
11120 (defvar defdecode)
11121 (defvar with-time)
11122 (defun org-read-date-display ()
11123 "Display the current date prompt interpretation in the minibuffer."
11124 (when org-read-date-display-live
11125 (when org-read-date-overlay
11126 (org-delete-overlay org-read-date-overlay))
11127 (let ((p (point)))
11128 (end-of-line 1)
11129 (while (not (equal (buffer-substring
11130 (max (point-min) (- (point) 4)) (point))
11131 " "))
11132 (insert " "))
11133 (goto-char p))
11134 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11135 " " (or org-ans1 org-ans2)))
11136 (org-end-time-was-given nil)
11137 (f (org-read-date-analyze ans def defdecode))
11138 (fmts (if org-dcst
11139 org-time-stamp-custom-formats
11140 org-time-stamp-formats))
11141 (fmt (if (or with-time
11142 (and (boundp 'org-time-was-given) org-time-was-given))
11143 (cdr fmts)
11144 (car fmts)))
11145 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11146 (when (and org-end-time-was-given
11147 (string-match org-plain-time-of-day-regexp txt))
11148 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11149 org-end-time-was-given
11150 (substring txt (match-end 0)))))
11151 (setq org-read-date-overlay
11152 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11153 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11155 (defun org-read-date-analyze (ans def defdecode)
11156 "Analyse the combined answer of the date prompt."
11157 ;; FIXME: cleanup and comment
11158 (let (delta deltan deltaw deltadef year month day
11159 hour minute second wday pm h2 m2 tl wday1
11160 iso-year iso-weekday iso-week iso-year iso-date)
11162 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11163 (setq ans "+0"))
11165 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11166 (setq ans (replace-match "" t t ans)
11167 deltan (car delta)
11168 deltaw (nth 1 delta)
11169 deltadef (nth 2 delta)))
11171 ;; Check if there is an iso week date in there
11172 ;; If yes, sore the info and postpone interpreting it until the rest
11173 ;; of the parsing is done
11174 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11175 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11176 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11177 iso-week (string-to-number (match-string 2 ans)))
11178 (setq ans (replace-match "" t t ans)))
11180 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11181 (when (string-match
11182 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11183 (setq year (if (match-end 2)
11184 (string-to-number (match-string 2 ans))
11185 (string-to-number (format-time-string "%Y")))
11186 month (string-to-number (match-string 3 ans))
11187 day (string-to-number (match-string 4 ans)))
11188 (if (< year 100) (setq year (+ 2000 year)))
11189 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11190 t nil ans)))
11191 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11192 ;; If there is a time with am/pm, and *no* time without it, we convert
11193 ;; so that matching will be successful.
11194 (loop for i from 1 to 2 do ; twice, for end time as well
11195 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11196 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11197 (setq hour (string-to-number (match-string 1 ans))
11198 minute (if (match-end 3)
11199 (string-to-number (match-string 3 ans))
11201 pm (equal ?p
11202 (string-to-char (downcase (match-string 4 ans)))))
11203 (if (and (= hour 12) (not pm))
11204 (setq hour 0)
11205 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11206 (setq ans (replace-match (format "%02d:%02d" hour minute)
11207 t t ans))))
11209 ;; Check if a time range is given as a duration
11210 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11211 (setq hour (string-to-number (match-string 1 ans))
11212 h2 (+ hour (string-to-number (match-string 3 ans)))
11213 minute (string-to-number (match-string 2 ans))
11214 m2 (+ minute (if (match-end 5) (string-to-number
11215 (match-string 5 ans))0)))
11216 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11217 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11218 t t ans)))
11220 ;; Check if there is a time range
11221 (when (boundp 'org-end-time-was-given)
11222 (setq org-time-was-given nil)
11223 (when (and (string-match org-plain-time-of-day-regexp ans)
11224 (match-end 8))
11225 (setq org-end-time-was-given (match-string 8 ans))
11226 (setq ans (concat (substring ans 0 (match-beginning 7))
11227 (substring ans (match-end 7))))))
11229 (setq tl (parse-time-string ans)
11230 day (or (nth 3 tl) (nth 3 defdecode))
11231 month (or (nth 4 tl)
11232 (if (and org-read-date-prefer-future
11233 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11234 (1+ (nth 4 defdecode))
11235 (nth 4 defdecode)))
11236 year (or (nth 5 tl)
11237 (if (and org-read-date-prefer-future
11238 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11239 (1+ (nth 5 defdecode))
11240 (nth 5 defdecode)))
11241 hour (or (nth 2 tl) (nth 2 defdecode))
11242 minute (or (nth 1 tl) (nth 1 defdecode))
11243 second (or (nth 0 tl) 0)
11244 wday (nth 6 tl))
11246 ;; Special date definitions below
11247 (cond
11248 (iso-week
11249 ;; There was an iso week
11250 (setq year (or iso-year year)
11251 day (or iso-weekday wday 1)
11252 wday nil ; to make sure that the trigger below does not match
11253 iso-date (calendar-gregorian-from-absolute
11254 (calendar-absolute-from-iso
11255 (list iso-week day year))))
11256 ; FIXME: Should we also push ISO weeks into the future?
11257 ; (when (and org-read-date-prefer-future
11258 ; (not iso-year)
11259 ; (< (calendar-absolute-from-gregorian iso-date)
11260 ; (time-to-days (current-time))))
11261 ; (setq year (1+ year)
11262 ; iso-date (calendar-gregorian-from-absolute
11263 ; (calendar-absolute-from-iso
11264 ; (list iso-week day year)))))
11265 (setq month (car iso-date)
11266 year (nth 2 iso-date)
11267 day (nth 1 iso-date)))
11268 (deltan
11269 (unless deltadef
11270 (let ((now (decode-time (current-time))))
11271 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11272 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11273 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11274 ((equal deltaw "m") (setq month (+ month deltan)))
11275 ((equal deltaw "y") (setq year (+ year deltan)))))
11276 ((and wday (not (nth 3 tl)))
11277 ;; Weekday was given, but no day, so pick that day in the week
11278 ;; on or after the derived date.
11279 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11280 (unless (equal wday wday1)
11281 (setq day (+ day (% (- wday wday1 -7) 7))))))
11282 (if (and (boundp 'org-time-was-given)
11283 (nth 2 tl))
11284 (setq org-time-was-given t))
11285 (if (< year 100) (setq year (+ 2000 year)))
11286 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11287 (list second minute hour day month year)))
11289 (defvar parse-time-weekdays)
11291 (defun org-read-date-get-relative (s today default)
11292 "Check string S for special relative date string.
11293 TODAY and DEFAULT are internal times, for today and for a default.
11294 Return shift list (N what def-flag)
11295 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11296 N is the number of WHATs to shift.
11297 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11298 the DEFAULT date rather than TODAY."
11299 (when (and
11300 (string-match
11301 (concat
11302 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11303 "\\([0-9]+\\)?"
11304 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11305 "\\([ \t]\\|$\\)") s)
11306 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11307 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11308 (string-to-char (substring (match-string 1 s) -1))
11309 ?+))
11310 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11311 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11312 (what (if (match-end 3) (match-string 3 s) "d"))
11313 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11314 (date (if rel default today))
11315 (wday (nth 6 (decode-time date)))
11316 delta)
11317 (if wday1
11318 (progn
11319 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11320 (if (= dir ?-) (setq delta (- delta 7)))
11321 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11322 (list delta "d" rel))
11323 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11325 (defun org-eval-in-calendar (form &optional keepdate)
11326 "Eval FORM in the calendar window and return to current window.
11327 Also, store the cursor date in variable org-ans2."
11328 (let ((sw (selected-window)))
11329 (select-window (get-buffer-window "*Calendar*"))
11330 (eval form)
11331 (when (and (not keepdate) (calendar-cursor-to-date))
11332 (let* ((date (calendar-cursor-to-date))
11333 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11334 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11335 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11336 (select-window sw)))
11338 (defun org-calendar-select ()
11339 "Return to `org-read-date' with the date currently selected.
11340 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11341 (interactive)
11342 (when (calendar-cursor-to-date)
11343 (let* ((date (calendar-cursor-to-date))
11344 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11345 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11346 (if (active-minibuffer-window) (exit-minibuffer))))
11348 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11349 "Insert a date stamp for the date given by the internal TIME.
11350 WITH-HM means, use the stamp format that includes the time of the day.
11351 INACTIVE means use square brackets instead of angular ones, so that the
11352 stamp will not contribute to the agenda.
11353 PRE and POST are optional strings to be inserted before and after the
11354 stamp.
11355 The command returns the inserted time stamp."
11356 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11357 stamp)
11358 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11359 (insert-before-markers (or pre ""))
11360 (insert-before-markers (setq stamp (format-time-string fmt time)))
11361 (when (listp extra)
11362 (setq extra (car extra))
11363 (if (and (stringp extra)
11364 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11365 (setq extra (format "-%02d:%02d"
11366 (string-to-number (match-string 1 extra))
11367 (string-to-number (match-string 2 extra))))
11368 (setq extra nil)))
11369 (when extra
11370 (backward-char 1)
11371 (insert-before-markers extra)
11372 (forward-char 1))
11373 (insert-before-markers (or post ""))
11374 (setq org-last-inserted-timestamp stamp)))
11376 (defun org-toggle-time-stamp-overlays ()
11377 "Toggle the use of custom time stamp formats."
11378 (interactive)
11379 (setq org-display-custom-times (not org-display-custom-times))
11380 (unless org-display-custom-times
11381 (let ((p (point-min)) (bmp (buffer-modified-p)))
11382 (while (setq p (next-single-property-change p 'display))
11383 (if (and (get-text-property p 'display)
11384 (eq (get-text-property p 'face) 'org-date))
11385 (remove-text-properties
11386 p (setq p (next-single-property-change p 'display))
11387 '(display t))))
11388 (set-buffer-modified-p bmp)))
11389 (if (featurep 'xemacs)
11390 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11391 (org-restart-font-lock)
11392 (setq org-table-may-need-update t)
11393 (if org-display-custom-times
11394 (message "Time stamps are overlayed with custom format")
11395 (message "Time stamp overlays removed")))
11397 (defun org-display-custom-time (beg end)
11398 "Overlay modified time stamp format over timestamp between BEG and END."
11399 (let* ((ts (buffer-substring beg end))
11400 t1 w1 with-hm tf time str w2 (off 0))
11401 (save-match-data
11402 (setq t1 (org-parse-time-string ts t))
11403 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11404 (setq off (- (match-end 0) (match-beginning 0)))))
11405 (setq end (- end off))
11406 (setq w1 (- end beg)
11407 with-hm (and (nth 1 t1) (nth 2 t1))
11408 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11409 time (org-fix-decoded-time t1)
11410 str (org-add-props
11411 (format-time-string
11412 (substring tf 1 -1) (apply 'encode-time time))
11413 nil 'mouse-face 'highlight)
11414 w2 (length str))
11415 (if (not (= w2 w1))
11416 (add-text-properties (1+ beg) (+ 2 beg)
11417 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11418 (if (featurep 'xemacs)
11419 (progn
11420 (put-text-property beg end 'invisible t)
11421 (put-text-property beg end 'end-glyph (make-glyph str)))
11422 (put-text-property beg end 'display str))))
11424 (defun org-translate-time (string)
11425 "Translate all timestamps in STRING to custom format.
11426 But do this only if the variable `org-display-custom-times' is set."
11427 (when org-display-custom-times
11428 (save-match-data
11429 (let* ((start 0)
11430 (re org-ts-regexp-both)
11431 t1 with-hm inactive tf time str beg end)
11432 (while (setq start (string-match re string start))
11433 (setq beg (match-beginning 0)
11434 end (match-end 0)
11435 t1 (save-match-data
11436 (org-parse-time-string (substring string beg end) t))
11437 with-hm (and (nth 1 t1) (nth 2 t1))
11438 inactive (equal (substring string beg (1+ beg)) "[")
11439 tf (funcall (if with-hm 'cdr 'car)
11440 org-time-stamp-custom-formats)
11441 time (org-fix-decoded-time t1)
11442 str (format-time-string
11443 (concat
11444 (if inactive "[" "<") (substring tf 1 -1)
11445 (if inactive "]" ">"))
11446 (apply 'encode-time time))
11447 string (replace-match str t t string)
11448 start (+ start (length str)))))))
11449 string)
11451 (defun org-fix-decoded-time (time)
11452 "Set 0 instead of nil for the first 6 elements of time.
11453 Don't touch the rest."
11454 (let ((n 0))
11455 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11457 (defun org-days-to-time (timestamp-string)
11458 "Difference between TIMESTAMP-STRING and now in days."
11459 (- (time-to-days (org-time-string-to-time timestamp-string))
11460 (time-to-days (current-time))))
11462 (defun org-deadline-close (timestamp-string &optional ndays)
11463 "Is the time in TIMESTAMP-STRING close to the current date?"
11464 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11465 (and (< (org-days-to-time timestamp-string) ndays)
11466 (not (org-entry-is-done-p))))
11468 (defun org-get-wdays (ts)
11469 "Get the deadline lead time appropriate for timestring TS."
11470 (cond
11471 ((<= org-deadline-warning-days 0)
11472 ;; 0 or negative, enforce this value no matter what
11473 (- org-deadline-warning-days))
11474 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11475 ;; lead time is specified.
11476 (floor (* (string-to-number (match-string 1 ts))
11477 (cdr (assoc (match-string 2 ts)
11478 '(("d" . 1) ("w" . 7)
11479 ("m" . 30.4) ("y" . 365.25)))))))
11480 ;; go for the default.
11481 (t org-deadline-warning-days)))
11483 (defun org-calendar-select-mouse (ev)
11484 "Return to `org-read-date' with the date currently selected.
11485 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11486 (interactive "e")
11487 (mouse-set-point ev)
11488 (when (calendar-cursor-to-date)
11489 (let* ((date (calendar-cursor-to-date))
11490 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11491 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11492 (if (active-minibuffer-window) (exit-minibuffer))))
11494 (defun org-check-deadlines (ndays)
11495 "Check if there are any deadlines due or past due.
11496 A deadline is considered due if it happens within `org-deadline-warning-days'
11497 days from today's date. If the deadline appears in an entry marked DONE,
11498 it is not shown. The prefix arg NDAYS can be used to test that many
11499 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11500 (interactive "P")
11501 (let* ((org-warn-days
11502 (cond
11503 ((equal ndays '(4)) 100000)
11504 (ndays (prefix-numeric-value ndays))
11505 (t (abs org-deadline-warning-days))))
11506 (case-fold-search nil)
11507 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11508 (callback
11509 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11511 (message "%d deadlines past-due or due within %d days"
11512 (org-occur regexp nil callback)
11513 org-warn-days)))
11515 (defun org-check-before-date (date)
11516 "Check if there are deadlines or scheduled entries before DATE."
11517 (interactive (list (org-read-date)))
11518 (let ((case-fold-search nil)
11519 (regexp (concat "\\<\\(" org-deadline-string
11520 "\\|" org-scheduled-string
11521 "\\) *<\\([^>]+\\)>"))
11522 (callback
11523 (lambda () (time-less-p
11524 (org-time-string-to-time (match-string 2))
11525 (org-time-string-to-time date)))))
11526 (message "%d entries before %s"
11527 (org-occur regexp nil callback) date)))
11529 (defun org-evaluate-time-range (&optional to-buffer)
11530 "Evaluate a time range by computing the difference between start and end.
11531 Normally the result is just printed in the echo area, but with prefix arg
11532 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11533 If the time range is actually in a table, the result is inserted into the
11534 next column.
11535 For time difference computation, a year is assumed to be exactly 365
11536 days in order to avoid rounding problems."
11537 (interactive "P")
11539 (org-clock-update-time-maybe)
11540 (save-excursion
11541 (unless (org-at-date-range-p t)
11542 (goto-char (point-at-bol))
11543 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11544 (if (not (org-at-date-range-p t))
11545 (error "Not at a time-stamp range, and none found in current line")))
11546 (let* ((ts1 (match-string 1))
11547 (ts2 (match-string 2))
11548 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11549 (match-end (match-end 0))
11550 (time1 (org-time-string-to-time ts1))
11551 (time2 (org-time-string-to-time ts2))
11552 (t1 (time-to-seconds time1))
11553 (t2 (time-to-seconds time2))
11554 (diff (abs (- t2 t1)))
11555 (negative (< (- t2 t1) 0))
11556 ;; (ys (floor (* 365 24 60 60)))
11557 (ds (* 24 60 60))
11558 (hs (* 60 60))
11559 (fy "%dy %dd %02d:%02d")
11560 (fy1 "%dy %dd")
11561 (fd "%dd %02d:%02d")
11562 (fd1 "%dd")
11563 (fh "%02d:%02d")
11564 y d h m align)
11565 (if havetime
11566 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11568 d (floor (/ diff ds)) diff (mod diff ds)
11569 h (floor (/ diff hs)) diff (mod diff hs)
11570 m (floor (/ diff 60)))
11571 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11573 d (floor (+ (/ diff ds) 0.5))
11574 h 0 m 0))
11575 (if (not to-buffer)
11576 (message "%s" (org-make-tdiff-string y d h m))
11577 (if (org-at-table-p)
11578 (progn
11579 (goto-char match-end)
11580 (setq align t)
11581 (and (looking-at " *|") (goto-char (match-end 0))))
11582 (goto-char match-end))
11583 (if (looking-at
11584 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11585 (replace-match ""))
11586 (if negative (insert " -"))
11587 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11588 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11589 (insert " " (format fh h m))))
11590 (if align (org-table-align))
11591 (message "Time difference inserted")))))
11593 (defun org-make-tdiff-string (y d h m)
11594 (let ((fmt "")
11595 (l nil))
11596 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11597 l (push y l)))
11598 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11599 l (push d l)))
11600 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11601 l (push h l)))
11602 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11603 l (push m l)))
11604 (apply 'format fmt (nreverse l))))
11606 (defun org-time-string-to-time (s)
11607 (apply 'encode-time (org-parse-time-string s)))
11609 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11610 "Convert a time stamp to an absolute day number.
11611 If there is a specifyer for a cyclic time stamp, get the closest date to
11612 DAYNR.
11613 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11614 (cond
11615 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11616 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11617 daynr
11618 (+ daynr 1000)))
11619 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11620 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11621 (time-to-days (current-time))) (match-string 0 s)
11622 prefer show-all))
11623 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11625 (defun org-days-to-iso-week (days)
11626 "Return the iso week number."
11627 (require 'cal-iso)
11628 (car (calendar-iso-from-absolute days)))
11630 (defun org-small-year-to-year (year)
11631 "Convert 2-digit years into 4-digit years.
11632 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11633 The year 2000 cannot be abbreviated. Any year larger than 99
11634 is returned unchanged."
11635 (if (< year 38)
11636 (setq year (+ 2000 year))
11637 (if (< year 100)
11638 (setq year (+ 1900 year))))
11639 year)
11641 (defun org-time-from-absolute (d)
11642 "Return the time corresponding to date D.
11643 D may be an absolute day number, or a calendar-type list (month day year)."
11644 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11645 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11647 (defun org-calendar-holiday ()
11648 "List of holidays, for Diary display in Org-mode."
11649 (require 'holidays)
11650 (let ((hl (funcall
11651 (if (fboundp 'calendar-check-holidays)
11652 'calendar-check-holidays 'check-calendar-holidays) date)))
11653 (if hl (mapconcat 'identity hl "; "))))
11655 (defun org-diary-sexp-entry (sexp entry date)
11656 "Process a SEXP diary ENTRY for DATE."
11657 (require 'diary-lib)
11658 (let ((result (if calendar-debug-sexp
11659 (let ((stack-trace-on-error t))
11660 (eval (car (read-from-string sexp))))
11661 (condition-case nil
11662 (eval (car (read-from-string sexp)))
11663 (error
11664 (beep)
11665 (message "Bad sexp at line %d in %s: %s"
11666 (org-current-line)
11667 (buffer-file-name) sexp)
11668 (sleep-for 2))))))
11669 (cond ((stringp result) result)
11670 ((and (consp result)
11671 (stringp (cdr result))) (cdr result))
11672 (result entry)
11673 (t nil))))
11675 (defun org-diary-to-ical-string (frombuf)
11676 "Get iCalendar entries from diary entries in buffer FROMBUF.
11677 This uses the icalendar.el library."
11678 (let* ((tmpdir (if (featurep 'xemacs)
11679 (temp-directory)
11680 temporary-file-directory))
11681 (tmpfile (make-temp-name
11682 (expand-file-name "orgics" tmpdir)))
11683 buf rtn b e)
11684 (save-excursion
11685 (set-buffer frombuf)
11686 (icalendar-export-region (point-min) (point-max) tmpfile)
11687 (setq buf (find-buffer-visiting tmpfile))
11688 (set-buffer buf)
11689 (goto-char (point-min))
11690 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11691 (setq b (match-beginning 0)))
11692 (goto-char (point-max))
11693 (if (re-search-backward "^END:VEVENT" nil t)
11694 (setq e (match-end 0)))
11695 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11696 (kill-buffer buf)
11697 (delete-file tmpfile)
11698 rtn))
11700 (defun org-closest-date (start current change prefer show-all)
11701 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11702 When PREFER is `past' return a date that is either CURRENT or past.
11703 When PREFER is `future', return a date that is either CURRENT or future.
11704 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11705 ;; Make the proper lists from the dates
11706 (catch 'exit
11707 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11708 dn dw sday cday n1 n2 n0
11709 d m y y1 y2 date1 date2 nmonths nm ny m2)
11711 (setq start (org-date-to-gregorian start)
11712 current (org-date-to-gregorian
11713 (if show-all
11714 current
11715 (time-to-days (current-time))))
11716 sday (calendar-absolute-from-gregorian start)
11717 cday (calendar-absolute-from-gregorian current))
11719 (if (<= cday sday) (throw 'exit sday))
11721 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11722 (setq dn (string-to-number (match-string 1 change))
11723 dw (cdr (assoc (match-string 2 change) a1)))
11724 (error "Invalid change specifyer: %s" change))
11725 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11726 (cond
11727 ((eq dw 'day)
11728 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11729 n2 (+ n1 dn)))
11730 ((eq dw 'year)
11731 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11732 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11733 (setq date1 (list m d y1)
11734 n1 (calendar-absolute-from-gregorian date1)
11735 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11736 n2 (calendar-absolute-from-gregorian date2)))
11737 ((eq dw 'month)
11738 ;; approx number of month between the two dates
11739 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11740 ;; How often does dn fit in there?
11741 (setq d (nth 1 start) m (car start) y (nth 2 start)
11742 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11743 m (+ m nm)
11744 ny (floor (/ m 12))
11745 y (+ y ny)
11746 m (- m (* ny 12)))
11747 (while (> m 12) (setq m (- m 12) y (1+ y)))
11748 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11749 (setq m2 (+ m dn) y2 y)
11750 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11751 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11752 (while (<= n2 cday)
11753 (setq n1 n2 m m2 y y2)
11754 (setq m2 (+ m dn) y2 y)
11755 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11756 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11757 ;; Make sure n1 is the earlier date
11758 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11759 (if show-all
11760 (cond
11761 ((eq prefer 'past) n1)
11762 ((eq prefer 'future) (if (= cday n1) n1 n2))
11763 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11764 (cond
11765 ((eq prefer 'past) n1)
11766 ((eq prefer 'future) (if (= cday n1) n1 n2))
11767 (t (if (= cday n1) n1 n2)))))))
11769 (defun org-date-to-gregorian (date)
11770 "Turn any specification of DATE into a gregorian date for the calendar."
11771 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11772 ((and (listp date) (= (length date) 3)) date)
11773 ((stringp date)
11774 (setq date (org-parse-time-string date))
11775 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11776 ((listp date)
11777 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11779 (defun org-parse-time-string (s &optional nodefault)
11780 "Parse the standard Org-mode time string.
11781 This should be a lot faster than the normal `parse-time-string'.
11782 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11783 hour and minute fields will be nil if not given."
11784 (if (string-match org-ts-regexp0 s)
11785 (list 0
11786 (if (or (match-beginning 8) (not nodefault))
11787 (string-to-number (or (match-string 8 s) "0")))
11788 (if (or (match-beginning 7) (not nodefault))
11789 (string-to-number (or (match-string 7 s) "0")))
11790 (string-to-number (match-string 4 s))
11791 (string-to-number (match-string 3 s))
11792 (string-to-number (match-string 2 s))
11793 nil nil nil)
11794 (make-list 9 0)))
11796 (defun org-timestamp-up (&optional arg)
11797 "Increase the date item at the cursor by one.
11798 If the cursor is on the year, change the year. If it is on the month or
11799 the day, change that.
11800 With prefix ARG, change by that many units."
11801 (interactive "p")
11802 (org-timestamp-change (prefix-numeric-value arg)))
11804 (defun org-timestamp-down (&optional arg)
11805 "Decrease the date item at the cursor by one.
11806 If the cursor is on the year, change the year. If it is on the month or
11807 the day, change that.
11808 With prefix ARG, change by that many units."
11809 (interactive "p")
11810 (org-timestamp-change (- (prefix-numeric-value arg))))
11812 (defun org-timestamp-up-day (&optional arg)
11813 "Increase the date in the time stamp by one day.
11814 With prefix ARG, change that many days."
11815 (interactive "p")
11816 (if (and (not (org-at-timestamp-p t))
11817 (org-on-heading-p))
11818 (org-todo 'up)
11819 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11821 (defun org-timestamp-down-day (&optional arg)
11822 "Decrease the date in the time stamp by one day.
11823 With prefix ARG, change that many days."
11824 (interactive "p")
11825 (if (and (not (org-at-timestamp-p t))
11826 (org-on-heading-p))
11827 (org-todo 'down)
11828 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11830 (defun org-at-timestamp-p (&optional inactive-ok)
11831 "Determine if the cursor is in or at a timestamp."
11832 (interactive)
11833 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11834 (pos (point))
11835 (ans (or (looking-at tsr)
11836 (save-excursion
11837 (skip-chars-backward "^[<\n\r\t")
11838 (if (> (point) (point-min)) (backward-char 1))
11839 (and (looking-at tsr)
11840 (> (- (match-end 0) pos) -1))))))
11841 (and ans
11842 (boundp 'org-ts-what)
11843 (setq org-ts-what
11844 (cond
11845 ((= pos (match-beginning 0)) 'bracket)
11846 ((= pos (1- (match-end 0))) 'bracket)
11847 ((org-pos-in-match-range pos 2) 'year)
11848 ((org-pos-in-match-range pos 3) 'month)
11849 ((org-pos-in-match-range pos 7) 'hour)
11850 ((org-pos-in-match-range pos 8) 'minute)
11851 ((or (org-pos-in-match-range pos 4)
11852 (org-pos-in-match-range pos 5)) 'day)
11853 ((and (> pos (or (match-end 8) (match-end 5)))
11854 (< pos (match-end 0)))
11855 (- pos (or (match-end 8) (match-end 5))))
11856 (t 'day))))
11857 ans))
11859 (defun org-toggle-timestamp-type ()
11860 "Toggle the type (<active> or [inactive]) of a time stamp."
11861 (interactive)
11862 (when (org-at-timestamp-p t)
11863 (let ((beg (match-beginning 0)) (end (match-end 0))
11864 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11865 (save-excursion
11866 (goto-char beg)
11867 (while (re-search-forward "[][<>]" end t)
11868 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11869 t t)))
11870 (message "Timestamp is now %sactive"
11871 (if (equal (char-after beg) ?<) "" "in")))))
11873 (defun org-timestamp-change (n &optional what)
11874 "Change the date in the time stamp at point.
11875 The date will be changed by N times WHAT. WHAT can be `day', `month',
11876 `year', `minute', `second'. If WHAT is not given, the cursor position
11877 in the timestamp determines what will be changed."
11878 (let ((pos (point))
11879 with-hm inactive
11880 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11881 org-ts-what
11882 extra rem
11883 ts time time0)
11884 (if (not (org-at-timestamp-p t))
11885 (error "Not at a timestamp"))
11886 (if (and (not what) (eq org-ts-what 'bracket))
11887 (org-toggle-timestamp-type)
11888 (if (and (not what) (not (eq org-ts-what 'day))
11889 org-display-custom-times
11890 (get-text-property (point) 'display)
11891 (not (get-text-property (1- (point)) 'display)))
11892 (setq org-ts-what 'day))
11893 (setq org-ts-what (or what org-ts-what)
11894 inactive (= (char-after (match-beginning 0)) ?\[)
11895 ts (match-string 0))
11896 (replace-match "")
11897 (if (string-match
11898 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11900 (setq extra (match-string 1 ts)))
11901 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11902 (setq with-hm t))
11903 (setq time0 (org-parse-time-string ts))
11904 (when (and (eq org-ts-what 'minute)
11905 (eq current-prefix-arg nil))
11906 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11907 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11908 (setcar (cdr time0) (+ (nth 1 time0)
11909 (if (> n 0) (- rem) (- dm rem))))))
11910 (setq time
11911 (encode-time (or (car time0) 0)
11912 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11913 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11914 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11915 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11916 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11917 (nthcdr 6 time0)))
11918 (when (integerp org-ts-what)
11919 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11920 (if (eq what 'calendar)
11921 (let ((cal-date (org-get-date-from-calendar)))
11922 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11923 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11924 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11925 (setcar time0 (or (car time0) 0))
11926 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11927 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11928 (setq time (apply 'encode-time time0))))
11929 (setq org-last-changed-timestamp
11930 (org-insert-time-stamp time with-hm inactive nil nil extra))
11931 (org-clock-update-time-maybe)
11932 (goto-char pos)
11933 ;; Try to recenter the calendar window, if any
11934 (if (and org-calendar-follow-timestamp-change
11935 (get-buffer-window "*Calendar*" t)
11936 (memq org-ts-what '(day month year)))
11937 (org-recenter-calendar (time-to-days time))))))
11939 (defun org-modify-ts-extra (s pos n dm)
11940 "Change the different parts of the lead-time and repeat fields in timestamp."
11941 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11942 ng h m new rem)
11943 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11944 (cond
11945 ((or (org-pos-in-match-range pos 2)
11946 (org-pos-in-match-range pos 3))
11947 (setq m (string-to-number (match-string 3 s))
11948 h (string-to-number (match-string 2 s)))
11949 (if (org-pos-in-match-range pos 2)
11950 (setq h (+ h n))
11951 (setq n (* dm (org-no-warnings (signum n))))
11952 (when (not (= 0 (setq rem (% m dm))))
11953 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11954 (setq m (+ m n)))
11955 (if (< m 0) (setq m (+ m 60) h (1- h)))
11956 (if (> m 59) (setq m (- m 60) h (1+ h)))
11957 (setq h (min 24 (max 0 h)))
11958 (setq ng 1 new (format "-%02d:%02d" h m)))
11959 ((org-pos-in-match-range pos 6)
11960 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11961 ((org-pos-in-match-range pos 5)
11962 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11964 ((org-pos-in-match-range pos 9)
11965 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11966 ((org-pos-in-match-range pos 8)
11967 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11969 (when ng
11970 (setq s (concat
11971 (substring s 0 (match-beginning ng))
11973 (substring s (match-end ng))))))
11976 (defun org-recenter-calendar (date)
11977 "If the calendar is visible, recenter it to DATE."
11978 (let* ((win (selected-window))
11979 (cwin (get-buffer-window "*Calendar*" t))
11980 (calendar-move-hook nil))
11981 (when cwin
11982 (select-window cwin)
11983 (calendar-goto-date (if (listp date) date
11984 (calendar-gregorian-from-absolute date)))
11985 (select-window win))))
11987 (defun org-goto-calendar (&optional arg)
11988 "Go to the Emacs calendar at the current date.
11989 If there is a time stamp in the current line, go to that date.
11990 A prefix ARG can be used to force the current date."
11991 (interactive "P")
11992 (let ((tsr org-ts-regexp) diff
11993 (calendar-move-hook nil)
11994 (calendar-view-holidays-initially-flag nil)
11995 (view-calendar-holidays-initially nil)
11996 (calendar-view-diary-initially-flag nil)
11997 (view-diary-entries-initially nil))
11998 (if (or (org-at-timestamp-p)
11999 (save-excursion
12000 (beginning-of-line 1)
12001 (looking-at (concat ".*" tsr))))
12002 (let ((d1 (time-to-days (current-time)))
12003 (d2 (time-to-days
12004 (org-time-string-to-time (match-string 1)))))
12005 (setq diff (- d2 d1))))
12006 (calendar)
12007 (calendar-goto-today)
12008 (if (and diff (not arg)) (calendar-forward-day diff))))
12010 (defun org-get-date-from-calendar ()
12011 "Return a list (month day year) of date at point in calendar."
12012 (with-current-buffer "*Calendar*"
12013 (save-match-data
12014 (calendar-cursor-to-date))))
12016 (defun org-date-from-calendar ()
12017 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12018 If there is already a time stamp at the cursor position, update it."
12019 (interactive)
12020 (if (org-at-timestamp-p t)
12021 (org-timestamp-change 0 'calendar)
12022 (let ((cal-date (org-get-date-from-calendar)))
12023 (org-insert-time-stamp
12024 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12026 (defun org-minutes-to-hh:mm-string (m)
12027 "Compute H:MM from a number of minutes."
12028 (let ((h (/ m 60)))
12029 (setq m (- m (* 60 h)))
12030 (format org-time-clocksum-format h m)))
12032 (defun org-hh:mm-string-to-minutes (s)
12033 "Convert a string H:MM to a number of minutes."
12034 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12035 (+ (* (string-to-number (match-string 1 s)) 60)
12036 (string-to-number (match-string 2 s)))
12039 ;;;; Agenda files
12041 ;;;###autoload
12042 (defun org-iswitchb (&optional arg)
12043 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12044 With a prefix argument, restrict available to files.
12045 With two prefix arguments, restrict available buffers to agenda files.
12047 Due to some yet unresolved reason, the global function
12048 `iswitchb-mode' needs to be active for this function to work."
12049 (interactive "P")
12050 (require 'iswitchb)
12051 (let ((enabled iswitchb-mode) blist)
12052 (or enabled (iswitchb-mode 1))
12053 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12054 ((equal arg '(16)) (org-buffer-list 'agenda))
12055 (t (org-buffer-list))))
12056 (unwind-protect
12057 (let ((iswitchb-make-buflist-hook
12058 (lambda ()
12059 (setq iswitchb-temp-buflist
12060 (mapcar 'buffer-name blist)))))
12061 (switch-to-buffer
12062 (iswitchb-read-buffer
12063 "Switch-to: " nil t))
12064 (or enabled (iswitchb-mode -1))))))
12066 ;;;###autoload
12067 (defun org-ido-switchb (&optional arg)
12068 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12069 With a prefix argument, restrict available to files.
12070 With two prefix arguments, restrict available buffers to agenda files."
12071 (interactive "P")
12072 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12073 ((equal arg '(16)) (org-buffer-list 'agenda))
12074 (t (org-buffer-list)))))
12075 (switch-to-buffer
12076 (org-ido-completing-read "Org buffer: "
12077 (mapcar 'buffer-name blist)
12078 nil t))))
12080 (defun org-buffer-list (&optional predicate exclude-tmp)
12081 "Return a list of Org buffers.
12082 PREDICATE can be `export', `files' or `agenda'.
12084 export restrict the list to Export buffers.
12085 files restrict the list to buffers visiting Org files.
12086 agenda restrict the list to buffers visiting agenda files.
12088 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12089 (let* ((bfn nil)
12090 (agenda-files (and (eq predicate 'agenda)
12091 (mapcar 'file-truename (org-agenda-files t))))
12092 (filter
12093 (cond
12094 ((eq predicate 'files)
12095 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12096 ((eq predicate 'export)
12097 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12098 ((eq predicate 'agenda)
12099 (lambda (b)
12100 (with-current-buffer b
12101 (and (eq major-mode 'org-mode)
12102 (setq bfn (buffer-file-name b))
12103 (member (file-truename bfn) agenda-files)))))
12104 (t (lambda (b) (with-current-buffer b
12105 (or (eq major-mode 'org-mode)
12106 (string-match "\*Org .*Export"
12107 (buffer-name b)))))))))
12108 (delq nil
12109 (mapcar
12110 (lambda(b)
12111 (if (and (funcall filter b)
12112 (or (not exclude-tmp)
12113 (not (string-match "tmp" (buffer-name b)))))
12115 nil))
12116 (buffer-list)))))
12118 (defun org-agenda-files (&optional unrestricted archives)
12119 "Get the list of agenda files.
12120 Optional UNRESTRICTED means return the full list even if a restriction
12121 is currently in place.
12122 When ARCHIVES is t, include all archive files hat are really being
12123 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12124 `org-agenda-archives-mode' is t."
12125 (let ((files
12126 (cond
12127 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12128 ((stringp org-agenda-files) (org-read-agenda-file-list))
12129 ((listp org-agenda-files) org-agenda-files)
12130 (t (error "Invalid value of `org-agenda-files'")))))
12131 (setq files (apply 'append
12132 (mapcar (lambda (f)
12133 (if (file-directory-p f)
12134 (directory-files
12135 f t org-agenda-file-regexp)
12136 (list f)))
12137 files)))
12138 (when org-agenda-skip-unavailable-files
12139 (setq files (delq nil
12140 (mapcar (function
12141 (lambda (file)
12142 (and (file-readable-p file) file)))
12143 files))))
12144 (when (or (eq archives t)
12145 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12146 (setq files (org-add-archive-files files)))
12147 files))
12149 (defun org-edit-agenda-file-list ()
12150 "Edit the list of agenda files.
12151 Depending on setup, this either uses customize to edit the variable
12152 `org-agenda-files', or it visits the file that is holding the list. In the
12153 latter case, the buffer is set up in a way that saving it automatically kills
12154 the buffer and restores the previous window configuration."
12155 (interactive)
12156 (if (stringp org-agenda-files)
12157 (let ((cw (current-window-configuration)))
12158 (find-file org-agenda-files)
12159 (org-set-local 'org-window-configuration cw)
12160 (org-add-hook 'after-save-hook
12161 (lambda ()
12162 (set-window-configuration
12163 (prog1 org-window-configuration
12164 (kill-buffer (current-buffer))))
12165 (org-install-agenda-files-menu)
12166 (message "New agenda file list installed"))
12167 nil 'local)
12168 (message "%s" (substitute-command-keys
12169 "Edit list and finish with \\[save-buffer]")))
12170 (customize-variable 'org-agenda-files)))
12172 (defun org-store-new-agenda-file-list (list)
12173 "Set new value for the agenda file list and save it correctly."
12174 (if (stringp org-agenda-files)
12175 (let ((f org-agenda-files) b)
12176 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12177 (with-temp-file f
12178 (insert (mapconcat 'identity list "\n") "\n")))
12179 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12180 (setq org-agenda-files list)
12181 (customize-save-variable 'org-agenda-files org-agenda-files))))
12183 (defun org-read-agenda-file-list ()
12184 "Read the list of agenda files from a file."
12185 (when (file-directory-p org-agenda-files)
12186 (error "`org-agenda-files' cannot be a single directory"))
12187 (when (stringp org-agenda-files)
12188 (with-temp-buffer
12189 (insert-file-contents org-agenda-files)
12190 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12193 ;;;###autoload
12194 (defun org-cycle-agenda-files ()
12195 "Cycle through the files in `org-agenda-files'.
12196 If the current buffer visits an agenda file, find the next one in the list.
12197 If the current buffer does not, find the first agenda file."
12198 (interactive)
12199 (let* ((fs (org-agenda-files t))
12200 (files (append fs (list (car fs))))
12201 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12202 file)
12203 (unless files (error "No agenda files"))
12204 (catch 'exit
12205 (while (setq file (pop files))
12206 (if (equal (file-truename file) tcf)
12207 (when (car files)
12208 (find-file (car files))
12209 (throw 'exit t))))
12210 (find-file (car fs)))
12211 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12213 (defun org-agenda-file-to-front (&optional to-end)
12214 "Move/add the current file to the top of the agenda file list.
12215 If the file is not present in the list, it is added to the front. If it is
12216 present, it is moved there. With optional argument TO-END, add/move to the
12217 end of the list."
12218 (interactive "P")
12219 (let ((org-agenda-skip-unavailable-files nil)
12220 (file-alist (mapcar (lambda (x)
12221 (cons (file-truename x) x))
12222 (org-agenda-files t)))
12223 (ctf (file-truename buffer-file-name))
12224 x had)
12225 (setq x (assoc ctf file-alist) had x)
12227 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12228 (if to-end
12229 (setq file-alist (append (delq x file-alist) (list x)))
12230 (setq file-alist (cons x (delq x file-alist))))
12231 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12232 (org-install-agenda-files-menu)
12233 (message "File %s to %s of agenda file list"
12234 (if had "moved" "added") (if to-end "end" "front"))))
12236 (defun org-remove-file (&optional file)
12237 "Remove current file from the list of files in variable `org-agenda-files'.
12238 These are the files which are being checked for agenda entries.
12239 Optional argument FILE means, use this file instead of the current."
12240 (interactive)
12241 (let* ((org-agenda-skip-unavailable-files nil)
12242 (file (or file buffer-file-name))
12243 (true-file (file-truename file))
12244 (afile (abbreviate-file-name file))
12245 (files (delq nil (mapcar
12246 (lambda (x)
12247 (if (equal true-file
12248 (file-truename x))
12249 nil x))
12250 (org-agenda-files t)))))
12251 (if (not (= (length files) (length (org-agenda-files t))))
12252 (progn
12253 (org-store-new-agenda-file-list files)
12254 (org-install-agenda-files-menu)
12255 (message "Removed file: %s" afile))
12256 (message "File was not in list: %s (not removed)" afile))))
12258 (defun org-file-menu-entry (file)
12259 (vector file (list 'find-file file) t))
12261 (defun org-check-agenda-file (file)
12262 "Make sure FILE exists. If not, ask user what to do."
12263 (when (not (file-exists-p file))
12264 (message "non-existent file %s. [R]emove from list or [A]bort?"
12265 (abbreviate-file-name file))
12266 (let ((r (downcase (read-char-exclusive))))
12267 (cond
12268 ((equal r ?r)
12269 (org-remove-file file)
12270 (throw 'nextfile t))
12271 (t (error "Abort"))))))
12273 (defun org-get-agenda-file-buffer (file)
12274 "Get a buffer visiting FILE. If the buffer needs to be created, add
12275 it to the list of buffers which might be released later."
12276 (let ((buf (org-find-base-buffer-visiting file)))
12277 (if buf
12278 buf ; just return it
12279 ;; Make a new buffer and remember it
12280 (setq buf (find-file-noselect file))
12281 (if buf (push buf org-agenda-new-buffers))
12282 buf)))
12284 (defun org-release-buffers (blist)
12285 "Release all buffers in list, asking the user for confirmation when needed.
12286 When a buffer is unmodified, it is just killed. When modified, it is saved
12287 \(if the user agrees) and then killed."
12288 (let (buf file)
12289 (while (setq buf (pop blist))
12290 (setq file (buffer-file-name buf))
12291 (when (and (buffer-modified-p buf)
12292 file
12293 (y-or-n-p (format "Save file %s? " file)))
12294 (with-current-buffer buf (save-buffer)))
12295 (kill-buffer buf))))
12297 (defun org-prepare-agenda-buffers (files)
12298 "Create buffers for all agenda files, protect archived trees and comments."
12299 (interactive)
12300 (let ((pa '(:org-archived t))
12301 (pc '(:org-comment t))
12302 (pall '(:org-archived t :org-comment t))
12303 (inhibit-read-only t)
12304 (rea (concat ":" org-archive-tag ":"))
12305 bmp file re)
12306 (save-excursion
12307 (save-restriction
12308 (while (setq file (pop files))
12309 (if (bufferp file)
12310 (set-buffer file)
12311 (org-check-agenda-file file)
12312 (set-buffer (org-get-agenda-file-buffer file)))
12313 (widen)
12314 (setq bmp (buffer-modified-p))
12315 (org-refresh-category-properties)
12316 (setq org-todo-keywords-for-agenda
12317 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12318 (setq org-done-keywords-for-agenda
12319 (append org-done-keywords-for-agenda org-done-keywords))
12320 (setq org-todo-keyword-alist-for-agenda
12321 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12322 (setq org-tag-alist-for-agenda
12323 (append org-tag-alist-for-agenda org-tag-alist))
12325 (save-excursion
12326 (remove-text-properties (point-min) (point-max) pall)
12327 (when org-agenda-skip-archived-trees
12328 (goto-char (point-min))
12329 (while (re-search-forward rea nil t)
12330 (if (org-on-heading-p t)
12331 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12332 (goto-char (point-min))
12333 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12334 (while (re-search-forward re nil t)
12335 (add-text-properties
12336 (match-beginning 0) (org-end-of-subtree t) pc)))
12337 (set-buffer-modified-p bmp))))
12338 (setq org-todo-keyword-alist-for-agenda
12339 (org-uniquify org-todo-keyword-alist-for-agenda)
12340 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12342 ;;;; Embedded LaTeX
12344 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12345 "Keymap for the minor `org-cdlatex-mode'.")
12347 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12348 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12349 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12350 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12351 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12353 (defvar org-cdlatex-texmathp-advice-is-done nil
12354 "Flag remembering if we have applied the advice to texmathp already.")
12356 (define-minor-mode org-cdlatex-mode
12357 "Toggle the minor `org-cdlatex-mode'.
12358 This mode supports entering LaTeX environment and math in LaTeX fragments
12359 in Org-mode.
12360 \\{org-cdlatex-mode-map}"
12361 nil " OCDL" nil
12362 (when org-cdlatex-mode (require 'cdlatex))
12363 (unless org-cdlatex-texmathp-advice-is-done
12364 (setq org-cdlatex-texmathp-advice-is-done t)
12365 (defadvice texmathp (around org-math-always-on activate)
12366 "Always return t in org-mode buffers.
12367 This is because we want to insert math symbols without dollars even outside
12368 the LaTeX math segments. If Orgmode thinks that point is actually inside
12369 an embedded LaTeX fragment, let texmathp do its job.
12370 \\[org-cdlatex-mode-map]"
12371 (interactive)
12372 (let (p)
12373 (cond
12374 ((not (org-mode-p)) ad-do-it)
12375 ((eq this-command 'cdlatex-math-symbol)
12376 (setq ad-return-value t
12377 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12379 (let ((p (org-inside-LaTeX-fragment-p)))
12380 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12381 (setq ad-return-value t
12382 texmathp-why '("Org-mode embedded math" . 0))
12383 (if p ad-do-it)))))))))
12385 (defun turn-on-org-cdlatex ()
12386 "Unconditionally turn on `org-cdlatex-mode'."
12387 (org-cdlatex-mode 1))
12389 (defun org-inside-LaTeX-fragment-p ()
12390 "Test if point is inside a LaTeX fragment.
12391 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12392 sequence appearing also before point.
12393 Even though the matchers for math are configurable, this function assumes
12394 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12395 delimiters are skipped when they have been removed by customization.
12396 The return value is nil, or a cons cell with the delimiter and
12397 and the position of this delimiter.
12399 This function does a reasonably good job, but can locally be fooled by
12400 for example currency specifications. For example it will assume being in
12401 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12402 fragments that are properly closed, but during editing, we have to live
12403 with the uncertainty caused by missing closing delimiters. This function
12404 looks only before point, not after."
12405 (catch 'exit
12406 (let ((pos (point))
12407 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12408 (lim (progn
12409 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12410 (point)))
12411 dd-on str (start 0) m re)
12412 (goto-char pos)
12413 (when dodollar
12414 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12415 re (nth 1 (assoc "$" org-latex-regexps)))
12416 (while (string-match re str start)
12417 (cond
12418 ((= (match-end 0) (length str))
12419 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12420 ((= (match-end 0) (- (length str) 5))
12421 (throw 'exit nil))
12422 (t (setq start (match-end 0))))))
12423 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12424 (goto-char pos)
12425 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12426 (and (match-beginning 2) (throw 'exit nil))
12427 ;; count $$
12428 (while (re-search-backward "\\$\\$" lim t)
12429 (setq dd-on (not dd-on)))
12430 (goto-char pos)
12431 (if dd-on (cons "$$" m))))))
12434 (defun org-try-cdlatex-tab ()
12435 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12436 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12437 - inside a LaTeX fragment, or
12438 - after the first word in a line, where an abbreviation expansion could
12439 insert a LaTeX environment."
12440 (when org-cdlatex-mode
12441 (cond
12442 ((save-excursion
12443 (skip-chars-backward "a-zA-Z0-9*")
12444 (skip-chars-backward " \t")
12445 (bolp))
12446 (cdlatex-tab) t)
12447 ((org-inside-LaTeX-fragment-p)
12448 (cdlatex-tab) t)
12449 (t nil))))
12451 (defun org-cdlatex-underscore-caret (&optional arg)
12452 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12453 Revert to the normal definition outside of these fragments."
12454 (interactive "P")
12455 (if (org-inside-LaTeX-fragment-p)
12456 (call-interactively 'cdlatex-sub-superscript)
12457 (let (org-cdlatex-mode)
12458 (call-interactively (key-binding (vector last-input-event))))))
12460 (defun org-cdlatex-math-modify (&optional arg)
12461 "Execute `cdlatex-math-modify' in LaTeX fragments.
12462 Revert to the normal definition outside of these fragments."
12463 (interactive "P")
12464 (if (org-inside-LaTeX-fragment-p)
12465 (call-interactively 'cdlatex-math-modify)
12466 (let (org-cdlatex-mode)
12467 (call-interactively (key-binding (vector last-input-event))))))
12469 (defvar org-latex-fragment-image-overlays nil
12470 "List of overlays carrying the images of latex fragments.")
12471 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12473 (defun org-remove-latex-fragment-image-overlays ()
12474 "Remove all overlays with LaTeX fragment images in current buffer."
12475 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12476 (setq org-latex-fragment-image-overlays nil))
12478 (defun org-preview-latex-fragment (&optional subtree)
12479 "Preview the LaTeX fragment at point, or all locally or globally.
12480 If the cursor is in a LaTeX fragment, create the image and overlay
12481 it over the source code. If there is no fragment at point, display
12482 all fragments in the current text, from one headline to the next. With
12483 prefix SUBTREE, display all fragments in the current subtree. With a
12484 double prefix `C-u C-u', or when the cursor is before the first headline,
12485 display all fragments in the buffer.
12486 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12487 (interactive "P")
12488 (org-remove-latex-fragment-image-overlays)
12489 (save-excursion
12490 (save-restriction
12491 (let (beg end at msg)
12492 (cond
12493 ((or (equal subtree '(16))
12494 (not (save-excursion
12495 (re-search-backward (concat "^" outline-regexp) nil t))))
12496 (setq beg (point-min) end (point-max)
12497 msg "Creating images for buffer...%s"))
12498 ((equal subtree '(4))
12499 (org-back-to-heading)
12500 (setq beg (point) end (org-end-of-subtree t)
12501 msg "Creating images for subtree...%s"))
12503 (if (setq at (org-inside-LaTeX-fragment-p))
12504 (goto-char (max (point-min) (- (cdr at) 2)))
12505 (org-back-to-heading))
12506 (setq beg (point) end (progn (outline-next-heading) (point))
12507 msg (if at "Creating image...%s"
12508 "Creating images for entry...%s"))))
12509 (message msg "")
12510 (narrow-to-region beg end)
12511 (goto-char beg)
12512 (org-format-latex
12513 (concat "ltxpng/" (file-name-sans-extension
12514 (file-name-nondirectory
12515 buffer-file-name)))
12516 default-directory 'overlays msg at 'forbuffer)
12517 (message msg "done. Use `C-c C-c' to remove images.")))))
12519 (defvar org-latex-regexps
12520 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12521 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12522 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12523 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12524 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12525 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12526 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12527 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12528 "Regular expressions for matching embedded LaTeX.")
12530 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12531 "Replace LaTeX fragments with links to an image, and produce images."
12532 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12533 (let* ((prefixnodir (file-name-nondirectory prefix))
12534 (absprefix (expand-file-name prefix dir))
12535 (todir (file-name-directory absprefix))
12536 (opt org-format-latex-options)
12537 (matchers (plist-get opt :matchers))
12538 (re-list org-latex-regexps)
12539 (cnt 0) txt link beg end re e checkdir
12540 m n block linkfile movefile ov)
12541 ;; Check if there are old images files with this prefix, and remove them
12542 (when (file-directory-p todir)
12543 (mapc 'delete-file
12544 (directory-files
12545 todir 'full
12546 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12547 ;; Check the different regular expressions
12548 (while (setq e (pop re-list))
12549 (setq m (car e) re (nth 1 e) n (nth 2 e)
12550 block (if (nth 3 e) "\n\n" ""))
12551 (when (member m matchers)
12552 (goto-char (point-min))
12553 (while (re-search-forward re nil t)
12554 (when (or (not at) (equal (cdr at) (match-beginning n)))
12555 (setq txt (match-string n)
12556 beg (match-beginning n) end (match-end n)
12557 cnt (1+ cnt)
12558 linkfile (format "%s_%04d.png" prefix cnt)
12559 movefile (format "%s_%04d.png" absprefix cnt)
12560 link (concat block "[[file:" linkfile "]]" block))
12561 (if msg (message msg cnt))
12562 (goto-char beg)
12563 (unless checkdir ; make sure the directory exists
12564 (setq checkdir t)
12565 (or (file-directory-p todir) (make-directory todir)))
12566 (org-create-formula-image
12567 txt movefile opt forbuffer)
12568 (if overlays
12569 (progn
12570 (setq ov (org-make-overlay beg end))
12571 (if (featurep 'xemacs)
12572 (progn
12573 (org-overlay-put ov 'invisible t)
12574 (org-overlay-put
12575 ov 'end-glyph
12576 (make-glyph (vector 'png :file movefile))))
12577 (org-overlay-put
12578 ov 'display
12579 (list 'image :type 'png :file movefile :ascent 'center)))
12580 (push ov org-latex-fragment-image-overlays)
12581 (goto-char end))
12582 (delete-region beg end)
12583 (insert link))))))))
12585 ;; This function borrows from Ganesh Swami's latex2png.el
12586 (defun org-create-formula-image (string tofile options buffer)
12587 (let* ((tmpdir (if (featurep 'xemacs)
12588 (temp-directory)
12589 temporary-file-directory))
12590 (texfilebase (make-temp-name
12591 (expand-file-name "orgtex" tmpdir)))
12592 (texfile (concat texfilebase ".tex"))
12593 (dvifile (concat texfilebase ".dvi"))
12594 (pngfile (concat texfilebase ".png"))
12595 (fnh (if (featurep 'xemacs)
12596 (font-height (get-face-font 'default))
12597 (face-attribute 'default :height nil)))
12598 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12599 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12600 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12601 "Black"))
12602 (bg (or (plist-get options (if buffer :background :html-background))
12603 "Transparent")))
12604 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12605 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12606 (with-temp-file texfile
12607 (insert org-format-latex-header
12608 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12609 (let ((dir default-directory))
12610 (condition-case nil
12611 (progn
12612 (cd tmpdir)
12613 (call-process "latex" nil nil nil texfile))
12614 (error nil))
12615 (cd dir))
12616 (if (not (file-exists-p dvifile))
12617 (progn (message "Failed to create dvi file from %s" texfile) nil)
12618 (condition-case nil
12619 (call-process "dvipng" nil nil nil
12620 "-E" "-fg" fg "-bg" bg
12621 "-D" dpi
12622 ;;"-x" scale "-y" scale
12623 "-T" "tight"
12624 "-o" pngfile
12625 dvifile)
12626 (error nil))
12627 (if (not (file-exists-p pngfile))
12628 (progn (message "Failed to create png file from %s" texfile) nil)
12629 ;; Use the requested file name and clean up
12630 (copy-file pngfile tofile 'replace)
12631 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12632 (delete-file (concat texfilebase e)))
12633 pngfile))))
12635 (defun org-dvipng-color (attr)
12636 "Return an rgb color specification for dvipng."
12637 (apply 'format "rgb %s %s %s"
12638 (mapcar 'org-normalize-color
12639 (color-values (face-attribute 'default attr nil)))))
12641 (defun org-normalize-color (value)
12642 "Return string to be used as color value for an RGB component."
12643 (format "%g" (/ value 65535.0)))
12645 ;;;; Key bindings
12647 ;; Make `C-c C-x' a prefix key
12648 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12650 ;; TAB key with modifiers
12651 (org-defkey org-mode-map "\C-i" 'org-cycle)
12652 (org-defkey org-mode-map [(tab)] 'org-cycle)
12653 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12654 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12655 (org-defkey org-mode-map "\M-\t" 'org-complete)
12656 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12657 ;; The following line is necessary under Suse GNU/Linux
12658 (unless (featurep 'xemacs)
12659 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12660 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12661 (define-key org-mode-map [backtab] 'org-shifttab)
12663 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12664 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12665 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12667 ;; Cursor keys with modifiers
12668 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12669 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12670 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12671 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12673 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12674 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12675 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12676 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12678 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12679 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12680 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12681 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12683 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12684 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12686 ;;; Extra keys for tty access.
12687 ;; We only set them when really needed because otherwise the
12688 ;; menus don't show the simple keys
12690 (when (or org-use-extra-keys
12691 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12692 (not window-system))
12693 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12694 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12695 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12696 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12697 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12698 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12699 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12700 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12701 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12702 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12703 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12704 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12705 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12706 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12707 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12708 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12709 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12710 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12711 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12712 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12713 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12714 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12716 ;; All the other keys
12718 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12719 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12720 (if (boundp 'narrow-map)
12721 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12722 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12723 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12724 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12725 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12726 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12727 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12728 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12729 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12730 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12731 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12732 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12733 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12734 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12735 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12736 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12737 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12738 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12739 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12740 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12741 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12742 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12743 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12744 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12745 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12746 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12747 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12748 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12749 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12750 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12751 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12752 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12753 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12754 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12755 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12756 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12757 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12758 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12759 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12760 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12761 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12762 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12763 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12764 (org-defkey org-mode-map "\C-c^" 'org-sort)
12765 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12766 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12767 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12768 (org-defkey org-mode-map "\C-m" 'org-return)
12769 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12770 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12771 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12772 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12773 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12774 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12775 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12776 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12777 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12778 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12779 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12780 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12781 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12782 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12783 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12784 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12785 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12787 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12788 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12789 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12790 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12792 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12793 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12794 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12795 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12796 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12797 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12798 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12799 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12800 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12801 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12802 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12803 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12805 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12806 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12807 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12808 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12810 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12812 (when (featurep 'xemacs)
12813 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12815 (defvar org-table-auto-blank-field) ; defined in org-table.el
12816 (defun org-self-insert-command (N)
12817 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12818 If the cursor is in a table looking at whitespace, the whitespace is
12819 overwritten, and the table is not marked as requiring realignment."
12820 (interactive "p")
12821 (if (and (org-table-p)
12822 (progn
12823 ;; check if we blank the field, and if that triggers align
12824 (and (featurep 'org-table) org-table-auto-blank-field
12825 (member last-command
12826 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12827 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12828 ;; got extra space, this field does not determine column width
12829 (let (org-table-may-need-update) (org-table-blank-field))
12830 ;; no extra space, this field may determine column width
12831 (org-table-blank-field)))
12833 (eq N 1)
12834 (looking-at "[^|\n]* |"))
12835 (let (org-table-may-need-update)
12836 (goto-char (1- (match-end 0)))
12837 (delete-backward-char 1)
12838 (goto-char (match-beginning 0))
12839 (self-insert-command N))
12840 (setq org-table-may-need-update t)
12841 (self-insert-command N)
12842 (org-fix-tags-on-the-fly)))
12844 (defun org-fix-tags-on-the-fly ()
12845 (when (and (equal (char-after (point-at-bol)) ?*)
12846 (org-on-heading-p))
12847 (org-align-tags-here org-tags-column)))
12849 (defun org-delete-backward-char (N)
12850 "Like `delete-backward-char', insert whitespace at field end in tables.
12851 When deleting backwards, in tables this function will insert whitespace in
12852 front of the next \"|\" separator, to keep the table aligned. The table will
12853 still be marked for re-alignment if the field did fill the entire column,
12854 because, in this case the deletion might narrow the column."
12855 (interactive "p")
12856 (if (and (org-table-p)
12857 (eq N 1)
12858 (string-match "|" (buffer-substring (point-at-bol) (point)))
12859 (looking-at ".*?|"))
12860 (let ((pos (point))
12861 (noalign (looking-at "[^|\n\r]* |"))
12862 (c org-table-may-need-update))
12863 (backward-delete-char N)
12864 (skip-chars-forward "^|")
12865 (insert " ")
12866 (goto-char (1- pos))
12867 ;; noalign: if there were two spaces at the end, this field
12868 ;; does not determine the width of the column.
12869 (if noalign (setq org-table-may-need-update c)))
12870 (backward-delete-char N)
12871 (org-fix-tags-on-the-fly)))
12873 (defun org-delete-char (N)
12874 "Like `delete-char', but insert whitespace at field end in tables.
12875 When deleting characters, in tables this function will insert whitespace in
12876 front of the next \"|\" separator, to keep the table aligned. The table will
12877 still be marked for re-alignment if the field did fill the entire column,
12878 because, in this case the deletion might narrow the column."
12879 (interactive "p")
12880 (if (and (org-table-p)
12881 (not (bolp))
12882 (not (= (char-after) ?|))
12883 (eq N 1))
12884 (if (looking-at ".*?|")
12885 (let ((pos (point))
12886 (noalign (looking-at "[^|\n\r]* |"))
12887 (c org-table-may-need-update))
12888 (replace-match (concat
12889 (substring (match-string 0) 1 -1)
12890 " |"))
12891 (goto-char pos)
12892 ;; noalign: if there were two spaces at the end, this field
12893 ;; does not determine the width of the column.
12894 (if noalign (setq org-table-may-need-update c)))
12895 (delete-char N))
12896 (delete-char N)
12897 (org-fix-tags-on-the-fly)))
12899 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12900 (put 'org-self-insert-command 'delete-selection t)
12901 (put 'orgtbl-self-insert-command 'delete-selection t)
12902 (put 'org-delete-char 'delete-selection 'supersede)
12903 (put 'org-delete-backward-char 'delete-selection 'supersede)
12904 (put 'org-yank 'delete-selection 'yank)
12906 ;; Make `flyspell-mode' delay after some commands
12907 (put 'org-self-insert-command 'flyspell-delayed t)
12908 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12909 (put 'org-delete-char 'flyspell-delayed t)
12910 (put 'org-delete-backward-char 'flyspell-delayed t)
12912 ;; Make pabbrev-mode expand after org-mode commands
12913 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12914 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12916 ;; How to do this: Measure non-white length of current string
12917 ;; If equal to column width, we should realign.
12919 (defun org-remap (map &rest commands)
12920 "In MAP, remap the functions given in COMMANDS.
12921 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12922 (let (new old)
12923 (while commands
12924 (setq old (pop commands) new (pop commands))
12925 (if (fboundp 'command-remapping)
12926 (org-defkey map (vector 'remap old) new)
12927 (substitute-key-definition old new map global-map)))))
12929 (when (eq org-enable-table-editor 'optimized)
12930 ;; If the user wants maximum table support, we need to hijack
12931 ;; some standard editing functions
12932 (org-remap org-mode-map
12933 'self-insert-command 'org-self-insert-command
12934 'delete-char 'org-delete-char
12935 'delete-backward-char 'org-delete-backward-char)
12936 (org-defkey org-mode-map "|" 'org-force-self-insert))
12938 (defun org-shiftcursor-error ()
12939 "Throw an error, a modified cursor command was applied in wrong context."
12940 (error "This command is active in special context like tables, headlines or items"))
12942 (defun org-shiftselect-error ()
12943 "Throw an error because Shift-Cursor command was applied in wrong context."
12944 (if (and (boundp 'shift-select-mode) shift-select-mode)
12945 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
12946 (error "This command works only in special context like headlines or timestamps.")))
12948 (defun org-call-for-shift-select (cmd)
12949 (let ((this-command-keys-shift-translated t))
12950 (call-interactively cmd)))
12952 (defun org-shifttab (&optional arg)
12953 "Global visibility cycling or move to previous table field.
12954 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12955 on context.
12956 See the individual commands for more information."
12957 (interactive "P")
12958 (cond
12959 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12960 ((integerp arg)
12961 (message "Content view to level: %d" arg)
12962 (org-content (prefix-numeric-value arg))
12963 (setq org-cycle-global-status 'overview))
12964 (t (call-interactively 'org-global-cycle))))
12966 (defun org-shiftmetaleft ()
12967 "Promote subtree or delete table column.
12968 Calls `org-promote-subtree', `org-outdent-item',
12969 or `org-table-delete-column', depending on context.
12970 See the individual commands for more information."
12971 (interactive)
12972 (cond
12973 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12974 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12975 ((org-at-item-p) (call-interactively 'org-outdent-item))
12976 (t (org-shiftcursor-error))))
12978 (defun org-shiftmetaright ()
12979 "Demote subtree or insert table column.
12980 Calls `org-demote-subtree', `org-indent-item',
12981 or `org-table-insert-column', depending on context.
12982 See the individual commands for more information."
12983 (interactive)
12984 (cond
12985 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12986 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12987 ((org-at-item-p) (call-interactively 'org-indent-item))
12988 (t (org-shiftcursor-error))))
12990 (defun org-shiftmetaup (&optional arg)
12991 "Move subtree up or kill table row.
12992 Calls `org-move-subtree-up' or `org-table-kill-row' or
12993 `org-move-item-up' depending on context. See the individual commands
12994 for more information."
12995 (interactive "P")
12996 (cond
12997 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12998 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12999 ((org-at-item-p) (call-interactively 'org-move-item-up))
13000 (t (org-shiftcursor-error))))
13001 (defun org-shiftmetadown (&optional arg)
13002 "Move subtree down or insert table row.
13003 Calls `org-move-subtree-down' or `org-table-insert-row' or
13004 `org-move-item-down', depending on context. See the individual
13005 commands for more information."
13006 (interactive "P")
13007 (cond
13008 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13009 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13010 ((org-at-item-p) (call-interactively 'org-move-item-down))
13011 (t (org-shiftcursor-error))))
13013 (defun org-metaleft (&optional arg)
13014 "Promote heading or move table column to left.
13015 Calls `org-do-promote' or `org-table-move-column', depending on context.
13016 With no specific context, calls the Emacs default `backward-word'.
13017 See the individual commands for more information."
13018 (interactive "P")
13019 (cond
13020 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13021 ((or (org-on-heading-p) (org-region-active-p))
13022 (call-interactively 'org-do-promote))
13023 ((org-at-item-p) (call-interactively 'org-outdent-item))
13024 (t (call-interactively 'backward-word))))
13026 (defun org-metaright (&optional arg)
13027 "Demote subtree or move table column to right.
13028 Calls `org-do-demote' or `org-table-move-column', depending on context.
13029 With no specific context, calls the Emacs default `forward-word'.
13030 See the individual commands for more information."
13031 (interactive "P")
13032 (cond
13033 ((org-at-table-p) (call-interactively 'org-table-move-column))
13034 ((or (org-on-heading-p) (org-region-active-p))
13035 (call-interactively 'org-do-demote))
13036 ((org-at-item-p) (call-interactively 'org-indent-item))
13037 (t (call-interactively 'forward-word))))
13039 (defun org-metaup (&optional arg)
13040 "Move subtree up or move table row up.
13041 Calls `org-move-subtree-up' or `org-table-move-row' or
13042 `org-move-item-up', depending on context. See the individual commands
13043 for more information."
13044 (interactive "P")
13045 (cond
13046 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13047 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13048 ((org-at-item-p) (call-interactively 'org-move-item-up))
13049 (t (transpose-lines 1) (beginning-of-line -1))))
13051 (defun org-metadown (&optional arg)
13052 "Move subtree down or move table row down.
13053 Calls `org-move-subtree-down' or `org-table-move-row' or
13054 `org-move-item-down', depending on context. See the individual
13055 commands for more information."
13056 (interactive "P")
13057 (cond
13058 ((org-at-table-p) (call-interactively 'org-table-move-row))
13059 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13060 ((org-at-item-p) (call-interactively 'org-move-item-down))
13061 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13063 (defun org-shiftup (&optional arg)
13064 "Increase item in timestamp or increase priority of current headline.
13065 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13066 depending on context. See the individual commands for more information."
13067 (interactive "P")
13068 (cond
13069 ((and org-support-shift-select (org-region-active-p))
13070 (org-call-for-shift-select 'previous-line))
13071 ((org-at-timestamp-p t)
13072 (call-interactively (if org-edit-timestamp-down-means-later
13073 'org-timestamp-down 'org-timestamp-up)))
13074 ((and (not (eq org-support-shift-select 'always))
13075 (org-on-heading-p))
13076 (call-interactively 'org-priority-up))
13077 ((and (not org-support-shift-select) (org-at-item-p))
13078 (call-interactively 'org-previous-item))
13079 ((org-clocktable-try-shift 'up arg))
13080 (org-support-shift-select
13081 (org-call-for-shift-select 'previous-line))
13082 (t (org-shiftselect-error))))
13084 (defun org-shiftdown (&optional arg)
13085 "Decrease item in timestamp or decrease priority of current headline.
13086 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13087 depending on context. See the individual commands for more information."
13088 (interactive "P")
13089 (cond
13090 ((and org-support-shift-select (org-region-active-p))
13091 (org-call-for-shift-select 'next-line))
13092 ((org-at-timestamp-p t)
13093 (call-interactively (if org-edit-timestamp-down-means-later
13094 'org-timestamp-up 'org-timestamp-down)))
13095 ((and (not (eq org-support-shift-select 'always))
13096 (org-on-heading-p))
13097 (call-interactively 'org-priority-down))
13098 ((and (not org-support-shift-select) (org-at-item-p))
13099 (call-interactively 'org-next-item))
13100 ((org-clocktable-try-shift 'down arg))
13101 (org-support-shift-select
13102 (org-call-for-shift-select 'next-line))
13103 (t (org-shiftselect-error))))
13105 (defun org-shiftright (&optional arg)
13106 "Cycle the thing at point or in the current line, depending on context.
13107 Depending on context, this does one of the following:
13109 - switch a timestamp at point one day into the future
13110 - on a headline, switch to the next TODO keyword.
13111 - on an item, switch entire list to the next bullet type
13112 - on a property line, switch to the next allowed value
13113 - on a clocktable definition line, move time block into the future"
13114 (interactive "P")
13115 (cond
13116 ((and org-support-shift-select (org-region-active-p))
13117 (org-call-for-shift-select 'forward-char))
13118 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13119 ((and (not (eq org-support-shift-select 'always))
13120 (org-on-heading-p))
13121 (org-call-with-arg 'org-todo 'right))
13122 ((or (and org-support-shift-select (org-at-item-bullet-p))
13123 (and (not org-support-shift-select) (org-at-item-p)))
13124 (org-call-with-arg 'org-cycle-list-bullet nil))
13125 ((and (not (eq org-support-shift-select 'always))
13126 (org-at-property-p))
13127 (call-interactively 'org-property-next-allowed-value))
13128 ((org-clocktable-try-shift 'right arg))
13129 (org-support-shift-select
13130 (org-call-for-shift-select 'forward-char))
13131 (t (org-shiftselect-error))))
13133 (defun org-shiftleft (&optional arg)
13134 "Cycle the thing at point or in the current line, depending on context.
13135 Depending on context, this does one of the following:
13137 - switch a timestamp at point one day into the past
13138 - on a headline, switch to the previous TODO keyword.
13139 - on an item, switch entire list to the previous bullet type
13140 - on a property line, switch to the previous allowed value
13141 - on a clocktable definition line, move time block into the past"
13142 (interactive "P")
13143 (cond
13144 ((and org-support-shift-select (org-region-active-p))
13145 (org-call-for-shift-select 'backward-char))
13146 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13147 ((and (not (eq org-support-shift-select 'always))
13148 (org-on-heading-p))
13149 (org-call-with-arg 'org-todo 'left))
13150 ((or (and org-support-shift-select (org-at-item-bullet-p))
13151 (and (not org-support-shift-select) (org-at-item-p)))
13152 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13153 ((and (not (eq org-support-shift-select 'always))
13154 (org-at-property-p))
13155 (call-interactively 'org-property-previous-allowed-value))
13156 ((org-clocktable-try-shift 'left arg))
13157 (org-support-shift-select
13158 (org-call-for-shift-select 'backward-char))
13159 (t (org-shiftselect-error))))
13161 (defun org-shiftcontrolright ()
13162 "Switch to next TODO set."
13163 (interactive)
13164 (cond
13165 ((and org-support-shift-select (org-region-active-p))
13166 (org-call-for-shift-select 'forward-word))
13167 ((and (not (eq org-support-shift-select 'always))
13168 (org-on-heading-p))
13169 (org-call-with-arg 'org-todo 'nextset))
13170 (org-support-shift-select
13171 (org-call-for-shift-select 'forward-word))
13172 (t (org-shiftselect-error))))
13174 (defun org-shiftcontrolleft ()
13175 "Switch to previous TODO set."
13176 (interactive)
13177 (cond
13178 ((and org-support-shift-select (org-region-active-p))
13179 (org-call-for-shift-select 'backward-word))
13180 ((and (not (eq org-support-shift-select 'always))
13181 (org-on-heading-p))
13182 (org-call-with-arg 'org-todo 'previousset))
13183 (org-support-shift-select
13184 (org-call-for-shift-select 'backward-word))
13185 (t (org-shiftselect-error))))
13187 (defun org-ctrl-c-ret ()
13188 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13189 (interactive)
13190 (cond
13191 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13192 (t (call-interactively 'org-insert-heading))))
13194 (defun org-copy-special ()
13195 "Copy region in table or copy current subtree.
13196 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13197 See the individual commands for more information."
13198 (interactive)
13199 (call-interactively
13200 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13202 (defun org-cut-special ()
13203 "Cut region in table or cut current subtree.
13204 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13205 See the individual commands for more information."
13206 (interactive)
13207 (call-interactively
13208 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13210 (defun org-paste-special (arg)
13211 "Paste rectangular region into table, or past subtree relative to level.
13212 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13213 See the individual commands for more information."
13214 (interactive "P")
13215 (if (org-at-table-p)
13216 (org-table-paste-rectangle)
13217 (org-paste-subtree arg)))
13219 (defun org-edit-special ()
13220 "Call a special editor for the stuff at point.
13221 When at a table, call the formula editor with `org-table-edit-formulas'.
13222 When at the first line of an src example, call `org-edit-src-code'.
13223 When in an #+include line, visit the include file. Otherwise call
13224 `ffap' to visit the file at point."
13225 (interactive)
13226 (cond
13227 ((org-at-table-p)
13228 (call-interactively 'org-table-edit-formulas))
13229 ((save-excursion
13230 (beginning-of-line 1)
13231 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13232 (find-file (org-trim (match-string 1))))
13233 ((org-edit-src-code))
13234 ((org-edit-fixed-width-region))
13235 (t (call-interactively 'ffap))))
13237 (defun org-ctrl-c-ctrl-c (&optional arg)
13238 "Set tags in headline, or update according to changed information at point.
13240 This command does many different things, depending on context:
13242 - If the cursor is in a headline, prompt for tags and insert them
13243 into the current line, aligned to `org-tags-column'. When called
13244 with prefix arg, realign all tags in the current buffer.
13246 - If the cursor is in one of the special #+KEYWORD lines, this
13247 triggers scanning the buffer for these lines and updating the
13248 information.
13250 - If the cursor is inside a table, realign the table. This command
13251 works even if the automatic table editor has been turned off.
13253 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13254 the entire table.
13256 - If the cursor is at a footnote reference or definition, jump to
13257 the corresponding definition or references, respectively.
13259 - If the cursor is a the beginning of a dynamic block, update it.
13261 - If the cursor is inside a table created by the table.el package,
13262 activate that table.
13264 - If the current buffer is a remember buffer, close note and file
13265 it. A prefix argument of 1 files to the default location
13266 without further interaction. A prefix argument of 2 files to
13267 the currently clocking task.
13269 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13270 links in this buffer.
13272 - If the cursor is on a numbered item in a plain list, renumber the
13273 ordered list.
13275 - If the cursor is on a checkbox, toggle it."
13276 (interactive "P")
13277 (let ((org-enable-table-editor t))
13278 (cond
13279 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13280 org-occur-highlights
13281 org-latex-fragment-image-overlays)
13282 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13283 (org-remove-occur-highlights)
13284 (org-remove-latex-fragment-image-overlays)
13285 (message "Temporary highlights/overlays removed from current buffer"))
13286 ((and (local-variable-p 'org-finish-function (current-buffer))
13287 (fboundp org-finish-function))
13288 (funcall org-finish-function))
13289 ((org-at-property-p)
13290 (call-interactively 'org-property-action))
13291 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13292 ((org-on-heading-p) (call-interactively 'org-set-tags))
13293 ((org-at-table.el-p)
13294 (require 'table)
13295 (beginning-of-line 1)
13296 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13297 (call-interactively 'table-recognize-table))
13298 ((org-at-table-p)
13299 (org-table-maybe-eval-formula)
13300 (if arg
13301 (call-interactively 'org-table-recalculate)
13302 (org-table-maybe-recalculate-line))
13303 (call-interactively 'org-table-align))
13304 ((or (org-footnote-at-reference-p)
13305 (org-footnote-at-definition-p))
13306 (call-interactively 'org-footnote-action))
13307 ((org-at-item-checkbox-p)
13308 (call-interactively 'org-toggle-checkbox))
13309 ((org-at-item-p)
13310 (call-interactively 'org-maybe-renumber-ordered-list))
13311 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13312 ;; Dynamic block
13313 (beginning-of-line 1)
13314 (save-excursion (org-update-dblock)))
13315 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13316 (cond
13317 ((equal (match-string 1) "TBLFM")
13318 ;; Recalculate the table before this line
13319 (save-excursion
13320 (beginning-of-line 1)
13321 (skip-chars-backward " \r\n\t")
13322 (if (org-at-table-p)
13323 (org-call-with-arg 'org-table-recalculate t))))
13325 ; (org-set-regexps-and-options)
13326 ; (org-restart-font-lock)
13327 (let ((org-inhibit-startup t)) (org-mode-restart))
13328 (message "Local setup has been refreshed"))))
13329 (t (error "C-c C-c can do nothing useful at this location.")))))
13331 (defun org-mode-restart ()
13332 "Restart Org-mode, to scan again for special lines.
13333 Also updates the keyword regular expressions."
13334 (interactive)
13335 (org-mode)
13336 (message "Org-mode restarted"))
13338 (defun org-kill-note-or-show-branches ()
13339 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13340 (interactive)
13341 (if (not org-finish-function)
13342 (call-interactively 'show-branches)
13343 (let ((org-note-abort t))
13344 (funcall org-finish-function))))
13346 (defun org-return (&optional indent)
13347 "Goto next table row or insert a newline.
13348 Calls `org-table-next-row' or `newline', depending on context.
13349 See the individual commands for more information."
13350 (interactive)
13351 (cond
13352 ((bobp) (if indent (newline-and-indent) (newline)))
13353 ((and (org-at-heading-p)
13354 (looking-at
13355 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13356 (org-show-entry)
13357 (end-of-line 1)
13358 (newline))
13359 ((org-at-table-p)
13360 (org-table-justify-field-maybe)
13361 (call-interactively 'org-table-next-row))
13362 (t (if indent (newline-and-indent) (newline)))))
13364 (defun org-return-indent ()
13365 "Goto next table row or insert a newline and indent.
13366 Calls `org-table-next-row' or `newline-and-indent', depending on
13367 context. See the individual commands for more information."
13368 (interactive)
13369 (org-return t))
13371 (defun org-ctrl-c-star ()
13372 "Compute table, or change heading status of lines.
13373 Calls `org-table-recalculate' or `org-toggle-heading',
13374 depending on context."
13375 (interactive)
13376 (cond
13377 ((org-at-table-p)
13378 (call-interactively 'org-table-recalculate))
13380 ;; Convert all lines in region to list items
13381 (call-interactively 'org-toggle-heading))))
13383 (defun org-ctrl-c-minus ()
13384 "Insert separator line in table or modify bullet status of line.
13385 Also turns a plain line or a region of lines into list items.
13386 Calls `org-table-insert-hline', `org-toggle-item', or
13387 `org-cycle-list-bullet', depending on context."
13388 (interactive)
13389 (cond
13390 ((org-at-table-p)
13391 (call-interactively 'org-table-insert-hline))
13392 ((org-region-active-p)
13393 (call-interactively 'org-toggle-item))
13394 ((org-in-item-p)
13395 (call-interactively 'org-cycle-list-bullet))
13397 (call-interactively 'org-toggle-item))))
13399 (defun org-toggle-item ()
13400 "Convert headings or normal lines to items, items to normal lines.
13401 If there is no active region, only the current line is considered.
13403 If the first line in the region is a headline, convert all headlines to items.
13405 If the first line in the region is an item, convert all items to normal lines.
13407 If the first line is normal text, add an item bullet to each line."
13408 (interactive)
13409 (let (l2 l beg end)
13410 (if (org-region-active-p)
13411 (setq beg (region-beginning) end (region-end))
13412 (setq beg (point-at-bol)
13413 end (min (1+ (point-at-eol)) (point-max))))
13414 (save-excursion
13415 (goto-char end)
13416 (setq l2 (org-current-line))
13417 (goto-char beg)
13418 (beginning-of-line 1)
13419 (setq l (1- (org-current-line)))
13420 (if (org-at-item-p)
13421 ;; We already have items, de-itemize
13422 (while (< (setq l (1+ l)) l2)
13423 (when (org-at-item-p)
13424 (goto-char (match-beginning 2))
13425 (delete-region (match-beginning 2) (match-end 2))
13426 (and (looking-at "[ \t]+") (replace-match "")))
13427 (beginning-of-line 2))
13428 (if (org-on-heading-p)
13429 ;; Headings, convert to items
13430 (while (< (setq l (1+ l)) l2)
13431 (if (looking-at org-outline-regexp)
13432 (replace-match "- " t t))
13433 (beginning-of-line 2))
13434 ;; normal lines, turn them into items
13435 (while (< (setq l (1+ l)) l2)
13436 (unless (org-at-item-p)
13437 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13438 (replace-match "\\1- \\2")))
13439 (beginning-of-line 2)))))))
13441 (defun org-toggle-heading (&optional nstars)
13442 "Convert headings to normal text, or items or text to headings.
13443 If there is no active region, only the current line is considered.
13445 If the first line is a heading, remove the stars from all headlines
13446 in the region.
13448 If the first line is a plain list item, turn all plain list items into
13449 headings.
13451 If the first line is a normal line, turn each and every line in the region
13452 into a heading.
13454 When converting a line into a heading, the number of stars is chosen
13455 such that the lines become children of the current entry. However, when
13456 a prefix argument is given, its value determines the number of stars to add."
13457 (interactive "P")
13458 (let (l2 l itemp beg end)
13459 (if (org-region-active-p)
13460 (setq beg (region-beginning) end (region-end))
13461 (setq beg (point-at-bol)
13462 end (min (1+ (point-at-eol)) (point-max))))
13463 (save-excursion
13464 (goto-char end)
13465 (setq l2 (org-current-line))
13466 (goto-char beg)
13467 (beginning-of-line 1)
13468 (setq l (1- (org-current-line)))
13469 (if (org-on-heading-p)
13470 ;; We already have headlines, de-star them
13471 (while (< (setq l (1+ l)) l2)
13472 (when (org-on-heading-p t)
13473 (and (looking-at outline-regexp) (replace-match "")))
13474 (beginning-of-line 2))
13475 (setq itemp (org-at-item-p))
13476 (let* ((stars
13477 (if nstars
13478 (make-string (prefix-numeric-value current-prefix-arg)
13480 (save-excursion
13481 (re-search-backward org-complex-heading-regexp nil t)
13482 (or (match-string 1) "*"))))
13483 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13484 (rpl (concat stars add-stars " ")))
13485 (while (< (setq l (1+ l)) l2)
13486 (if itemp
13487 (and (org-at-item-p) (replace-match rpl t t))
13488 (unless (org-on-heading-p)
13489 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13490 (replace-match (concat rpl (match-string 2))))))
13491 (beginning-of-line 2)))))))
13493 (defun org-meta-return (&optional arg)
13494 "Insert a new heading or wrap a region in a table.
13495 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13496 See the individual commands for more information."
13497 (interactive "P")
13498 (cond
13499 ((org-at-table-p)
13500 (call-interactively 'org-table-wrap-region))
13501 (t (call-interactively 'org-insert-heading))))
13503 ;;; Menu entries
13505 ;; Define the Org-mode menus
13506 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13507 '("Tbl"
13508 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13509 ["Next Field" org-cycle (org-at-table-p)]
13510 ["Previous Field" org-shifttab (org-at-table-p)]
13511 ["Next Row" org-return (org-at-table-p)]
13512 "--"
13513 ["Blank Field" org-table-blank-field (org-at-table-p)]
13514 ["Edit Field" org-table-edit-field (org-at-table-p)]
13515 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13516 "--"
13517 ("Column"
13518 ["Move Column Left" org-metaleft (org-at-table-p)]
13519 ["Move Column Right" org-metaright (org-at-table-p)]
13520 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13521 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13522 ("Row"
13523 ["Move Row Up" org-metaup (org-at-table-p)]
13524 ["Move Row Down" org-metadown (org-at-table-p)]
13525 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13526 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13527 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13528 "--"
13529 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13530 ("Rectangle"
13531 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13532 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13533 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13534 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13535 "--"
13536 ("Calculate"
13537 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13538 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13539 ["Edit Formulas" org-edit-special (org-at-table-p)]
13540 "--"
13541 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13542 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13543 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13544 "--"
13545 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13546 "--"
13547 ["Sum Column/Rectangle" org-table-sum
13548 (or (org-at-table-p) (org-region-active-p))]
13549 ["Which Column?" org-table-current-column (org-at-table-p)])
13550 ["Debug Formulas"
13551 org-table-toggle-formula-debugger
13552 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13553 ["Show Col/Row Numbers"
13554 org-table-toggle-coordinate-overlays
13555 :style toggle
13556 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13557 "--"
13558 ["Create" org-table-create (and (not (org-at-table-p))
13559 org-enable-table-editor)]
13560 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13561 ["Import from File" org-table-import (not (org-at-table-p))]
13562 ["Export to File" org-table-export (org-at-table-p)]
13563 "--"
13564 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13566 (easy-menu-define org-org-menu org-mode-map "Org menu"
13567 '("Org"
13568 ("Show/Hide"
13569 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13570 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13571 ["Sparse Tree..." org-sparse-tree t]
13572 ["Reveal Context" org-reveal t]
13573 ["Show All" show-all t]
13574 "--"
13575 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13576 "--"
13577 ["New Heading" org-insert-heading t]
13578 ("Navigate Headings"
13579 ["Up" outline-up-heading t]
13580 ["Next" outline-next-visible-heading t]
13581 ["Previous" outline-previous-visible-heading t]
13582 ["Next Same Level" outline-forward-same-level t]
13583 ["Previous Same Level" outline-backward-same-level t]
13584 "--"
13585 ["Jump" org-goto t])
13586 ("Edit Structure"
13587 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13588 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13589 "--"
13590 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13591 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13592 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13593 "--"
13594 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13595 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13596 ["Demote Heading" org-metaright (not (org-at-table-p))]
13597 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13598 "--"
13599 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13600 "--"
13601 ["Convert to odd levels" org-convert-to-odd-levels t]
13602 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13603 ("Editing"
13604 ["Emphasis..." org-emphasize t]
13605 ["Edit Source Example" org-edit-special t]
13606 "--"
13607 ["Footnote new/jump" org-footnote-action t]
13608 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13609 ("Archive"
13610 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13611 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13612 ; :active t :keys "C-u C-c C-x C-a"]
13613 ["Sparse trees open ARCHIVE trees"
13614 (setq org-sparse-tree-open-archived-trees
13615 (not org-sparse-tree-open-archived-trees))
13616 :style toggle :selected org-sparse-tree-open-archived-trees]
13617 ["Cycling opens ARCHIVE trees"
13618 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13619 :style toggle :selected org-cycle-open-archived-trees]
13620 "--"
13621 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13622 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13623 ; ["Check and Move Children" (org-archive-subtree '(4))
13624 ; :active t :keys "C-u C-c C-x C-s"]
13626 "--"
13627 ("TODO Lists"
13628 ["TODO/DONE/-" org-todo t]
13629 ("Select keyword"
13630 ["Next keyword" org-shiftright (org-on-heading-p)]
13631 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13632 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13633 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13634 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13635 ["Show TODO Tree" org-show-todo-tree t]
13636 ["Global TODO list" org-todo-list t]
13637 "--"
13638 ["Set Priority" org-priority t]
13639 ["Priority Up" org-shiftup t]
13640 ["Priority Down" org-shiftdown t])
13641 ("TAGS and Properties"
13642 ["Set Tags" org-set-tags-command t]
13643 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13644 "--"
13645 ["Set property" org-set-property t]
13646 ["Column view of properties" org-columns t]
13647 ["Insert Column View DBlock" org-insert-columns-dblock t])
13648 ("Dates and Scheduling"
13649 ["Timestamp" org-time-stamp t]
13650 ["Timestamp (inactive)" org-time-stamp-inactive t]
13651 ("Change Date"
13652 ["1 Day Later" org-shiftright t]
13653 ["1 Day Earlier" org-shiftleft t]
13654 ["1 ... Later" org-shiftup t]
13655 ["1 ... Earlier" org-shiftdown t])
13656 ["Compute Time Range" org-evaluate-time-range t]
13657 ["Schedule Item" org-schedule t]
13658 ["Deadline" org-deadline t]
13659 "--"
13660 ["Custom time format" org-toggle-time-stamp-overlays
13661 :style radio :selected org-display-custom-times]
13662 "--"
13663 ["Goto Calendar" org-goto-calendar t]
13664 ["Date from Calendar" org-date-from-calendar t]
13665 "--"
13666 ["Start/Restart Timer" org-timer-start t]
13667 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13668 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13669 ["Insert Timer String" org-timer t]
13670 ["Insert Timer Item" org-timer-item t])
13671 ("Logging work"
13672 ["Clock in" org-clock-in t]
13673 ["Clock out" org-clock-out t]
13674 ["Clock cancel" org-clock-cancel t]
13675 ["Goto running clock" org-clock-goto t]
13676 ["Display times" org-clock-display t]
13677 ["Create clock table" org-clock-report t]
13678 "--"
13679 ["Record DONE time"
13680 (progn (setq org-log-done (not org-log-done))
13681 (message "Switching to %s will %s record a timestamp"
13682 (car org-done-keywords)
13683 (if org-log-done "automatically" "not")))
13684 :style toggle :selected org-log-done])
13685 "--"
13686 ["Agenda Command..." org-agenda t]
13687 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13688 ("File List for Agenda")
13689 ("Special views current file"
13690 ["TODO Tree" org-show-todo-tree t]
13691 ["Check Deadlines" org-check-deadlines t]
13692 ["Timeline" org-timeline t]
13693 ["Tags Tree" org-tags-sparse-tree t])
13694 "--"
13695 ("Hyperlinks"
13696 ["Store Link (Global)" org-store-link t]
13697 ["Insert Link" org-insert-link t]
13698 ["Follow Link" org-open-at-point t]
13699 "--"
13700 ["Next link" org-next-link t]
13701 ["Previous link" org-previous-link t]
13702 "--"
13703 ["Descriptive Links"
13704 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13705 :style radio
13706 :selected (member '(org-link) buffer-invisibility-spec)]
13707 ["Literal Links"
13708 (progn
13709 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13710 :style radio
13711 :selected (not (member '(org-link) buffer-invisibility-spec))])
13712 "--"
13713 ["Export/Publish..." org-export t]
13714 ("LaTeX"
13715 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13716 :selected org-cdlatex-mode]
13717 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13718 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13719 ["Modify math symbol" org-cdlatex-math-modify
13720 (org-inside-LaTeX-fragment-p)]
13721 ["Export LaTeX fragments as images"
13722 (if (featurep 'org-exp)
13723 (setq org-export-with-LaTeX-fragments
13724 (not org-export-with-LaTeX-fragments))
13725 (require 'org-exp))
13726 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13727 org-export-with-LaTeX-fragments)])
13728 "--"
13729 ("Documentation"
13730 ["Show Version" org-version t]
13731 ["Info Documentation" org-info t])
13732 ("Customize"
13733 ["Browse Org Group" org-customize t]
13734 "--"
13735 ["Expand This Menu" org-create-customize-menu
13736 (fboundp 'customize-menu-create)])
13737 "--"
13738 ["Refresh setup" org-mode-restart t]
13741 (defun org-info (&optional node)
13742 "Read documentation for Org-mode in the info system.
13743 With optional NODE, go directly to that node."
13744 (interactive)
13745 (info (format "(org)%s" (or node ""))))
13747 (defun org-install-agenda-files-menu ()
13748 (let ((bl (buffer-list)))
13749 (save-excursion
13750 (while bl
13751 (set-buffer (pop bl))
13752 (if (org-mode-p) (setq bl nil)))
13753 (when (org-mode-p)
13754 (easy-menu-change
13755 '("Org") "File List for Agenda"
13756 (append
13757 (list
13758 ["Edit File List" (org-edit-agenda-file-list) t]
13759 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13760 ["Remove Current File from List" org-remove-file t]
13761 ["Cycle through agenda files" org-cycle-agenda-files t]
13762 ["Occur in all agenda files" org-occur-in-agenda-files t]
13763 "--")
13764 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13766 ;;;; Documentation
13768 ;;;###autoload
13769 (defun org-require-autoloaded-modules ()
13770 (interactive)
13771 (mapc 'require
13772 '(org-agenda org-archive org-clock org-colview
13773 org-exp org-id org-export-latex org-publish
13774 org-remember org-table)))
13776 ;;;###autoload
13777 (defun org-customize ()
13778 "Call the customize function with org as argument."
13779 (interactive)
13780 (org-load-modules-maybe)
13781 (org-require-autoloaded-modules)
13782 (customize-browse 'org))
13784 (defun org-create-customize-menu ()
13785 "Create a full customization menu for Org-mode, insert it into the menu."
13786 (interactive)
13787 (org-load-modules-maybe)
13788 (org-require-autoloaded-modules)
13789 (if (fboundp 'customize-menu-create)
13790 (progn
13791 (easy-menu-change
13792 '("Org") "Customize"
13793 `(["Browse Org group" org-customize t]
13794 "--"
13795 ,(customize-menu-create 'org)
13796 ["Set" Custom-set t]
13797 ["Save" Custom-save t]
13798 ["Reset to Current" Custom-reset-current t]
13799 ["Reset to Saved" Custom-reset-saved t]
13800 ["Reset to Standard Settings" Custom-reset-standard t]))
13801 (message "\"Org\"-menu now contains full customization menu"))
13802 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13804 ;;;; Miscellaneous stuff
13806 ;;; Generally useful functions
13808 (defun org-find-text-property-in-string (prop s)
13809 "Return the first non-nil value of property PROP in string S."
13810 (or (get-text-property 0 prop s)
13811 (get-text-property (or (next-single-property-change 0 prop s) 0)
13812 prop s)))
13814 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13815 "Display the given MESSAGE as a warning."
13816 (if (fboundp 'display-warning)
13817 (display-warning 'org message
13818 (if (featurep 'xemacs)
13819 'warning
13820 :warning))
13821 (let ((buf (get-buffer-create "*Org warnings*")))
13822 (with-current-buffer buf
13823 (goto-char (point-max))
13824 (insert "Warning (Org): " message)
13825 (unless (bolp)
13826 (newline)))
13827 (display-buffer buf)
13828 (sit-for 0))))
13830 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13831 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13832 (if (and marker (marker-buffer marker)
13833 (buffer-live-p (marker-buffer marker)))
13834 (progn
13835 (switch-to-buffer (marker-buffer marker))
13836 (if (or (> marker (point-max)) (< marker (point-min)))
13837 (widen))
13838 (goto-char marker)
13839 (org-show-context 'org-goto))
13840 (if bookmark
13841 (bookmark-jump bookmark)
13842 (error "Cannot find location"))))
13844 (defun org-quote-csv-field (s)
13845 "Quote field for inclusion in CSV material."
13846 (if (string-match "[\",]" s)
13847 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13850 (defun org-plist-delete (plist property)
13851 "Delete PROPERTY from PLIST.
13852 This is in contrast to merely setting it to 0."
13853 (let (p)
13854 (while plist
13855 (if (not (eq property (car plist)))
13856 (setq p (plist-put p (car plist) (nth 1 plist))))
13857 (setq plist (cddr plist)))
13860 (defun org-force-self-insert (N)
13861 "Needed to enforce self-insert under remapping."
13862 (interactive "p")
13863 (self-insert-command N))
13865 (defun org-string-width (s)
13866 "Compute width of string, ignoring invisible characters.
13867 This ignores character with invisibility property `org-link', and also
13868 characters with property `org-cwidth', because these will become invisible
13869 upon the next fontification round."
13870 (let (b l)
13871 (when (or (eq t buffer-invisibility-spec)
13872 (assq 'org-link buffer-invisibility-spec))
13873 (while (setq b (text-property-any 0 (length s)
13874 'invisible 'org-link s))
13875 (setq s (concat (substring s 0 b)
13876 (substring s (or (next-single-property-change
13877 b 'invisible s) (length s)))))))
13878 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13879 (setq s (concat (substring s 0 b)
13880 (substring s (or (next-single-property-change
13881 b 'org-cwidth s) (length s))))))
13882 (setq l (string-width s) b -1)
13883 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13884 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13887 (defun org-get-indentation (&optional line)
13888 "Get the indentation of the current line, interpreting tabs.
13889 When LINE is given, assume it represents a line and compute its indentation."
13890 (if line
13891 (if (string-match "^ *" (org-remove-tabs line))
13892 (match-end 0))
13893 (save-excursion
13894 (beginning-of-line 1)
13895 (skip-chars-forward " \t")
13896 (current-column))))
13898 (defun org-remove-tabs (s &optional width)
13899 "Replace tabulators in S with spaces.
13900 Assumes that s is a single line, starting in column 0."
13901 (setq width (or width tab-width))
13902 (while (string-match "\t" s)
13903 (setq s (replace-match
13904 (make-string
13905 (- (* width (/ (+ (match-beginning 0) width) width))
13906 (match-beginning 0)) ?\ )
13907 t t s)))
13910 (defun org-fix-indentation (line ind)
13911 "Fix indentation in LINE.
13912 IND is a cons cell with target and minimum indentation.
13913 If the current indentation in LINE is smaller than the minimum,
13914 leave it alone. If it is larger than ind, set it to the target."
13915 (let* ((l (org-remove-tabs line))
13916 (i (org-get-indentation l))
13917 (i1 (car ind)) (i2 (cdr ind)))
13918 (if (>= i i2) (setq l (substring line i2)))
13919 (if (> i1 0)
13920 (concat (make-string i1 ?\ ) l)
13921 l)))
13923 (defun org-base-buffer (buffer)
13924 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13925 (if (not buffer)
13926 buffer
13927 (or (buffer-base-buffer buffer)
13928 buffer)))
13930 (defun org-trim (s)
13931 "Remove whitespace at beginning and end of string."
13932 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13933 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13936 (defun org-wrap (string &optional width lines)
13937 "Wrap string to either a number of lines, or a width in characters.
13938 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13939 that costs. If there is a word longer than WIDTH, the text is actually
13940 wrapped to the length of that word.
13941 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13942 many lines, whatever width that takes.
13943 The return value is a list of lines, without newlines at the end."
13944 (let* ((words (org-split-string string "[ \t\n]+"))
13945 (maxword (apply 'max (mapcar 'org-string-width words)))
13946 w ll)
13947 (cond (width
13948 (org-do-wrap words (max maxword width)))
13949 (lines
13950 (setq w maxword)
13951 (setq ll (org-do-wrap words maxword))
13952 (if (<= (length ll) lines)
13954 (setq ll words)
13955 (while (> (length ll) lines)
13956 (setq w (1+ w))
13957 (setq ll (org-do-wrap words w)))
13958 ll))
13959 (t (error "Cannot wrap this")))))
13961 (defun org-do-wrap (words width)
13962 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13963 (let (lines line)
13964 (while words
13965 (setq line (pop words))
13966 (while (and words (< (+ (length line) (length (car words))) width))
13967 (setq line (concat line " " (pop words))))
13968 (setq lines (push line lines)))
13969 (nreverse lines)))
13971 (defun org-split-string (string &optional separators)
13972 "Splits STRING into substrings at SEPARATORS.
13973 No empty strings are returned if there are matches at the beginning
13974 and end of string."
13975 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13976 (start 0)
13977 notfirst
13978 (list nil))
13979 (while (and (string-match rexp string
13980 (if (and notfirst
13981 (= start (match-beginning 0))
13982 (< start (length string)))
13983 (1+ start) start))
13984 (< (match-beginning 0) (length string)))
13985 (setq notfirst t)
13986 (or (eq (match-beginning 0) 0)
13987 (and (eq (match-beginning 0) (match-end 0))
13988 (eq (match-beginning 0) start))
13989 (setq list
13990 (cons (substring string start (match-beginning 0))
13991 list)))
13992 (setq start (match-end 0)))
13993 (or (eq start (length string))
13994 (setq list
13995 (cons (substring string start)
13996 list)))
13997 (nreverse list)))
13999 (defun org-context ()
14000 "Return a list of contexts of the current cursor position.
14001 If several contexts apply, all are returned.
14002 Each context entry is a list with a symbol naming the context, and
14003 two positions indicating start and end of the context. Possible
14004 contexts are:
14006 :headline anywhere in a headline
14007 :headline-stars on the leading stars in a headline
14008 :todo-keyword on a TODO keyword (including DONE) in a headline
14009 :tags on the TAGS in a headline
14010 :priority on the priority cookie in a headline
14011 :item on the first line of a plain list item
14012 :item-bullet on the bullet/number of a plain list item
14013 :checkbox on the checkbox in a plain list item
14014 :table in an org-mode table
14015 :table-special on a special filed in a table
14016 :table-table in a table.el table
14017 :link on a hyperlink
14018 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14019 :target on a <<target>>
14020 :radio-target on a <<<radio-target>>>
14021 :latex-fragment on a LaTeX fragment
14022 :latex-preview on a LaTeX fragment with overlayed preview image
14024 This function expects the position to be visible because it uses font-lock
14025 faces as a help to recognize the following contexts: :table-special, :link,
14026 and :keyword."
14027 (let* ((f (get-text-property (point) 'face))
14028 (faces (if (listp f) f (list f)))
14029 (p (point)) clist o)
14030 ;; First the large context
14031 (cond
14032 ((org-on-heading-p t)
14033 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14034 (when (progn
14035 (beginning-of-line 1)
14036 (looking-at org-todo-line-tags-regexp))
14037 (push (org-point-in-group p 1 :headline-stars) clist)
14038 (push (org-point-in-group p 2 :todo-keyword) clist)
14039 (push (org-point-in-group p 4 :tags) clist))
14040 (goto-char p)
14041 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14042 (if (looking-at "\\[#[A-Z0-9]\\]")
14043 (push (org-point-in-group p 0 :priority) clist)))
14045 ((org-at-item-p)
14046 (push (org-point-in-group p 2 :item-bullet) clist)
14047 (push (list :item (point-at-bol)
14048 (save-excursion (org-end-of-item) (point)))
14049 clist)
14050 (and (org-at-item-checkbox-p)
14051 (push (org-point-in-group p 0 :checkbox) clist)))
14053 ((org-at-table-p)
14054 (push (list :table (org-table-begin) (org-table-end)) clist)
14055 (if (memq 'org-formula faces)
14056 (push (list :table-special
14057 (previous-single-property-change p 'face)
14058 (next-single-property-change p 'face)) clist)))
14059 ((org-at-table-p 'any)
14060 (push (list :table-table) clist)))
14061 (goto-char p)
14063 ;; Now the small context
14064 (cond
14065 ((org-at-timestamp-p)
14066 (push (org-point-in-group p 0 :timestamp) clist))
14067 ((memq 'org-link faces)
14068 (push (list :link
14069 (previous-single-property-change p 'face)
14070 (next-single-property-change p 'face)) clist))
14071 ((memq 'org-special-keyword faces)
14072 (push (list :keyword
14073 (previous-single-property-change p 'face)
14074 (next-single-property-change p 'face)) clist))
14075 ((org-on-target-p)
14076 (push (org-point-in-group p 0 :target) clist)
14077 (goto-char (1- (match-beginning 0)))
14078 (if (looking-at org-radio-target-regexp)
14079 (push (org-point-in-group p 0 :radio-target) clist))
14080 (goto-char p))
14081 ((setq o (car (delq nil
14082 (mapcar
14083 (lambda (x)
14084 (if (memq x org-latex-fragment-image-overlays) x))
14085 (org-overlays-at (point))))))
14086 (push (list :latex-fragment
14087 (org-overlay-start o) (org-overlay-end o)) clist)
14088 (push (list :latex-preview
14089 (org-overlay-start o) (org-overlay-end o)) clist))
14090 ((org-inside-LaTeX-fragment-p)
14091 ;; FIXME: positions wrong.
14092 (push (list :latex-fragment (point) (point)) clist)))
14094 (setq clist (nreverse (delq nil clist)))
14095 clist))
14097 ;; FIXME: Compare with at-regexp-p Do we need both?
14098 (defun org-in-regexp (re &optional nlines visually)
14099 "Check if point is inside a match of regexp.
14100 Normally only the current line is checked, but you can include NLINES extra
14101 lines both before and after point into the search.
14102 If VISUALLY is set, require that the cursor is not after the match but
14103 really on, so that the block visually is on the match."
14104 (catch 'exit
14105 (let ((pos (point))
14106 (eol (point-at-eol (+ 1 (or nlines 0))))
14107 (inc (if visually 1 0)))
14108 (save-excursion
14109 (beginning-of-line (- 1 (or nlines 0)))
14110 (while (re-search-forward re eol t)
14111 (if (and (<= (match-beginning 0) pos)
14112 (>= (+ inc (match-end 0)) pos))
14113 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14115 (defun org-at-regexp-p (regexp)
14116 "Is point inside a match of REGEXP in the current line?"
14117 (catch 'exit
14118 (save-excursion
14119 (let ((pos (point)) (end (point-at-eol)))
14120 (beginning-of-line 1)
14121 (while (re-search-forward regexp end t)
14122 (if (and (<= (match-beginning 0) pos)
14123 (>= (match-end 0) pos))
14124 (throw 'exit t)))
14125 nil))))
14127 (defun org-occur-in-agenda-files (regexp &optional nlines)
14128 "Call `multi-occur' with buffers for all agenda files."
14129 (interactive "sOrg-files matching: \np")
14130 (let* ((files (org-agenda-files))
14131 (tnames (mapcar 'file-truename files))
14132 (extra org-agenda-text-search-extra-files)
14134 (when (eq (car extra) 'agenda-archives)
14135 (setq extra (cdr extra))
14136 (setq files (org-add-archive-files files)))
14137 (while (setq f (pop extra))
14138 (unless (member (file-truename f) tnames)
14139 (add-to-list 'files f 'append)
14140 (add-to-list 'tnames (file-truename f) 'append)))
14141 (multi-occur
14142 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14143 regexp)))
14145 (if (boundp 'occur-mode-find-occurrence-hook)
14146 ;; Emacs 23
14147 (add-hook 'occur-mode-find-occurrence-hook
14148 (lambda ()
14149 (when (org-mode-p)
14150 (org-reveal))))
14151 ;; Emacs 22
14152 (defadvice occur-mode-goto-occurrence
14153 (after org-occur-reveal activate)
14154 (and (org-mode-p) (org-reveal)))
14155 (defadvice occur-mode-goto-occurrence-other-window
14156 (after org-occur-reveal activate)
14157 (and (org-mode-p) (org-reveal)))
14158 (defadvice occur-mode-display-occurrence
14159 (after org-occur-reveal activate)
14160 (when (org-mode-p)
14161 (let ((pos (occur-mode-find-occurrence)))
14162 (with-current-buffer (marker-buffer pos)
14163 (save-excursion
14164 (goto-char pos)
14165 (org-reveal)))))))
14167 (defun org-uniquify (list)
14168 "Remove duplicate elements from LIST."
14169 (let (res)
14170 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14171 res))
14173 (defun org-delete-all (elts list)
14174 "Remove all elements in ELTS from LIST."
14175 (while elts
14176 (setq list (delete (pop elts) list)))
14177 list)
14179 (defun org-back-over-empty-lines ()
14180 "Move backwards over whitespace, to the beginning of the first empty line.
14181 Returns the number of empty lines passed."
14182 (let ((pos (point)))
14183 (skip-chars-backward " \t\n\r")
14184 (beginning-of-line 2)
14185 (goto-char (min (point) pos))
14186 (count-lines (point) pos)))
14188 (defun org-skip-whitespace ()
14189 (skip-chars-forward " \t\n\r"))
14191 (defun org-point-in-group (point group &optional context)
14192 "Check if POINT is in match-group GROUP.
14193 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14194 match. If the match group does ot exist or point is not inside it,
14195 return nil."
14196 (and (match-beginning group)
14197 (>= point (match-beginning group))
14198 (<= point (match-end group))
14199 (if context
14200 (list context (match-beginning group) (match-end group))
14201 t)))
14203 (defun org-switch-to-buffer-other-window (&rest args)
14204 "Switch to buffer in a second window on the current frame.
14205 In particular, do not allow pop-up frames."
14206 (let (pop-up-frames special-display-buffer-names special-display-regexps
14207 special-display-function)
14208 (apply 'switch-to-buffer-other-window args)))
14210 (defun org-combine-plists (&rest plists)
14211 "Create a single property list from all plists in PLISTS.
14212 The process starts by copying the first list, and then setting properties
14213 from the other lists. Settings in the last list are the most significant
14214 ones and overrule settings in the other lists."
14215 (let ((rtn (copy-sequence (pop plists)))
14216 p v ls)
14217 (while plists
14218 (setq ls (pop plists))
14219 (while ls
14220 (setq p (pop ls) v (pop ls))
14221 (setq rtn (plist-put rtn p v))))
14222 rtn))
14224 (defun org-move-line-down (arg)
14225 "Move the current line down. With prefix argument, move it past ARG lines."
14226 (interactive "p")
14227 (let ((col (current-column))
14228 beg end pos)
14229 (beginning-of-line 1) (setq beg (point))
14230 (beginning-of-line 2) (setq end (point))
14231 (beginning-of-line (+ 1 arg))
14232 (setq pos (move-marker (make-marker) (point)))
14233 (insert (delete-and-extract-region beg end))
14234 (goto-char pos)
14235 (org-move-to-column col)))
14237 (defun org-move-line-up (arg)
14238 "Move the current line up. With prefix argument, move it past ARG lines."
14239 (interactive "p")
14240 (let ((col (current-column))
14241 beg end pos)
14242 (beginning-of-line 1) (setq beg (point))
14243 (beginning-of-line 2) (setq end (point))
14244 (beginning-of-line (- arg))
14245 (setq pos (move-marker (make-marker) (point)))
14246 (insert (delete-and-extract-region beg end))
14247 (goto-char pos)
14248 (org-move-to-column col)))
14250 (defun org-replace-escapes (string table)
14251 "Replace %-escapes in STRING with values in TABLE.
14252 TABLE is an association list with keys like \"%a\" and string values.
14253 The sequences in STRING may contain normal field width and padding information,
14254 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14255 so values can contain further %-escapes if they are define later in TABLE."
14256 (let ((case-fold-search nil)
14257 e re rpl)
14258 (while (setq e (pop table))
14259 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14260 (while (string-match re string)
14261 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14262 (cdr e)))
14263 (setq string (replace-match rpl t t string))))
14264 string))
14267 (defun org-sublist (list start end)
14268 "Return a section of LIST, from START to END.
14269 Counting starts at 1."
14270 (let (rtn (c start))
14271 (setq list (nthcdr (1- start) list))
14272 (while (and list (<= c end))
14273 (push (pop list) rtn)
14274 (setq c (1+ c)))
14275 (nreverse rtn)))
14277 (defun org-find-base-buffer-visiting (file)
14278 "Like `find-buffer-visiting' but alway return the base buffer and
14279 not an indirect buffer."
14280 (let ((buf (find-buffer-visiting file)))
14281 (if buf
14282 (or (buffer-base-buffer buf) buf)
14283 nil)))
14285 (defun org-image-file-name-regexp (&optional extensions)
14286 "Return regexp matching the file names of images.
14287 If EXTENSIONS is given, only match these."
14288 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14289 (image-file-name-regexp)
14290 (let ((image-file-name-extensions
14291 (or extensions
14292 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14293 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14294 (concat "\\."
14295 (regexp-opt (nconc (mapcar 'upcase
14296 image-file-name-extensions)
14297 image-file-name-extensions)
14299 "\\'"))))
14301 (defun org-file-image-p (file &optional extensions)
14302 "Return non-nil if FILE is an image."
14303 (save-match-data
14304 (string-match (org-image-file-name-regexp extensions) file)))
14306 (defun org-get-cursor-date ()
14307 "Return the date at cursor in as a time.
14308 This works in the calendar and in the agenda, anywhere else it just
14309 returns the current time."
14310 (let (date day defd)
14311 (cond
14312 ((eq major-mode 'calendar-mode)
14313 (setq date (calendar-cursor-to-date)
14314 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14315 ((eq major-mode 'org-agenda-mode)
14316 (setq day (get-text-property (point) 'day))
14317 (if day
14318 (setq date (calendar-gregorian-from-absolute day)
14319 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14320 (nth 2 date))))))
14321 (or defd (current-time))))
14323 (defvar org-agenda-action-marker (make-marker)
14324 "Marker pointing to the entry for the next agenda action.")
14326 (defun org-mark-entry-for-agenda-action ()
14327 "Mark the current entry as target of an agenda action.
14328 Agenda actions are actions executed from the agenda with the key `k',
14329 which make use of the date at the cursor."
14330 (interactive)
14331 (move-marker org-agenda-action-marker
14332 (save-excursion (org-back-to-heading t) (point))
14333 (current-buffer))
14334 (message
14335 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14337 ;;; Paragraph filling stuff.
14338 ;; We want this to be just right, so use the full arsenal.
14340 (defun org-indent-line-function ()
14341 "Indent line like previous, but further if previous was headline or item."
14342 (interactive)
14343 (let* ((pos (point))
14344 (itemp (org-at-item-p))
14345 column bpos bcol tpos tcol bullet btype bullet-type)
14346 ;; Find the previous relevant line
14347 (beginning-of-line 1)
14348 (cond
14349 ((looking-at "#") (setq column 0))
14350 ((looking-at "\\*+ ") (setq column 0))
14352 (beginning-of-line 0)
14353 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14354 (beginning-of-line 0))
14355 (cond
14356 ((looking-at "\\*+[ \t]+")
14357 (if (not org-adapt-indentation)
14358 (setq column 0)
14359 (goto-char (match-end 0))
14360 (setq column (current-column))))
14361 ((org-in-item-p)
14362 (org-beginning-of-item)
14363 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14364 (setq bpos (match-beginning 1) tpos (match-end 0)
14365 bcol (progn (goto-char bpos) (current-column))
14366 tcol (progn (goto-char tpos) (current-column))
14367 bullet (match-string 1)
14368 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14369 (if (> tcol (+ bcol org-description-max-indent))
14370 (setq tcol (+ bcol 5)))
14371 (if (not itemp)
14372 (setq column tcol)
14373 (goto-char pos)
14374 (beginning-of-line 1)
14375 (if (looking-at "\\S-")
14376 (progn
14377 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14378 (setq bullet (match-string 1)
14379 btype (if (string-match "[0-9]" bullet) "n" bullet))
14380 (setq column (if (equal btype bullet-type) bcol tcol)))
14381 (setq column (org-get-indentation)))))
14382 (t (setq column (org-get-indentation))))))
14383 (goto-char pos)
14384 (if (<= (current-column) (current-indentation))
14385 (org-indent-line-to column)
14386 (save-excursion (org-indent-line-to column)))
14387 (setq column (current-column))
14388 (beginning-of-line 1)
14389 (if (looking-at
14390 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14391 (replace-match (concat "\\1" (format org-property-format
14392 (match-string 2) (match-string 3)))
14393 t nil))
14394 (org-move-to-column column)))
14396 (defun org-set-autofill-regexps ()
14397 (interactive)
14398 ;; In the paragraph separator we include headlines, because filling
14399 ;; text in a line directly attached to a headline would otherwise
14400 ;; fill the headline as well.
14401 (org-set-local 'comment-start-skip "^#+[ \t]*")
14402 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14403 ;; The paragraph starter includes hand-formatted lists.
14404 (org-set-local 'paragraph-start
14405 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14406 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14407 ;; But only if the user has not turned off tables or fixed-width regions
14408 (org-set-local
14409 'auto-fill-inhibit-regexp
14410 (concat "\\*+ \\|#\\+"
14411 "\\|[ \t]*" org-keyword-time-regexp
14412 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14413 (concat
14414 "\\|[ \t]*["
14415 (if org-enable-table-editor "|" "")
14416 (if org-enable-fixed-width-editor ":" "")
14417 "]"))))
14418 ;; We use our own fill-paragraph function, to make sure that tables
14419 ;; and fixed-width regions are not wrapped. That function will pass
14420 ;; through to `fill-paragraph' when appropriate.
14421 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14422 ; Adaptive filling: To get full control, first make sure that
14423 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14424 (org-set-local 'adaptive-fill-regexp "\000")
14425 (org-set-local 'adaptive-fill-function
14426 'org-adaptive-fill-function)
14427 (org-set-local
14428 'align-mode-rules-list
14429 '((org-in-buffer-settings
14430 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14431 (modes . '(org-mode))))))
14433 (defun org-fill-paragraph (&optional justify)
14434 "Re-align a table, pass through to fill-paragraph if no table."
14435 (let ((table-p (org-at-table-p))
14436 (table.el-p (org-at-table.el-p)))
14437 (cond ((and (equal (char-after (point-at-bol)) ?*)
14438 (save-excursion (goto-char (point-at-bol))
14439 (looking-at outline-regexp)))
14440 t) ; skip headlines
14441 (table.el-p t) ; skip table.el tables
14442 (table-p (org-table-align) t) ; align org-mode tables
14443 (t nil)))) ; call paragraph-fill
14445 ;; For reference, this is the default value of adaptive-fill-regexp
14446 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14448 (defun org-adaptive-fill-function ()
14449 "Return a fill prefix for org-mode files.
14450 In particular, this makes sure hanging paragraphs for hand-formatted lists
14451 work correctly."
14452 (cond ((looking-at "#[ \t]+")
14453 (match-string 0))
14454 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14455 (save-excursion
14456 (if (> (match-end 1) (+ (match-beginning 1)
14457 org-description-max-indent))
14458 (goto-char (+ (match-beginning 1) 5))
14459 (goto-char (match-end 0)))
14460 (make-string (current-column) ?\ )))
14461 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14462 (save-excursion
14463 (goto-char (match-end 0))
14464 (make-string (current-column) ?\ )))
14465 (t nil)))
14467 ;;; Other stuff.
14469 (defun org-toggle-fixed-width-section (arg)
14470 "Toggle the fixed-width export.
14471 If there is no active region, the QUOTE keyword at the current headline is
14472 inserted or removed. When present, it causes the text between this headline
14473 and the next to be exported as fixed-width text, and unmodified.
14474 If there is an active region, this command adds or removes a colon as the
14475 first character of this line. If the first character of a line is a colon,
14476 this line is also exported in fixed-width font."
14477 (interactive "P")
14478 (let* ((cc 0)
14479 (regionp (org-region-active-p))
14480 (beg (if regionp (region-beginning) (point)))
14481 (end (if regionp (region-end)))
14482 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14483 (case-fold-search nil)
14484 (re "[ \t]*\\(:\\)")
14485 off)
14486 (if regionp
14487 (save-excursion
14488 (goto-char beg)
14489 (setq cc (current-column))
14490 (beginning-of-line 1)
14491 (setq off (looking-at re))
14492 (while (> nlines 0)
14493 (setq nlines (1- nlines))
14494 (beginning-of-line 1)
14495 (cond
14496 (arg
14497 (org-move-to-column cc t)
14498 (insert ":\n")
14499 (forward-line -1))
14500 ((and off (looking-at re))
14501 (replace-match "" t t nil 1))
14502 ((not off) (org-move-to-column cc t) (insert ":")))
14503 (forward-line 1)))
14504 (save-excursion
14505 (org-back-to-heading)
14506 (if (looking-at (concat outline-regexp
14507 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14508 (replace-match "" t t nil 1)
14509 (if (looking-at outline-regexp)
14510 (progn
14511 (goto-char (match-end 0))
14512 (insert org-quote-string " "))))))))
14514 ;;;; Functions extending outline functionality
14516 (defun org-beginning-of-line (&optional arg)
14517 "Go to the beginning of the current line. If that is invisible, continue
14518 to a visible line beginning. This makes the function of C-a more intuitive.
14519 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14520 first attempt, and only move to after the tags when the cursor is already
14521 beyond the end of the headline."
14522 (interactive "P")
14523 (let ((pos (point)) refpos)
14524 (beginning-of-line 1)
14525 (if (bobp)
14527 (backward-char 1)
14528 (if (org-invisible-p)
14529 (while (and (not (bobp)) (org-invisible-p))
14530 (backward-char 1)
14531 (beginning-of-line 1))
14532 (forward-char 1)))
14533 (when org-special-ctrl-a/e
14534 (cond
14535 ((and (looking-at org-complex-heading-regexp)
14536 (= (char-after (match-end 1)) ?\ ))
14537 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14538 (point-at-eol)))
14539 (goto-char
14540 (if (eq org-special-ctrl-a/e t)
14541 (cond ((> pos refpos) refpos)
14542 ((= pos (point)) refpos)
14543 (t (point)))
14544 (cond ((> pos (point)) (point))
14545 ((not (eq last-command this-command)) (point))
14546 (t refpos)))))
14547 ((org-at-item-p)
14548 (goto-char
14549 (if (eq org-special-ctrl-a/e t)
14550 (cond ((> pos (match-end 4)) (match-end 4))
14551 ((= pos (point)) (match-end 4))
14552 (t (point)))
14553 (cond ((> pos (point)) (point))
14554 ((not (eq last-command this-command)) (point))
14555 (t (match-end 4))))))))
14556 (org-no-warnings
14557 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14559 (defun org-end-of-line (&optional arg)
14560 "Go to the end of the line.
14561 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14562 first attempt, and only move to after the tags when the cursor is already
14563 beyond the end of the headline."
14564 (interactive "P")
14565 (if (or (not org-special-ctrl-a/e)
14566 (not (org-on-heading-p)))
14567 (end-of-line arg)
14568 (let ((pos (point)))
14569 (beginning-of-line 1)
14570 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14571 (if (eq org-special-ctrl-a/e t)
14572 (if (or (< pos (match-beginning 1))
14573 (= pos (match-end 0)))
14574 (goto-char (match-beginning 1))
14575 (goto-char (match-end 0)))
14576 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14577 (goto-char (match-end 0))
14578 (goto-char (match-beginning 1))))
14579 (end-of-line arg))))
14580 (org-no-warnings
14581 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14584 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14585 (define-key org-mode-map "\C-e" 'org-end-of-line)
14587 (defun org-kill-line (&optional arg)
14588 "Kill line, to tags or end of line."
14589 (interactive "P")
14590 (cond
14591 ((or (not org-special-ctrl-k)
14592 (bolp)
14593 (not (org-on-heading-p)))
14594 (call-interactively 'kill-line))
14595 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14596 (kill-region (point) (match-beginning 1))
14597 (org-set-tags nil t))
14598 (t (kill-region (point) (point-at-eol)))))
14600 (define-key org-mode-map "\C-k" 'org-kill-line)
14602 (defun org-yank (&optional arg)
14603 "Yank. If the kill is a subtree, treat it specially.
14604 This command will look at the current kill and check if is a single
14605 subtree, or a series of subtrees[1]. If it passes the test, and if the
14606 cursor is at the beginning of a line or after the stars of a currently
14607 empty headline, then the yank is handled specially. How exactly depends
14608 on the value of the following variables, both set by default.
14610 org-yank-folded-subtrees
14611 When set, the subtree(s) will be folded after insertion, but only
14612 if doing so would now swallow text after the yanked text.
14614 org-yank-adjusted-subtrees
14615 When set, the subtree will be promoted or demoted in order to
14616 fit into the local outline tree structure, which means that the level
14617 will be adjusted so that it becomes the smaller one of the two
14618 *visible* surrounding headings.
14620 Any prefix to this command will cause `yank' to be called directly with
14621 no special treatment. In particular, a simple `C-u' prefix will just
14622 plainly yank the text as it is.
14624 \[1] Basically, the test checks if the first non-white line is a heading
14625 and if there are no other headings with fewer stars."
14626 (interactive "P")
14627 (setq this-command 'yank)
14628 (if arg
14629 (call-interactively 'yank)
14630 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14631 (and (org-kill-is-subtree-p)
14632 (or (bolp)
14633 (and (looking-at "[ \t]*$")
14634 (string-match
14635 "\\`\\*+\\'"
14636 (buffer-substring (point-at-bol) (point)))))))
14637 swallowp)
14638 (cond
14639 ((and subtreep org-yank-folded-subtrees)
14640 (let ((beg (point))
14641 end)
14642 (if (and subtreep org-yank-adjusted-subtrees)
14643 (org-paste-subtree nil nil 'for-yank)
14644 (call-interactively 'yank))
14645 (setq end (point))
14646 (goto-char beg)
14647 (when (and (bolp) subtreep
14648 (not (setq swallowp
14649 (org-yank-folding-would-swallow-text beg end))))
14650 (or (looking-at outline-regexp)
14651 (re-search-forward (concat "^" outline-regexp) end t))
14652 (while (and (< (point) end) (looking-at outline-regexp))
14653 (hide-subtree)
14654 (org-cycle-show-empty-lines 'folded)
14655 (condition-case nil
14656 (outline-forward-same-level 1)
14657 (error (goto-char end)))))
14658 (when swallowp
14659 (message
14660 "Yanked text not folded because that would swallow text"))
14661 (goto-char end)
14662 (skip-chars-forward " \t\n\r")
14663 (beginning-of-line 1)
14664 (push-mark beg 'nomsg)))
14665 ((and subtreep org-yank-adjusted-subtrees)
14666 (let ((beg (point-at-bol)))
14667 (org-paste-subtree nil nil 'for-yank)
14668 (push-mark beg 'nomsg)))
14670 (call-interactively 'yank))))))
14672 (defun org-yank-folding-would-swallow-text (beg end)
14673 "Would hide-subtree at BEG swallow any text after END?"
14674 (let (level)
14675 (save-excursion
14676 (goto-char beg)
14677 (when (or (looking-at outline-regexp)
14678 (re-search-forward (concat "^" outline-regexp) end t))
14679 (setq level (org-outline-level)))
14680 (goto-char end)
14681 (skip-chars-forward " \t\r\n\v\f")
14682 (if (or (eobp)
14683 (and (bolp) (looking-at org-outline-regexp)
14684 (<= (org-outline-level) level)))
14685 nil ; Nothing would be swallowed
14686 t)))) ; something would swallow
14688 (define-key org-mode-map "\C-y" 'org-yank)
14690 (defun org-invisible-p ()
14691 "Check if point is at a character currently not visible."
14692 ;; Early versions of noutline don't have `outline-invisible-p'.
14693 (if (fboundp 'outline-invisible-p)
14694 (outline-invisible-p)
14695 (get-char-property (point) 'invisible)))
14697 (defun org-invisible-p2 ()
14698 "Check if point is at a character currently not visible."
14699 (save-excursion
14700 (if (and (eolp) (not (bobp))) (backward-char 1))
14701 ;; Early versions of noutline don't have `outline-invisible-p'.
14702 (if (fboundp 'outline-invisible-p)
14703 (outline-invisible-p)
14704 (get-char-property (point) 'invisible))))
14706 (defun org-back-to-heading (&optional invisible-ok)
14707 "Call `outline-back-to-heading', but provide a better error message."
14708 (condition-case nil
14709 (outline-back-to-heading invisible-ok)
14710 (error (error "Before first headline at position %d in buffer %s"
14711 (point) (current-buffer)))))
14713 (defun org-before-first-heading-p ()
14714 "Before first heading?"
14715 (save-excursion
14716 (null (re-search-backward "^\\*+ " nil t))))
14718 (defalias 'org-on-heading-p 'outline-on-heading-p)
14719 (defalias 'org-at-heading-p 'outline-on-heading-p)
14720 (defun org-at-heading-or-item-p ()
14721 (or (org-on-heading-p) (org-at-item-p)))
14723 (defun org-on-target-p ()
14724 (or (org-in-regexp org-radio-target-regexp)
14725 (org-in-regexp org-target-regexp)))
14727 (defun org-up-heading-all (arg)
14728 "Move to the heading line of which the present line is a subheading.
14729 This function considers both visible and invisible heading lines.
14730 With argument, move up ARG levels."
14731 (if (fboundp 'outline-up-heading-all)
14732 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14733 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14735 (defun org-up-heading-safe ()
14736 "Move to the heading line of which the present line is a subheading.
14737 This version will not throw an error. It will return the level of the
14738 headline found, or nil if no higher level is found."
14739 (let (start-level re)
14740 (org-back-to-heading t)
14741 (setq start-level (funcall outline-level))
14742 (if (equal start-level 1)
14744 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14745 (if (re-search-backward re nil t)
14746 (funcall outline-level)))))
14748 (defun org-first-sibling-p ()
14749 "Is this heading the first child of its parents?"
14750 (interactive)
14751 (let ((re (concat "^" outline-regexp))
14752 level l)
14753 (unless (org-at-heading-p t)
14754 (error "Not at a heading"))
14755 (setq level (funcall outline-level))
14756 (save-excursion
14757 (if (not (re-search-backward re nil t))
14759 (setq l (funcall outline-level))
14760 (< l level)))))
14762 (defun org-goto-sibling (&optional previous)
14763 "Goto the next sibling, even if it is invisible.
14764 When PREVIOUS is set, go to the previous sibling instead. Returns t
14765 when a sibling was found. When none is found, return nil and don't
14766 move point."
14767 (let ((fun (if previous 're-search-backward 're-search-forward))
14768 (pos (point))
14769 (re (concat "^" outline-regexp))
14770 level l)
14771 (when (condition-case nil (org-back-to-heading t) (error nil))
14772 (setq level (funcall outline-level))
14773 (catch 'exit
14774 (or previous (forward-char 1))
14775 (while (funcall fun re nil t)
14776 (setq l (funcall outline-level))
14777 (when (< l level) (goto-char pos) (throw 'exit nil))
14778 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14779 (goto-char pos)
14780 nil))))
14782 (defun org-show-siblings ()
14783 "Show all siblings of the current headline."
14784 (save-excursion
14785 (while (org-goto-sibling) (org-flag-heading nil)))
14786 (save-excursion
14787 (while (org-goto-sibling 'previous)
14788 (org-flag-heading nil))))
14790 (defun org-show-hidden-entry ()
14791 "Show an entry where even the heading is hidden."
14792 (save-excursion
14793 (org-show-entry)))
14795 (defun org-flag-heading (flag &optional entry)
14796 "Flag the current heading. FLAG non-nil means make invisible.
14797 When ENTRY is non-nil, show the entire entry."
14798 (save-excursion
14799 (org-back-to-heading t)
14800 ;; Check if we should show the entire entry
14801 (if entry
14802 (progn
14803 (org-show-entry)
14804 (save-excursion
14805 (and (outline-next-heading)
14806 (org-flag-heading nil))))
14807 (outline-flag-region (max (point-min) (1- (point)))
14808 (save-excursion (outline-end-of-heading) (point))
14809 flag))))
14811 (defun org-forward-same-level (arg)
14812 "Move forward to the ARG'th subheading at same level as this one.
14813 Stop at the first and last subheadings of a superior heading.
14814 This is like outline-forward-same-level, but invisible headings are ok."
14815 (interactive "p")
14816 (org-back-to-heading t)
14817 (while (> arg 0)
14818 (let ((point-to-move-to (save-excursion
14819 (org-get-next-sibling))))
14820 (if point-to-move-to
14821 (progn
14822 (goto-char point-to-move-to)
14823 (setq arg (1- arg)))
14824 (progn
14825 (setq arg 0)
14826 (error "No following same-level heading"))))))
14828 (defun org-get-next-sibling ()
14829 "Move to next heading of the same level, and return point.
14830 If there is no such heading, return nil.
14831 This is like outline-next-sibling, but invisible headings are ok."
14832 (let ((level (funcall outline-level)))
14833 (outline-next-heading)
14834 (while (and (not (eobp)) (> (funcall outline-level) level))
14835 (outline-next-heading))
14836 (if (or (eobp) (< (funcall outline-level) level))
14838 (point))))
14840 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14841 ;; This is an exact copy of the original function, but it uses
14842 ;; `org-back-to-heading', to make it work also in invisible
14843 ;; trees. And is uses an invisible-OK argument.
14844 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14845 (org-back-to-heading invisible-OK)
14846 (let ((first t)
14847 (level (funcall outline-level)))
14848 (while (and (not (eobp))
14849 (or first (> (funcall outline-level) level)))
14850 (setq first nil)
14851 (outline-next-heading))
14852 (unless to-heading
14853 (if (memq (preceding-char) '(?\n ?\^M))
14854 (progn
14855 ;; Go to end of line before heading
14856 (forward-char -1)
14857 (if (memq (preceding-char) '(?\n ?\^M))
14858 ;; leave blank line before heading
14859 (forward-char -1))))))
14860 (point))
14862 (defun org-show-subtree ()
14863 "Show everything after this heading at deeper levels."
14864 (outline-flag-region
14865 (point)
14866 (save-excursion
14867 (outline-end-of-subtree) (outline-next-heading) (point))
14868 nil))
14870 (defun org-show-entry ()
14871 "Show the body directly following this heading.
14872 Show the heading too, if it is currently invisible."
14873 (interactive)
14874 (save-excursion
14875 (condition-case nil
14876 (progn
14877 (org-back-to-heading t)
14878 (outline-flag-region
14879 (max (point-min) (1- (point)))
14880 (save-excursion
14881 (re-search-forward
14882 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14883 (or (match-beginning 1) (point-max)))
14884 nil))
14885 (error nil))))
14887 (defun org-make-options-regexp (kwds)
14888 "Make a regular expression for keyword lines."
14889 (concat
14891 "#?[ \t]*\\+\\("
14892 (mapconcat 'regexp-quote kwds "\\|")
14893 "\\):[ \t]*"
14894 "\\(.+\\)"))
14896 ;; Make isearch reveal the necessary context
14897 (defun org-isearch-end ()
14898 "Reveal context after isearch exits."
14899 (when isearch-success ; only if search was successful
14900 (if (featurep 'xemacs)
14901 ;; Under XEmacs, the hook is run in the correct place,
14902 ;; we directly show the context.
14903 (org-show-context 'isearch)
14904 ;; In Emacs the hook runs *before* restoring the overlays.
14905 ;; So we have to use a one-time post-command-hook to do this.
14906 ;; (Emacs 22 has a special variable, see function `org-mode')
14907 (unless (and (boundp 'isearch-mode-end-hook-quit)
14908 isearch-mode-end-hook-quit)
14909 ;; Only when the isearch was not quitted.
14910 (org-add-hook 'post-command-hook 'org-isearch-post-command
14911 'append 'local)))))
14913 (defun org-isearch-post-command ()
14914 "Remove self from hook, and show context."
14915 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14916 (org-show-context 'isearch))
14919 ;;;; Integration with and fixes for other packages
14921 ;;; Imenu support
14923 (defvar org-imenu-markers nil
14924 "All markers currently used by Imenu.")
14925 (make-variable-buffer-local 'org-imenu-markers)
14927 (defun org-imenu-new-marker (&optional pos)
14928 "Return a new marker for use by Imenu, and remember the marker."
14929 (let ((m (make-marker)))
14930 (move-marker m (or pos (point)))
14931 (push m org-imenu-markers)
14934 (defun org-imenu-get-tree ()
14935 "Produce the index for Imenu."
14936 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14937 (setq org-imenu-markers nil)
14938 (let* ((n org-imenu-depth)
14939 (re (concat "^" outline-regexp))
14940 (subs (make-vector (1+ n) nil))
14941 (last-level 0)
14942 m level head)
14943 (save-excursion
14944 (save-restriction
14945 (widen)
14946 (goto-char (point-max))
14947 (while (re-search-backward re nil t)
14948 (setq level (org-reduced-level (funcall outline-level)))
14949 (when (<= level n)
14950 (looking-at org-complex-heading-regexp)
14951 (setq head (org-link-display-format
14952 (org-match-string-no-properties 4))
14953 m (org-imenu-new-marker))
14954 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14955 (if (>= level last-level)
14956 (push (cons head m) (aref subs level))
14957 (push (cons head (aref subs (1+ level))) (aref subs level))
14958 (loop for i from (1+ level) to n do (aset subs i nil)))
14959 (setq last-level level)))))
14960 (aref subs 1)))
14962 (eval-after-load "imenu"
14963 '(progn
14964 (add-hook 'imenu-after-jump-hook
14965 (lambda ()
14966 (if (eq major-mode 'org-mode)
14967 (org-show-context 'org-goto))))))
14969 (defun org-link-display-format (link)
14970 "Replace a link with either the description, or the link target
14971 if no description is present"
14972 (save-match-data
14973 (if (string-match org-bracket-link-analytic-regexp link)
14974 (replace-match (or (match-string 5 link)
14975 (concat (match-string 1 link)
14976 (match-string 3 link)))
14977 nil nil link)
14978 link)))
14980 ;; Speedbar support
14982 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14983 "Overlay marking the agenda restriction line in speedbar.")
14984 (org-overlay-put org-speedbar-restriction-lock-overlay
14985 'face 'org-agenda-restriction-lock)
14986 (org-overlay-put org-speedbar-restriction-lock-overlay
14987 'help-echo "Agendas are currently limited to this item.")
14988 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14990 (defun org-speedbar-set-agenda-restriction ()
14991 "Restrict future agenda commands to the location at point in speedbar.
14992 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14993 (interactive)
14994 (require 'org-agenda)
14995 (let (p m tp np dir txt)
14996 (cond
14997 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14998 'org-imenu t))
14999 (setq m (get-text-property p 'org-imenu-marker))
15000 (save-excursion
15001 (save-restriction
15002 (set-buffer (marker-buffer m))
15003 (goto-char m)
15004 (org-agenda-set-restriction-lock 'subtree))))
15005 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15006 'speedbar-function 'speedbar-find-file))
15007 (setq tp (previous-single-property-change
15008 (1+ p) 'speedbar-function)
15009 np (next-single-property-change
15010 tp 'speedbar-function)
15011 dir (speedbar-line-directory)
15012 txt (buffer-substring-no-properties (or tp (point-min))
15013 (or np (point-max))))
15014 (save-excursion
15015 (save-restriction
15016 (set-buffer (find-file-noselect
15017 (let ((default-directory dir))
15018 (expand-file-name txt))))
15019 (unless (org-mode-p)
15020 (error "Cannot restrict to non-Org-mode file"))
15021 (org-agenda-set-restriction-lock 'file))))
15022 (t (error "Don't know how to restrict Org-mode's agenda")))
15023 (org-move-overlay org-speedbar-restriction-lock-overlay
15024 (point-at-bol) (point-at-eol))
15025 (setq current-prefix-arg nil)
15026 (org-agenda-maybe-redo)))
15028 (eval-after-load "speedbar"
15029 '(progn
15030 (speedbar-add-supported-extension ".org")
15031 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15032 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15033 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15034 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15035 (add-hook 'speedbar-visiting-tag-hook
15036 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15039 ;;; Fixes and Hacks for problems with other packages
15041 ;; Make flyspell not check words in links, to not mess up our keymap
15042 (defun org-mode-flyspell-verify ()
15043 "Don't let flyspell put overlays at active buttons."
15044 (not (get-text-property (point) 'keymap)))
15046 ;; Make `bookmark-jump' show the jump location if it was hidden.
15047 (eval-after-load "bookmark"
15048 '(if (boundp 'bookmark-after-jump-hook)
15049 ;; We can use the hook
15050 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15051 ;; Hook not available, use advice
15052 (defadvice bookmark-jump (after org-make-visible activate)
15053 "Make the position visible."
15054 (org-bookmark-jump-unhide))))
15056 ;; Make sure saveplace show the location if it was hidden
15057 (eval-after-load "saveplace"
15058 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15059 "Make the position visible."
15060 (org-bookmark-jump-unhide)))
15062 (defun org-bookmark-jump-unhide ()
15063 "Unhide the current position, to show the bookmark location."
15064 (and (org-mode-p)
15065 (or (org-invisible-p)
15066 (save-excursion (goto-char (max (point-min) (1- (point))))
15067 (org-invisible-p)))
15068 (org-show-context 'bookmark-jump)))
15070 ;; Make session.el ignore our circular variable
15071 (eval-after-load "session"
15072 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15074 ;;;; Experimental code
15076 (defun org-closed-in-range ()
15077 "Sparse tree of items closed in a certain time range.
15078 Still experimental, may disappear in the future."
15079 (interactive)
15080 ;; Get the time interval from the user.
15081 (let* ((time1 (time-to-seconds
15082 (org-read-date nil 'to-time nil "Starting date: ")))
15083 (time2 (time-to-seconds
15084 (org-read-date nil 'to-time nil "End date:")))
15085 ;; callback function
15086 (callback (lambda ()
15087 (let ((time
15088 (time-to-seconds
15089 (apply 'encode-time
15090 (org-parse-time-string
15091 (match-string 1))))))
15092 ;; check if time in interval
15093 (and (>= time time1) (<= time time2))))))
15094 ;; make tree, check each match with the callback
15095 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15098 ;;;; Finish up
15100 (provide 'org)
15102 (run-hooks 'org-load-hook)
15104 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15106 ;;; org.el ends here