Shift-selection: More tweaking.
[org-mode.git] / lisp / org.el
blob0d81fbba38f9e050dd731ce1c0552a9b00109da3
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 regions started in this way.
207 In Org-mode, in special contexts, these same keys are used for other
208 purposes, important enough to compete with shift selection. Org tries
209 to balance these needs by supporting `shift-select-mode' outside these
210 special contexts, under control of this variable.
212 The default of this variable is nil, to avoid confusing behavior. Shifted
213 cursor keys will then execute Org commands in the following contexts:
214 - on a headline, changing TODO state (left/right) and priority (up/down)
215 - on a time stamp, changing the time
216 - in a plain list item, changing the bullet type
217 - in a property definition line, switching between allowed values
218 - in the BEGIN line of a clock table (changing the time block).
219 Outside these contexts, the commands will throw an error.
221 When this variable is t and the cursor is not in a special context,
222 Org-mode will support shift-selection for making and enlarging regions.
223 To make this more effective, the bullet cycling will no longer happen
224 anywhere in an item line, but only if the cursor is exactly on the bullet.
226 If you set this variable to the symbol `always', then the keys
227 will not be special in headlines, property lines, and item lines, to make
228 shift selection work there as well. If this is what you want, you can
229 use the following alternative commands: `C-c C-t' and `C-c ,' to
230 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
231 TODO sets, `C-c -' to cycle item bullet types, and properties can be
232 edited by hand or in column view.
234 However, when the cursor is on a timestamp, shift-cursor commands
235 will still edit the time stamp - this is just too good to give up.
237 XEmacs user should have this variable set to nil, because shift-select-mode
238 is Emacs 23 only."
239 :group 'org
240 :type '(choice
241 (const :tag "Never" nil)
242 (const :tag "When outside special context" t)
243 (const :tag "Everywhere except timestamps" always)))
245 (defgroup org-startup nil
246 "Options concerning startup of Org-mode."
247 :tag "Org Startup"
248 :group 'org)
250 (defcustom org-startup-folded t
251 "Non-nil means, entering Org-mode will switch to OVERVIEW.
252 This can also be configured on a per-file basis by adding one of
253 the following lines anywhere in the buffer:
255 #+STARTUP: fold
256 #+STARTUP: nofold
257 #+STARTUP: content"
258 :group 'org-startup
259 :type '(choice
260 (const :tag "nofold: show all" nil)
261 (const :tag "fold: overview" t)
262 (const :tag "content: all headlines" content)))
264 (defcustom org-startup-truncated t
265 "Non-nil means, entering Org-mode will set `truncate-lines'.
266 This is useful since some lines containing links can be very long and
267 uninteresting. Also tables look terrible when wrapped."
268 :group 'org-startup
269 :type 'boolean)
271 (defcustom org-startup-align-all-tables nil
272 "Non-nil means, align all tables when visiting a file.
273 This is useful when the column width in tables is forced with <N> cookies
274 in table fields. Such tables will look correct only after the first re-align.
275 This can also be configured on a per-file basis by adding one of
276 the following lines anywhere in the buffer:
277 #+STARTUP: align
278 #+STARTUP: noalign"
279 :group 'org-startup
280 :type 'boolean)
282 (defcustom org-insert-mode-line-in-empty-file nil
283 "Non-nil means insert the first line setting Org-mode in empty files.
284 When the function `org-mode' is called interactively in an empty file, this
285 normally means that the file name does not automatically trigger Org-mode.
286 To ensure that the file will always be in Org-mode in the future, a
287 line enforcing Org-mode will be inserted into the buffer, if this option
288 has been set."
289 :group 'org-startup
290 :type 'boolean)
292 (defcustom org-replace-disputed-keys nil
293 "Non-nil means use alternative key bindings for some keys.
294 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
295 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
296 If you want to use Org-mode together with one of these other modes,
297 or more generally if you would like to move some Org-mode commands to
298 other keys, set this variable and configure the keys with the variable
299 `org-disputed-keys'.
301 This option is only relevant at load-time of Org-mode, and must be set
302 *before* org.el is loaded. Changing it requires a restart of Emacs to
303 become effective."
304 :group 'org-startup
305 :type 'boolean)
307 (defcustom org-use-extra-keys nil
308 "Non-nil means use extra key sequence definitions for certain
309 commands. This happens automatically if you run XEmacs or if
310 window-system is nil. This variable lets you do the same
311 manually. You must set it before loading org.
313 Example: on Carbon Emacs 22 running graphically, with an external
314 keyboard on a Powerbook, the default way of setting M-left might
315 not work for either Alt or ESC. Setting this variable will make
316 it work for ESC."
317 :group 'org-startup
318 :type 'boolean)
320 (if (fboundp 'defvaralias)
321 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
323 (defcustom org-disputed-keys
324 '(([(shift up)] . [(meta p)])
325 ([(shift down)] . [(meta n)])
326 ([(shift left)] . [(meta -)])
327 ([(shift right)] . [(meta +)])
328 ([(control shift right)] . [(meta shift +)])
329 ([(control shift left)] . [(meta shift -)]))
330 "Keys for which Org-mode and other modes compete.
331 This is an alist, cars are the default keys, second element specifies
332 the alternative to use when `org-replace-disputed-keys' is t.
334 Keys can be specified in any syntax supported by `define-key'.
335 The value of this option takes effect only at Org-mode's startup,
336 therefore you'll have to restart Emacs to apply it after changing."
337 :group 'org-startup
338 :type 'alist)
340 (defun org-key (key)
341 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
342 Or return the original if not disputed."
343 (if org-replace-disputed-keys
344 (let* ((nkey (key-description key))
345 (x (org-find-if (lambda (x)
346 (equal (key-description (car x)) nkey))
347 org-disputed-keys)))
348 (if x (cdr x) key))
349 key))
351 (defun org-find-if (predicate seq)
352 (catch 'exit
353 (while seq
354 (if (funcall predicate (car seq))
355 (throw 'exit (car seq))
356 (pop seq)))))
358 (defun org-defkey (keymap key def)
359 "Define a key, possibly translated, as returned by `org-key'."
360 (define-key keymap (org-key key) def))
362 (defcustom org-ellipsis nil
363 "The ellipsis to use in the Org-mode outline.
364 When nil, just use the standard three dots. When a string, use that instead,
365 When a face, use the standard 3 dots, but with the specified face.
366 The change affects only Org-mode (which will then use its own display table).
367 Changing this requires executing `M-x org-mode' in a buffer to become
368 effective."
369 :group 'org-startup
370 :type '(choice (const :tag "Default" nil)
371 (face :tag "Face" :value org-warning)
372 (string :tag "String" :value "...#")))
374 (defvar org-display-table nil
375 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
377 (defgroup org-keywords nil
378 "Keywords in Org-mode."
379 :tag "Org Keywords"
380 :group 'org)
382 (defcustom org-deadline-string "DEADLINE:"
383 "String to mark deadline entries.
384 A deadline is this string, followed by a time stamp. Should be a word,
385 terminated by a colon. You can insert a schedule keyword and
386 a timestamp with \\[org-deadline].
387 Changes become only effective after restarting Emacs."
388 :group 'org-keywords
389 :type 'string)
391 (defcustom org-scheduled-string "SCHEDULED:"
392 "String to mark scheduled TODO entries.
393 A schedule is this string, followed by a time stamp. Should be a word,
394 terminated by a colon. You can insert a schedule keyword and
395 a timestamp with \\[org-schedule].
396 Changes become only effective after restarting Emacs."
397 :group 'org-keywords
398 :type 'string)
400 (defcustom org-closed-string "CLOSED:"
401 "String used as the prefix for timestamps logging closing a TODO entry."
402 :group 'org-keywords
403 :type 'string)
405 (defcustom org-clock-string "CLOCK:"
406 "String used as prefix for timestamps clocking work hours on an item."
407 :group 'org-keywords
408 :type 'string)
410 (defcustom org-comment-string "COMMENT"
411 "Entries starting with this keyword will never be exported.
412 An entry can be toggled between COMMENT and normal with
413 \\[org-toggle-comment].
414 Changes become only effective after restarting Emacs."
415 :group 'org-keywords
416 :type 'string)
418 (defcustom org-quote-string "QUOTE"
419 "Entries starting with this keyword will be exported in fixed-width font.
420 Quoting applies only to the text in the entry following the headline, and does
421 not extend beyond the next headline, even if that is lower level.
422 An entry can be toggled between QUOTE and normal with
423 \\[org-toggle-fixed-width-section]."
424 :group 'org-keywords
425 :type 'string)
427 (defconst org-repeat-re
428 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
429 "Regular expression for specifying repeated events.
430 After a match, group 1 contains the repeat expression.")
432 (defgroup org-structure nil
433 "Options concerning the general structure of Org-mode files."
434 :tag "Org Structure"
435 :group 'org)
437 (defgroup org-reveal-location nil
438 "Options about how to make context of a location visible."
439 :tag "Org Reveal Location"
440 :group 'org-structure)
442 (defconst org-context-choice
443 '(choice
444 (const :tag "Always" t)
445 (const :tag "Never" nil)
446 (repeat :greedy t :tag "Individual contexts"
447 (cons
448 (choice :tag "Context"
449 (const agenda)
450 (const org-goto)
451 (const occur-tree)
452 (const tags-tree)
453 (const link-search)
454 (const mark-goto)
455 (const bookmark-jump)
456 (const isearch)
457 (const default))
458 (boolean))))
459 "Contexts for the reveal options.")
461 (defcustom org-show-hierarchy-above '((default . t))
462 "Non-nil means, show full hierarchy when revealing a location.
463 Org-mode often shows locations in an org-mode file which might have
464 been invisible before. When this is set, the hierarchy of headings
465 above the exposed location is shown.
466 Turning this off for example for sparse trees makes them very compact.
467 Instead of t, this can also be an alist specifying this option for different
468 contexts. Valid contexts are
469 agenda when exposing an entry from the agenda
470 org-goto when using the command `org-goto' on key C-c C-j
471 occur-tree when using the command `org-occur' on key C-c /
472 tags-tree when constructing a sparse tree based on tags matches
473 link-search when exposing search matches associated with a link
474 mark-goto when exposing the jump goal of a mark
475 bookmark-jump when exposing a bookmark location
476 isearch when exiting from an incremental search
477 default default for all contexts not set explicitly"
478 :group 'org-reveal-location
479 :type org-context-choice)
481 (defcustom org-show-following-heading '((default . nil))
482 "Non-nil means, show following heading when revealing a location.
483 Org-mode often shows locations in an org-mode file which might have
484 been invisible before. When this is set, the heading following the
485 match is shown.
486 Turning this off for example for sparse trees makes them very compact,
487 but makes it harder to edit the location of the match. In such a case,
488 use the command \\[org-reveal] to show more context.
489 Instead of t, this can also be an alist specifying this option for different
490 contexts. See `org-show-hierarchy-above' for valid contexts."
491 :group 'org-reveal-location
492 :type org-context-choice)
494 (defcustom org-show-siblings '((default . nil) (isearch t))
495 "Non-nil means, show all sibling heading when revealing a location.
496 Org-mode often shows locations in an org-mode file which might have
497 been invisible before. When this is set, the sibling of the current entry
498 heading are all made visible. If `org-show-hierarchy-above' is t,
499 the same happens on each level of the hierarchy above the current entry.
501 By default this is on for the isearch context, off for all other contexts.
502 Turning this off for example for sparse trees makes them very compact,
503 but makes it harder to edit the location of the match. In such a case,
504 use the command \\[org-reveal] to show more context.
505 Instead of t, this can also be an alist specifying this option for different
506 contexts. See `org-show-hierarchy-above' for valid contexts."
507 :group 'org-reveal-location
508 :type org-context-choice)
510 (defcustom org-show-entry-below '((default . nil))
511 "Non-nil means, show the entry below a headline when revealing a location.
512 Org-mode often shows locations in an org-mode file which might have
513 been invisible before. When this is set, the text below the headline that is
514 exposed is also shown.
516 By default this is off for all contexts.
517 Instead of t, this can also be an alist specifying this option for different
518 contexts. See `org-show-hierarchy-above' for valid contexts."
519 :group 'org-reveal-location
520 :type org-context-choice)
522 (defcustom org-indirect-buffer-display 'other-window
523 "How should indirect tree buffers be displayed?
524 This applies to indirect buffers created with the commands
525 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
526 Valid values are:
527 current-window Display in the current window
528 other-window Just display in another window.
529 dedicated-frame Create one new frame, and re-use it each time.
530 new-frame Make a new frame each time. Note that in this case
531 previously-made indirect buffers are kept, and you need to
532 kill these buffers yourself."
533 :group 'org-structure
534 :group 'org-agenda-windows
535 :type '(choice
536 (const :tag "In current window" current-window)
537 (const :tag "In current frame, other window" other-window)
538 (const :tag "Each time a new frame" new-frame)
539 (const :tag "One dedicated frame" dedicated-frame)))
541 (defgroup org-cycle nil
542 "Options concerning visibility cycling in Org-mode."
543 :tag "Org Cycle"
544 :group 'org-structure)
546 (defcustom org-drawers '("PROPERTIES" "CLOCK")
547 "Names of drawers. Drawers are not opened by cycling on the headline above.
548 Drawers only open with a TAB on the drawer line itself. A drawer looks like
549 this:
550 :DRAWERNAME:
551 .....
552 :END:
553 The drawer \"PROPERTIES\" is special for capturing properties through
554 the property API.
556 Drawers can be defined on the per-file basis with a line like:
558 #+DRAWERS: HIDDEN STATE PROPERTIES"
559 :group 'org-structure
560 :type '(repeat (string :tag "Drawer Name")))
562 (defcustom org-cycle-global-at-bob nil
563 "Cycle globally if cursor is at beginning of buffer and not at a headline.
564 This makes it possible to do global cycling without having to use S-TAB or
565 C-u TAB. For this special case to work, the first line of the buffer
566 must not be a headline - it may be empty ot some other text. When used in
567 this way, `org-cycle-hook' is disables temporarily, to make sure the
568 cursor stays at the beginning of the buffer.
569 When this option is nil, don't do anything special at the beginning
570 of the buffer."
571 :group 'org-cycle
572 :type 'boolean)
574 (defcustom org-cycle-emulate-tab t
575 "Where should `org-cycle' emulate TAB.
576 nil Never
577 white Only in completely white lines
578 whitestart Only at the beginning of lines, before the first non-white char
579 t Everywhere except in headlines
580 exc-hl-bol Everywhere except at the start of a headline
581 If TAB is used in a place where it does not emulate TAB, the current subtree
582 visibility is cycled."
583 :group 'org-cycle
584 :type '(choice (const :tag "Never" nil)
585 (const :tag "Only in completely white lines" white)
586 (const :tag "Before first char in a line" whitestart)
587 (const :tag "Everywhere except in headlines" t)
588 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
591 (defcustom org-cycle-separator-lines 2
592 "Number of empty lines needed to keep an empty line between collapsed trees.
593 If you leave an empty line between the end of a subtree and the following
594 headline, this empty line is hidden when the subtree is folded.
595 Org-mode will leave (exactly) one empty line visible if the number of
596 empty lines is equal or larger to the number given in this variable.
597 So the default 2 means, at least 2 empty lines after the end of a subtree
598 are needed to produce free space between a collapsed subtree and the
599 following headline.
601 Special case: when 0, never leave empty lines in collapsed view."
602 :group 'org-cycle
603 :type 'integer)
604 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
606 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
607 org-cycle-hide-drawers
608 org-cycle-show-empty-lines
609 org-optimize-window-after-visibility-change)
610 "Hook that is run after `org-cycle' has changed the buffer visibility.
611 The function(s) in this hook must accept a single argument which indicates
612 the new state that was set by the most recent `org-cycle' command. The
613 argument is a symbol. After a global state change, it can have the values
614 `overview', `content', or `all'. After a local state change, it can have
615 the values `folded', `children', or `subtree'."
616 :group 'org-cycle
617 :type 'hook)
619 (defgroup org-edit-structure nil
620 "Options concerning structure editing in Org-mode."
621 :tag "Org Edit Structure"
622 :group 'org-structure)
624 (defcustom org-odd-levels-only nil
625 "Non-nil means, skip even levels and only use odd levels for the outline.
626 This has the effect that two stars are being added/taken away in
627 promotion/demotion commands. It also influences how levels are
628 handled by the exporters.
629 Changing it requires restart of `font-lock-mode' to become effective
630 for fontification also in regions already fontified.
631 You may also set this on a per-file basis by adding one of the following
632 lines to the buffer:
634 #+STARTUP: odd
635 #+STARTUP: oddeven"
636 :group 'org-edit-structure
637 :group 'org-font-lock
638 :type 'boolean)
640 (defcustom org-adapt-indentation t
641 "Non-nil means, adapt indentation when promoting and demoting.
642 When this is set and the *entire* text in an entry is indented, the
643 indentation is increased by one space in a demotion command, and
644 decreased by one in a promotion command. If any line in the entry
645 body starts at column 0, indentation is not changed at all."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defcustom org-special-ctrl-a/e nil
650 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
651 When t, `C-a' will bring back the cursor to the beginning of the
652 headline text, i.e. after the stars and after a possible TODO keyword.
653 In an item, this will be the position after the bullet.
654 When the cursor is already at that position, another `C-a' will bring
655 it to the beginning of the line.
656 `C-e' will jump to the end of the headline, ignoring the presence of tags
657 in the headline. A second `C-e' will then jump to the true end of the
658 line, after any tags.
659 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
660 and only a directly following, identical keypress will bring the cursor
661 to the special positions."
662 :group 'org-edit-structure
663 :type '(choice
664 (const :tag "off" nil)
665 (const :tag "after bullet first" t)
666 (const :tag "border first" reversed)))
668 (if (fboundp 'defvaralias)
669 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
671 (defcustom org-special-ctrl-k nil
672 "Non-nil means `C-k' will behave specially in headlines.
673 When nil, `C-k' will call the default `kill-line' command.
674 When t, the following will happen while the cursor is in the headline:
676 - When the cursor is at the beginning of a headline, kill the entire
677 line and possible the folded subtree below the line.
678 - When in the middle of the headline text, kill the headline up to the tags.
679 - When after the headline text, kill the tags."
680 :group 'org-edit-structure
681 :type 'boolean)
683 (defcustom org-yank-folded-subtrees t
684 "Non-nil means, when yanking subtrees, fold them.
685 If the kill is a single subtree, or a sequence of subtrees, i.e. if
686 it starts with a heading and all other headings in it are either children
687 or siblings, then fold all the subtrees. However, do this only if no
688 text after the yank would be swallowed into a folded tree by this action."
689 :group 'org-edit-structure
690 :type 'boolean)
692 (defcustom org-yank-adjusted-subtrees t
693 "Non-nil means, when yanking subtrees, adjust the level.
694 With this setting, `org-paste-subtree' is used to insert the subtree, see
695 this function for details."
696 :group 'org-edit-structure
697 :type 'boolean)
699 (defcustom org-M-RET-may-split-line '((default . t))
700 "Non-nil means, M-RET will split the line at the cursor position.
701 When nil, it will go to the end of the line before making a
702 new line.
703 You may also set this option in a different way for different
704 contexts. Valid contexts are:
706 headline when creating a new headline
707 item when creating a new item
708 table in a table field
709 default the value to be used for all contexts not explicitly
710 customized"
711 :group 'org-structure
712 :group 'org-table
713 :type '(choice
714 (const :tag "Always" t)
715 (const :tag "Never" nil)
716 (repeat :greedy t :tag "Individual contexts"
717 (cons
718 (choice :tag "Context"
719 (const headline)
720 (const item)
721 (const table)
722 (const default))
723 (boolean)))))
726 (defcustom org-insert-heading-respect-content nil
727 "Non-nil means, insert new headings after the current subtree.
728 When nil, the new heading is created directly after the current line.
729 The commands \\[org-insert-heading-respect-content] and
730 \\[org-insert-todo-heading-respect-content] turn this variable on
731 for the duration of the command."
732 :group 'org-structure
733 :type 'boolean)
735 (defcustom org-blank-before-new-entry '((heading . auto)
736 (plain-list-item . auto))
737 "Should `org-insert-heading' leave a blank line before new heading/item?
738 The value is an alist, with `heading' and `plain-list-item' as car,
739 and a boolean flag as cdr."
740 :group 'org-edit-structure
741 :type '(list
742 (cons (const heading)
743 (choice (const :tag "Never" nil)
744 (const :tag "Always" t)
745 (const :tag "Auto" auto)))
746 (cons (const plain-list-item)
747 (choice (const :tag "Never" nil)
748 (const :tag "Always" t)
749 (const :tag "Auto" auto)))))
751 (defcustom org-insert-heading-hook nil
752 "Hook being run after inserting a new heading."
753 :group 'org-edit-structure
754 :type 'hook)
756 (defcustom org-enable-fixed-width-editor t
757 "Non-nil means, lines starting with \":\" are treated as fixed-width.
758 This currently only means, they are never auto-wrapped.
759 When nil, such lines will be treated like ordinary lines.
760 See also the QUOTE keyword."
761 :group 'org-edit-structure
762 :type 'boolean)
764 (defcustom org-edit-src-region-extra nil
765 "Additional regexps to identify regions for editing with `org-edit-src-code'.
766 For examples see the function `org-edit-src-find-region-and-lang'.
767 The regular expression identifying the begin marker should end with a newline,
768 and the regexp marking the end line should start with a newline, to make sure
769 there are kept outside the narrowed region."
770 :group 'org-edit-structure
771 :type '(repeat
772 (list
773 (regexp :tag "begin regexp")
774 (regexp :tag "end regexp")
775 (choice :tag "language"
776 (string :tag "specify")
777 (integer :tag "from match group")
778 (const :tag "from `lang' element")
779 (const :tag "from `style' element")))))
781 (defcustom org-coderef-label-format "(ref:%s)"
782 "The default coderef format.
783 This format string will be used to search for coderef labels in literal
784 examples (EXAMPLE and SRC blocks). The format can be overwritten
785 an individual literal example with the -f option, like
787 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
789 #+END_SRC
791 If you want to use this for HTML export, make sure that the format does
792 not introduce special font-locking, and avoid the HTML special
793 characters `<', `>', and `&'. The reason for this restriction is that
794 the labels are searched for only after htmlize has done its job."
795 :group 'org-edit-structure ; FIXME this is not in the right group
796 :type 'string)
798 (defcustom org-edit-fixed-width-region-mode 'artist-mode
799 "The mode that should be used to edit fixed-width regions.
800 These are the regions where each line starts with a colon."
801 :group 'org-edit-structure
802 :type '(choice
803 (const artist-mode)
804 (const picture-mode)
805 (const fundamental-mode)
806 (function :tag "Other (specify)")))
808 (defcustom org-goto-auto-isearch t
809 "Non-nil means, typing characters in org-goto starts incremental search."
810 :group 'org-edit-structure
811 :type 'boolean)
813 (defgroup org-sparse-trees nil
814 "Options concerning sparse trees in Org-mode."
815 :tag "Org Sparse Trees"
816 :group 'org-structure)
818 (defcustom org-highlight-sparse-tree-matches t
819 "Non-nil means, highlight all matches that define a sparse tree.
820 The highlights will automatically disappear the next time the buffer is
821 changed by an edit command."
822 :group 'org-sparse-trees
823 :type 'boolean)
825 (defcustom org-remove-highlights-with-change t
826 "Non-nil means, any change to the buffer will remove temporary highlights.
827 Such highlights are created by `org-occur' and `org-clock-display'.
828 When nil, `C-c C-c needs to be used to get rid of the highlights.
829 The highlights created by `org-preview-latex-fragment' always need
830 `C-c C-c' to be removed."
831 :group 'org-sparse-trees
832 :group 'org-time
833 :type 'boolean)
836 (defcustom org-occur-hook '(org-first-headline-recenter)
837 "Hook that is run after `org-occur' has constructed a sparse tree.
838 This can be used to recenter the window to show as much of the structure
839 as possible."
840 :group 'org-sparse-trees
841 :type 'hook)
843 (defgroup org-imenu-and-speedbar nil
844 "Options concerning imenu and speedbar in Org-mode."
845 :tag "Org Imenu and Speedbar"
846 :group 'org-structure)
848 (defcustom org-imenu-depth 2
849 "The maximum level for Imenu access to Org-mode headlines.
850 This also applied for speedbar access."
851 :group 'org-imenu-and-speedbar
852 :type 'number)
854 (defgroup org-table nil
855 "Options concerning tables in Org-mode."
856 :tag "Org Table"
857 :group 'org)
859 (defcustom org-enable-table-editor 'optimized
860 "Non-nil means, lines starting with \"|\" are handled by the table editor.
861 When nil, such lines will be treated like ordinary lines.
863 When equal to the symbol `optimized', the table editor will be optimized to
864 do the following:
865 - Automatic overwrite mode in front of whitespace in table fields.
866 This makes the structure of the table stay in tact as long as the edited
867 field does not exceed the column width.
868 - Minimize the number of realigns. Normally, the table is aligned each time
869 TAB or RET are pressed to move to another field. With optimization this
870 happens only if changes to a field might have changed the column width.
871 Optimization requires replacing the functions `self-insert-command',
872 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
873 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
874 very good at guessing when a re-align will be necessary, but you can always
875 force one with \\[org-ctrl-c-ctrl-c].
877 If you would like to use the optimized version in Org-mode, but the
878 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
880 This variable can be used to turn on and off the table editor during a session,
881 but in order to toggle optimization, a restart is required.
883 See also the variable `org-table-auto-blank-field'."
884 :group 'org-table
885 :type '(choice
886 (const :tag "off" nil)
887 (const :tag "on" t)
888 (const :tag "on, optimized" optimized)))
890 (defcustom org-table-tab-recognizes-table.el t
891 "Non-nil means, TAB will automatically notice a table.el table.
892 When it sees such a table, it moves point into it and - if necessary -
893 calls `table-recognize-table'."
894 :group 'org-table-editing
895 :type 'boolean)
897 (defgroup org-link nil
898 "Options concerning links in Org-mode."
899 :tag "Org Link"
900 :group 'org)
902 (defvar org-link-abbrev-alist-local nil
903 "Buffer-local version of `org-link-abbrev-alist', which see.
904 The value of this is taken from the #+LINK lines.")
905 (make-variable-buffer-local 'org-link-abbrev-alist-local)
907 (defcustom org-link-abbrev-alist nil
908 "Alist of link abbreviations.
909 The car of each element is a string, to be replaced at the start of a link.
910 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
911 links in Org-mode buffers can have an optional tag after a double colon, e.g.
913 [[linkkey:tag][description]]
915 If REPLACE is a string, the tag will simply be appended to create the link.
916 If the string contains \"%s\", the tag will be inserted there. Alternatively,
917 the placeholder \"%h\" will cause a url-encoded version of the tag to
918 be inserted at that point (see the function `url-hexify-string').
920 REPLACE may also be a function that will be called with the tag as the
921 only argument to create the link, which should be returned as a string.
923 See the manual for examples."
924 :group 'org-link
925 :type '(repeat
926 (cons
927 (string :tag "Protocol")
928 (choice
929 (string :tag "Format")
930 (function)))))
932 (defcustom org-descriptive-links t
933 "Non-nil means, hide link part and only show description of bracket links.
934 Bracket links are like [[link][description]]. This variable sets the initial
935 state in new org-mode buffers. The setting can then be toggled on a
936 per-buffer basis from the Org->Hyperlinks menu."
937 :group 'org-link
938 :type 'boolean)
940 (defcustom org-link-file-path-type 'adaptive
941 "How the path name in file links should be stored.
942 Valid values are:
944 relative Relative to the current directory, i.e. the directory of the file
945 into which the link is being inserted.
946 absolute Absolute path, if possible with ~ for home directory.
947 noabbrev Absolute path, no abbreviation of home directory.
948 adaptive Use relative path for files in the current directory and sub-
949 directories of it. For other files, use an absolute path."
950 :group 'org-link
951 :type '(choice
952 (const relative)
953 (const absolute)
954 (const noabbrev)
955 (const adaptive)))
957 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
958 "Types of links that should be activated in Org-mode files.
959 This is a list of symbols, each leading to the activation of a certain link
960 type. In principle, it does not hurt to turn on most link types - there may
961 be a small gain when turning off unused link types. The types are:
963 bracket The recommended [[link][description]] or [[link]] links with hiding.
964 angular Links in angular brackets that may contain whitespace like
965 <bbdb:Carsten Dominik>.
966 plain Plain links in normal text, no whitespace, like http://google.com.
967 radio Text that is matched by a radio target, see manual for details.
968 tag Tag settings in a headline (link to tag search).
969 date Time stamps (link to calendar).
970 footnote Footnote labels.
972 Changing this variable requires a restart of Emacs to become effective."
973 :group 'org-link
974 :type '(set :greedy t
975 (const :tag "Double bracket links (new style)" bracket)
976 (const :tag "Angular bracket links (old style)" angular)
977 (const :tag "Plain text links" plain)
978 (const :tag "Radio target matches" radio)
979 (const :tag "Tags" tag)
980 (const :tag "Timestamps" date)
981 (const :tag "Footnotes" footnote)))
983 (defcustom org-make-link-description-function nil
984 "Function to use to generate link descriptions from links. If
985 nil the link location will be used. This function must take two
986 parameters; the first is the link and the second the description
987 org-insert-link has generated, and should return the description
988 to use."
989 :group 'org-link
990 :type 'function)
992 (defgroup org-link-store nil
993 "Options concerning storing links in Org-mode."
994 :tag "Org Store Link"
995 :group 'org-link)
997 (defcustom org-email-link-description-format "Email %c: %.30s"
998 "Format of the description part of a link to an email or usenet message.
999 The following %-escapes will be replaced by corresponding information:
1001 %F full \"From\" field
1002 %f name, taken from \"From\" field, address if no name
1003 %T full \"To\" field
1004 %t first name in \"To\" field, address if no name
1005 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1006 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1007 %s subject
1008 %m message-id.
1010 You may use normal field width specification between the % and the letter.
1011 This is for example useful to limit the length of the subject.
1013 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1014 :group 'org-link-store
1015 :type 'string)
1017 (defcustom org-from-is-user-regexp
1018 (let (r1 r2)
1019 (when (and user-mail-address (not (string= user-mail-address "")))
1020 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1021 (when (and user-full-name (not (string= user-full-name "")))
1022 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1023 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1024 "Regexp matched against the \"From:\" header of an email or usenet message.
1025 It should match if the message is from the user him/herself."
1026 :group 'org-link-store
1027 :type 'regexp)
1029 (defcustom org-link-to-org-use-id 'create-if-interactive
1030 "Non-nil means, storing a link to an Org file will use entry IDs.
1032 Note that before this variable is even considered, org-id must be loaded,
1033 to please customize `org-modules' and turn it on.
1035 The variable can have the following values:
1037 t Create an ID if needed to make a link to the current entry.
1039 create-if-interactive
1040 If `org-store-link' is called directly (interactively, as a user
1041 command), do create an ID to support the link. But when doing the
1042 job for remember, only use the ID if it already exists. The
1043 purpose of this setting is to avoid proliferation of unwanted
1044 IDs, just because you happen to be in an Org file when you
1045 call `org-remember' that automatically and preemptively
1046 creates a link. If you do want to get an ID link in a remember
1047 template to an entry not having an ID, create it first by
1048 explicitly creating a link to it, using `C-c C-l' first.
1050 use-existing
1051 Use existing ID, do not create one.
1053 nil Never use an ID to make a link, instead link using a text search for
1054 the headline text."
1055 :group 'org-link-store
1056 :type '(choice
1057 (const :tag "Create ID to make link" t)
1058 (const :tag "Create if string link interactively"
1059 'create-if-interactive)
1060 (const :tag "Only use existing" 'use-existing)
1061 (const :tag "Do not use ID to create link" nil)))
1063 (defcustom org-context-in-file-links t
1064 "Non-nil means, file links from `org-store-link' contain context.
1065 A search string will be added to the file name with :: as separator and
1066 used to find the context when the link is activated by the command
1067 `org-open-at-point'.
1068 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1069 negates this setting for the duration of the command."
1070 :group 'org-link-store
1071 :type 'boolean)
1073 (defcustom org-keep-stored-link-after-insertion nil
1074 "Non-nil means, keep link in list for entire session.
1076 The command `org-store-link' adds a link pointing to the current
1077 location to an internal list. These links accumulate during a session.
1078 The command `org-insert-link' can be used to insert links into any
1079 Org-mode file (offering completion for all stored links). When this
1080 option is nil, every link which has been inserted once using \\[org-insert-link]
1081 will be removed from the list, to make completing the unused links
1082 more efficient."
1083 :group 'org-link-store
1084 :type 'boolean)
1086 (defgroup org-link-follow nil
1087 "Options concerning following links in Org-mode."
1088 :tag "Org Follow Link"
1089 :group 'org-link)
1091 (defcustom org-link-translation-function nil
1092 "Function to translate links with different syntax to Org syntax.
1093 This can be used to translate links created for example by the Planner
1094 or emacs-wiki packages to Org syntax.
1095 The function must accept two parameters, a TYPE containing the link
1096 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1097 which is everything after the link protocol. It should return a cons
1098 with possibly modified values of type and path.
1099 Org contains a function for this, so if you set this variable to
1100 `org-translate-link-from-planner', you should be able follow many
1101 links created by planner."
1102 :group 'org-link-follow
1103 :type 'function)
1105 (defcustom org-follow-link-hook nil
1106 "Hook that is run after a link has been followed."
1107 :group 'org-link-follow
1108 :type 'hook)
1110 (defcustom org-tab-follows-link nil
1111 "Non-nil means, on links TAB will follow the link.
1112 Needs to be set before org.el is loaded."
1113 :group 'org-link-follow
1114 :type 'boolean)
1116 (defcustom org-return-follows-link nil
1117 "Non-nil means, on links RET will follow the link.
1118 Needs to be set before org.el is loaded."
1119 :group 'org-link-follow
1120 :type 'boolean)
1122 (defcustom org-mouse-1-follows-link
1123 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1124 "Non-nil means, mouse-1 on a link will follow the link.
1125 A longer mouse click will still set point. Does not work on XEmacs.
1126 Needs to be set before org.el is loaded."
1127 :group 'org-link-follow
1128 :type 'boolean)
1130 (defcustom org-mark-ring-length 4
1131 "Number of different positions to be recorded in the ring
1132 Changing this requires a restart of Emacs to work correctly."
1133 :group 'org-link-follow
1134 :type 'integer)
1136 (defcustom org-link-frame-setup
1137 '((vm . vm-visit-folder-other-frame)
1138 (gnus . gnus-other-frame)
1139 (file . find-file-other-window))
1140 "Setup the frame configuration for following links.
1141 When following a link with Emacs, it may often be useful to display
1142 this link in another window or frame. This variable can be used to
1143 set this up for the different types of links.
1144 For VM, use any of
1145 `vm-visit-folder'
1146 `vm-visit-folder-other-frame'
1147 For Gnus, use any of
1148 `gnus'
1149 `gnus-other-frame'
1150 `org-gnus-no-new-news'
1151 For FILE, use any of
1152 `find-file'
1153 `find-file-other-window'
1154 `find-file-other-frame'
1155 For the calendar, use the variable `calendar-setup'.
1156 For BBDB, it is currently only possible to display the matches in
1157 another window."
1158 :group 'org-link-follow
1159 :type '(list
1160 (cons (const vm)
1161 (choice
1162 (const vm-visit-folder)
1163 (const vm-visit-folder-other-window)
1164 (const vm-visit-folder-other-frame)))
1165 (cons (const gnus)
1166 (choice
1167 (const gnus)
1168 (const gnus-other-frame)
1169 (const org-gnus-no-new-news)))
1170 (cons (const file)
1171 (choice
1172 (const find-file)
1173 (const find-file-other-window)
1174 (const find-file-other-frame)))))
1176 (defcustom org-display-internal-link-with-indirect-buffer nil
1177 "Non-nil means, use indirect buffer to display infile links.
1178 Activating internal links (from one location in a file to another location
1179 in the same file) normally just jumps to the location. When the link is
1180 activated with a C-u prefix (or with mouse-3), the link is displayed in
1181 another window. When this option is set, the other window actually displays
1182 an indirect buffer clone of the current buffer, to avoid any visibility
1183 changes to the current buffer."
1184 :group 'org-link-follow
1185 :type 'boolean)
1187 (defcustom org-open-non-existing-files nil
1188 "Non-nil means, `org-open-file' will open non-existing files.
1189 When nil, an error will be generated."
1190 :group 'org-link-follow
1191 :type 'boolean)
1193 (defcustom org-open-directory-means-index-dot-org nil
1194 "Non-nil means, a link to a directory really means to index.org.
1195 When nil, following a directory link will run dired or open a finder/explorer
1196 window on that directory."
1197 :group 'org-link-follow
1198 :type 'boolean)
1200 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1201 "Function and arguments to call for following mailto links.
1202 This is a list with the first element being a lisp function, and the
1203 remaining elements being arguments to the function. In string arguments,
1204 %a will be replaced by the address, and %s will be replaced by the subject
1205 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1206 :group 'org-link-follow
1207 :type '(choice
1208 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1209 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1210 (const :tag "message-mail" (message-mail "%a" "%s"))
1211 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1213 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1214 "Non-nil means, ask for confirmation before executing shell links.
1215 Shell links can be dangerous: just think about a link
1217 [[shell:rm -rf ~/*][Google Search]]
1219 This link would show up in your Org-mode document as \"Google Search\",
1220 but really it would remove your entire home directory.
1221 Therefore we advise against setting this variable to nil.
1222 Just change it to `y-or-n-p' of you want to confirm with a
1223 single keystroke rather than having to type \"yes\"."
1224 :group 'org-link-follow
1225 :type '(choice
1226 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1227 (const :tag "with y-or-n (faster)" y-or-n-p)
1228 (const :tag "no confirmation (dangerous)" nil)))
1230 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1231 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1232 Elisp links can be dangerous: just think about a link
1234 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1236 This link would show up in your Org-mode document as \"Google Search\",
1237 but really it would remove your entire home directory.
1238 Therefore we advise against setting this variable to nil.
1239 Just change it to `y-or-n-p' of you want to confirm with a
1240 single keystroke rather than having to type \"yes\"."
1241 :group 'org-link-follow
1242 :type '(choice
1243 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1244 (const :tag "with y-or-n (faster)" y-or-n-p)
1245 (const :tag "no confirmation (dangerous)" nil)))
1247 (defconst org-file-apps-defaults-gnu
1248 '((remote . emacs)
1249 (system . mailcap)
1250 (t . mailcap))
1251 "Default file applications on a UNIX or GNU/Linux system.
1252 See `org-file-apps'.")
1254 (defconst org-file-apps-defaults-macosx
1255 '((remote . emacs)
1256 (t . "open %s")
1257 (system . "open %s")
1258 ("ps.gz" . "gv %s")
1259 ("eps.gz" . "gv %s")
1260 ("dvi" . "xdvi %s")
1261 ("fig" . "xfig %s"))
1262 "Default file applications on a MacOS X system.
1263 The system \"open\" is known as a default, but we use X11 applications
1264 for some files for which the OS does not have a good default.
1265 See `org-file-apps'.")
1267 (defconst org-file-apps-defaults-windowsnt
1268 (list
1269 '(remote . emacs)
1270 (cons t
1271 (list (if (featurep 'xemacs)
1272 'mswindows-shell-execute
1273 'w32-shell-execute)
1274 "open" 'file))
1275 (cons 'system
1276 (list (if (featurep 'xemacs)
1277 'mswindows-shell-execute
1278 'w32-shell-execute)
1279 "open" 'file)))
1280 "Default file applications on a Windows NT system.
1281 The system \"open\" is used for most files.
1282 See `org-file-apps'.")
1284 (defcustom org-file-apps
1286 (auto-mode . emacs)
1287 ("\\.x?html?\\'" . default)
1288 ("\\.pdf\\'" . default)
1290 "External applications for opening `file:path' items in a document.
1291 Org-mode uses system defaults for different file types, but
1292 you can use this variable to set the application for a given file
1293 extension. The entries in this list are cons cells where the car identifies
1294 files and the cdr the corresponding command. Possible values for the
1295 file identifier are
1296 \"regex\" Regular expression matched against the file name. For backward
1297 compatibility, this can also be a string with only alphanumeric
1298 characters, which is then interpreted as an extension.
1299 `directory' Matches a directory
1300 `remote' Matches a remote file, accessible through tramp or efs.
1301 Remote files most likely should be visited through Emacs
1302 because external applications cannot handle such paths.
1303 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1304 so all files Emacs knows how to handle. Using this with
1305 command `emacs' will open most files in Emacs. Beware that this
1306 will also open html files inside Emacs, unless you add
1307 (\"html\" . default) to the list as well.
1308 t Default for files not matched by any of the other options.
1309 `system' The system command to open files, like `open' on Windows
1310 and Mac OS X, and mailcap under GNU/Linux. This is the command
1311 that will be selected if you call `C-c C-o' with a double
1312 `C-u C-u' prefix.
1314 Possible values for the command are:
1315 `emacs' The file will be visited by the current Emacs process.
1316 `default' Use the default application for this file type, which is the
1317 association for t in the list, most likely in the system-specific
1318 part.
1319 This can be used to overrule an unwanted setting in the
1320 system-specific variable.
1321 `system' Use the system command for opening files, like \"open\".
1322 This command is specified by the entry whose car is `system'.
1323 Most likely, the system-specific version of this variable
1324 does define this command, but you can overrule/replace it
1325 here.
1326 string A command to be executed by a shell; %s will be replaced
1327 by the path to the file.
1328 sexp A Lisp form which will be evaluated. The file path will
1329 be available in the Lisp variable `file'.
1330 For more examples, see the system specific constants
1331 `org-file-apps-defaults-macosx'
1332 `org-file-apps-defaults-windowsnt'
1333 `org-file-apps-defaults-gnu'."
1334 :group 'org-link-follow
1335 :type '(repeat
1336 (cons (choice :value ""
1337 (string :tag "Extension")
1338 (const :tag "System command to open files" system)
1339 (const :tag "Default for unrecognized files" t)
1340 (const :tag "Remote file" remote)
1341 (const :tag "Links to a directory" directory)
1342 (const :tag "Any files that have Emacs modes"
1343 auto-mode))
1344 (choice :value ""
1345 (const :tag "Visit with Emacs" emacs)
1346 (const :tag "Use default" default)
1347 (const :tag "Use the system command" system)
1348 (string :tag "Command")
1349 (sexp :tag "Lisp form")))))
1351 (defgroup org-refile nil
1352 "Options concerning refiling entries in Org-mode."
1353 :tag "Org Refile"
1354 :group 'org)
1356 (defcustom org-directory "~/org"
1357 "Directory with org files.
1358 This directory will be used as default to prompt for org files.
1359 Used by the hooks for remember.el."
1360 :group 'org-refile
1361 :group 'org-remember
1362 :type 'directory)
1364 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1365 "Default target for storing notes.
1366 Used by the hooks for remember.el. This can be a string, or nil to mean
1367 the value of `remember-data-file'.
1368 You can set this on a per-template basis with the variable
1369 `org-remember-templates'."
1370 :group 'org-refile
1371 :group 'org-remember
1372 :type '(choice
1373 (const :tag "Default from remember-data-file" nil)
1374 file))
1376 (defcustom org-goto-interface 'outline
1377 "The default interface to be used for `org-goto'.
1378 Allowed values are:
1379 outline The interface shows an outline of the relevant file
1380 and the correct heading is found by moving through
1381 the outline or by searching with incremental search.
1382 outline-path-completion Headlines in the current buffer are offered via
1383 completion. This is the interface also used by
1384 the refile command."
1385 :group 'org-refile
1386 :type '(choice
1387 (const :tag "Outline" outline)
1388 (const :tag "Outline-path-completion" outline-path-completion)))
1390 (defcustom org-goto-max-level 5
1391 "Maximum level to be considered when running org-goto with refile interface."
1392 :group 'org-refile
1393 :type 'number)
1395 (defcustom org-reverse-note-order nil
1396 "Non-nil means, store new notes at the beginning of a file or entry.
1397 When nil, new notes will be filed to the end of a file or entry.
1398 This can also be a list with cons cells of regular expressions that
1399 are matched against file names, and values."
1400 :group 'org-remember
1401 :group 'org-refile
1402 :type '(choice
1403 (const :tag "Reverse always" t)
1404 (const :tag "Reverse never" nil)
1405 (repeat :tag "By file name regexp"
1406 (cons regexp boolean))))
1408 (defcustom org-refile-targets nil
1409 "Targets for refiling entries with \\[org-refile].
1410 This is list of cons cells. Each cell contains:
1411 - a specification of the files to be considered, either a list of files,
1412 or a symbol whose function or variable value will be used to retrieve
1413 a file name or a list of file names. If you use `org-agenda-files' for
1414 that, all agenda files will be scanned for targets. Nil means, consider
1415 headings in the current buffer.
1416 - A specification of how to select find candidate refile targets. This
1417 may be any of
1418 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1419 This tag has to be present in all target headlines, inheritance will
1420 not be considered.
1421 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1422 todo keyword.
1423 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1424 headlines that are refiling targets.
1425 - a cons cell (:level . N). Any headline of level N is considered a target.
1426 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1428 When this variable is nil, all top-level headlines in the current buffer
1429 are used, equivalent to the value `((nil . (:level . 1))'."
1430 :group 'org-refile
1431 :type '(repeat
1432 (cons
1433 (choice :value org-agenda-files
1434 (const :tag "All agenda files" org-agenda-files)
1435 (const :tag "Current buffer" nil)
1436 (function) (variable) (file))
1437 (choice :tag "Identify target headline by"
1438 (cons :tag "Specific tag" (const :value :tag) (string))
1439 (cons :tag "TODO keyword" (const :value :todo) (string))
1440 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1441 (cons :tag "Level number" (const :value :level) (integer))
1442 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1444 (defcustom org-refile-use-outline-path nil
1445 "Non-nil means, provide refile targets as paths.
1446 So a level 3 headline will be available as level1/level2/level3.
1447 When the value is `file', also include the file name (without directory)
1448 into the path. When `full-file-path', include the full file path."
1449 :group 'org-refile
1450 :type '(choice
1451 (const :tag "Not" nil)
1452 (const :tag "Yes" t)
1453 (const :tag "Start with file name" file)
1454 (const :tag "Start with full file path" full-file-path)))
1456 (defcustom org-outline-path-complete-in-steps t
1457 "Non-nil means, complete the outline path in hierarchical steps.
1458 When Org-mode uses the refile interface to select an outline path
1459 \(see variable `org-refile-use-outline-path'), the completion of
1460 the path can be done is a single go, or if can be done in steps down
1461 the headline hierarchy. Going in steps is probably the best if you
1462 do not use a special completion package like `ido' or `icicles'.
1463 However, when using these packages, going in one step can be very
1464 fast, while still showing the whole path to the entry."
1465 :group 'org-refile
1466 :type 'boolean)
1468 (defgroup org-todo nil
1469 "Options concerning TODO items in Org-mode."
1470 :tag "Org TODO"
1471 :group 'org)
1473 (defgroup org-progress nil
1474 "Options concerning Progress logging in Org-mode."
1475 :tag "Org Progress"
1476 :group 'org-time)
1478 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1479 "List of TODO entry keyword sequences and their interpretation.
1480 \\<org-mode-map>This is a list of sequences.
1482 Each sequence starts with a symbol, either `sequence' or `type',
1483 indicating if the keywords should be interpreted as a sequence of
1484 action steps, or as different types of TODO items. The first
1485 keywords are states requiring action - these states will select a headline
1486 for inclusion into the global TODO list Org-mode produces. If one of
1487 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1488 signify that no further action is necessary. If \"|\" is not found,
1489 the last keyword is treated as the only DONE state of the sequence.
1491 The command \\[org-todo] cycles an entry through these states, and one
1492 additional state where no keyword is present. For details about this
1493 cycling, see the manual.
1495 TODO keywords and interpretation can also be set on a per-file basis with
1496 the special #+SEQ_TODO and #+TYP_TODO lines.
1498 Each keyword can optionally specify a character for fast state selection
1499 \(in combination with the variable `org-use-fast-todo-selection')
1500 and specifiers for state change logging, using the same syntax
1501 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1502 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1503 indicates to record a time stamp each time this state is selected.
1505 Each keyword may also specify if a timestamp or a note should be
1506 recorded when entering or leaving the state, by adding additional
1507 characters in the parenthesis after the keyword. This looks like this:
1508 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1509 record only the time of the state change. With X and Y being either
1510 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1511 Y when leaving the state if and only if the *target* state does not
1512 define X. You may omit any of the fast-selection key or X or /Y,
1513 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1515 For backward compatibility, this variable may also be just a list
1516 of keywords - in this case the interpretation (sequence or type) will be
1517 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1518 :group 'org-todo
1519 :group 'org-keywords
1520 :type '(choice
1521 (repeat :tag "Old syntax, just keywords"
1522 (string :tag "Keyword"))
1523 (repeat :tag "New syntax"
1524 (cons
1525 (choice
1526 :tag "Interpretation"
1527 (const :tag "Sequence (cycling hits every state)" sequence)
1528 (const :tag "Type (cycling directly to DONE)" type))
1529 (repeat
1530 (string :tag "Keyword"))))))
1532 (defvar org-todo-keywords-1 nil
1533 "All TODO and DONE keywords active in a buffer.")
1534 (make-variable-buffer-local 'org-todo-keywords-1)
1535 (defvar org-todo-keywords-for-agenda nil)
1536 (defvar org-done-keywords-for-agenda nil)
1537 (defvar org-todo-keyword-alist-for-agenda nil)
1538 (defvar org-tag-alist-for-agenda nil)
1539 (defvar org-agenda-contributing-files nil)
1540 (defvar org-not-done-keywords nil)
1541 (make-variable-buffer-local 'org-not-done-keywords)
1542 (defvar org-done-keywords nil)
1543 (make-variable-buffer-local 'org-done-keywords)
1544 (defvar org-todo-heads nil)
1545 (make-variable-buffer-local 'org-todo-heads)
1546 (defvar org-todo-sets nil)
1547 (make-variable-buffer-local 'org-todo-sets)
1548 (defvar org-todo-log-states nil)
1549 (make-variable-buffer-local 'org-todo-log-states)
1550 (defvar org-todo-kwd-alist nil)
1551 (make-variable-buffer-local 'org-todo-kwd-alist)
1552 (defvar org-todo-key-alist nil)
1553 (make-variable-buffer-local 'org-todo-key-alist)
1554 (defvar org-todo-key-trigger nil)
1555 (make-variable-buffer-local 'org-todo-key-trigger)
1557 (defcustom org-todo-interpretation 'sequence
1558 "Controls how TODO keywords are interpreted.
1559 This variable is in principle obsolete and is only used for
1560 backward compatibility, if the interpretation of todo keywords is
1561 not given already in `org-todo-keywords'. See that variable for
1562 more information."
1563 :group 'org-todo
1564 :group 'org-keywords
1565 :type '(choice (const sequence)
1566 (const type)))
1568 (defcustom org-use-fast-todo-selection 'prefix
1569 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1570 This variable describes if and under what circumstances the cycling
1571 mechanism for TODO keywords will be replaced by a single-key, direct
1572 selection scheme.
1574 When nil, fast selection is never used.
1576 When the symbol `prefix', it will be used when `org-todo' is called with
1577 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1578 in an agenda buffer.
1580 When t, fast selection is used by default. In this case, the prefix
1581 argument forces cycling instead.
1583 In all cases, the special interface is only used if access keys have actually
1584 been assigned by the user, i.e. if keywords in the configuration are followed
1585 by a letter in parenthesis, like TODO(t)."
1586 :group 'org-todo
1587 :type '(choice
1588 (const :tag "Never" nil)
1589 (const :tag "By default" t)
1590 (const :tag "Only with C-u C-c C-t" prefix)))
1592 (defcustom org-provide-todo-statistics t
1593 "Non-nil means, update todo statistics after insert and toggle.
1594 When this is set, todo statistics is updated in the parent of the current
1595 entry each time a todo state is changed."
1596 :group 'org-todo
1597 :type 'boolean)
1599 (defcustom org-after-todo-state-change-hook nil
1600 "Hook which is run after the state of a TODO item was changed.
1601 The new state (a string with a TODO keyword, or nil) is available in the
1602 Lisp variable `state'."
1603 :group 'org-todo
1604 :type 'hook)
1606 (defcustom org-todo-state-tags-triggers nil
1607 "Tag changes that should be triggered by TODO state changes.
1608 This is a list. Each entry is
1610 (state-change (tag . flag) .......)
1612 State-change can be a string with a state, and empty string to indicate the
1613 state that has no TODO keyword, or it can be one of the symbols `todo'
1614 or `done', meaning any not-done or done state, respectively."
1615 :group 'org-todo
1616 :group 'org-tags
1617 :type '(repeat
1618 (cons (choice :tag "When changing to"
1619 (const :tag "Not-done state" todo)
1620 (const :tag "Done state" done)
1621 (string :tag "State"))
1622 (repeat
1623 (cons :tag "Tag action"
1624 (string :tag "Tag")
1625 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1627 (defcustom org-log-done nil
1628 "Information to record when a task moves to the DONE state.
1630 Possible values are:
1632 nil Don't add anything, just change the keyword
1633 time Add a time stamp to the task
1634 note Prompt a closing note and add it with template `org-log-note-headings'
1636 This option can also be set with on a per-file-basis with
1638 #+STARTUP: nologdone
1639 #+STARTUP: logdone
1640 #+STARTUP: lognotedone
1642 You can have local logging settings for a subtree by setting the LOGGING
1643 property to one or more of these keywords."
1644 :group 'org-todo
1645 :group 'org-progress
1646 :type '(choice
1647 (const :tag "No logging" nil)
1648 (const :tag "Record CLOSED timestamp" time)
1649 (const :tag "Record CLOSED timestamp with closing note." note)))
1651 ;; Normalize old uses of org-log-done.
1652 (cond
1653 ((eq org-log-done t) (setq org-log-done 'time))
1654 ((and (listp org-log-done) (memq 'done org-log-done))
1655 (setq org-log-done 'note)))
1657 (defcustom org-log-note-clock-out nil
1658 "Non-nil means, record a note when clocking out of an item.
1659 This can also be configured on a per-file basis by adding one of
1660 the following lines anywhere in the buffer:
1662 #+STARTUP: lognoteclock-out
1663 #+STARTUP: nolognoteclock-out"
1664 :group 'org-todo
1665 :group 'org-progress
1666 :type 'boolean)
1668 (defcustom org-log-done-with-time t
1669 "Non-nil means, the CLOSED time stamp will contain date and time.
1670 When nil, only the date will be recorded."
1671 :group 'org-progress
1672 :type 'boolean)
1674 (defcustom org-log-note-headings
1675 '((done . "CLOSING NOTE %t")
1676 (state . "State %-12s %t")
1677 (note . "Note taken on %t")
1678 (clock-out . ""))
1679 "Headings for notes added to entries.
1680 The value is an alist, with the car being a symbol indicating the note
1681 context, and the cdr is the heading to be used. The heading may also be the
1682 empty string.
1683 %t in the heading will be replaced by a time stamp.
1684 %s will be replaced by the new TODO state, in double quotes.
1685 %u will be replaced by the user name.
1686 %U will be replaced by the full user name."
1687 :group 'org-todo
1688 :group 'org-progress
1689 :type '(list :greedy t
1690 (cons (const :tag "Heading when closing an item" done) string)
1691 (cons (const :tag
1692 "Heading when changing todo state (todo sequence only)"
1693 state) string)
1694 (cons (const :tag "Heading when just taking a note" note) string)
1695 (cons (const :tag "Heading when clocking out" clock-out) string)))
1697 (unless (assq 'note org-log-note-headings)
1698 (push '(note . "%t") org-log-note-headings))
1700 (defcustom org-log-state-notes-insert-after-drawers nil
1701 "Non-nil means, insert state change notes after any drawers in entry.
1702 Only the drawers that *immediately* follow the headline and the
1703 deadline/scheduled line are skipped.
1704 When nil, insert notes right after the heading and perhaps the line
1705 with deadline/scheduling if present."
1706 :group 'org-todo
1707 :group 'org-progress
1708 :type 'boolean)
1710 (defcustom org-log-states-order-reversed t
1711 "Non-nil means, the latest state change note will be directly after heading.
1712 When nil, the notes will be orderer according to time."
1713 :group 'org-todo
1714 :group 'org-progress
1715 :type 'boolean)
1717 (defcustom org-log-repeat 'time
1718 "Non-nil means, record moving through the DONE state when triggering repeat.
1719 An auto-repeating tasks is immediately switched back to TODO when marked
1720 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1721 the TODO keyword definition, or recording a closing note by setting
1722 `org-log-done', there will be no record of the task moving through DONE.
1723 This variable forces taking a note anyway. Possible values are:
1725 nil Don't force a record
1726 time Record a time stamp
1727 note Record a note
1729 This option can also be set with on a per-file-basis with
1731 #+STARTUP: logrepeat
1732 #+STARTUP: lognoterepeat
1733 #+STARTUP: nologrepeat
1735 You can have local logging settings for a subtree by setting the LOGGING
1736 property to one or more of these keywords."
1737 :group 'org-todo
1738 :group 'org-progress
1739 :type '(choice
1740 (const :tag "Don't force a record" nil)
1741 (const :tag "Force recording the DONE state" time)
1742 (const :tag "Force recording a note with the DONE state" note)))
1745 (defgroup org-priorities nil
1746 "Priorities in Org-mode."
1747 :tag "Org Priorities"
1748 :group 'org-todo)
1750 (defcustom org-highest-priority ?A
1751 "The highest priority of TODO items. A character like ?A, ?B etc.
1752 Must have a smaller ASCII number than `org-lowest-priority'."
1753 :group 'org-priorities
1754 :type 'character)
1756 (defcustom org-lowest-priority ?C
1757 "The lowest priority of TODO items. A character like ?A, ?B etc.
1758 Must have a larger ASCII number than `org-highest-priority'."
1759 :group 'org-priorities
1760 :type 'character)
1762 (defcustom org-default-priority ?B
1763 "The default priority of TODO items.
1764 This is the priority an item get if no explicit priority is given."
1765 :group 'org-priorities
1766 :type 'character)
1768 (defcustom org-priority-start-cycle-with-default t
1769 "Non-nil means, start with default priority when starting to cycle.
1770 When this is nil, the first step in the cycle will be (depending on the
1771 command used) one higher or lower that the default priority."
1772 :group 'org-priorities
1773 :type 'boolean)
1775 (defgroup org-time nil
1776 "Options concerning time stamps and deadlines in Org-mode."
1777 :tag "Org Time"
1778 :group 'org)
1780 (defcustom org-insert-labeled-timestamps-at-point nil
1781 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1782 When nil, these labeled time stamps are forces into the second line of an
1783 entry, just after the headline. When scheduling from the global TODO list,
1784 the time stamp will always be forced into the second line."
1785 :group 'org-time
1786 :type 'boolean)
1788 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1789 "Formats for `format-time-string' which are used for time stamps.
1790 It is not recommended to change this constant.")
1792 (defcustom org-time-stamp-rounding-minutes '(0 5)
1793 "Number of minutes to round time stamps to.
1794 These are two values, the first applies when first creating a time stamp.
1795 The second applies when changing it with the commands `S-up' and `S-down'.
1796 When changing the time stamp, this means that it will change in steps
1797 of N minutes, as given by the second value.
1799 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1800 numbers should be factors of 60, so for example 5, 10, 15.
1802 When this is larger than 1, you can still force an exact time-stamp by using
1803 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1804 and by using a prefix arg to `S-up/down' to specify the exact number
1805 of minutes to shift."
1806 :group 'org-time
1807 :get '(lambda (var) ; Make sure all entries have 5 elements
1808 (if (integerp (default-value var))
1809 (list (default-value var) 5)
1810 (default-value var)))
1811 :type '(list
1812 (integer :tag "when inserting times")
1813 (integer :tag "when modifying times")))
1815 ;; Normalize old customizations of this variable.
1816 (when (integerp org-time-stamp-rounding-minutes)
1817 (setq org-time-stamp-rounding-minutes
1818 (list org-time-stamp-rounding-minutes
1819 org-time-stamp-rounding-minutes)))
1821 (defcustom org-display-custom-times nil
1822 "Non-nil means, overlay custom formats over all time stamps.
1823 The formats are defined through the variable `org-time-stamp-custom-formats'.
1824 To turn this on on a per-file basis, insert anywhere in the file:
1825 #+STARTUP: customtime"
1826 :group 'org-time
1827 :set 'set-default
1828 :type 'sexp)
1829 (make-variable-buffer-local 'org-display-custom-times)
1831 (defcustom org-time-stamp-custom-formats
1832 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1833 "Custom formats for time stamps. See `format-time-string' for the syntax.
1834 These are overlayed over the default ISO format if the variable
1835 `org-display-custom-times' is set. Time like %H:%M should be at the
1836 end of the second format."
1837 :group 'org-time
1838 :type 'sexp)
1840 (defun org-time-stamp-format (&optional long inactive)
1841 "Get the right format for a time string."
1842 (let ((f (if long (cdr org-time-stamp-formats)
1843 (car org-time-stamp-formats))))
1844 (if inactive
1845 (concat "[" (substring f 1 -1) "]")
1846 f)))
1848 (defcustom org-time-clocksum-format "%d:%02d"
1849 "The format string used when creating CLOCKSUM lines, or when
1850 org-mode generates a time duration."
1851 :group 'org-time
1852 :type 'string)
1854 (defcustom org-deadline-warning-days 14
1855 "No. of days before expiration during which a deadline becomes active.
1856 This variable governs the display in sparse trees and in the agenda.
1857 When 0 or negative, it means use this number (the absolute value of it)
1858 even if a deadline has a different individual lead time specified."
1859 :group 'org-time
1860 :group 'org-agenda-daily/weekly
1861 :type 'number)
1863 (defcustom org-read-date-prefer-future t
1864 "Non-nil means, assume future for incomplete date input from user.
1865 This affects the following situations:
1866 1. The user gives a day, but no month.
1867 For example, if today is the 15th, and you enter \"3\", Org-mode will
1868 read this as the third of *next* month. However, if you enter \"17\",
1869 it will be considered as *this* month.
1870 2. The user gives a month but not a year.
1871 For example, if it is april and you enter \"feb 2\", this will be read
1872 as feb 2, *next* year. \"May 5\", however, will be this year.
1874 Currently this does not work for ISO week specifications.
1876 When this option is nil, the current month and year will always be used
1877 as defaults."
1878 :group 'org-time
1879 :type 'boolean)
1881 (defcustom org-read-date-display-live t
1882 "Non-nil means, display current interpretation of date prompt live.
1883 This display will be in an overlay, in the minibuffer."
1884 :group 'org-time
1885 :type 'boolean)
1887 (defcustom org-read-date-popup-calendar t
1888 "Non-nil means, pop up a calendar when prompting for a date.
1889 In the calendar, the date can be selected with mouse-1. However, the
1890 minibuffer will also be active, and you can simply enter the date as well.
1891 When nil, only the minibuffer will be available."
1892 :group 'org-time
1893 :type 'boolean)
1894 (if (fboundp 'defvaralias)
1895 (defvaralias 'org-popup-calendar-for-date-prompt
1896 'org-read-date-popup-calendar))
1898 (defcustom org-extend-today-until 0
1899 "The hour when your day really ends. Must be an integer.
1900 This has influence for the following applications:
1901 - When switching the agenda to \"today\". It it is still earlier than
1902 the time given here, the day recognized as TODAY is actually yesterday.
1903 - When a date is read from the user and it is still before the time given
1904 here, the current date and time will be assumed to be yesterday, 23:59.
1905 Also, timestamps inserted in remember templates follow this rule.
1907 IMPORTANT: This is a feature whose implementation is and likely will
1908 remain incomplete. Really, it is only here because past midnight seems to
1909 be the favorite working time of John Wiegley :-)"
1910 :group 'org-time
1911 :type 'number)
1913 (defcustom org-edit-timestamp-down-means-later nil
1914 "Non-nil means, S-down will increase the time in a time stamp.
1915 When nil, S-up will increase."
1916 :group 'org-time
1917 :type 'boolean)
1919 (defcustom org-calendar-follow-timestamp-change t
1920 "Non-nil means, make the calendar window follow timestamp changes.
1921 When a timestamp is modified and the calendar window is visible, it will be
1922 moved to the new date."
1923 :group 'org-time
1924 :type 'boolean)
1926 (defgroup org-tags nil
1927 "Options concerning tags in Org-mode."
1928 :tag "Org Tags"
1929 :group 'org)
1931 (defcustom org-tag-alist nil
1932 "List of tags allowed in Org-mode files.
1933 When this list is nil, Org-mode will base TAG input on what is already in the
1934 buffer.
1935 The value of this variable is an alist, the car of each entry must be a
1936 keyword as a string, the cdr may be a character that is used to select
1937 that tag through the fast-tag-selection interface.
1938 See the manual for details."
1939 :group 'org-tags
1940 :type '(repeat
1941 (choice
1942 (cons (string :tag "Tag name")
1943 (character :tag "Access char"))
1944 (const :tag "Start radio group" (:startgroup))
1945 (const :tag "End radio group" (:endgroup)))))
1947 (defvar org-file-tags nil
1948 "List of tags that can be inherited by all entries in the file.
1949 The tags will be inherited if the variable `org-use-tag-inheritance'
1950 says they should be.
1951 This variable is populated from #+TAG lines.")
1953 (defcustom org-use-fast-tag-selection 'auto
1954 "Non-nil means, use fast tag selection scheme.
1955 This is a special interface to select and deselect tags with single keys.
1956 When nil, fast selection is never used.
1957 When the symbol `auto', fast selection is used if and only if selection
1958 characters for tags have been configured, either through the variable
1959 `org-tag-alist' or through a #+TAGS line in the buffer.
1960 When t, fast selection is always used and selection keys are assigned
1961 automatically if necessary."
1962 :group 'org-tags
1963 :type '(choice
1964 (const :tag "Always" t)
1965 (const :tag "Never" nil)
1966 (const :tag "When selection characters are configured" 'auto)))
1968 (defcustom org-fast-tag-selection-single-key nil
1969 "Non-nil means, fast tag selection exits after first change.
1970 When nil, you have to press RET to exit it.
1971 During fast tag selection, you can toggle this flag with `C-c'.
1972 This variable can also have the value `expert'. In this case, the window
1973 displaying the tags menu is not even shown, until you press C-c again."
1974 :group 'org-tags
1975 :type '(choice
1976 (const :tag "No" nil)
1977 (const :tag "Yes" t)
1978 (const :tag "Expert" expert)))
1980 (defvar org-fast-tag-selection-include-todo nil
1981 "Non-nil means, fast tags selection interface will also offer TODO states.
1982 This is an undocumented feature, you should not rely on it.")
1984 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1985 "The column to which tags should be indented in a headline.
1986 If this number is positive, it specifies the column. If it is negative,
1987 it means that the tags should be flushright to that column. For example,
1988 -80 works well for a normal 80 character screen."
1989 :group 'org-tags
1990 :type 'integer)
1992 (defcustom org-auto-align-tags t
1993 "Non-nil means, realign tags after pro/demotion of TODO state change.
1994 These operations change the length of a headline and therefore shift
1995 the tags around. With this options turned on, after each such operation
1996 the tags are again aligned to `org-tags-column'."
1997 :group 'org-tags
1998 :type 'boolean)
2000 (defcustom org-use-tag-inheritance t
2001 "Non-nil means, tags in levels apply also for sublevels.
2002 When nil, only the tags directly given in a specific line apply there.
2003 This may also be a list of tags that should be inherited, or a regexp that
2004 matches tags that should be inherited. Additional control is possible
2005 with the variable `org-tags-exclude-from-inheritance' which gives an
2006 explicit list of tags to be excluded from inheritance., even if the value of
2007 `org-use-tag-inheritance' would select it for inheritance.
2009 If this option is t, a match early-on in a tree can lead to a large
2010 number of matches in the subtree when constructing the agenda or creating
2011 a sparse tree. If you only want to see the first match in a tree during
2012 a search, check out the variable `org-tags-match-list-sublevels'."
2013 :group 'org-tags
2014 :type '(choice
2015 (const :tag "Not" nil)
2016 (const :tag "Always" t)
2017 (repeat :tag "Specific tags" (string :tag "Tag"))
2018 (regexp :tag "Tags matched by regexp")))
2020 (defcustom org-tags-exclude-from-inheritance nil
2021 "List of tags that should never be inherited.
2022 This is a way to exclude a few tags from inheritance. For way to do
2023 the opposite, to actively allow inheritance for selected tags,
2024 see the variable `org-use-tag-inheritance'."
2025 :group 'org-tags
2026 :type '(repeat (string :tag "Tag")))
2028 (defun org-tag-inherit-p (tag)
2029 "Check if TAG is one that should be inherited."
2030 (cond
2031 ((member tag org-tags-exclude-from-inheritance) nil)
2032 ((eq org-use-tag-inheritance t) t)
2033 ((not org-use-tag-inheritance) nil)
2034 ((stringp org-use-tag-inheritance)
2035 (string-match org-use-tag-inheritance tag))
2036 ((listp org-use-tag-inheritance)
2037 (member tag org-use-tag-inheritance))
2038 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2040 (defcustom org-tags-match-list-sublevels t
2041 "Non-nil means list also sublevels of headlines matching tag search.
2042 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2043 the sublevels of a headline matching a tag search often also match
2044 the same search. Listing all of them can create very long lists.
2045 Setting this variable to nil causes subtrees of a match to be skipped.
2046 This option is off by default, because inheritance in on. If you turn
2047 inheritance off, you very likely want to turn this option on.
2049 As a special case, if the tag search is restricted to TODO items, the
2050 value of this variable is ignored and sublevels are always checked, to
2051 make sure all corresponding TODO items find their way into the list.
2053 This variable is semi-obsolete and probably should always be true. It
2054 is better to limit inheritance to certain tags using the variables
2055 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2056 :group 'org-tags
2057 :type 'boolean)
2059 (defvar org-tags-history nil
2060 "History of minibuffer reads for tags.")
2061 (defvar org-last-tags-completion-table nil
2062 "The last used completion table for tags.")
2063 (defvar org-after-tags-change-hook nil
2064 "Hook that is run after the tags in a line have changed.")
2066 (defgroup org-properties nil
2067 "Options concerning properties in Org-mode."
2068 :tag "Org Properties"
2069 :group 'org)
2071 (defcustom org-property-format "%-10s %s"
2072 "How property key/value pairs should be formatted by `indent-line'.
2073 When `indent-line' hits a property definition, it will format the line
2074 according to this format, mainly to make sure that the values are
2075 lined-up with respect to each other."
2076 :group 'org-properties
2077 :type 'string)
2079 (defcustom org-use-property-inheritance nil
2080 "Non-nil means, properties apply also for sublevels.
2082 This setting is chiefly used during property searches. Turning it on can
2083 cause significant overhead when doing a search, which is why it is not
2084 on by default.
2086 When nil, only the properties directly given in the current entry count.
2087 When t, every property is inherited. The value may also be a list of
2088 properties that should have inheritance, or a regular expression matching
2089 properties that should be inherited.
2091 However, note that some special properties use inheritance under special
2092 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2093 and the properties ending in \"_ALL\" when they are used as descriptor
2094 for valid values of a property.
2096 Note for programmers:
2097 When querying an entry with `org-entry-get', you can control if inheritance
2098 should be used. By default, `org-entry-get' looks only at the local
2099 properties. You can request inheritance by setting the inherit argument
2100 to t (to force inheritance) or to `selective' (to respect the setting
2101 in this variable)."
2102 :group 'org-properties
2103 :type '(choice
2104 (const :tag "Not" nil)
2105 (const :tag "Always" t)
2106 (repeat :tag "Specific properties" (string :tag "Property"))
2107 (regexp :tag "Properties matched by regexp")))
2109 (defun org-property-inherit-p (property)
2110 "Check if PROPERTY is one that should be inherited."
2111 (cond
2112 ((eq org-use-property-inheritance t) t)
2113 ((not org-use-property-inheritance) nil)
2114 ((stringp org-use-property-inheritance)
2115 (string-match org-use-property-inheritance property))
2116 ((listp org-use-property-inheritance)
2117 (member property org-use-property-inheritance))
2118 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2120 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2121 "The default column format, if no other format has been defined.
2122 This variable can be set on the per-file basis by inserting a line
2124 #+COLUMNS: %25ITEM ....."
2125 :group 'org-properties
2126 :type 'string)
2128 (defcustom org-columns-ellipses ".."
2129 "The ellipses to be used when a field in column view is truncated.
2130 When this is the empty string, as many characters as possible are shown,
2131 but then there will be no visual indication that the field has been truncated.
2132 When this is a string of length N, the last N characters of a truncated
2133 field are replaced by this string. If the column is narrower than the
2134 ellipses string, only part of the ellipses string will be shown."
2135 :group 'org-properties
2136 :type 'string)
2138 (defcustom org-columns-modify-value-for-display-function nil
2139 "Function that modifies values for display in column view.
2140 For example, it can be used to cut out a certain part from a time stamp.
2141 The function must take 2 arguments:
2143 column-title The title of the column (*not* the property name)
2144 value The value that should be modified.
2146 The function should return the value that should be displayed,
2147 or nil if the normal value should be used."
2148 :group 'org-properties
2149 :type 'function)
2151 (defcustom org-effort-property "Effort"
2152 "The property that is being used to keep track of effort estimates.
2153 Effort estimates given in this property need to have the format H:MM."
2154 :group 'org-properties
2155 :group 'org-progress
2156 :type '(string :tag "Property"))
2158 (defconst org-global-properties-fixed
2159 '(("VISIBILITY_ALL" . "folded children content all"))
2160 "List of property/value pairs that can be inherited by any entry.
2161 These are fixed values, for the preset properties.")
2164 (defcustom org-global-properties nil
2165 "List of property/value pairs that can be inherited by any entry.
2166 You can set buffer-local values for the same purpose in the variable
2167 `org-file-properties' this by adding lines like
2169 #+PROPERTY: NAME VALUE"
2170 :group 'org-properties
2171 :type '(repeat
2172 (cons (string :tag "Property")
2173 (string :tag "Value"))))
2175 (defvar org-file-properties nil
2176 "List of property/value pairs that can be inherited by any entry.
2177 Valid for the current buffer.
2178 This variable is populated from #+PROPERTY lines.")
2179 (make-variable-buffer-local 'org-file-properties)
2181 (defgroup org-agenda nil
2182 "Options concerning agenda views in Org-mode."
2183 :tag "Org Agenda"
2184 :group 'org)
2186 (defvar org-category nil
2187 "Variable used by org files to set a category for agenda display.
2188 Such files should use a file variable to set it, for example
2190 # -*- mode: org; org-category: \"ELisp\"
2192 or contain a special line
2194 #+CATEGORY: ELisp
2196 If the file does not specify a category, then file's base name
2197 is used instead.")
2198 (make-variable-buffer-local 'org-category)
2199 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2201 (defcustom org-agenda-files nil
2202 "The files to be used for agenda display.
2203 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2204 \\[org-remove-file]. You can also use customize to edit the list.
2206 If an entry is a directory, all files in that directory that are matched by
2207 `org-agenda-file-regexp' will be part of the file list.
2209 If the value of the variable is not a list but a single file name, then
2210 the list of agenda files is actually stored and maintained in that file, one
2211 agenda file per line."
2212 :group 'org-agenda
2213 :type '(choice
2214 (repeat :tag "List of files and directories" file)
2215 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2217 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2218 "Regular expression to match files for `org-agenda-files'.
2219 If any element in the list in that variable contains a directory instead
2220 of a normal file, all files in that directory that are matched by this
2221 regular expression will be included."
2222 :group 'org-agenda
2223 :type 'regexp)
2225 (defcustom org-agenda-text-search-extra-files nil
2226 "List of extra files to be searched by text search commands.
2227 These files will be search in addition to the agenda files by the
2228 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2229 Note that these files will only be searched for text search commands,
2230 not for the other agenda views like todo lists, tag searches or the weekly
2231 agenda. This variable is intended to list notes and possibly archive files
2232 that should also be searched by these two commands.
2233 In fact, if the first element in the list is the symbol `agenda-archives',
2234 than all archive files of all agenda files will be added to the search
2235 scope."
2236 :group 'org-agenda
2237 :type '(set :greedy t
2238 (const :tag "Agenda Archives" agenda-archives)
2239 (repeat :inline t (file))))
2241 (if (fboundp 'defvaralias)
2242 (defvaralias 'org-agenda-multi-occur-extra-files
2243 'org-agenda-text-search-extra-files))
2245 (defcustom org-agenda-skip-unavailable-files nil
2246 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2247 A nil value means to remove them, after a query, from the list."
2248 :group 'org-agenda
2249 :type 'boolean)
2251 (defcustom org-calendar-to-agenda-key [?c]
2252 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2253 The command `org-calendar-goto-agenda' will be bound to this key. The
2254 default is the character `c' because then `c' can be used to switch back and
2255 forth between agenda and calendar."
2256 :group 'org-agenda
2257 :type 'sexp)
2259 (defcustom org-calendar-agenda-action-key [?k]
2260 "The key to be installed in `calendar-mode-map' for agenda-action.
2261 The command `org-agenda-action' will be bound to this key. The
2262 default is the character `k' because we use the same key in the agenda."
2263 :group 'org-agenda
2264 :type 'sexp)
2266 (eval-after-load "calendar"
2267 '(progn
2268 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2269 'org-calendar-goto-agenda)
2270 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2271 'org-agenda-action)))
2273 (defgroup org-latex nil
2274 "Options for embedding LaTeX code into Org-mode."
2275 :tag "Org LaTeX"
2276 :group 'org)
2278 (defcustom org-format-latex-options
2279 '(:foreground default :background default :scale 1.0
2280 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2281 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2282 "Options for creating images from LaTeX fragments.
2283 This is a property list with the following properties:
2284 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2285 `default' means use the foreground of the default face.
2286 :background the background color, or \"Transparent\".
2287 `default' means use the background of the default face.
2288 :scale a scaling factor for the size of the images.
2289 :html-foreground, :html-background, :html-scale
2290 the same numbers for HTML export.
2291 :matchers a list indicating which matchers should be used to
2292 find LaTeX fragments. Valid members of this list are:
2293 \"begin\" find environments
2294 \"$1\" find single characters surrounded by $.$
2295 \"$\" find math expressions surrounded by $...$
2296 \"$$\" find math expressions surrounded by $$....$$
2297 \"\\(\" find math expressions surrounded by \\(...\\)
2298 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2299 :group 'org-latex
2300 :type 'plist)
2302 (defcustom org-format-latex-header "\\documentclass{article}
2303 \\usepackage{fullpage} % do not remove
2304 \\usepackage{amssymb}
2305 \\usepackage[usenames]{color}
2306 \\usepackage{amsmath}
2307 \\usepackage{latexsym}
2308 \\usepackage[mathscr]{eucal}
2309 \\pagestyle{empty} % do not remove"
2310 "The document header used for processing LaTeX fragments."
2311 :group 'org-latex
2312 :type 'string)
2315 (defgroup org-font-lock nil
2316 "Font-lock settings for highlighting in Org-mode."
2317 :tag "Org Font Lock"
2318 :group 'org)
2320 (defcustom org-level-color-stars-only nil
2321 "Non-nil means fontify only the stars in each headline.
2322 When nil, the entire headline is fontified.
2323 Changing it requires restart of `font-lock-mode' to become effective
2324 also in regions already fontified."
2325 :group 'org-font-lock
2326 :type 'boolean)
2328 (defcustom org-hide-leading-stars nil
2329 "Non-nil means, hide the first N-1 stars in a headline.
2330 This works by using the face `org-hide' for these stars. This
2331 face is white for a light background, and black for a dark
2332 background. You may have to customize the face `org-hide' to
2333 make this work.
2334 Changing it requires restart of `font-lock-mode' to become effective
2335 also in regions already fontified.
2336 You may also set this on a per-file basis by adding one of the following
2337 lines to the buffer:
2339 #+STARTUP: hidestars
2340 #+STARTUP: showstars"
2341 :group 'org-font-lock
2342 :type 'boolean)
2344 (defcustom org-fontify-done-headline nil
2345 "Non-nil means, change the face of a headline if it is marked DONE.
2346 Normally, only the TODO/DONE keyword indicates the state of a headline.
2347 When this is non-nil, the headline after the keyword is set to the
2348 `org-headline-done' as an additional indication."
2349 :group 'org-font-lock
2350 :type 'boolean)
2352 (defcustom org-fontify-emphasized-text t
2353 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2354 Changing this variable requires a restart of Emacs to take effect."
2355 :group 'org-font-lock
2356 :type 'boolean)
2358 (defcustom org-highlight-latex-fragments-and-specials nil
2359 "Non-nil means, fontify what is treated specially by the exporters."
2360 :group 'org-font-lock
2361 :type 'boolean)
2363 (defcustom org-hide-emphasis-markers nil
2364 "Non-nil mean font-lock should hide the emphasis marker characters."
2365 :group 'org-font-lock
2366 :type 'boolean)
2368 (defvar org-emph-re nil
2369 "Regular expression for matching emphasis.")
2370 (defvar org-verbatim-re nil
2371 "Regular expression for matching verbatim text.")
2372 (defvar org-emphasis-regexp-components) ; defined just below
2373 (defvar org-emphasis-alist) ; defined just below
2374 (defun org-set-emph-re (var val)
2375 "Set variable and compute the emphasis regular expression."
2376 (set var val)
2377 (when (and (boundp 'org-emphasis-alist)
2378 (boundp 'org-emphasis-regexp-components)
2379 org-emphasis-alist org-emphasis-regexp-components)
2380 (let* ((e org-emphasis-regexp-components)
2381 (pre (car e))
2382 (post (nth 1 e))
2383 (border (nth 2 e))
2384 (body (nth 3 e))
2385 (nl (nth 4 e))
2386 (body1 (concat body "*?"))
2387 (markers (mapconcat 'car org-emphasis-alist ""))
2388 (vmarkers (mapconcat
2389 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2390 org-emphasis-alist "")))
2391 ;; make sure special characters appear at the right position in the class
2392 (if (string-match "\\^" markers)
2393 (setq markers (concat (replace-match "" t t markers) "^")))
2394 (if (string-match "-" markers)
2395 (setq markers (concat (replace-match "" t t markers) "-")))
2396 (if (string-match "\\^" vmarkers)
2397 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2398 (if (string-match "-" vmarkers)
2399 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2400 (if (> nl 0)
2401 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2402 (int-to-string nl) "\\}")))
2403 ;; Make the regexp
2404 (setq org-emph-re
2405 (concat "\\([" pre "]\\|^\\)"
2406 "\\("
2407 "\\([" markers "]\\)"
2408 "\\("
2409 "[^" border "]\\|"
2410 "[^" border "]"
2411 body1
2412 "[^" border "]"
2413 "\\)"
2414 "\\3\\)"
2415 "\\([" post "]\\|$\\)"))
2416 (setq org-verbatim-re
2417 (concat "\\([" pre "]\\|^\\)"
2418 "\\("
2419 "\\([" vmarkers "]\\)"
2420 "\\("
2421 "[^" border "]\\|"
2422 "[^" border "]"
2423 body1
2424 "[^" border "]"
2425 "\\)"
2426 "\\3\\)"
2427 "\\([" post "]\\|$\\)")))))
2429 (defcustom org-emphasis-regexp-components
2430 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2431 "Components used to build the regular expression for emphasis.
2432 This is a list with 6 entries. Terminology: In an emphasis string
2433 like \" *strong word* \", we call the initial space PREMATCH, the final
2434 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2435 and \"trong wor\" is the body. The different components in this variable
2436 specify what is allowed/forbidden in each part:
2438 pre Chars allowed as prematch. Beginning of line will be allowed too.
2439 post Chars allowed as postmatch. End of line will be allowed too.
2440 border The chars *forbidden* as border characters.
2441 body-regexp A regexp like \".\" to match a body character. Don't use
2442 non-shy groups here, and don't allow newline here.
2443 newline The maximum number of newlines allowed in an emphasis exp.
2445 Use customize to modify this, or restart Emacs after changing it."
2446 :group 'org-font-lock
2447 :set 'org-set-emph-re
2448 :type '(list
2449 (sexp :tag "Allowed chars in pre ")
2450 (sexp :tag "Allowed chars in post ")
2451 (sexp :tag "Forbidden chars in border ")
2452 (sexp :tag "Regexp for body ")
2453 (integer :tag "number of newlines allowed")
2454 (option (boolean :tag "Please ignore this button"))))
2456 (defcustom org-emphasis-alist
2457 `(("*" bold "<b>" "</b>")
2458 ("/" italic "<i>" "</i>")
2459 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2460 ("=" org-code "<code>" "</code>" verbatim)
2461 ("~" org-verbatim "<code>" "</code>" verbatim)
2462 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2463 "<del>" "</del>")
2465 "Special syntax for emphasized text.
2466 Text starting and ending with a special character will be emphasized, for
2467 example *bold*, _underlined_ and /italic/. This variable sets the marker
2468 characters, the face to be used by font-lock for highlighting in Org-mode
2469 Emacs buffers, and the HTML tags to be used for this.
2470 Use customize to modify this, or restart Emacs after changing it."
2471 :group 'org-font-lock
2472 :set 'org-set-emph-re
2473 :type '(repeat
2474 (list
2475 (string :tag "Marker character")
2476 (choice
2477 (face :tag "Font-lock-face")
2478 (plist :tag "Face property list"))
2479 (string :tag "HTML start tag")
2480 (string :tag "HTML end tag")
2481 (option (const verbatim)))))
2483 ;;; Miscellaneous options
2485 (defgroup org-completion nil
2486 "Completion in Org-mode."
2487 :tag "Org Completion"
2488 :group 'org)
2490 (defcustom org-completion-use-ido nil
2491 "Non-nil means, use ido completion wherever possible.
2492 Note that `ido-mode' must be active for this variable to be relevant.
2493 If you decide to turn this variable on, you might well want to turn off
2494 `org-outline-path-complete-in-steps'."
2495 :group 'org-completion
2496 :type 'boolean)
2498 (defcustom org-completion-fallback-command 'hippie-expand
2499 "The expansion command called by \\[org-complete] in normal context.
2500 Normal means, no org-mode-specific context."
2501 :group 'org-completion
2502 :type 'function)
2504 ;;; Functions and variables from ther packages
2505 ;; Declared here to avoid compiler warnings
2507 ;; XEmacs only
2508 (defvar outline-mode-menu-heading)
2509 (defvar outline-mode-menu-show)
2510 (defvar outline-mode-menu-hide)
2511 (defvar zmacs-regions) ; XEmacs regions
2513 ;; Emacs only
2514 (defvar mark-active)
2516 ;; Various packages
2517 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2518 (declare-function calendar-forward-day "cal-move" (arg))
2519 (declare-function calendar-goto-date "cal-move" (date))
2520 (declare-function calendar-goto-today "cal-move" ())
2521 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2522 (defvar calc-embedded-close-formula)
2523 (defvar calc-embedded-open-formula)
2524 (declare-function cdlatex-tab "ext:cdlatex" ())
2525 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2526 (defvar font-lock-unfontify-region-function)
2527 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2528 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2529 (defvar iswitchb-temp-buflist)
2530 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2531 (defvar org-agenda-tags-todo-honor-ignore-options)
2532 (declare-function org-agenda-skip "org-agenda" ())
2533 (declare-function org-format-agenda-item "org-agenda"
2534 (extra txt &optional category tags dotime noprefix remove-re))
2535 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2536 (declare-function org-agenda-change-all-lines "org-agenda"
2537 (newhead hdmarker &optional fixface just-this))
2538 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2539 (declare-function org-agenda-maybe-redo "org-agenda" ())
2540 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2541 (beg end))
2542 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2543 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2544 "org-agenda" (&optional end))
2546 (declare-function parse-time-string "parse-time" (string))
2547 (declare-function remember "remember" (&optional initial))
2548 (declare-function remember-buffer-desc "remember" ())
2549 (declare-function remember-finalize "remember" ())
2550 (defvar remember-save-after-remembering)
2551 (defvar remember-data-file)
2552 (defvar remember-register)
2553 (defvar remember-buffer)
2554 (defvar remember-handler-functions)
2555 (defvar remember-annotation-functions)
2556 (defvar texmathp-why)
2557 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2558 (declare-function table--at-cell-p "table" (position &optional object at-column))
2560 (defvar w3m-current-url)
2561 (defvar w3m-current-title)
2563 (defvar org-latex-regexps)
2565 ;;; Autoload and prepare some org modules
2567 ;; Some table stuff that needs to be defined here, because it is used
2568 ;; by the functions setting up org-mode or checking for table context.
2570 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2571 "Detects an org-type or table-type table.")
2572 (defconst org-table-line-regexp "^[ \t]*|"
2573 "Detects an org-type table line.")
2574 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2575 "Detects an org-type table line.")
2576 (defconst org-table-hline-regexp "^[ \t]*|-"
2577 "Detects an org-type table hline.")
2578 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2579 "Detects a table-type table hline.")
2580 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2581 "Searching from within a table (any type) this finds the first line
2582 outside the table.")
2584 ;; Autoload the functions in org-table.el that are needed by functions here.
2586 (eval-and-compile
2587 (org-autoload "org-table"
2588 '(org-table-align org-table-begin org-table-blank-field
2589 org-table-convert org-table-convert-region org-table-copy-down
2590 org-table-copy-region org-table-create
2591 org-table-create-or-convert-from-region
2592 org-table-create-with-table.el org-table-current-dline
2593 org-table-cut-region org-table-delete-column org-table-edit-field
2594 org-table-edit-formulas org-table-end org-table-eval-formula
2595 org-table-export org-table-field-info
2596 org-table-get-stored-formulas org-table-goto-column
2597 org-table-hline-and-move org-table-import org-table-insert-column
2598 org-table-insert-hline org-table-insert-row org-table-iterate
2599 org-table-justify-field-maybe org-table-kill-row
2600 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2601 org-table-move-column org-table-move-column-left
2602 org-table-move-column-right org-table-move-row
2603 org-table-move-row-down org-table-move-row-up
2604 org-table-next-field org-table-next-row org-table-paste-rectangle
2605 org-table-previous-field org-table-recalculate
2606 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2607 org-table-toggle-coordinate-overlays
2608 org-table-toggle-formula-debugger org-table-wrap-region
2609 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2611 (defun org-at-table-p (&optional table-type)
2612 "Return t if the cursor is inside an org-type table.
2613 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2614 (if org-enable-table-editor
2615 (save-excursion
2616 (beginning-of-line 1)
2617 (looking-at (if table-type org-table-any-line-regexp
2618 org-table-line-regexp)))
2619 nil))
2620 (defsubst org-table-p () (org-at-table-p))
2622 (defun org-at-table.el-p ()
2623 "Return t if and only if we are at a table.el table."
2624 (and (org-at-table-p 'any)
2625 (save-excursion
2626 (goto-char (org-table-begin 'any))
2627 (looking-at org-table1-hline-regexp))))
2628 (defun org-table-recognize-table.el ()
2629 "If there is a table.el table nearby, recognize it and move into it."
2630 (if org-table-tab-recognizes-table.el
2631 (if (org-at-table.el-p)
2632 (progn
2633 (beginning-of-line 1)
2634 (if (looking-at org-table-dataline-regexp)
2636 (if (looking-at org-table1-hline-regexp)
2637 (progn
2638 (beginning-of-line 2)
2639 (if (looking-at org-table-any-border-regexp)
2640 (beginning-of-line -1)))))
2641 (if (re-search-forward "|" (org-table-end t) t)
2642 (progn
2643 (require 'table)
2644 (if (table--at-cell-p (point))
2646 (message "recognizing table.el table...")
2647 (table-recognize-table)
2648 (message "recognizing table.el table...done")))
2649 (error "This should not happen..."))
2651 nil)
2652 nil))
2654 (defun org-at-table-hline-p ()
2655 "Return t if the cursor is inside a hline in a table."
2656 (if org-enable-table-editor
2657 (save-excursion
2658 (beginning-of-line 1)
2659 (looking-at org-table-hline-regexp))
2660 nil))
2662 (defvar org-table-clean-did-remove-column nil)
2664 (defun org-table-map-tables (function)
2665 "Apply FUNCTION to the start of all tables in the buffer."
2666 (save-excursion
2667 (save-restriction
2668 (widen)
2669 (goto-char (point-min))
2670 (while (re-search-forward org-table-any-line-regexp nil t)
2671 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2672 (beginning-of-line 1)
2673 (if (looking-at org-table-line-regexp)
2674 (save-excursion (funcall function)))
2675 (re-search-forward org-table-any-border-regexp nil 1))))
2676 (message "Mapping tables: done"))
2678 ;; Declare and autoload functions from org-exp.el
2680 (declare-function org-default-export-plist "org-exp")
2681 (declare-function org-infile-export-plist "org-exp")
2682 (declare-function org-get-current-options "org-exp")
2683 (eval-and-compile
2684 (org-autoload "org-exp"
2685 '(org-export org-export-as-ascii org-export-visible
2686 org-insert-export-options-template org-export-as-html-and-open
2687 org-export-as-html-batch org-export-as-html-to-buffer
2688 org-replace-region-by-html org-export-region-as-html
2689 org-export-as-html org-export-icalendar-this-file
2690 org-export-icalendar-all-agenda-files
2691 org-table-clean-before-export
2692 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2694 ;; Declare and autoload functions from org-agenda.el
2696 (eval-and-compile
2697 (org-autoload "org-agenda"
2698 '(org-agenda org-agenda-list org-search-view
2699 org-todo-list org-tags-view org-agenda-list-stuck-projects
2700 org-diary org-agenda-to-appt
2701 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2703 ;; Autoload org-remember
2705 (eval-and-compile
2706 (org-autoload "org-remember"
2707 '(org-remember-insinuate org-remember-annotation
2708 org-remember-apply-template org-remember org-remember-handler)))
2710 ;; Autoload org-clock.el
2713 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2714 (beg end))
2715 (declare-function org-clock-update-mode-line "org-clock" ())
2716 (defvar org-clock-start-time)
2717 (defvar org-clock-marker (make-marker)
2718 "Marker recording the last clock-in.")
2720 (eval-and-compile
2721 (org-autoload
2722 "org-clock"
2723 '(org-clock-in org-clock-out org-clock-cancel
2724 org-clock-goto org-clock-sum org-clock-display
2725 org-clock-remove-overlays org-clock-report
2726 org-clocktable-shift org-dblock-write:clocktable
2727 org-get-clocktable)))
2729 (defun org-clock-update-time-maybe ()
2730 "If this is a CLOCK line, update it and return t.
2731 Otherwise, return nil."
2732 (interactive)
2733 (save-excursion
2734 (beginning-of-line 1)
2735 (skip-chars-forward " \t")
2736 (when (looking-at org-clock-string)
2737 (let ((re (concat "[ \t]*" org-clock-string
2738 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2739 "\\([ \t]*=>.*\\)?\\)?"))
2740 ts te h m s neg)
2741 (cond
2742 ((not (looking-at re))
2743 nil)
2744 ((not (match-end 2))
2745 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2746 (> org-clock-marker (point))
2747 (<= org-clock-marker (point-at-eol)))
2748 ;; The clock is running here
2749 (setq org-clock-start-time
2750 (apply 'encode-time
2751 (org-parse-time-string (match-string 1))))
2752 (org-clock-update-mode-line)))
2754 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2755 (end-of-line 1)
2756 (setq ts (match-string 1)
2757 te (match-string 3))
2758 (setq s (- (time-to-seconds
2759 (apply 'encode-time (org-parse-time-string te)))
2760 (time-to-seconds
2761 (apply 'encode-time (org-parse-time-string ts))))
2762 neg (< s 0)
2763 s (abs s)
2764 h (floor (/ s 3600))
2765 s (- s (* 3600 h))
2766 m (floor (/ s 60))
2767 s (- s (* 60 s)))
2768 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2769 t))))))
2771 (defun org-check-running-clock ()
2772 "Check if the current buffer contains the running clock.
2773 If yes, offer to stop it and to save the buffer with the changes."
2774 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2775 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2776 (buffer-name))))
2777 (org-clock-out)
2778 (when (y-or-n-p "Save changed buffer?")
2779 (save-buffer))))
2781 (defun org-clocktable-try-shift (dir n)
2782 "Check if this line starts a clock table, if yes, shift the time block."
2783 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2784 (org-clocktable-shift dir n)))
2786 ;; Autoload org-timer.el
2788 ;(declare-function org-timer "org-timer")
2790 (eval-and-compile
2791 (org-autoload
2792 "org-timer"
2793 '(org-timer-start org-timer org-timer-item
2794 org-timer-change-times-in-region)))
2797 ;; Autoload archiving code
2798 ;; The stuff that is needed for cycling and tags has to be defined here.
2800 (defgroup org-archive nil
2801 "Options concerning archiving in Org-mode."
2802 :tag "Org Archive"
2803 :group 'org-structure)
2805 (defcustom org-archive-location "%s_archive::"
2806 "The location where subtrees should be archived.
2808 The value of this variable is a string, consisting of two parts,
2809 separated by a double-colon. The first part is a filename and
2810 the second part is a headline.
2812 When the filename is omitted, archiving happens in the same file.
2813 %s in the filename will be replaced by the current file
2814 name (without the directory part). Archiving to a different file
2815 is useful to keep archived entries from contributing to the
2816 Org-mode Agenda.
2818 The archived entries will be filed as subtrees of the specified
2819 headline. When the headline is omitted, the subtrees are simply
2820 filed away at the end of the file, as top-level entries. Also in
2821 the heading you can use %s to represent the file name, this can be
2822 useful when using the same archive for a number of different files.
2824 Here are a few examples:
2825 \"%s_archive::\"
2826 If the current file is Projects.org, archive in file
2827 Projects.org_archive, as top-level trees. This is the default.
2829 \"::* Archived Tasks\"
2830 Archive in the current file, under the top-level headline
2831 \"* Archived Tasks\".
2833 \"~/org/archive.org::\"
2834 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2836 \"~/org/archive.org::From %s\"
2837 Archive in file ~/org/archive.org (absolute path), und headlines
2838 \"From FILENAME\" where file name is the current file name.
2840 \"basement::** Finished Tasks\"
2841 Archive in file ./basement (relative path), as level 3 trees
2842 below the level 2 heading \"** Finished Tasks\".
2844 You may set this option on a per-file basis by adding to the buffer a
2845 line like
2847 #+ARCHIVE: basement::** Finished Tasks
2849 You may also define it locally for a subtree by setting an ARCHIVE property
2850 in the entry. If such a property is found in an entry, or anywhere up
2851 the hierarchy, it will be used."
2852 :group 'org-archive
2853 :type 'string)
2855 (defcustom org-archive-tag "ARCHIVE"
2856 "The tag that marks a subtree as archived.
2857 An archived subtree does not open during visibility cycling, and does
2858 not contribute to the agenda listings.
2859 After changing this, font-lock must be restarted in the relevant buffers to
2860 get the proper fontification."
2861 :group 'org-archive
2862 :group 'org-keywords
2863 :type 'string)
2865 (defcustom org-agenda-skip-archived-trees t
2866 "Non-nil means, the agenda will skip any items located in archived trees.
2867 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2868 variable is no longer recommended, you should leave it at the value t.
2869 Instead, use the key `v' to cycle the archives-mode in the agenda."
2870 :group 'org-archive
2871 :group 'org-agenda-skip
2872 :type 'boolean)
2874 (defcustom org-cycle-open-archived-trees nil
2875 "Non-nil means, `org-cycle' will open archived trees.
2876 An archived tree is a tree marked with the tag ARCHIVE.
2877 When nil, archived trees will stay folded. You can still open them with
2878 normal outline commands like `show-all', but not with the cycling commands."
2879 :group 'org-archive
2880 :group 'org-cycle
2881 :type 'boolean)
2883 (defcustom org-sparse-tree-open-archived-trees nil
2884 "Non-nil means sparse tree construction shows matches in archived trees.
2885 When nil, matches in these trees are highlighted, but the trees are kept in
2886 collapsed state."
2887 :group 'org-archive
2888 :group 'org-sparse-trees
2889 :type 'boolean)
2891 (defun org-cycle-hide-archived-subtrees (state)
2892 "Re-hide all archived subtrees after a visibility state change."
2893 (when (and (not org-cycle-open-archived-trees)
2894 (not (memq state '(overview folded))))
2895 (save-excursion
2896 (let* ((globalp (memq state '(contents all)))
2897 (beg (if globalp (point-min) (point)))
2898 (end (if globalp (point-max) (org-end-of-subtree t))))
2899 (org-hide-archived-subtrees beg end)
2900 (goto-char beg)
2901 (if (looking-at (concat ".*:" org-archive-tag ":"))
2902 (message "%s" (substitute-command-keys
2903 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2905 (defun org-force-cycle-archived ()
2906 "Cycle subtree even if it is archived."
2907 (interactive)
2908 (setq this-command 'org-cycle)
2909 (let ((org-cycle-open-archived-trees t))
2910 (call-interactively 'org-cycle)))
2912 (defun org-hide-archived-subtrees (beg end)
2913 "Re-hide all archived subtrees after a visibility state change."
2914 (save-excursion
2915 (let* ((re (concat ":" org-archive-tag ":")))
2916 (goto-char beg)
2917 (while (re-search-forward re end t)
2918 (and (org-on-heading-p) (hide-subtree))
2919 (org-end-of-subtree t)))))
2921 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2923 (eval-and-compile
2924 (org-autoload "org-archive"
2925 '(org-add-archive-files org-archive-subtree
2926 org-archive-to-archive-sibling org-toggle-archive-tag)))
2928 ;; Autoload Column View Code
2930 (declare-function org-columns-number-to-string "org-colview")
2931 (declare-function org-columns-get-format-and-top-level "org-colview")
2932 (declare-function org-columns-compute "org-colview")
2934 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2935 '(org-columns-number-to-string org-columns-get-format-and-top-level
2936 org-columns-compute org-agenda-columns org-columns-remove-overlays
2937 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2939 ;; Autoload ID code
2941 (declare-function org-id-store-link "org-id")
2942 (org-autoload "org-id"
2943 '(org-id-get-create org-id-new org-id-copy org-id-get
2944 org-id-get-with-outline-path-completion
2945 org-id-get-with-outline-drilling
2946 org-id-goto org-id-find org-id-store-link))
2948 ;;; Variables for pre-computed regular expressions, all buffer local
2950 (defvar org-drawer-regexp nil
2951 "Matches first line of a hidden block.")
2952 (make-variable-buffer-local 'org-drawer-regexp)
2953 (defvar org-todo-regexp nil
2954 "Matches any of the TODO state keywords.")
2955 (make-variable-buffer-local 'org-todo-regexp)
2956 (defvar org-not-done-regexp nil
2957 "Matches any of the TODO state keywords except the last one.")
2958 (make-variable-buffer-local 'org-not-done-regexp)
2959 (defvar org-todo-line-regexp nil
2960 "Matches a headline and puts TODO state into group 2 if present.")
2961 (make-variable-buffer-local 'org-todo-line-regexp)
2962 (defvar org-complex-heading-regexp nil
2963 "Matches a headline and puts everything into groups:
2964 group 1: the stars
2965 group 2: The todo keyword, maybe
2966 group 3: Priority cookie
2967 group 4: True headline
2968 group 5: Tags")
2969 (make-variable-buffer-local 'org-complex-heading-regexp)
2970 (defvar org-todo-line-tags-regexp nil
2971 "Matches a headline and puts TODO state into group 2 if present.
2972 Also put tags into group 4 if tags are present.")
2973 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2974 (defvar org-nl-done-regexp nil
2975 "Matches newline followed by a headline with the DONE keyword.")
2976 (make-variable-buffer-local 'org-nl-done-regexp)
2977 (defvar org-looking-at-done-regexp nil
2978 "Matches the DONE keyword a point.")
2979 (make-variable-buffer-local 'org-looking-at-done-regexp)
2980 (defvar org-ds-keyword-length 12
2981 "Maximum length of the Deadline and SCHEDULED keywords.")
2982 (make-variable-buffer-local 'org-ds-keyword-length)
2983 (defvar org-deadline-regexp nil
2984 "Matches the DEADLINE keyword.")
2985 (make-variable-buffer-local 'org-deadline-regexp)
2986 (defvar org-deadline-time-regexp nil
2987 "Matches the DEADLINE keyword together with a time stamp.")
2988 (make-variable-buffer-local 'org-deadline-time-regexp)
2989 (defvar org-deadline-line-regexp nil
2990 "Matches the DEADLINE keyword and the rest of the line.")
2991 (make-variable-buffer-local 'org-deadline-line-regexp)
2992 (defvar org-scheduled-regexp nil
2993 "Matches the SCHEDULED keyword.")
2994 (make-variable-buffer-local 'org-scheduled-regexp)
2995 (defvar org-scheduled-time-regexp nil
2996 "Matches the SCHEDULED keyword together with a time stamp.")
2997 (make-variable-buffer-local 'org-scheduled-time-regexp)
2998 (defvar org-closed-time-regexp nil
2999 "Matches the CLOSED keyword together with a time stamp.")
3000 (make-variable-buffer-local 'org-closed-time-regexp)
3002 (defvar org-keyword-time-regexp nil
3003 "Matches any of the 4 keywords, together with the time stamp.")
3004 (make-variable-buffer-local 'org-keyword-time-regexp)
3005 (defvar org-keyword-time-not-clock-regexp nil
3006 "Matches any of the 3 keywords, together with the time stamp.")
3007 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3008 (defvar org-maybe-keyword-time-regexp nil
3009 "Matches a timestamp, possibly preceeded by a keyword.")
3010 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3011 (defvar org-planning-or-clock-line-re nil
3012 "Matches a line with planning or clock info.")
3013 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3015 (defconst org-plain-time-of-day-regexp
3016 (concat
3017 "\\(\\<[012]?[0-9]"
3018 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3019 "\\(--?"
3020 "\\(\\<[012]?[0-9]"
3021 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3022 "\\)?")
3023 "Regular expression to match a plain time or time range.
3024 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3025 groups carry important information:
3026 0 the full match
3027 1 the first time, range or not
3028 8 the second time, if it is a range.")
3030 (defconst org-plain-time-extension-regexp
3031 (concat
3032 "\\(\\<[012]?[0-9]"
3033 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3034 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3035 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3036 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3037 groups carry important information:
3038 0 the full match
3039 7 hours of duration
3040 9 minutes of duration")
3042 (defconst org-stamp-time-of-day-regexp
3043 (concat
3044 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3045 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3046 "\\(--?"
3047 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3048 "Regular expression to match a timestamp time or time range.
3049 After a match, the following groups carry important information:
3050 0 the full match
3051 1 date plus weekday, for backreferencing to make sure both times on same day
3052 2 the first time, range or not
3053 4 the second time, if it is a range.")
3055 (defconst org-startup-options
3056 '(("fold" org-startup-folded t)
3057 ("overview" org-startup-folded t)
3058 ("nofold" org-startup-folded nil)
3059 ("showall" org-startup-folded nil)
3060 ("content" org-startup-folded content)
3061 ("hidestars" org-hide-leading-stars t)
3062 ("showstars" org-hide-leading-stars nil)
3063 ("odd" org-odd-levels-only t)
3064 ("oddeven" org-odd-levels-only nil)
3065 ("align" org-startup-align-all-tables t)
3066 ("noalign" org-startup-align-all-tables nil)
3067 ("customtime" org-display-custom-times t)
3068 ("logdone" org-log-done time)
3069 ("lognotedone" org-log-done note)
3070 ("nologdone" org-log-done nil)
3071 ("lognoteclock-out" org-log-note-clock-out t)
3072 ("nolognoteclock-out" org-log-note-clock-out nil)
3073 ("logrepeat" org-log-repeat state)
3074 ("lognoterepeat" org-log-repeat note)
3075 ("nologrepeat" org-log-repeat nil)
3076 ("fninline" org-footnote-define-inline t)
3077 ("nofninline" org-footnote-define-inline nil)
3078 ("fnlocal" org-footnote-section nil)
3079 ("fnauto" org-footnote-auto-label t)
3080 ("fnprompt" org-footnote-auto-label nil)
3081 ("fnconfirm" org-footnote-auto-label confirm)
3082 ("fnplain" org-footnote-auto-label plain)
3083 ("constcgs" constants-unit-system cgs)
3084 ("constSI" constants-unit-system SI))
3085 "Variable associated with STARTUP options for org-mode.
3086 Each element is a list of three items: The startup options as written
3087 in the #+STARTUP line, the corresponding variable, and the value to
3088 set this variable to if the option is found. An optional forth element PUSH
3089 means to push this value onto the list in the variable.")
3091 (defun org-set-regexps-and-options ()
3092 "Precompute regular expressions for current buffer."
3093 (when (org-mode-p)
3094 (org-set-local 'org-todo-kwd-alist nil)
3095 (org-set-local 'org-todo-key-alist nil)
3096 (org-set-local 'org-todo-key-trigger nil)
3097 (org-set-local 'org-todo-keywords-1 nil)
3098 (org-set-local 'org-done-keywords nil)
3099 (org-set-local 'org-todo-heads nil)
3100 (org-set-local 'org-todo-sets nil)
3101 (org-set-local 'org-todo-log-states nil)
3102 (org-set-local 'org-file-properties nil)
3103 (org-set-local 'org-file-tags nil)
3104 (let ((re (org-make-options-regexp
3105 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3106 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3107 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3108 (splitre "[ \t]+")
3109 kwds kws0 kwsa key log value cat arch tags const links hw dws
3110 tail sep kws1 prio props ftags drawers
3111 ext-setup-or-nil setup-contents (start 0))
3112 (save-excursion
3113 (save-restriction
3114 (widen)
3115 (goto-char (point-min))
3116 (while (or (and ext-setup-or-nil
3117 (string-match re ext-setup-or-nil start)
3118 (setq start (match-end 0)))
3119 (and (setq ext-setup-or-nil nil start 0)
3120 (re-search-forward re nil t)))
3121 (setq key (upcase (match-string 1 ext-setup-or-nil))
3122 value (org-match-string-no-properties 2 ext-setup-or-nil))
3123 (cond
3124 ((equal key "CATEGORY")
3125 (if (string-match "[ \t]+$" value)
3126 (setq value (replace-match "" t t value)))
3127 (setq cat value))
3128 ((member key '("SEQ_TODO" "TODO"))
3129 (push (cons 'sequence (org-split-string value splitre)) kwds))
3130 ((equal key "TYP_TODO")
3131 (push (cons 'type (org-split-string value splitre)) kwds))
3132 ((equal key "TAGS")
3133 (setq tags (append tags (org-split-string value splitre))))
3134 ((equal key "COLUMNS")
3135 (org-set-local 'org-columns-default-format value))
3136 ((equal key "LINK")
3137 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3138 (push (cons (match-string 1 value)
3139 (org-trim (match-string 2 value)))
3140 links)))
3141 ((equal key "PRIORITIES")
3142 (setq prio (org-split-string value " +")))
3143 ((equal key "PROPERTY")
3144 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3145 (push (cons (match-string 1 value) (match-string 2 value))
3146 props)))
3147 ((equal key "FILETAGS")
3148 (when (string-match "\\S-" value)
3149 (setq ftags
3150 (append
3151 ftags
3152 (apply 'append
3153 (mapcar (lambda (x) (org-split-string x ":"))
3154 (org-split-string value)))))))
3155 ((equal key "DRAWERS")
3156 (setq drawers (org-split-string value splitre)))
3157 ((equal key "CONSTANTS")
3158 (setq const (append const (org-split-string value splitre))))
3159 ((equal key "STARTUP")
3160 (let ((opts (org-split-string value splitre))
3161 l var val)
3162 (while (setq l (pop opts))
3163 (when (setq l (assoc l org-startup-options))
3164 (setq var (nth 1 l) val (nth 2 l))
3165 (if (not (nth 3 l))
3166 (set (make-local-variable var) val)
3167 (if (not (listp (symbol-value var)))
3168 (set (make-local-variable var) nil))
3169 (set (make-local-variable var) (symbol-value var))
3170 (add-to-list var val))))))
3171 ((equal key "ARCHIVE")
3172 (string-match " *$" value)
3173 (setq arch (replace-match "" t t value))
3174 (remove-text-properties 0 (length arch)
3175 '(face t fontified t) arch))
3176 ((equal key "SETUPFILE")
3177 (setq setup-contents (org-file-contents
3178 (expand-file-name
3179 (org-remove-double-quotes value))
3180 'noerror))
3181 (if (not ext-setup-or-nil)
3182 (setq ext-setup-or-nil setup-contents start 0)
3183 (setq ext-setup-or-nil
3184 (concat (substring ext-setup-or-nil 0 start)
3185 "\n" setup-contents "\n"
3186 (substring ext-setup-or-nil start)))))
3187 ))))
3188 (when cat
3189 (org-set-local 'org-category (intern cat))
3190 (push (cons "CATEGORY" cat) props))
3191 (when prio
3192 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3193 (setq prio (mapcar 'string-to-char prio))
3194 (org-set-local 'org-highest-priority (nth 0 prio))
3195 (org-set-local 'org-lowest-priority (nth 1 prio))
3196 (org-set-local 'org-default-priority (nth 2 prio)))
3197 (and props (org-set-local 'org-file-properties (nreverse props)))
3198 (and ftags (org-set-local 'org-file-tags ftags))
3199 (and drawers (org-set-local 'org-drawers drawers))
3200 (and arch (org-set-local 'org-archive-location arch))
3201 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3202 ;; Process the TODO keywords
3203 (unless kwds
3204 ;; Use the global values as if they had been given locally.
3205 (setq kwds (default-value 'org-todo-keywords))
3206 (if (stringp (car kwds))
3207 (setq kwds (list (cons org-todo-interpretation
3208 (default-value 'org-todo-keywords)))))
3209 (setq kwds (reverse kwds)))
3210 (setq kwds (nreverse kwds))
3211 (let (inter kws kw)
3212 (while (setq kws (pop kwds))
3213 (setq inter (pop kws) sep (member "|" kws)
3214 kws0 (delete "|" (copy-sequence kws))
3215 kwsa nil
3216 kws1 (mapcar
3217 (lambda (x)
3218 ;; 1 2
3219 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3220 (progn
3221 (setq kw (match-string 1 x)
3222 key (and (match-end 2) (match-string 2 x))
3223 log (org-extract-log-state-settings x))
3224 (push (cons kw (and key (string-to-char key))) kwsa)
3225 (and log (push log org-todo-log-states))
3227 (error "Invalid TODO keyword %s" x)))
3228 kws0)
3229 kwsa (if kwsa (append '((:startgroup))
3230 (nreverse kwsa)
3231 '((:endgroup))))
3232 hw (car kws1)
3233 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3234 tail (list inter hw (car dws) (org-last dws)))
3235 (add-to-list 'org-todo-heads hw 'append)
3236 (push kws1 org-todo-sets)
3237 (setq org-done-keywords (append org-done-keywords dws nil))
3238 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3239 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3240 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3241 (setq org-todo-sets (nreverse org-todo-sets)
3242 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3243 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3244 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3245 ;; Process the constants
3246 (when const
3247 (let (e cst)
3248 (while (setq e (pop const))
3249 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3250 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3251 (setq org-table-formula-constants-local cst)))
3253 ;; Process the tags.
3254 (when tags
3255 (let (e tgs)
3256 (while (setq e (pop tags))
3257 (cond
3258 ((equal e "{") (push '(:startgroup) tgs))
3259 ((equal e "}") (push '(:endgroup) tgs))
3260 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3261 (push (cons (match-string 1 e)
3262 (string-to-char (match-string 2 e)))
3263 tgs))
3264 (t (push (list e) tgs))))
3265 (org-set-local 'org-tag-alist nil)
3266 (while (setq e (pop tgs))
3267 (or (and (stringp (car e))
3268 (assoc (car e) org-tag-alist))
3269 (push e org-tag-alist)))))
3271 ;; Compute the regular expressions and other local variables
3272 (if (not org-done-keywords)
3273 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3274 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3275 (length org-scheduled-string)
3276 (length org-clock-string)
3277 (length org-closed-string)))
3278 org-drawer-regexp
3279 (concat "^[ \t]*:\\("
3280 (mapconcat 'regexp-quote org-drawers "\\|")
3281 "\\):[ \t]*$")
3282 org-not-done-keywords
3283 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3284 org-todo-regexp
3285 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3286 "\\|") "\\)\\>")
3287 org-not-done-regexp
3288 (concat "\\<\\("
3289 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3290 "\\)\\>")
3291 org-todo-line-regexp
3292 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3293 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3294 "\\)\\>\\)?[ \t]*\\(.*\\)")
3295 org-complex-heading-regexp
3296 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3297 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3298 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3299 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3300 org-nl-done-regexp
3301 (concat "\n\\*+[ \t]+"
3302 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3303 "\\)" "\\>")
3304 org-todo-line-tags-regexp
3305 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3306 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3307 (org-re
3308 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3309 org-looking-at-done-regexp
3310 (concat "^" "\\(?:"
3311 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3312 "\\>")
3313 org-deadline-regexp (concat "\\<" org-deadline-string)
3314 org-deadline-time-regexp
3315 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3316 org-deadline-line-regexp
3317 (concat "\\<\\(" org-deadline-string "\\).*")
3318 org-scheduled-regexp
3319 (concat "\\<" org-scheduled-string)
3320 org-scheduled-time-regexp
3321 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3322 org-closed-time-regexp
3323 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3324 org-keyword-time-regexp
3325 (concat "\\<\\(" org-scheduled-string
3326 "\\|" org-deadline-string
3327 "\\|" org-closed-string
3328 "\\|" org-clock-string "\\)"
3329 " *[[<]\\([^]>]+\\)[]>]")
3330 org-keyword-time-not-clock-regexp
3331 (concat "\\<\\(" org-scheduled-string
3332 "\\|" org-deadline-string
3333 "\\|" org-closed-string
3334 "\\)"
3335 " *[[<]\\([^]>]+\\)[]>]")
3336 org-maybe-keyword-time-regexp
3337 (concat "\\(\\<\\(" org-scheduled-string
3338 "\\|" org-deadline-string
3339 "\\|" org-closed-string
3340 "\\|" org-clock-string "\\)\\)?"
3341 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3342 org-planning-or-clock-line-re
3343 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3344 "\\|" org-deadline-string
3345 "\\|" org-closed-string "\\|" org-clock-string
3346 "\\)\\>\\)")
3348 (org-compute-latex-and-specials-regexp)
3349 (org-set-font-lock-defaults))))
3351 (defun org-file-contents (file &optional noerror)
3352 "Return the contents of FILE, as a string."
3353 (if (or (not file)
3354 (not (file-readable-p file)))
3355 (if noerror
3356 (progn
3357 (message "Cannot read file %s" file)
3358 (ding) (sit-for 2)
3360 (error "Cannot read file %s" file))
3361 (with-temp-buffer
3362 (insert-file-contents file)
3363 (buffer-string))))
3365 (defun org-extract-log-state-settings (x)
3366 "Extract the log state setting from a TODO keyword string.
3367 This will extract info from a string like \"WAIT(w@/!)\"."
3368 (let (kw key log1 log2)
3369 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3370 (setq kw (match-string 1 x)
3371 key (and (match-end 2) (match-string 2 x))
3372 log1 (and (match-end 3) (match-string 3 x))
3373 log2 (and (match-end 4) (match-string 4 x)))
3374 (and (or log1 log2)
3375 (list kw
3376 (and log1 (if (equal log1 "!") 'time 'note))
3377 (and log2 (if (equal log2 "!") 'time 'note)))))))
3379 (defun org-remove-keyword-keys (list)
3380 "Remove a pair of parenthesis at the end of each string in LIST."
3381 (mapcar (lambda (x)
3382 (if (string-match "(.*)$" x)
3383 (substring x 0 (match-beginning 0))
3385 list))
3387 ;; FIXME: this could be done much better, using second characters etc.
3388 (defun org-assign-fast-keys (alist)
3389 "Assign fast keys to a keyword-key alist.
3390 Respect keys that are already there."
3391 (let (new e k c c1 c2 (char ?a))
3392 (while (setq e (pop alist))
3393 (cond
3394 ((equal e '(:startgroup)) (push e new))
3395 ((equal e '(:endgroup)) (push e new))
3397 (setq k (car e) c2 nil)
3398 (if (cdr e)
3399 (setq c (cdr e))
3400 ;; automatically assign a character.
3401 (setq c1 (string-to-char
3402 (downcase (substring
3403 k (if (= (string-to-char k) ?@) 1 0)))))
3404 (if (or (rassoc c1 new) (rassoc c1 alist))
3405 (while (or (rassoc char new) (rassoc char alist))
3406 (setq char (1+ char)))
3407 (setq c2 c1))
3408 (setq c (or c2 char)))
3409 (push (cons k c) new))))
3410 (nreverse new)))
3412 ;;; Some variables used in various places
3414 (defvar org-window-configuration nil
3415 "Used in various places to store a window configuration.")
3416 (defvar org-finish-function nil
3417 "Function to be called when `C-c C-c' is used.
3418 This is for getting out of special buffers like remember.")
3421 ;; FIXME: Occasionally check by commenting these, to make sure
3422 ;; no other functions uses these, forgetting to let-bind them.
3423 (defvar entry)
3424 (defvar state)
3425 (defvar last-state)
3426 (defvar date)
3427 (defvar description)
3429 ;; Defined somewhere in this file, but used before definition.
3430 (defvar org-html-entities)
3431 (defvar org-struct-menu)
3432 (defvar org-org-menu)
3433 (defvar org-tbl-menu)
3434 (defvar org-agenda-keymap)
3436 ;;;; Define the Org-mode
3438 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3439 (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."))
3442 ;; We use a before-change function to check if a table might need
3443 ;; an update.
3444 (defvar org-table-may-need-update t
3445 "Indicates that a table might need an update.
3446 This variable is set by `org-before-change-function'.
3447 `org-table-align' sets it back to nil.")
3448 (defun org-before-change-function (beg end)
3449 "Every change indicates that a table might need an update."
3450 (setq org-table-may-need-update t))
3451 (defvar org-mode-map)
3452 (defvar org-mode-hook nil
3453 "Mode hook for Org-mode, run after the mode was turned on.")
3454 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3455 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3456 (defvar org-table-buffer-is-an nil)
3457 (defconst org-outline-regexp "\\*+ ")
3459 ;;;###autoload
3460 (define-derived-mode org-mode outline-mode "Org"
3461 "Outline-based notes management and organizer, alias
3462 \"Carsten's outline-mode for keeping track of everything.\"
3464 Org-mode develops organizational tasks around a NOTES file which
3465 contains information about projects as plain text. Org-mode is
3466 implemented on top of outline-mode, which is ideal to keep the content
3467 of large files well structured. It supports ToDo items, deadlines and
3468 time stamps, which magically appear in the diary listing of the Emacs
3469 calendar. Tables are easily created with a built-in table editor.
3470 Plain text URL-like links connect to websites, emails (VM), Usenet
3471 messages (Gnus), BBDB entries, and any files related to the project.
3472 For printing and sharing of notes, an Org-mode file (or a part of it)
3473 can be exported as a structured ASCII or HTML file.
3475 The following commands are available:
3477 \\{org-mode-map}"
3479 ;; Get rid of Outline menus, they are not needed
3480 ;; Need to do this here because define-derived-mode sets up
3481 ;; the keymap so late. Still, it is a waste to call this each time
3482 ;; we switch another buffer into org-mode.
3483 (if (featurep 'xemacs)
3484 (when (boundp 'outline-mode-menu-heading)
3485 ;; Assume this is Greg's port, it used easymenu
3486 (easy-menu-remove outline-mode-menu-heading)
3487 (easy-menu-remove outline-mode-menu-show)
3488 (easy-menu-remove outline-mode-menu-hide))
3489 (define-key org-mode-map [menu-bar headings] 'undefined)
3490 (define-key org-mode-map [menu-bar hide] 'undefined)
3491 (define-key org-mode-map [menu-bar show] 'undefined))
3493 (org-load-modules-maybe)
3494 (easy-menu-add org-org-menu)
3495 (easy-menu-add org-tbl-menu)
3496 (org-install-agenda-files-menu)
3497 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3498 (org-add-to-invisibility-spec '(org-cwidth))
3499 (when (featurep 'xemacs)
3500 (org-set-local 'line-move-ignore-invisible t))
3501 (org-set-local 'outline-regexp org-outline-regexp)
3502 (org-set-local 'outline-level 'org-outline-level)
3503 (when (and org-ellipsis
3504 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3505 (fboundp 'make-glyph-code))
3506 (unless org-display-table
3507 (setq org-display-table (make-display-table)))
3508 (set-display-table-slot
3509 org-display-table 4
3510 (vconcat (mapcar
3511 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3512 org-ellipsis)))
3513 (if (stringp org-ellipsis) org-ellipsis "..."))))
3514 (setq buffer-display-table org-display-table))
3515 (org-set-regexps-and-options)
3516 (when (and org-tag-faces (not org-tags-special-faces-re))
3517 ;; tag faces set outside customize.... force initialization.
3518 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3519 ;; Calc embedded
3520 (org-set-local 'calc-embedded-open-mode "# ")
3521 (modify-syntax-entry ?# "<")
3522 (modify-syntax-entry ?@ "w")
3523 (if org-startup-truncated (setq truncate-lines t))
3524 (org-set-local 'font-lock-unfontify-region-function
3525 'org-unfontify-region)
3526 ;; Activate before-change-function
3527 (org-set-local 'org-table-may-need-update t)
3528 (org-add-hook 'before-change-functions 'org-before-change-function nil
3529 'local)
3530 ;; Check for running clock before killing a buffer
3531 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3532 ;; Paragraphs and auto-filling
3533 (org-set-autofill-regexps)
3534 (setq indent-line-function 'org-indent-line-function)
3535 (org-update-radio-target-regexp)
3537 ;; Comment characters
3538 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3539 (org-set-local 'comment-padding " ")
3541 ;; Align options lines
3542 (org-set-local
3543 'align-mode-rules-list
3544 '((org-in-buffer-settings
3545 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3546 (modes . '(org-mode)))))
3548 ;; Imenu
3549 (org-set-local 'imenu-create-index-function
3550 'org-imenu-get-tree)
3552 ;; Make isearch reveal context
3553 (if (or (featurep 'xemacs)
3554 (not (boundp 'outline-isearch-open-invisible-function)))
3555 ;; Emacs 21 and XEmacs make use of the hook
3556 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3557 ;; Emacs 22 deals with this through a special variable
3558 (org-set-local 'outline-isearch-open-invisible-function
3559 (lambda (&rest ignore) (org-show-context 'isearch))))
3561 ;; If empty file that did not turn on org-mode automatically, make it to.
3562 (if (and org-insert-mode-line-in-empty-file
3563 (interactive-p)
3564 (= (point-min) (point-max)))
3565 (insert "# -*- mode: org -*-\n\n"))
3567 (unless org-inhibit-startup
3568 (when org-startup-align-all-tables
3569 (let ((bmp (buffer-modified-p)))
3570 (org-table-map-tables 'org-table-align)
3571 (set-buffer-modified-p bmp)))
3572 (org-set-startup-visibility)))
3574 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3576 (defun org-current-time ()
3577 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3578 (if (> (car org-time-stamp-rounding-minutes) 1)
3579 (let ((r (car org-time-stamp-rounding-minutes))
3580 (time (decode-time)))
3581 (apply 'encode-time
3582 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3583 (nthcdr 2 time))))
3584 (current-time)))
3586 ;;;; Font-Lock stuff, including the activators
3588 (defvar org-mouse-map (make-sparse-keymap))
3589 (org-defkey org-mouse-map
3590 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3591 (org-defkey org-mouse-map
3592 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3593 (when org-mouse-1-follows-link
3594 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3595 (when org-tab-follows-link
3596 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3597 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3598 (when org-return-follows-link
3599 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3600 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3602 (require 'font-lock)
3604 (defconst org-non-link-chars "]\t\n\r<>")
3605 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3606 "shell" "elisp"))
3607 (defvar org-link-types-re nil
3608 "Matches a link that has a url-like prefix like \"http:\"")
3609 (defvar org-link-re-with-space nil
3610 "Matches a link with spaces, optional angular brackets around it.")
3611 (defvar org-link-re-with-space2 nil
3612 "Matches a link with spaces, optional angular brackets around it.")
3613 (defvar org-link-re-with-space3 nil
3614 "Matches a link with spaces, only for internal part in bracket links.")
3615 (defvar org-angle-link-re nil
3616 "Matches link with angular brackets, spaces are allowed.")
3617 (defvar org-plain-link-re nil
3618 "Matches plain link, without spaces.")
3619 (defvar org-bracket-link-regexp nil
3620 "Matches a link in double brackets.")
3621 (defvar org-bracket-link-analytic-regexp nil
3622 "Regular expression used to analyze links.
3623 Here is what the match groups contain after a match:
3624 1: http:
3625 2: http
3626 3: path
3627 4: [desc]
3628 5: desc")
3629 (defvar org-bracket-link-analytic-regexp++ nil
3630 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3631 (defvar org-any-link-re nil
3632 "Regular expression matching any link.")
3634 (defun org-make-link-regexps ()
3635 "Update the link regular expressions.
3636 This should be called after the variable `org-link-types' has changed."
3637 (setq org-link-types-re
3638 (concat
3639 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3640 org-link-re-with-space
3641 (concat
3642 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3643 "\\([^" org-non-link-chars " ]"
3644 "[^" org-non-link-chars "]*"
3645 "[^" org-non-link-chars " ]\\)>?")
3646 org-link-re-with-space2
3647 (concat
3648 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3649 "\\([^" org-non-link-chars " ]"
3650 "[^\t\n\r]*"
3651 "[^" org-non-link-chars " ]\\)>?")
3652 org-link-re-with-space3
3653 (concat
3654 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3655 "\\([^" org-non-link-chars " ]"
3656 "[^\t\n\r]*\\)")
3657 org-angle-link-re
3658 (concat
3659 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3660 "\\([^" org-non-link-chars " ]"
3661 "[^" org-non-link-chars "]*"
3662 "\\)>")
3663 org-plain-link-re
3664 (concat
3665 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3666 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3667 org-bracket-link-regexp
3668 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3669 org-bracket-link-analytic-regexp
3670 (concat
3671 "\\[\\["
3672 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3673 "\\([^]]+\\)"
3674 "\\]"
3675 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3676 "\\]")
3677 org-bracket-link-analytic-regexp++
3678 (concat
3679 "\\[\\["
3680 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3681 "\\([^]]+\\)"
3682 "\\]"
3683 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3684 "\\]")
3685 org-any-link-re
3686 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3687 org-angle-link-re "\\)\\|\\("
3688 org-plain-link-re "\\)")))
3690 (org-make-link-regexps)
3692 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3693 "Regular expression for fast time stamp matching.")
3694 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3695 "Regular expression for fast time stamp matching.")
3696 (defconst org-ts-regexp0 "\\(\\([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 This one does not require the space after the date, so it can be used
3699 on a string that terminates immediately after the date.")
3700 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3701 "Regular expression matching time strings for analysis.")
3702 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3703 "Regular expression matching time stamps, with groups.")
3704 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3705 "Regular expression matching time stamps (also [..]), with groups.")
3706 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3707 "Regular expression matching a time stamp range.")
3708 (defconst org-tr-regexp-both
3709 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3710 "Regular expression matching a time stamp range.")
3711 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3712 org-ts-regexp "\\)?")
3713 "Regular expression matching a time stamp or time stamp range.")
3714 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3715 org-ts-regexp-both "\\)?")
3716 "Regular expression matching a time stamp or time stamp range.
3717 The time stamps may be either active or inactive.")
3719 (defvar org-emph-face nil)
3721 (defun org-do-emphasis-faces (limit)
3722 "Run through the buffer and add overlays to links."
3723 (let (rtn)
3724 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3725 (if (not (= (char-after (match-beginning 3))
3726 (char-after (match-beginning 4))))
3727 (progn
3728 (setq rtn t)
3729 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3730 'face
3731 (nth 1 (assoc (match-string 3)
3732 org-emphasis-alist)))
3733 (add-text-properties (match-beginning 2) (match-end 2)
3734 '(font-lock-multiline t))
3735 (when org-hide-emphasis-markers
3736 (add-text-properties (match-end 4) (match-beginning 5)
3737 '(invisible org-link))
3738 (add-text-properties (match-beginning 3) (match-end 3)
3739 '(invisible org-link)))))
3740 (backward-char 1))
3741 rtn))
3743 (defun org-emphasize (&optional char)
3744 "Insert or change an emphasis, i.e. a font like bold or italic.
3745 If there is an active region, change that region to a new emphasis.
3746 If there is no region, just insert the marker characters and position
3747 the cursor between them.
3748 CHAR should be either the marker character, or the first character of the
3749 HTML tag associated with that emphasis. If CHAR is a space, the means
3750 to remove the emphasis of the selected region.
3751 If char is not given (for example in an interactive call) it
3752 will be prompted for."
3753 (interactive)
3754 (let ((eal org-emphasis-alist) e det
3755 (erc org-emphasis-regexp-components)
3756 (prompt "")
3757 (string "") beg end move tag c s)
3758 (if (org-region-active-p)
3759 (setq beg (region-beginning) end (region-end)
3760 string (buffer-substring beg end))
3761 (setq move t))
3763 (while (setq e (pop eal))
3764 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3765 c (aref tag 0))
3766 (push (cons c (string-to-char (car e))) det)
3767 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3768 (substring tag 1)))))
3769 (setq det (nreverse det))
3770 (unless char
3771 (message "%s" (concat "Emphasis marker or tag:" prompt))
3772 (setq char (read-char-exclusive)))
3773 (setq char (or (cdr (assoc char det)) char))
3774 (if (equal char ?\ )
3775 (setq s "" move nil)
3776 (unless (assoc (char-to-string char) org-emphasis-alist)
3777 (error "No such emphasis marker: \"%c\"" char))
3778 (setq s (char-to-string char)))
3779 (while (and (> (length string) 1)
3780 (equal (substring string 0 1) (substring string -1))
3781 (assoc (substring string 0 1) org-emphasis-alist))
3782 (setq string (substring string 1 -1)))
3783 (setq string (concat s string s))
3784 (if beg (delete-region beg end))
3785 (unless (or (bolp)
3786 (string-match (concat "[" (nth 0 erc) "\n]")
3787 (char-to-string (char-before (point)))))
3788 (insert " "))
3789 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3790 (char-to-string (char-after (point))))
3791 (insert " ") (backward-char 1))
3792 (insert string)
3793 (and move (backward-char 1))))
3795 (defconst org-nonsticky-props
3796 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3799 (defun org-activate-plain-links (limit)
3800 "Run through the buffer and add overlays to links."
3801 (catch 'exit
3802 (let (f)
3803 (while (re-search-forward org-plain-link-re limit t)
3804 (setq f (get-text-property (match-beginning 0) 'face))
3805 (if (or (eq f 'org-tag)
3806 (and (listp f) (memq 'org-tag f)))
3808 (add-text-properties (match-beginning 0) (match-end 0)
3809 (list 'mouse-face 'highlight
3810 'rear-nonsticky org-nonsticky-props
3811 'keymap org-mouse-map
3813 (throw 'exit t))))))
3815 (defun org-activate-code (limit)
3816 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3817 (progn
3818 (remove-text-properties (match-beginning 0) (match-end 0)
3819 '(display t invisible t intangible t))
3820 t)))
3822 (defun org-activate-angle-links (limit)
3823 "Run through the buffer and add overlays to links."
3824 (if (re-search-forward org-angle-link-re limit t)
3825 (progn
3826 (add-text-properties (match-beginning 0) (match-end 0)
3827 (list 'mouse-face 'highlight
3828 'rear-nonsticky org-nonsticky-props
3829 'keymap org-mouse-map
3831 t)))
3833 (defun org-activate-footnote-links (limit)
3834 "Run through the buffer and add overlays to links."
3835 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3836 limit t)
3837 (progn
3838 (add-text-properties (match-beginning 2) (match-end 2)
3839 (list 'mouse-face 'highlight
3840 'rear-nonsticky org-nonsticky-props
3841 'keymap org-mouse-map
3842 'help-echo
3843 (if (= (point-at-bol) (match-beginning 2))
3844 "Footnote definition"
3845 "Footnote reference")
3847 t)))
3849 (defun org-activate-bracket-links (limit)
3850 "Run through the buffer and add overlays to bracketed links."
3851 (if (re-search-forward org-bracket-link-regexp limit t)
3852 (let* ((help (concat "LINK: "
3853 (org-match-string-no-properties 1)))
3854 ;; FIXME: above we should remove the escapes.
3855 ;; but that requires another match, protecting match data,
3856 ;; a lot of overhead for font-lock.
3857 (ip (org-maybe-intangible
3858 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3859 'keymap org-mouse-map 'mouse-face 'highlight
3860 'font-lock-multiline t 'help-echo help)))
3861 (vp (list 'rear-nonsticky org-nonsticky-props
3862 'keymap org-mouse-map 'mouse-face 'highlight
3863 ' font-lock-multiline t 'help-echo help)))
3864 ;; We need to remove the invisible property here. Table narrowing
3865 ;; may have made some of this invisible.
3866 (remove-text-properties (match-beginning 0) (match-end 0)
3867 '(invisible nil))
3868 (if (match-end 3)
3869 (progn
3870 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3871 (add-text-properties (match-beginning 3) (match-end 3) vp)
3872 (add-text-properties (match-end 3) (match-end 0) ip))
3873 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3874 (add-text-properties (match-beginning 1) (match-end 1) vp)
3875 (add-text-properties (match-end 1) (match-end 0) ip))
3876 t)))
3878 (defun org-activate-dates (limit)
3879 "Run through the buffer and add overlays to dates."
3880 (if (re-search-forward org-tsr-regexp-both limit t)
3881 (progn
3882 (add-text-properties (match-beginning 0) (match-end 0)
3883 (list 'mouse-face 'highlight
3884 'rear-nonsticky org-nonsticky-props
3885 'keymap org-mouse-map))
3886 (when org-display-custom-times
3887 (if (match-end 3)
3888 (org-display-custom-time (match-beginning 3) (match-end 3)))
3889 (org-display-custom-time (match-beginning 1) (match-end 1)))
3890 t)))
3892 (defvar org-target-link-regexp nil
3893 "Regular expression matching radio targets in plain text.")
3894 (make-variable-buffer-local 'org-target-link-regexp)
3895 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3896 "Regular expression matching a link target.")
3897 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3898 "Regular expression matching a radio target.")
3899 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3900 "Regular expression matching any target.")
3902 (defun org-activate-target-links (limit)
3903 "Run through the buffer and add overlays to target matches."
3904 (when org-target-link-regexp
3905 (let ((case-fold-search t))
3906 (if (re-search-forward org-target-link-regexp limit t)
3907 (progn
3908 (add-text-properties (match-beginning 0) (match-end 0)
3909 (list 'mouse-face 'highlight
3910 'rear-nonsticky org-nonsticky-props
3911 'keymap org-mouse-map
3912 'help-echo "Radio target link"
3913 'org-linked-text t))
3914 t)))))
3916 (defun org-update-radio-target-regexp ()
3917 "Find all radio targets in this file and update the regular expression."
3918 (interactive)
3919 (when (memq 'radio org-activate-links)
3920 (setq org-target-link-regexp
3921 (org-make-target-link-regexp (org-all-targets 'radio)))
3922 (org-restart-font-lock)))
3924 (defun org-hide-wide-columns (limit)
3925 (let (s e)
3926 (setq s (text-property-any (point) (or limit (point-max))
3927 'org-cwidth t))
3928 (when s
3929 (setq e (next-single-property-change s 'org-cwidth))
3930 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3931 (goto-char e)
3932 t)))
3934 (defvar org-latex-and-specials-regexp nil
3935 "Regular expression for highlighting export special stuff.")
3936 (defvar org-match-substring-regexp)
3937 (defvar org-match-substring-with-braces-regexp)
3938 (defvar org-export-html-special-string-regexps)
3940 (defun org-compute-latex-and-specials-regexp ()
3941 "Compute regular expression for stuff treated specially by exporters."
3942 (if (not org-highlight-latex-fragments-and-specials)
3943 (org-set-local 'org-latex-and-specials-regexp nil)
3944 (require 'org-exp)
3945 (let*
3946 ((matchers (plist-get org-format-latex-options :matchers))
3947 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3948 org-latex-regexps)))
3949 (options (org-combine-plists (org-default-export-plist)
3950 (org-infile-export-plist)))
3951 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3952 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3953 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3954 (org-export-html-expand (plist-get options :expand-quoted-html))
3955 (org-export-with-special-strings (plist-get options :special-strings))
3956 (re-sub
3957 (cond
3958 ((equal org-export-with-sub-superscripts '{})
3959 (list org-match-substring-with-braces-regexp))
3960 (org-export-with-sub-superscripts
3961 (list org-match-substring-regexp))
3962 (t nil)))
3963 (re-latex
3964 (if org-export-with-LaTeX-fragments
3965 (mapcar (lambda (x) (nth 1 x)) latexs)))
3966 (re-macros
3967 (if org-export-with-TeX-macros
3968 (list (concat "\\\\"
3969 (regexp-opt
3970 (append (mapcar 'car org-html-entities)
3971 (if (boundp 'org-latex-entities)
3972 org-latex-entities nil))
3973 'words))) ; FIXME
3975 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3976 (re-special (if org-export-with-special-strings
3977 (mapcar (lambda (x) (car x))
3978 org-export-html-special-string-regexps)))
3979 (re-rest
3980 (delq nil
3981 (list
3982 (if org-export-html-expand "@<[^>\n]+>")
3983 ))))
3984 (org-set-local
3985 'org-latex-and-specials-regexp
3986 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3987 re-rest) "\\|")))))
3989 (defun org-do-latex-and-special-faces (limit)
3990 "Run through the buffer and add overlays to links."
3991 (when org-latex-and-specials-regexp
3992 (let (rtn d)
3993 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3994 limit t))
3995 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3996 'face))
3997 '(org-code org-verbatim underline)))
3998 (progn
3999 (setq rtn t
4000 d (cond ((member (char-after (1+ (match-beginning 0)))
4001 '(?_ ?^)) 1)
4002 (t 0)))
4003 (font-lock-prepend-text-property
4004 (+ d (match-beginning 0)) (match-end 0)
4005 'face 'org-latex-and-export-specials)
4006 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4007 '(font-lock-multiline t)))))
4008 rtn)))
4010 (defun org-restart-font-lock ()
4011 "Restart font-lock-mode, to force refontification."
4012 (when (and (boundp 'font-lock-mode) font-lock-mode)
4013 (font-lock-mode -1)
4014 (font-lock-mode 1)))
4016 (defun org-all-targets (&optional radio)
4017 "Return a list of all targets in this file.
4018 With optional argument RADIO, only find radio targets."
4019 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4020 rtn)
4021 (save-excursion
4022 (goto-char (point-min))
4023 (while (re-search-forward re nil t)
4024 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4025 rtn)))
4027 (defun org-make-target-link-regexp (targets)
4028 "Make regular expression matching all strings in TARGETS.
4029 The regular expression finds the targets also if there is a line break
4030 between words."
4031 (and targets
4032 (concat
4033 "\\<\\("
4034 (mapconcat
4035 (lambda (x)
4036 (while (string-match " +" x)
4037 (setq x (replace-match "\\s-+" t t x)))
4039 targets
4040 "\\|")
4041 "\\)\\>")))
4043 (defun org-activate-tags (limit)
4044 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4045 (progn
4046 (add-text-properties (match-beginning 1) (match-end 1)
4047 (list 'mouse-face 'highlight
4048 'rear-nonsticky org-nonsticky-props
4049 'keymap org-mouse-map))
4050 t)))
4052 (defun org-outline-level ()
4053 (save-excursion
4054 (looking-at outline-regexp)
4055 (if (match-beginning 1)
4056 (+ (org-get-string-indentation (match-string 1)) 1000)
4057 (1- (- (match-end 0) (match-beginning 0))))))
4059 (defvar org-font-lock-keywords nil)
4061 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4062 "Regular expression matching a property line.")
4064 (defvar org-font-lock-hook nil
4065 "Functions to be called for special font lock stuff.")
4067 (defun org-font-lock-hook (limit)
4068 (run-hook-with-args 'org-font-lock-hook limit))
4070 (defun org-set-font-lock-defaults ()
4071 (let* ((em org-fontify-emphasized-text)
4072 (lk org-activate-links)
4073 (org-font-lock-extra-keywords
4074 (list
4075 ;; Call the hook
4076 '(org-font-lock-hook)
4077 ;; Headlines
4078 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4079 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4080 ;; Table lines
4081 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4082 (1 'org-table t))
4083 ;; Table internals
4084 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4085 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4086 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4087 ;; Drawers
4088 (list org-drawer-regexp '(0 'org-special-keyword t))
4089 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4090 ;; Properties
4091 (list org-property-re
4092 '(1 'org-special-keyword t)
4093 '(3 'org-property-value t))
4094 (if org-format-transports-properties-p
4095 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4096 ;; Links
4097 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4098 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4099 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4100 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4101 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4102 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4103 (if (memq 'footnote lk) '(org-activate-footnote-links
4104 (2 'org-footnote t)))
4105 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4106 '(org-hide-wide-columns (0 nil append))
4107 ;; TODO lines
4108 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4109 '(1 (org-get-todo-face 1) t))
4110 ;; DONE
4111 (if org-fontify-done-headline
4112 (list (concat "^[*]+ +\\<\\("
4113 (mapconcat 'regexp-quote org-done-keywords "\\|")
4114 "\\)\\(.*\\)")
4115 '(2 'org-headline-done t))
4116 nil)
4117 ;; Priorities
4118 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4119 ;; Tags
4120 '(org-font-lock-add-tag-faces)
4121 ;; Special keywords
4122 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4123 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4124 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4125 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4126 ;; Emphasis
4127 (if em
4128 (if (featurep 'xemacs)
4129 '(org-do-emphasis-faces (0 nil append))
4130 '(org-do-emphasis-faces)))
4131 ;; Checkboxes
4132 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4133 2 'bold prepend)
4134 (if org-provide-checkbox-statistics
4135 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4136 (0 (org-get-checkbox-statistics-face) t)))
4137 ;; Description list items
4138 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4139 2 'bold prepend)
4140 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4141 '(1 'org-archived prepend))
4142 ;; Specials
4143 '(org-do-latex-and-special-faces)
4144 ;; Code
4145 '(org-activate-code (1 'org-code t))
4146 ;; COMMENT
4147 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4148 "\\|" org-quote-string "\\)\\>")
4149 '(1 'org-special-keyword t))
4150 '("^#.*" (0 'font-lock-comment-face t))
4152 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4153 ;; Now set the full font-lock-keywords
4154 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4155 (org-set-local 'font-lock-defaults
4156 '(org-font-lock-keywords t nil nil backward-paragraph))
4157 (kill-local-variable 'font-lock-keywords) nil))
4159 (defvar org-m nil)
4160 (defvar org-l nil)
4161 (defvar org-f nil)
4162 (defun org-get-level-face (n)
4163 "Get the right face for match N in font-lock matching of headlines."
4164 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4165 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4166 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4167 (cond
4168 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4169 ((eq n 2) org-f)
4170 (t (if org-level-color-stars-only nil org-f))))
4172 (defun org-get-todo-face (kwd)
4173 "Get the right face for a TODO keyword KWD.
4174 If KWD is a number, get the corresponding match group."
4175 (if (numberp kwd) (setq kwd (match-string kwd)))
4176 (or (cdr (assoc kwd org-todo-keyword-faces))
4177 (and (member kwd org-done-keywords) 'org-done)
4178 'org-todo))
4180 (defun org-font-lock-add-tag-faces (limit)
4181 "Add the special tag faces."
4182 (when (and org-tag-faces org-tags-special-faces-re)
4183 (while (re-search-forward org-tags-special-faces-re limit t)
4184 (add-text-properties (match-beginning 1) (match-end 1)
4185 (list 'face (org-get-tag-face 1)
4186 'font-lock-fontified t))
4187 (backward-char 1))))
4189 (defun org-get-tag-face (kwd)
4190 "Get the right face for a TODO keyword KWD.
4191 If KWD is a number, get the corresponding match group."
4192 (if (numberp kwd) (setq kwd (match-string kwd)))
4193 (or (cdr (assoc kwd org-tag-faces))
4194 'org-tag))
4196 (defun org-unfontify-region (beg end &optional maybe_loudly)
4197 "Remove fontification and activation overlays from links."
4198 (font-lock-default-unfontify-region beg end)
4199 (let* ((buffer-undo-list t)
4200 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4201 (inhibit-modification-hooks t)
4202 deactivate-mark buffer-file-name buffer-file-truename)
4203 (remove-text-properties beg end
4204 '(mouse-face t keymap t org-linked-text t
4205 invisible t intangible t))))
4207 ;;;; Visibility cycling, including org-goto and indirect buffer
4209 ;;; Cycling
4211 (defvar org-cycle-global-status nil)
4212 (make-variable-buffer-local 'org-cycle-global-status)
4213 (defvar org-cycle-subtree-status nil)
4214 (make-variable-buffer-local 'org-cycle-subtree-status)
4216 ;;;###autoload
4217 (defun org-cycle (&optional arg)
4218 "Visibility cycling for Org-mode.
4220 - When this function is called with a prefix argument, rotate the entire
4221 buffer through 3 states (global cycling)
4222 1. OVERVIEW: Show only top-level headlines.
4223 2. CONTENTS: Show all headlines of all levels, but no body text.
4224 3. SHOW ALL: Show everything.
4225 When called with two C-u C-u prefixes, switch to the startup visibility,
4226 determined by the variable `org-startup-folded', and by any VISIBILITY
4227 properties in the buffer.
4228 When called with three C-u C-u C-u prefixed, show the entire buffer,
4229 including drawers.
4231 - When point is at the beginning of a headline, rotate the subtree started
4232 by this line through 3 different states (local cycling)
4233 1. FOLDED: Only the main headline is shown.
4234 2. CHILDREN: The main headline and the direct children are shown.
4235 From this state, you can move to one of the children
4236 and zoom in further.
4237 3. SUBTREE: Show the entire subtree, including body text.
4239 - When there is a numeric prefix, go up to a heading with level ARG, do
4240 a `show-subtree' and return to the previous cursor position. If ARG
4241 is negative, go up that many levels.
4243 - When point is not at the beginning of a headline, execute the global
4244 binding for TAB, which is re-indenting the line. See the option
4245 `org-cycle-emulate-tab' for details.
4247 - Special case: if point is at the beginning of the buffer and there is
4248 no headline in line 1, this function will act as if called with prefix arg.
4249 But only if also the variable `org-cycle-global-at-bob' is t."
4250 (interactive "P")
4251 (org-load-modules-maybe)
4252 (let* ((outline-regexp
4253 (if (and (org-mode-p) org-cycle-include-plain-lists)
4254 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4255 outline-regexp))
4256 (bob-special (and org-cycle-global-at-bob (bobp)
4257 (not (looking-at outline-regexp))))
4258 (org-cycle-hook
4259 (if bob-special
4260 (delq 'org-optimize-window-after-visibility-change
4261 (copy-sequence org-cycle-hook))
4262 org-cycle-hook))
4263 (pos (point)))
4265 (if (or bob-special (equal arg '(4)))
4266 ;; special case: use global cycling
4267 (setq arg t))
4269 (cond
4271 ((equal arg '(16))
4272 (org-set-startup-visibility)
4273 (message "Startup visibility, plus VISIBILITY properties"))
4275 ((equal arg '(64))
4276 (show-all)
4277 (message "Entire buffer visible, including drawers"))
4279 ((org-at-table-p 'any)
4280 ;; Enter the table or move to the next field in the table
4281 (or (org-table-recognize-table.el)
4282 (progn
4283 (if arg (org-table-edit-field t)
4284 (org-table-justify-field-maybe)
4285 (call-interactively 'org-table-next-field)))))
4287 ((eq arg t) ;; Global cycling
4289 (cond
4290 ((and (eq last-command this-command)
4291 (eq org-cycle-global-status 'overview))
4292 ;; We just created the overview - now do table of contents
4293 ;; This can be slow in very large buffers, so indicate action
4294 (message "CONTENTS...")
4295 (org-content)
4296 (message "CONTENTS...done")
4297 (setq org-cycle-global-status 'contents)
4298 (run-hook-with-args 'org-cycle-hook 'contents))
4300 ((and (eq last-command this-command)
4301 (eq org-cycle-global-status 'contents))
4302 ;; We just showed the table of contents - now show everything
4303 (show-all)
4304 (message "SHOW ALL")
4305 (setq org-cycle-global-status 'all)
4306 (run-hook-with-args 'org-cycle-hook 'all))
4309 ;; Default action: go to overview
4310 (org-overview)
4311 (message "OVERVIEW")
4312 (setq org-cycle-global-status 'overview)
4313 (run-hook-with-args 'org-cycle-hook 'overview))))
4315 ((and org-drawers org-drawer-regexp
4316 (save-excursion
4317 (beginning-of-line 1)
4318 (looking-at org-drawer-regexp)))
4319 ;; Toggle block visibility
4320 (org-flag-drawer
4321 (not (get-char-property (match-end 0) 'invisible))))
4323 ((integerp arg)
4324 ;; Show-subtree, ARG levels up from here.
4325 (save-excursion
4326 (org-back-to-heading)
4327 (outline-up-heading (if (< arg 0) (- arg)
4328 (- (funcall outline-level) arg)))
4329 (org-show-subtree)))
4331 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4332 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4333 ;; At a heading: rotate between three different views
4334 (org-back-to-heading)
4335 (let ((goal-column 0) eoh eol eos)
4336 ;; First, some boundaries
4337 (save-excursion
4338 (org-back-to-heading)
4339 (save-excursion
4340 (beginning-of-line 2)
4341 (while (and (not (eobp)) ;; this is like `next-line'
4342 (get-char-property (1- (point)) 'invisible))
4343 (beginning-of-line 2)) (setq eol (point)))
4344 (outline-end-of-heading) (setq eoh (point))
4345 (org-end-of-subtree t)
4346 (unless (eobp)
4347 (skip-chars-forward " \t\n")
4348 (beginning-of-line 1) ; in case this is an item
4350 (setq eos (1- (point))))
4351 ;; Find out what to do next and set `this-command'
4352 (cond
4353 ((= eos eoh)
4354 ;; Nothing is hidden behind this heading
4355 (message "EMPTY ENTRY")
4356 (setq org-cycle-subtree-status nil)
4357 (save-excursion
4358 (goto-char eos)
4359 (outline-next-heading)
4360 (if (org-invisible-p) (org-flag-heading nil))))
4361 ((or (>= eol eos)
4362 (not (string-match "\\S-" (buffer-substring eol eos))))
4363 ;; Entire subtree is hidden in one line: open it
4364 (org-show-entry)
4365 (show-children)
4366 (message "CHILDREN")
4367 (save-excursion
4368 (goto-char eos)
4369 (outline-next-heading)
4370 (if (org-invisible-p) (org-flag-heading nil)))
4371 (setq org-cycle-subtree-status 'children)
4372 (run-hook-with-args 'org-cycle-hook 'children))
4373 ((and (eq last-command this-command)
4374 (eq org-cycle-subtree-status 'children))
4375 ;; We just showed the children, now show everything.
4376 (org-show-subtree)
4377 (message "SUBTREE")
4378 (setq org-cycle-subtree-status 'subtree)
4379 (run-hook-with-args 'org-cycle-hook 'subtree))
4381 ;; Default action: hide the subtree.
4382 (hide-subtree)
4383 (message "FOLDED")
4384 (setq org-cycle-subtree-status 'folded)
4385 (run-hook-with-args 'org-cycle-hook 'folded)))))
4387 ;; TAB emulation and template completion
4388 (buffer-read-only (org-back-to-heading))
4390 ((org-try-structure-completion))
4392 ((org-try-cdlatex-tab))
4394 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4395 (or (not (bolp))
4396 (not (looking-at outline-regexp))))
4397 (call-interactively (global-key-binding "\t")))
4399 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4400 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4401 (or (and (eq org-cycle-emulate-tab 'white)
4402 (= (match-end 0) (point-at-eol)))
4403 (and (eq org-cycle-emulate-tab 'whitestart)
4404 (>= (match-end 0) pos))))
4406 (eq org-cycle-emulate-tab t))
4407 (call-interactively (global-key-binding "\t")))
4409 (t (save-excursion
4410 (org-back-to-heading)
4411 (org-cycle))))))
4413 ;;;###autoload
4414 (defun org-global-cycle (&optional arg)
4415 "Cycle the global visibility. For details see `org-cycle'.
4416 With C-u prefix arg, switch to startup visibility.
4417 With a numeric prefix, show all headlines up to that level."
4418 (interactive "P")
4419 (let ((org-cycle-include-plain-lists
4420 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4421 (cond
4422 ((integerp arg)
4423 (show-all)
4424 (hide-sublevels arg)
4425 (setq org-cycle-global-status 'contents))
4426 ((equal arg '(4))
4427 (org-set-startup-visibility)
4428 (message "Startup visibility, plus VISIBILITY properties."))
4430 (org-cycle '(4))))))
4432 (defun org-set-startup-visibility ()
4433 "Set the visibility required by startup options and properties."
4434 (cond
4435 ((eq org-startup-folded t)
4436 (org-cycle '(4)))
4437 ((eq org-startup-folded 'content)
4438 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4439 (org-cycle '(4)) (org-cycle '(4)))))
4440 (org-set-visibility-according-to-property 'no-cleanup)
4441 (org-cycle-hide-archived-subtrees 'all)
4442 (org-cycle-hide-drawers 'all)
4443 (org-cycle-show-empty-lines 'all))
4445 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4446 "Switch subtree visibilities according to :VISIBILITY: property."
4447 (interactive)
4448 (let (org-show-entry-below state)
4449 (save-excursion
4450 (goto-char (point-min))
4451 (while (re-search-forward
4452 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4453 nil t)
4454 (setq state (match-string 1))
4455 (save-excursion
4456 (org-back-to-heading t)
4457 (hide-subtree)
4458 (org-reveal)
4459 (cond
4460 ((equal state '("fold" "folded"))
4461 (hide-subtree))
4462 ((equal state "children")
4463 (org-show-hidden-entry)
4464 (show-children))
4465 ((equal state "content")
4466 (save-excursion
4467 (save-restriction
4468 (org-narrow-to-subtree)
4469 (org-content))))
4470 ((member state '("all" "showall"))
4471 (show-subtree)))))
4472 (unless no-cleanup
4473 (org-cycle-hide-archived-subtrees 'all)
4474 (org-cycle-hide-drawers 'all)
4475 (org-cycle-show-empty-lines 'all)))))
4477 (defun org-overview ()
4478 "Switch to overview mode, showing only top-level headlines.
4479 Really, this shows all headlines with level equal or greater than the level
4480 of the first headline in the buffer. This is important, because if the
4481 first headline is not level one, then (hide-sublevels 1) gives confusing
4482 results."
4483 (interactive)
4484 (let ((level (save-excursion
4485 (goto-char (point-min))
4486 (if (re-search-forward (concat "^" outline-regexp) nil t)
4487 (progn
4488 (goto-char (match-beginning 0))
4489 (funcall outline-level))))))
4490 (and level (hide-sublevels level))))
4492 (defun org-content (&optional arg)
4493 "Show all headlines in the buffer, like a table of contents.
4494 With numerical argument N, show content up to level N."
4495 (interactive "P")
4496 (save-excursion
4497 ;; Visit all headings and show their offspring
4498 (and (integerp arg) (org-overview))
4499 (goto-char (point-max))
4500 (catch 'exit
4501 (while (and (progn (condition-case nil
4502 (outline-previous-visible-heading 1)
4503 (error (goto-char (point-min))))
4505 (looking-at outline-regexp))
4506 (if (integerp arg)
4507 (show-children (1- arg))
4508 (show-branches))
4509 (if (bobp) (throw 'exit nil))))))
4512 (defun org-optimize-window-after-visibility-change (state)
4513 "Adjust the window after a change in outline visibility.
4514 This function is the default value of the hook `org-cycle-hook'."
4515 (when (get-buffer-window (current-buffer))
4516 (cond
4517 ; ((eq state 'overview) (org-first-headline-recenter 1))
4518 ; ((eq state 'overview) (org-beginning-of-line))
4519 ((eq state 'content) nil)
4520 ((eq state 'all) nil)
4521 ((eq state 'folded) nil)
4522 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4523 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4525 (defun org-compact-display-after-subtree-move ()
4526 "Show a compacter version of the tree of the entry's parent."
4527 (save-excursion
4528 (if (org-up-heading-safe)
4529 (progn
4530 (hide-subtree)
4531 (show-entry)
4532 (show-children)
4533 (org-cycle-show-empty-lines 'children)
4534 (org-cycle-hide-drawers 'children))
4535 (org-overview))))
4537 (defun org-cycle-show-empty-lines (state)
4538 "Show empty lines above all visible headlines.
4539 The region to be covered depends on STATE when called through
4540 `org-cycle-hook'. Lisp program can use t for STATE to get the
4541 entire buffer covered. Note that an empty line is only shown if there
4542 are at least `org-cycle-separator-lines' empty lines before the headline."
4543 (when (> org-cycle-separator-lines 0)
4544 (save-excursion
4545 (let* ((n org-cycle-separator-lines)
4546 (re (cond
4547 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4548 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4549 (t (let ((ns (number-to-string (- n 2))))
4550 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4551 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4552 beg end)
4553 (cond
4554 ((memq state '(overview contents t))
4555 (setq beg (point-min) end (point-max)))
4556 ((memq state '(children folded))
4557 (setq beg (point) end (progn (org-end-of-subtree t t)
4558 (beginning-of-line 2)
4559 (point)))))
4560 (when beg
4561 (goto-char beg)
4562 (while (re-search-forward re end t)
4563 (if (not (get-char-property (match-end 1) 'invisible))
4564 (outline-flag-region
4565 (match-beginning 1) (match-end 1) nil)))))))
4566 ;; Never hide empty lines at the end of the file.
4567 (save-excursion
4568 (goto-char (point-max))
4569 (outline-previous-heading)
4570 (outline-end-of-heading)
4571 (if (and (looking-at "[ \t\n]+")
4572 (= (match-end 0) (point-max)))
4573 (outline-flag-region (point) (match-end 0) nil))))
4575 (defun org-show-empty-lines-in-parent ()
4576 "Move to the parent and re-show empty lines before visible headlines."
4577 (save-excursion
4578 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4579 (org-cycle-show-empty-lines context))))
4581 (defun org-cycle-hide-drawers (state)
4582 "Re-hide all drawers after a visibility state change."
4583 (when (and (org-mode-p)
4584 (not (memq state '(overview folded))))
4585 (save-excursion
4586 (let* ((globalp (memq state '(contents all)))
4587 (beg (if globalp (point-min) (point)))
4588 (end (if globalp (point-max) (org-end-of-subtree t))))
4589 (goto-char beg)
4590 (while (re-search-forward org-drawer-regexp end t)
4591 (org-flag-drawer t))))))
4593 (defun org-flag-drawer (flag)
4594 (save-excursion
4595 (beginning-of-line 1)
4596 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4597 (let ((b (match-end 0))
4598 (outline-regexp org-outline-regexp))
4599 (if (re-search-forward
4600 "^[ \t]*:END:"
4601 (save-excursion (outline-next-heading) (point)) t)
4602 (outline-flag-region b (point-at-eol) flag)
4603 (error ":END: line missing"))))))
4605 (defun org-subtree-end-visible-p ()
4606 "Is the end of the current subtree visible?"
4607 (pos-visible-in-window-p
4608 (save-excursion (org-end-of-subtree t) (point))))
4610 (defun org-first-headline-recenter (&optional N)
4611 "Move cursor to the first headline and recenter the headline.
4612 Optional argument N means, put the headline into the Nth line of the window."
4613 (goto-char (point-min))
4614 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4615 (beginning-of-line)
4616 (recenter (prefix-numeric-value N))))
4618 ;;; Org-goto
4620 (defvar org-goto-window-configuration nil)
4621 (defvar org-goto-marker nil)
4622 (defvar org-goto-map
4623 (let ((map (make-sparse-keymap)))
4624 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4625 (while (setq cmd (pop cmds))
4626 (substitute-key-definition cmd cmd map global-map)))
4627 (suppress-keymap map)
4628 (org-defkey map "\C-m" 'org-goto-ret)
4629 (org-defkey map [(return)] 'org-goto-ret)
4630 (org-defkey map [(left)] 'org-goto-left)
4631 (org-defkey map [(right)] 'org-goto-right)
4632 (org-defkey map [(control ?g)] 'org-goto-quit)
4633 (org-defkey map "\C-i" 'org-cycle)
4634 (org-defkey map [(tab)] 'org-cycle)
4635 (org-defkey map [(down)] 'outline-next-visible-heading)
4636 (org-defkey map [(up)] 'outline-previous-visible-heading)
4637 (if org-goto-auto-isearch
4638 (if (fboundp 'define-key-after)
4639 (define-key-after map [t] 'org-goto-local-auto-isearch)
4640 nil)
4641 (org-defkey map "q" 'org-goto-quit)
4642 (org-defkey map "n" 'outline-next-visible-heading)
4643 (org-defkey map "p" 'outline-previous-visible-heading)
4644 (org-defkey map "f" 'outline-forward-same-level)
4645 (org-defkey map "b" 'outline-backward-same-level)
4646 (org-defkey map "u" 'outline-up-heading))
4647 (org-defkey map "/" 'org-occur)
4648 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4649 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4650 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4651 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4652 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4653 map))
4655 (defconst org-goto-help
4656 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4657 RET=jump to location [Q]uit and return to previous location
4658 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4660 (defvar org-goto-start-pos) ; dynamically scoped parameter
4662 ;; FIXME: Docstring doe not mention both interfaces
4663 (defun org-goto (&optional alternative-interface)
4664 "Look up a different location in the current file, keeping current visibility.
4666 When you want look-up or go to a different location in a document, the
4667 fastest way is often to fold the entire buffer and then dive into the tree.
4668 This method has the disadvantage, that the previous location will be folded,
4669 which may not be what you want.
4671 This command works around this by showing a copy of the current buffer
4672 in an indirect buffer, in overview mode. You can dive into the tree in
4673 that copy, use org-occur and incremental search to find a location.
4674 When pressing RET or `Q', the command returns to the original buffer in
4675 which the visibility is still unchanged. After RET is will also jump to
4676 the location selected in the indirect buffer and expose the
4677 the headline hierarchy above."
4678 (interactive "P")
4679 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4680 (org-refile-use-outline-path t)
4681 (interface
4682 (if (not alternative-interface)
4683 org-goto-interface
4684 (if (eq org-goto-interface 'outline)
4685 'outline-path-completion
4686 'outline)))
4687 (org-goto-start-pos (point))
4688 (selected-point
4689 (if (eq interface 'outline)
4690 (car (org-get-location (current-buffer) org-goto-help))
4691 (nth 3 (org-refile-get-location "Goto: ")))))
4692 (if selected-point
4693 (progn
4694 (org-mark-ring-push org-goto-start-pos)
4695 (goto-char selected-point)
4696 (if (or (org-invisible-p) (org-invisible-p2))
4697 (org-show-context 'org-goto)))
4698 (message "Quit"))))
4700 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4701 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4702 (defvar org-goto-local-auto-isearch-map) ; defined below
4704 (defun org-get-location (buf help)
4705 "Let the user select a location in the Org-mode buffer BUF.
4706 This function uses a recursive edit. It returns the selected position
4707 or nil."
4708 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4709 (isearch-hide-immediately nil)
4710 (isearch-search-fun-function
4711 (lambda () 'org-goto-local-search-headings))
4712 (org-goto-selected-point org-goto-exit-command))
4713 (save-excursion
4714 (save-window-excursion
4715 (delete-other-windows)
4716 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4717 (switch-to-buffer
4718 (condition-case nil
4719 (make-indirect-buffer (current-buffer) "*org-goto*")
4720 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4721 (with-output-to-temp-buffer "*Help*"
4722 (princ help))
4723 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4724 (setq buffer-read-only nil)
4725 (let ((org-startup-truncated t)
4726 (org-startup-folded nil)
4727 (org-startup-align-all-tables nil))
4728 (org-mode)
4729 (org-overview))
4730 (setq buffer-read-only t)
4731 (if (and (boundp 'org-goto-start-pos)
4732 (integer-or-marker-p org-goto-start-pos))
4733 (let ((org-show-hierarchy-above t)
4734 (org-show-siblings t)
4735 (org-show-following-heading t))
4736 (goto-char org-goto-start-pos)
4737 (and (org-invisible-p) (org-show-context)))
4738 (goto-char (point-min)))
4739 (org-beginning-of-line)
4740 (message "Select location and press RET")
4741 (use-local-map org-goto-map)
4742 (recursive-edit)
4744 (kill-buffer "*org-goto*")
4745 (cons org-goto-selected-point org-goto-exit-command)))
4747 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4748 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4749 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4750 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4752 (defun org-goto-local-search-headings (string bound noerror)
4753 "Search and make sure that any matches are in headlines."
4754 (catch 'return
4755 (while (if isearch-forward
4756 (search-forward string bound noerror)
4757 (search-backward string bound noerror))
4758 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4759 (and (member :headline context)
4760 (not (member :tags context))))
4761 (throw 'return (point))))))
4763 (defun org-goto-local-auto-isearch ()
4764 "Start isearch."
4765 (interactive)
4766 (goto-char (point-min))
4767 (let ((keys (this-command-keys)))
4768 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4769 (isearch-mode t)
4770 (isearch-process-search-char (string-to-char keys)))))
4772 (defun org-goto-ret (&optional arg)
4773 "Finish `org-goto' by going to the new location."
4774 (interactive "P")
4775 (setq org-goto-selected-point (point)
4776 org-goto-exit-command 'return)
4777 (throw 'exit nil))
4779 (defun org-goto-left ()
4780 "Finish `org-goto' by going to the new location."
4781 (interactive)
4782 (if (org-on-heading-p)
4783 (progn
4784 (beginning-of-line 1)
4785 (setq org-goto-selected-point (point)
4786 org-goto-exit-command 'left)
4787 (throw 'exit nil))
4788 (error "Not on a heading")))
4790 (defun org-goto-right ()
4791 "Finish `org-goto' by going to the new location."
4792 (interactive)
4793 (if (org-on-heading-p)
4794 (progn
4795 (setq org-goto-selected-point (point)
4796 org-goto-exit-command 'right)
4797 (throw 'exit nil))
4798 (error "Not on a heading")))
4800 (defun org-goto-quit ()
4801 "Finish `org-goto' without cursor motion."
4802 (interactive)
4803 (setq org-goto-selected-point nil)
4804 (setq org-goto-exit-command 'quit)
4805 (throw 'exit nil))
4807 ;;; Indirect buffer display of subtrees
4809 (defvar org-indirect-dedicated-frame nil
4810 "This is the frame being used for indirect tree display.")
4811 (defvar org-last-indirect-buffer nil)
4813 (defun org-tree-to-indirect-buffer (&optional arg)
4814 "Create indirect buffer and narrow it to current subtree.
4815 With numerical prefix ARG, go up to this level and then take that tree.
4816 If ARG is negative, go up that many levels.
4817 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4818 indirect buffer previously made with this command, to avoid proliferation of
4819 indirect buffers. However, when you call the command with a `C-u' prefix, or
4820 when `org-indirect-buffer-display' is `new-frame', the last buffer
4821 is kept so that you can work with several indirect buffers at the same time.
4822 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4823 requests that a new frame be made for the new buffer, so that the dedicated
4824 frame is not changed."
4825 (interactive "P")
4826 (let ((cbuf (current-buffer))
4827 (cwin (selected-window))
4828 (pos (point))
4829 beg end level heading ibuf)
4830 (save-excursion
4831 (org-back-to-heading t)
4832 (when (numberp arg)
4833 (setq level (org-outline-level))
4834 (if (< arg 0) (setq arg (+ level arg)))
4835 (while (> (setq level (org-outline-level)) arg)
4836 (outline-up-heading 1 t)))
4837 (setq beg (point)
4838 heading (org-get-heading))
4839 (org-end-of-subtree t) (setq end (point)))
4840 (if (and (buffer-live-p org-last-indirect-buffer)
4841 (not (eq org-indirect-buffer-display 'new-frame))
4842 (not arg))
4843 (kill-buffer org-last-indirect-buffer))
4844 (setq ibuf (org-get-indirect-buffer cbuf)
4845 org-last-indirect-buffer ibuf)
4846 (cond
4847 ((or (eq org-indirect-buffer-display 'new-frame)
4848 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4849 (select-frame (make-frame))
4850 (delete-other-windows)
4851 (switch-to-buffer ibuf)
4852 (org-set-frame-title heading))
4853 ((eq org-indirect-buffer-display 'dedicated-frame)
4854 (raise-frame
4855 (select-frame (or (and org-indirect-dedicated-frame
4856 (frame-live-p org-indirect-dedicated-frame)
4857 org-indirect-dedicated-frame)
4858 (setq org-indirect-dedicated-frame (make-frame)))))
4859 (delete-other-windows)
4860 (switch-to-buffer ibuf)
4861 (org-set-frame-title (concat "Indirect: " heading)))
4862 ((eq org-indirect-buffer-display 'current-window)
4863 (switch-to-buffer ibuf))
4864 ((eq org-indirect-buffer-display 'other-window)
4865 (pop-to-buffer ibuf))
4866 (t (error "Invalid value.")))
4867 (if (featurep 'xemacs)
4868 (save-excursion (org-mode) (turn-on-font-lock)))
4869 (narrow-to-region beg end)
4870 (show-all)
4871 (goto-char pos)
4872 (and (window-live-p cwin) (select-window cwin))))
4874 (defun org-get-indirect-buffer (&optional buffer)
4875 (setq buffer (or buffer (current-buffer)))
4876 (let ((n 1) (base (buffer-name buffer)) bname)
4877 (while (buffer-live-p
4878 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4879 (setq n (1+ n)))
4880 (condition-case nil
4881 (make-indirect-buffer buffer bname 'clone)
4882 (error (make-indirect-buffer buffer bname)))))
4884 (defun org-set-frame-title (title)
4885 "Set the title of the current frame to the string TITLE."
4886 ;; FIXME: how to name a single frame in XEmacs???
4887 (unless (featurep 'xemacs)
4888 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4890 ;;;; Structure editing
4892 ;;; Inserting headlines
4894 (defun org-previous-line-empty-p ()
4895 (save-excursion
4896 (and (not (bobp))
4897 (or (beginning-of-line 0) t)
4898 (save-match-data
4899 (looking-at "[ \t]*$")))))
4901 (defun org-insert-heading (&optional force-heading)
4902 "Insert a new heading or item with same depth at point.
4903 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4904 If point is at the beginning of a headline, insert a sibling before the
4905 current headline. If point is not at the beginning, do not split the line,
4906 but create the new headline after the current line."
4907 (interactive "P")
4908 (if (= (buffer-size) 0)
4909 (insert "\n* ")
4910 (when (or force-heading (not (org-insert-item)))
4911 (let* ((empty-line-p nil)
4912 (head (save-excursion
4913 (condition-case nil
4914 (progn
4915 (org-back-to-heading)
4916 (setq empty-line-p (org-previous-line-empty-p))
4917 (match-string 0))
4918 (error "*"))))
4919 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4920 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4921 pos hide-previous previous-pos)
4922 (cond
4923 ((and (org-on-heading-p) (bolp)
4924 (or (bobp)
4925 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4926 ;; insert before the current line
4927 (open-line (if blank 2 1)))
4928 ((and (bolp)
4929 (or (bobp)
4930 (save-excursion
4931 (backward-char 1) (not (org-invisible-p)))))
4932 ;; insert right here
4933 nil)
4935 ;; somewhere in the line
4936 (save-excursion
4937 (setq previous-pos (point-at-bol))
4938 (end-of-line)
4939 (setq hide-previous (org-invisible-p)))
4940 (and org-insert-heading-respect-content (org-show-subtree))
4941 (let ((split
4942 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4943 (save-excursion
4944 (let ((p (point)))
4945 (goto-char (point-at-bol))
4946 (and (looking-at org-complex-heading-regexp)
4947 (> p (match-beginning 4)))))))
4948 tags pos)
4949 (cond
4950 (org-insert-heading-respect-content
4951 (org-end-of-subtree nil t)
4952 (or (bolp) (newline))
4953 (or (org-previous-line-empty-p)
4954 (and blank (newline)))
4955 (open-line 1))
4956 ((org-on-heading-p)
4957 (when hide-previous
4958 (show-children)
4959 (org-show-entry))
4960 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4961 (setq tags (and (match-end 2) (match-string 2)))
4962 (and (match-end 1)
4963 (delete-region (match-beginning 1) (match-end 1)))
4964 (setq pos (point-at-bol))
4965 (or split (end-of-line 1))
4966 (delete-horizontal-space)
4967 (newline (if blank 2 1))
4968 (when tags
4969 (save-excursion
4970 (goto-char pos)
4971 (end-of-line 1)
4972 (insert " " tags)
4973 (org-set-tags nil 'align))))
4975 (or split (end-of-line 1))
4976 (newline (if blank 2 1)))))))
4977 (insert head) (just-one-space)
4978 (setq pos (point))
4979 (end-of-line 1)
4980 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4981 (when (and org-insert-heading-respect-content hide-previous)
4982 (save-excursion
4983 (goto-char previous-pos)
4984 (hide-subtree)))
4985 (run-hooks 'org-insert-heading-hook)))))
4987 (defun org-get-heading (&optional no-tags)
4988 "Return the heading of the current entry, without the stars."
4989 (save-excursion
4990 (org-back-to-heading t)
4991 (if (looking-at
4992 (if no-tags
4993 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4994 "\\*+[ \t]+\\([^\r\n]*\\)"))
4995 (match-string 1) "")))
4997 (defun org-heading-components ()
4998 "Return the components of the current heading.
4999 This is a list with the following elements:
5000 - the level as an integer
5001 - the reduced level, different if `org-odd-levels-only' is set.
5002 - the TODO keyword, or nil
5003 - the priority character, like ?A, or nil if no priority is given
5004 - the headline text itself, or the tags string if no headline text
5005 - the tags string, or nil."
5006 (save-excursion
5007 (org-back-to-heading t)
5008 (if (looking-at org-complex-heading-regexp)
5009 (list (length (match-string 1))
5010 (org-reduced-level (length (match-string 1)))
5011 (org-match-string-no-properties 2)
5012 (and (match-end 3) (aref (match-string 3) 2))
5013 (org-match-string-no-properties 4)
5014 (org-match-string-no-properties 5)))))
5016 (defun org-insert-heading-after-current ()
5017 "Insert a new heading with same level as current, after current subtree."
5018 (interactive)
5019 (org-back-to-heading)
5020 (org-insert-heading)
5021 (org-move-subtree-down)
5022 (end-of-line 1))
5024 (defun org-insert-heading-respect-content ()
5025 (interactive)
5026 (let ((org-insert-heading-respect-content t))
5027 (org-insert-heading t)))
5029 (defun org-insert-todo-heading-respect-content (&optional force-state)
5030 (interactive "P")
5031 (let ((org-insert-heading-respect-content t))
5032 (org-insert-todo-heading force-state t)))
5034 (defun org-insert-todo-heading (arg &optional force-heading)
5035 "Insert a new heading with the same level and TODO state as current heading.
5036 If the heading has no TODO state, or if the state is DONE, use the first
5037 state (TODO by default). Also with prefix arg, force first state."
5038 (interactive "P")
5039 (when (or force-heading (not (org-insert-item 'checkbox)))
5040 (org-insert-heading force-heading)
5041 (save-excursion
5042 (org-back-to-heading)
5043 (outline-previous-heading)
5044 (looking-at org-todo-line-regexp))
5045 (if (or arg
5046 (not (match-beginning 2))
5047 (member (match-string 2) org-done-keywords))
5048 (insert (car org-todo-keywords-1) " ")
5049 (insert (match-string 2) " "))
5050 (when org-provide-todo-statistics
5051 (org-update-parent-todo-statistics))))
5053 (defun org-insert-subheading (arg)
5054 "Insert a new subheading and demote it.
5055 Works for outline headings and for plain lists alike."
5056 (interactive "P")
5057 (org-insert-heading arg)
5058 (cond
5059 ((org-on-heading-p) (org-do-demote))
5060 ((org-at-item-p) (org-indent-item 1))))
5062 (defun org-insert-todo-subheading (arg)
5063 "Insert a new subheading with TODO keyword or checkbox and demote it.
5064 Works for outline headings and for plain lists alike."
5065 (interactive "P")
5066 (org-insert-todo-heading arg)
5067 (cond
5068 ((org-on-heading-p) (org-do-demote))
5069 ((org-at-item-p) (org-indent-item 1))))
5071 ;;; Promotion and Demotion
5073 (defun org-promote-subtree ()
5074 "Promote the entire subtree.
5075 See also `org-promote'."
5076 (interactive)
5077 (save-excursion
5078 (org-map-tree 'org-promote))
5079 (org-fix-position-after-promote))
5081 (defun org-demote-subtree ()
5082 "Demote the entire subtree. See `org-demote'.
5083 See also `org-promote'."
5084 (interactive)
5085 (save-excursion
5086 (org-map-tree 'org-demote))
5087 (org-fix-position-after-promote))
5090 (defun org-do-promote ()
5091 "Promote the current heading higher up the tree.
5092 If the region is active in `transient-mark-mode', promote all headings
5093 in the region."
5094 (interactive)
5095 (save-excursion
5096 (if (org-region-active-p)
5097 (org-map-region 'org-promote (region-beginning) (region-end))
5098 (org-promote)))
5099 (org-fix-position-after-promote))
5101 (defun org-do-demote ()
5102 "Demote the current heading lower down the tree.
5103 If the region is active in `transient-mark-mode', demote all headings
5104 in the region."
5105 (interactive)
5106 (save-excursion
5107 (if (org-region-active-p)
5108 (org-map-region 'org-demote (region-beginning) (region-end))
5109 (org-demote)))
5110 (org-fix-position-after-promote))
5112 (defun org-fix-position-after-promote ()
5113 "Make sure that after pro/demotion cursor position is right."
5114 (let ((pos (point)))
5115 (when (save-excursion
5116 (beginning-of-line 1)
5117 (looking-at org-todo-line-regexp)
5118 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5119 (cond ((eobp) (insert " "))
5120 ((eolp) (insert " "))
5121 ((equal (char-after) ?\ ) (forward-char 1))))))
5123 (defun org-reduced-level (l)
5124 "Compute the effective level of a heading.
5125 This takes into account the setting of `org-odd-levels-only'."
5126 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5128 (defun org-get-valid-level (level &optional change)
5129 "Rectify a level change under the influence of `org-odd-levels-only'
5130 LEVEL is a current level, CHANGE is by how much the level should be
5131 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5132 even level numbers will become the next higher odd number."
5133 (if org-odd-levels-only
5134 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5135 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5136 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5137 (max 1 (+ level change))))
5139 (if (boundp 'define-obsolete-function-alias)
5140 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5141 (define-obsolete-function-alias 'org-get-legal-level
5142 'org-get-valid-level)
5143 (define-obsolete-function-alias 'org-get-legal-level
5144 'org-get-valid-level "23.1")))
5146 (defun org-promote ()
5147 "Promote the current heading higher up the tree.
5148 If the region is active in `transient-mark-mode', promote all headings
5149 in the region."
5150 (org-back-to-heading t)
5151 (let* ((level (save-match-data (funcall outline-level)))
5152 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5153 (diff (abs (- level (length up-head) -1))))
5154 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5155 (replace-match up-head nil t)
5156 ;; Fixup tag positioning
5157 (and org-auto-align-tags (org-set-tags nil t))
5158 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5160 (defun org-demote ()
5161 "Demote the current heading lower down the tree.
5162 If the region is active in `transient-mark-mode', demote all headings
5163 in the region."
5164 (org-back-to-heading t)
5165 (let* ((level (save-match-data (funcall outline-level)))
5166 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5167 (diff (abs (- level (length down-head) -1))))
5168 (replace-match down-head nil t)
5169 ;; Fixup tag positioning
5170 (and org-auto-align-tags (org-set-tags nil t))
5171 (if org-adapt-indentation (org-fixup-indentation diff))))
5173 (defun org-map-tree (fun)
5174 "Call FUN for every heading underneath the current one."
5175 (org-back-to-heading)
5176 (let ((level (funcall outline-level)))
5177 (save-excursion
5178 (funcall fun)
5179 (while (and (progn
5180 (outline-next-heading)
5181 (> (funcall outline-level) level))
5182 (not (eobp)))
5183 (funcall fun)))))
5185 (defun org-map-region (fun beg end)
5186 "Call FUN for every heading between BEG and END."
5187 (let ((org-ignore-region t))
5188 (save-excursion
5189 (setq end (copy-marker end))
5190 (goto-char beg)
5191 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5192 (< (point) end))
5193 (funcall fun))
5194 (while (and (progn
5195 (outline-next-heading)
5196 (< (point) end))
5197 (not (eobp)))
5198 (funcall fun)))))
5200 (defun org-fixup-indentation (diff)
5201 "Change the indentation in the current entry by DIFF
5202 However, if any line in the current entry has no indentation, or if it
5203 would end up with no indentation after the change, nothing at all is done."
5204 (save-excursion
5205 (let ((end (save-excursion (outline-next-heading)
5206 (point-marker)))
5207 (prohibit (if (> diff 0)
5208 "^\\S-"
5209 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5210 col)
5211 (unless (save-excursion (end-of-line 1)
5212 (re-search-forward prohibit end t))
5213 (while (and (< (point) end)
5214 (re-search-forward "^[ \t]+" end t))
5215 (goto-char (match-end 0))
5216 (setq col (current-column))
5217 (if (< diff 0) (replace-match ""))
5218 (org-indent-to-column (+ diff col))))
5219 (move-marker end nil))))
5221 (defun org-convert-to-odd-levels ()
5222 "Convert an org-mode file with all levels allowed to one with odd levels.
5223 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5224 level 5 etc."
5225 (interactive)
5226 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5227 (let ((org-odd-levels-only nil) n)
5228 (save-excursion
5229 (goto-char (point-min))
5230 (while (re-search-forward "^\\*\\*+ " nil t)
5231 (setq n (- (length (match-string 0)) 2))
5232 (while (>= (setq n (1- n)) 0)
5233 (org-demote))
5234 (end-of-line 1))))))
5237 (defun org-convert-to-oddeven-levels ()
5238 "Convert an org-mode file with only odd levels to one with odd and even levels.
5239 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5240 section with an even level, conversion would destroy the structure of the file. An error
5241 is signaled in this case."
5242 (interactive)
5243 (goto-char (point-min))
5244 ;; First check if there are no even levels
5245 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5246 (org-show-context t)
5247 (error "Not all levels are odd in this file. Conversion not possible."))
5248 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5249 (let ((org-odd-levels-only nil) n)
5250 (save-excursion
5251 (goto-char (point-min))
5252 (while (re-search-forward "^\\*\\*+ " nil t)
5253 (setq n (/ (1- (length (match-string 0))) 2))
5254 (while (>= (setq n (1- n)) 0)
5255 (org-promote))
5256 (end-of-line 1))))))
5258 (defun org-tr-level (n)
5259 "Make N odd if required."
5260 (if org-odd-levels-only (1+ (/ n 2)) n))
5262 ;;; Vertical tree motion, cutting and pasting of subtrees
5264 (defun org-move-subtree-up (&optional arg)
5265 "Move the current subtree up past ARG headlines of the same level."
5266 (interactive "p")
5267 (org-move-subtree-down (- (prefix-numeric-value arg))))
5269 (defun org-move-subtree-down (&optional arg)
5270 "Move the current subtree down past ARG headlines of the same level."
5271 (interactive "p")
5272 (setq arg (prefix-numeric-value arg))
5273 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5274 'outline-get-last-sibling))
5275 (ins-point (make-marker))
5276 (cnt (abs arg))
5277 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5278 ;; Select the tree
5279 (org-back-to-heading)
5280 (setq beg0 (point))
5281 (save-excursion
5282 (setq ne-beg (org-back-over-empty-lines))
5283 (setq beg (point)))
5284 (save-match-data
5285 (save-excursion (outline-end-of-heading)
5286 (setq folded (org-invisible-p)))
5287 (outline-end-of-subtree))
5288 (outline-next-heading)
5289 (setq ne-end (org-back-over-empty-lines))
5290 (setq end (point))
5291 (goto-char beg0)
5292 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5293 ;; include less whitespace
5294 (save-excursion
5295 (goto-char beg)
5296 (forward-line (- ne-beg ne-end))
5297 (setq beg (point))))
5298 ;; Find insertion point, with error handling
5299 (while (> cnt 0)
5300 (or (and (funcall movfunc) (looking-at outline-regexp))
5301 (progn (goto-char beg0)
5302 (error "Cannot move past superior level or buffer limit")))
5303 (setq cnt (1- cnt)))
5304 (if (> arg 0)
5305 ;; Moving forward - still need to move over subtree
5306 (progn (org-end-of-subtree t t)
5307 (save-excursion
5308 (org-back-over-empty-lines)
5309 (or (bolp) (newline)))))
5310 (setq ne-ins (org-back-over-empty-lines))
5311 (move-marker ins-point (point))
5312 (setq txt (buffer-substring beg end))
5313 (org-save-markers-in-region beg end)
5314 (delete-region beg end)
5315 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5316 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5317 (let ((bbb (point)))
5318 (insert-before-markers txt)
5319 (org-reinstall-markers-in-region bbb)
5320 (move-marker ins-point bbb))
5321 (or (bolp) (insert "\n"))
5322 (setq ins-end (point))
5323 (goto-char ins-point)
5324 (org-skip-whitespace)
5325 (when (and (< arg 0)
5326 (org-first-sibling-p)
5327 (> ne-ins ne-beg))
5328 ;; Move whitespace back to beginning
5329 (save-excursion
5330 (goto-char ins-end)
5331 (let ((kill-whole-line t))
5332 (kill-line (- ne-ins ne-beg)) (point)))
5333 (insert (make-string (- ne-ins ne-beg) ?\n)))
5334 (move-marker ins-point nil)
5335 (org-compact-display-after-subtree-move)
5336 (org-show-empty-lines-in-parent)
5337 (unless folded
5338 (org-show-entry)
5339 (show-children)
5340 (org-cycle-hide-drawers 'children))))
5342 (defvar org-subtree-clip ""
5343 "Clipboard for cut and paste of subtrees.
5344 This is actually only a copy of the kill, because we use the normal kill
5345 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5347 (defvar org-subtree-clip-folded nil
5348 "Was the last copied subtree folded?
5349 This is used to fold the tree back after pasting.")
5351 (defun org-cut-subtree (&optional n)
5352 "Cut the current subtree into the clipboard.
5353 With prefix arg N, cut this many sequential subtrees.
5354 This is a short-hand for marking the subtree and then cutting it."
5355 (interactive "p")
5356 (org-copy-subtree n 'cut))
5358 (defun org-copy-subtree (&optional n cut force-store-markers)
5359 "Cut the current subtree into the clipboard.
5360 With prefix arg N, cut this many sequential subtrees.
5361 This is a short-hand for marking the subtree and then copying it.
5362 If CUT is non-nil, actually cut the subtree.
5363 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5364 of some markers in the region, even if CUT is non-nil. This is
5365 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5366 (interactive "p")
5367 (let (beg end folded (beg0 (point)))
5368 (if (interactive-p)
5369 (org-back-to-heading nil) ; take what looks like a subtree
5370 (org-back-to-heading t)) ; take what is really there
5371 (org-back-over-empty-lines)
5372 (setq beg (point))
5373 (skip-chars-forward " \t\r\n")
5374 (save-match-data
5375 (save-excursion (outline-end-of-heading)
5376 (setq folded (org-invisible-p)))
5377 (condition-case nil
5378 (outline-forward-same-level (1- n))
5379 (error nil))
5380 (org-end-of-subtree t t))
5381 (org-back-over-empty-lines)
5382 (setq end (point))
5383 (goto-char beg0)
5384 (when (> end beg)
5385 (setq org-subtree-clip-folded folded)
5386 (when (or cut force-store-markers)
5387 (org-save-markers-in-region beg end))
5388 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5389 (setq org-subtree-clip (current-kill 0))
5390 (message "%s: Subtree(s) with %d characters"
5391 (if cut "Cut" "Copied")
5392 (length org-subtree-clip)))))
5394 (defun org-paste-subtree (&optional level tree for-yank)
5395 "Paste the clipboard as a subtree, with modification of headline level.
5396 The entire subtree is promoted or demoted in order to match a new headline
5397 level.
5399 If the cursor is at the beginning of a headline, the same level as
5400 that headline is used to paste the tree
5402 If not, the new level is derived from the *visible* headings
5403 before and after the insertion point, and taken to be the inferior headline
5404 level of the two. So if the previous visible heading is level 3 and the
5405 next is level 4 (or vice versa), level 4 will be used for insertion.
5406 This makes sure that the subtree remains an independent subtree and does
5407 not swallow low level entries.
5409 You can also force a different level, either by using a numeric prefix
5410 argument, or by inserting the heading marker by hand. For example, if the
5411 cursor is after \"*****\", then the tree will be shifted to level 5.
5413 If optional TREE is given, use this text instead of the kill ring.
5415 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5416 move back over whitespace before inserting, and move point to the end of
5417 the inserted text when done."
5418 (interactive "P")
5419 (unless (org-kill-is-subtree-p tree)
5420 (error "%s"
5421 (substitute-command-keys
5422 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5423 (let* ((visp (not (org-invisible-p)))
5424 (txt (or tree (and kill-ring (current-kill 0))))
5425 (^re (concat "^\\(" outline-regexp "\\)"))
5426 (re (concat "\\(" outline-regexp "\\)"))
5427 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5429 (old-level (if (string-match ^re txt)
5430 (- (match-end 0) (match-beginning 0) 1)
5431 -1))
5432 (force-level (cond (level (prefix-numeric-value level))
5433 ((and (looking-at "[ \t]*$")
5434 (string-match
5435 ^re_ (buffer-substring
5436 (point-at-bol) (point))))
5437 (- (match-end 1) (match-beginning 1)))
5438 ((and (bolp)
5439 (looking-at org-outline-regexp))
5440 (- (match-end 0) (point) 1))
5441 (t nil)))
5442 (previous-level (save-excursion
5443 (condition-case nil
5444 (progn
5445 (outline-previous-visible-heading 1)
5446 (if (looking-at re)
5447 (- (match-end 0) (match-beginning 0) 1)
5449 (error 1))))
5450 (next-level (save-excursion
5451 (condition-case nil
5452 (progn
5453 (or (looking-at outline-regexp)
5454 (outline-next-visible-heading 1))
5455 (if (looking-at re)
5456 (- (match-end 0) (match-beginning 0) 1)
5458 (error 1))))
5459 (new-level (or force-level (max previous-level next-level)))
5460 (shift (if (or (= old-level -1)
5461 (= new-level -1)
5462 (= old-level new-level))
5464 (- new-level old-level)))
5465 (delta (if (> shift 0) -1 1))
5466 (func (if (> shift 0) 'org-demote 'org-promote))
5467 (org-odd-levels-only nil)
5468 beg end newend)
5469 ;; Remove the forced level indicator
5470 (if force-level
5471 (delete-region (point-at-bol) (point)))
5472 ;; Paste
5473 (beginning-of-line 1)
5474 (unless for-yank (org-back-over-empty-lines))
5475 (setq beg (point))
5476 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5477 (insert-before-markers txt)
5478 (unless (string-match "\n\\'" txt) (insert "\n"))
5479 (setq newend (point))
5480 (org-reinstall-markers-in-region beg)
5481 (setq end (point))
5482 (goto-char beg)
5483 (skip-chars-forward " \t\n\r")
5484 (setq beg (point))
5485 (if (and (org-invisible-p) visp)
5486 (save-excursion (outline-show-heading)))
5487 ;; Shift if necessary
5488 (unless (= shift 0)
5489 (save-restriction
5490 (narrow-to-region beg end)
5491 (while (not (= shift 0))
5492 (org-map-region func (point-min) (point-max))
5493 (setq shift (+ delta shift)))
5494 (goto-char (point-min))
5495 (setq newend (point-max))))
5496 (when (or (interactive-p) for-yank)
5497 (message "Clipboard pasted as level %d subtree" new-level))
5498 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5499 kill-ring
5500 (eq org-subtree-clip (current-kill 0))
5501 org-subtree-clip-folded)
5502 ;; The tree was folded before it was killed/copied
5503 (hide-subtree))
5504 (and for-yank (goto-char newend))))
5506 (defun org-kill-is-subtree-p (&optional txt)
5507 "Check if the current kill is an outline subtree, or a set of trees.
5508 Returns nil if kill does not start with a headline, or if the first
5509 headline level is not the largest headline level in the tree.
5510 So this will actually accept several entries of equal levels as well,
5511 which is OK for `org-paste-subtree'.
5512 If optional TXT is given, check this string instead of the current kill."
5513 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5514 (start-level (and kill
5515 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5516 org-outline-regexp "\\)")
5517 kill)
5518 (- (match-end 2) (match-beginning 2) 1)))
5519 (re (concat "^" org-outline-regexp))
5520 (start (1+ (or (match-beginning 2) -1))))
5521 (if (not start-level)
5522 (progn
5523 nil) ;; does not even start with a heading
5524 (catch 'exit
5525 (while (setq start (string-match re kill (1+ start)))
5526 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5527 (throw 'exit nil)))
5528 t))))
5530 (defvar org-markers-to-move nil
5531 "Markers that should be moved with a cut-and-paste operation.
5532 Those markers are stored together with their positions relative to
5533 the start of the region.")
5535 (defun org-save-markers-in-region (beg end)
5536 "Check markers in region.
5537 If these markers are between BEG and END, record their position relative
5538 to BEG, so that after moving the block of text, we can put the markers back
5539 into place.
5540 This function gets called just before an entry or tree gets cut from the
5541 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5542 called immediately, to move the markers with the entries."
5543 (setq org-markers-to-move nil)
5544 (when (featurep 'org-clock)
5545 (org-clock-save-markers-for-cut-and-paste beg end))
5546 (when (featurep 'org-agenda)
5547 (org-agenda-save-markers-for-cut-and-paste beg end)))
5549 (defun org-check-and-save-marker (marker beg end)
5550 "Check if MARKER is between BEG and END.
5551 If yes, remember the marker and the distance to BEG."
5552 (when (and (marker-buffer marker)
5553 (equal (marker-buffer marker) (current-buffer)))
5554 (if (and (>= marker beg) (< marker end))
5555 (push (cons marker (- marker beg)) org-markers-to-move))))
5557 (defun org-reinstall-markers-in-region (beg)
5558 "Move all remembered markers to their position relative to BEG."
5559 (mapc (lambda (x)
5560 (move-marker (car x) (+ beg (cdr x))))
5561 org-markers-to-move)
5562 (setq org-markers-to-move nil))
5564 (defun org-narrow-to-subtree ()
5565 "Narrow buffer to the current subtree."
5566 (interactive)
5567 (save-excursion
5568 (save-match-data
5569 (narrow-to-region
5570 (progn (org-back-to-heading) (point))
5571 (progn (org-end-of-subtree t) (point))))))
5574 ;;; Outline Sorting
5576 (defun org-sort (with-case)
5577 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5578 Optional argument WITH-CASE means sort case-sensitively."
5579 (interactive "P")
5580 (if (org-at-table-p)
5581 (org-call-with-arg 'org-table-sort-lines with-case)
5582 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5584 (defun org-sort-remove-invisible (s)
5585 (remove-text-properties 0 (length s) org-rm-props s)
5586 (while (string-match org-bracket-link-regexp s)
5587 (setq s (replace-match (if (match-end 2)
5588 (match-string 3 s)
5589 (match-string 1 s)) t t s)))
5592 (defvar org-priority-regexp) ; defined later in the file
5594 (defun org-sort-entries-or-items
5595 (&optional with-case sorting-type getkey-func compare-func property)
5596 "Sort entries on a certain level of an outline tree.
5597 If there is an active region, the entries in the region are sorted.
5598 Else, if the cursor is before the first entry, sort the top-level items.
5599 Else, the children of the entry at point are sorted.
5601 Sorting can be alphabetically, numerically, and by date/time as given by
5602 the first time stamp in the entry. The command prompts for the sorting
5603 type unless it has been given to the function through the SORTING-TYPE
5604 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5605 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5606 called with point at the beginning of the record. It must return either
5607 a string or a number that should serve as the sorting key for that record.
5609 Comparing entries ignores case by default. However, with an optional argument
5610 WITH-CASE, the sorting considers case as well."
5611 (interactive "P")
5612 (let ((case-func (if with-case 'identity 'downcase))
5613 start beg end stars re re2
5614 txt what tmp plain-list-p)
5615 ;; Find beginning and end of region to sort
5616 (cond
5617 ((org-region-active-p)
5618 ;; we will sort the region
5619 (setq end (region-end)
5620 what "region")
5621 (goto-char (region-beginning))
5622 (if (not (org-on-heading-p)) (outline-next-heading))
5623 (setq start (point)))
5624 ((org-at-item-p)
5625 ;; we will sort this plain list
5626 (org-beginning-of-item-list) (setq start (point))
5627 (org-end-of-item-list) (setq end (point))
5628 (goto-char start)
5629 (setq plain-list-p t
5630 what "plain list"))
5631 ((or (org-on-heading-p)
5632 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5633 ;; we will sort the children of the current headline
5634 (org-back-to-heading)
5635 (setq start (point)
5636 end (progn (org-end-of-subtree t t)
5637 (org-back-over-empty-lines)
5638 (point))
5639 what "children")
5640 (goto-char start)
5641 (show-subtree)
5642 (outline-next-heading))
5644 ;; we will sort the top-level entries in this file
5645 (goto-char (point-min))
5646 (or (org-on-heading-p) (outline-next-heading))
5647 (setq start (point) end (point-max) what "top-level")
5648 (goto-char start)
5649 (show-all)))
5651 (setq beg (point))
5652 (if (>= beg end) (error "Nothing to sort"))
5654 (unless plain-list-p
5655 (looking-at "\\(\\*+\\)")
5656 (setq stars (match-string 1)
5657 re (concat "^" (regexp-quote stars) " +")
5658 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5659 txt (buffer-substring beg end))
5660 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5661 (if (and (not (equal stars "*")) (string-match re2 txt))
5662 (error "Region to sort contains a level above the first entry")))
5664 (unless sorting-type
5665 (message
5666 (if plain-list-p
5667 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5668 "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:")
5669 what)
5670 (setq sorting-type (read-char-exclusive))
5672 (and (= (downcase sorting-type) ?f)
5673 (setq getkey-func
5674 (org-ido-completing-read "Sort using function: "
5675 obarray 'fboundp t nil nil))
5676 (setq getkey-func (intern getkey-func)))
5678 (and (= (downcase sorting-type) ?r)
5679 (setq property
5680 (org-ido-completing-read "Property: "
5681 (mapcar 'list (org-buffer-property-keys t))
5682 nil t))))
5684 (message "Sorting entries...")
5686 (save-restriction
5687 (narrow-to-region start end)
5689 (let ((dcst (downcase sorting-type))
5690 (now (current-time)))
5691 (sort-subr
5692 (/= dcst sorting-type)
5693 ;; This function moves to the beginning character of the "record" to
5694 ;; be sorted.
5695 (if plain-list-p
5696 (lambda nil
5697 (if (org-at-item-p) t (goto-char (point-max))))
5698 (lambda nil
5699 (if (re-search-forward re nil t)
5700 (goto-char (match-beginning 0))
5701 (goto-char (point-max)))))
5702 ;; This function moves to the last character of the "record" being
5703 ;; sorted.
5704 (if plain-list-p
5705 'org-end-of-item
5706 (lambda nil
5707 (save-match-data
5708 (condition-case nil
5709 (outline-forward-same-level 1)
5710 (error
5711 (goto-char (point-max)))))))
5713 ;; This function returns the value that gets sorted against.
5714 (if plain-list-p
5715 (lambda nil
5716 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5717 (cond
5718 ((= dcst ?n)
5719 (string-to-number (buffer-substring (match-end 0)
5720 (point-at-eol))))
5721 ((= dcst ?a)
5722 (buffer-substring (match-end 0) (point-at-eol)))
5723 ((= dcst ?t)
5724 (if (re-search-forward org-ts-regexp
5725 (point-at-eol) t)
5726 (org-time-string-to-time (match-string 0))
5727 now))
5728 ((= dcst ?f)
5729 (if getkey-func
5730 (progn
5731 (setq tmp (funcall getkey-func))
5732 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5733 tmp)
5734 (error "Invalid key function `%s'" getkey-func)))
5735 (t (error "Invalid sorting type `%c'" sorting-type)))))
5736 (lambda nil
5737 (cond
5738 ((= dcst ?n)
5739 (if (looking-at org-complex-heading-regexp)
5740 (string-to-number (match-string 4))
5741 nil))
5742 ((= dcst ?a)
5743 (if (looking-at org-complex-heading-regexp)
5744 (funcall case-func (match-string 4))
5745 nil))
5746 ((= dcst ?t)
5747 (if (re-search-forward org-ts-regexp
5748 (save-excursion
5749 (forward-line 2)
5750 (point)) t)
5751 (org-time-string-to-time (match-string 0))
5752 now))
5753 ((= dcst ?p)
5754 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5755 (string-to-char (match-string 2))
5756 org-default-priority))
5757 ((= dcst ?r)
5758 (or (org-entry-get nil property) ""))
5759 ((= dcst ?o)
5760 (if (looking-at org-complex-heading-regexp)
5761 (- 9999 (length (member (match-string 2)
5762 org-todo-keywords-1)))))
5763 ((= dcst ?f)
5764 (if getkey-func
5765 (progn
5766 (setq tmp (funcall getkey-func))
5767 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5768 tmp)
5769 (error "Invalid key function `%s'" getkey-func)))
5770 (t (error "Invalid sorting type `%c'" sorting-type)))))
5772 (cond
5773 ((= dcst ?a) 'string<)
5774 ((= dcst ?t) 'time-less-p)
5775 ((= dcst ?f) compare-func)
5776 (t nil)))))
5777 (message "Sorting entries...done")))
5779 (defun org-do-sort (table what &optional with-case sorting-type)
5780 "Sort TABLE of WHAT according to SORTING-TYPE.
5781 The user will be prompted for the SORTING-TYPE if the call to this
5782 function does not specify it. WHAT is only for the prompt, to indicate
5783 what is being sorted. The sorting key will be extracted from
5784 the car of the elements of the table.
5785 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5786 (unless sorting-type
5787 (message
5788 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5789 what)
5790 (setq sorting-type (read-char-exclusive)))
5791 (let ((dcst (downcase sorting-type))
5792 extractfun comparefun)
5793 ;; Define the appropriate functions
5794 (cond
5795 ((= dcst ?n)
5796 (setq extractfun 'string-to-number
5797 comparefun (if (= dcst sorting-type) '< '>)))
5798 ((= dcst ?a)
5799 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5800 (lambda(x) (downcase (org-sort-remove-invisible x))))
5801 comparefun (if (= dcst sorting-type)
5802 'string<
5803 (lambda (a b) (and (not (string< a b))
5804 (not (string= a b)))))))
5805 ((= dcst ?t)
5806 (setq extractfun
5807 (lambda (x)
5808 (if (string-match org-ts-regexp x)
5809 (time-to-seconds
5810 (org-time-string-to-time (match-string 0 x)))
5812 comparefun (if (= dcst sorting-type) '< '>)))
5813 (t (error "Invalid sorting type `%c'" sorting-type)))
5815 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5816 table)
5817 (lambda (a b) (funcall comparefun (car a) (car b))))))
5819 ;;; Editing source examples
5821 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5822 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5823 (defvar org-edit-src-force-single-line nil)
5824 (defvar org-edit-src-from-org-mode nil)
5825 (defvar org-edit-src-picture nil)
5827 (define-minor-mode org-exit-edit-mode
5828 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5830 (defun org-edit-src-code ()
5831 "Edit the source code example at point.
5832 An indirect buffer is created, and that buffer is then narrowed to the
5833 example at point and switched to the correct language mode. When done,
5834 exit by killing the buffer with \\[org-edit-src-exit]."
5835 (interactive)
5836 (let ((line (org-current-line))
5837 (case-fold-search t)
5838 (msg (substitute-command-keys
5839 "Edit, then exit with C-c ' (C-c and single quote)"))
5840 (info (org-edit-src-find-region-and-lang))
5841 (org-mode-p (eq major-mode 'org-mode))
5842 beg end lang lang-f single lfmt)
5843 (if (not info)
5845 (setq beg (nth 0 info)
5846 end (nth 1 info)
5847 lang (nth 2 info)
5848 single (nth 3 info)
5849 lfmt (nth 4 info)
5850 lang-f (intern (concat lang "-mode")))
5851 (unless (functionp lang-f)
5852 (error "No such language mode: %s" lang-f))
5853 (goto-line line)
5854 (if (get-buffer "*Org Edit Src Example*")
5855 (kill-buffer "*Org Edit Src Example*"))
5856 (switch-to-buffer (make-indirect-buffer (current-buffer)
5857 "*Org Edit Src Example*"))
5858 (narrow-to-region beg end)
5859 (remove-text-properties beg end '(display nil invisible nil
5860 intangible nil))
5861 (let ((org-inhibit-startup t))
5862 (funcall lang-f))
5863 (set (make-local-variable 'org-edit-src-force-single-line) single)
5864 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5865 (when lfmt
5866 (set (make-local-variable 'org-coderef-label-format) lfmt))
5867 (when org-mode-p
5868 (goto-char (point-min))
5869 (while (re-search-forward "^," nil t)
5870 (replace-match "")))
5871 (goto-line line)
5872 (org-exit-edit-mode)
5873 (org-set-local 'header-line-format msg)
5874 (message "%s" msg)
5875 t)))
5877 (defun org-edit-fixed-width-region ()
5878 "Edit the fixed-width ascii drawing at point.
5879 This must be a region where each line starts with a colon followed by
5880 a space character.
5881 An indirect buffer is created, and that buffer is then narrowed to the
5882 example at point and switched to artist-mode. When done,
5883 exit by killing the buffer with \\[org-edit-src-exit]."
5884 (interactive)
5885 (let ((line (org-current-line))
5886 (case-fold-search t)
5887 (msg (substitute-command-keys
5888 "Edit, then exit with C-c ' (C-c and single quote)"))
5889 (org-mode-p (eq major-mode 'org-mode))
5890 beg end)
5891 (beginning-of-line 1)
5892 (if (looking-at "[ \t]*[^:\n \t]")
5894 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5895 (setq beg (point) end beg)
5896 (save-excursion
5897 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5898 (setq beg (point-at-bol 2))
5899 (setq beg (point))))
5900 (save-excursion
5901 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5902 (setq end (1- (match-beginning 0)))
5903 (setq end (point))))
5904 (goto-line line))
5905 (if (get-buffer "*Org Edit Picture*")
5906 (kill-buffer "*Org Edit Picture*"))
5907 (switch-to-buffer (make-indirect-buffer (current-buffer)
5908 "*Org Edit Picture*"))
5909 (narrow-to-region beg end)
5910 (remove-text-properties beg end '(display nil invisible nil
5911 intangible nil))
5912 (when (fboundp 'font-lock-unfontify-region)
5913 (font-lock-unfontify-region (point-min) (point-max)))
5914 (cond
5915 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5916 (fundamental-mode)
5917 (artist-mode 1))
5918 (t (funcall org-edit-fixed-width-region-mode)))
5919 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5920 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5921 (set (make-local-variable 'org-edit-src-picture) t)
5922 (goto-char (point-min))
5923 (while (re-search-forward "^[ \t]*: ?" nil t)
5924 (replace-match ""))
5925 (goto-line line)
5926 (org-exit-edit-mode)
5927 (org-set-local 'header-line-format msg)
5928 (message "%s" msg)
5929 t)))
5932 (defun org-edit-src-find-region-and-lang ()
5933 "Find the region and language for a local edit.
5934 Return a list with beginning and end of the region, a string representing
5935 the language, a switch telling of the content should be in a single line."
5936 (let ((re-list
5937 (append
5938 org-edit-src-region-extra
5940 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5941 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5942 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5943 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5944 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5945 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5946 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5947 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5948 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5949 ("^#\\+html:" "\n" "html" single-line)
5950 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5951 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5952 ("^#\\+latex:" "\n" "latex" single-line)
5953 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5954 ("^#\\+ascii:" "\n" "ascii" single-line)
5956 (pos (point))
5957 re1 re2 single beg end lang lfmt match-re1)
5958 (catch 'exit
5959 (while (setq entry (pop re-list))
5960 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5961 single (nth 3 entry))
5962 (save-excursion
5963 (if (or (looking-at re1)
5964 (re-search-backward re1 nil t))
5965 (progn
5966 (setq match-re1 (match-string 0))
5967 (setq beg (match-end 0)
5968 lang (org-edit-src-get-lang lang)
5969 lfmt (org-edit-src-get-label-format match-re1))
5970 (if (and (re-search-forward re2 nil t)
5971 (>= (match-end 0) pos))
5972 (throw 'exit (list beg (match-beginning 0)
5973 lang single lfmt))))
5974 (if (or (looking-at re2)
5975 (re-search-forward re2 nil t))
5976 (progn
5977 (setq end (match-beginning 0))
5978 (if (and (re-search-backward re1 nil t)
5979 (<= (match-beginning 0) pos))
5980 (progn
5981 (setq lfmt (org-edit-src-get-label-format
5982 (match-string 0)))
5983 (throw 'exit
5984 (list (match-end 0) end
5985 (org-edit-src-get-lang lang)
5986 single lfmt))))))))))))
5988 (defun org-edit-src-get-lang (lang)
5989 "Extract the src language."
5990 (let ((m (match-string 0)))
5991 (cond
5992 ((stringp lang) lang)
5993 ((integerp lang) (match-string lang))
5994 ((and (eq lang 'lang)
5995 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5996 (match-string 1 m))
5997 ((and (eq lang 'style)
5998 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5999 (match-string 1 m))
6000 (t "fundamental"))))
6002 (defun org-edit-src-get-label-format (s)
6003 "Extract the label format."
6004 (save-match-data
6005 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6006 (match-string 1 s))))
6008 (defun org-edit-src-exit ()
6009 "Exit special edit and protect problematic lines."
6010 (interactive)
6011 (unless (buffer-base-buffer (current-buffer))
6012 (error "This is not an indirect buffer, something is wrong..."))
6013 (unless (> (point-min) 1)
6014 (error "This buffer is not narrowed, something is wrong..."))
6015 (goto-char (point-min))
6016 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6017 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6018 (when (org-bound-and-true-p org-edit-src-force-single-line)
6019 (goto-char (point-min))
6020 (while (re-search-forward "\n" nil t)
6021 (replace-match " "))
6022 (goto-char (point-min))
6023 (if (looking-at "\\s-*") (replace-match " "))
6024 (if (re-search-forward "\\s-+\\'" nil t)
6025 (replace-match "")))
6026 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6027 (goto-char (point-min))
6028 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6029 (replace-match ",\\1"))
6030 (when font-lock-mode
6031 (font-lock-unfontify-region (point-min) (point-max)))
6032 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6033 (when (org-bound-and-true-p org-edit-src-picture)
6034 (untabify (point-min) (point-max))
6035 (goto-char (point-min))
6036 (while (re-search-forward "^" nil t)
6037 (replace-match ": "))
6038 (when font-lock-mode
6039 (font-lock-unfontify-region (point-min) (point-max)))
6040 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6041 (kill-buffer (current-buffer))
6042 (and (org-mode-p) (org-restart-font-lock)))
6045 ;;; The orgstruct minor mode
6047 ;; Define a minor mode which can be used in other modes in order to
6048 ;; integrate the org-mode structure editing commands.
6050 ;; This is really a hack, because the org-mode structure commands use
6051 ;; keys which normally belong to the major mode. Here is how it
6052 ;; works: The minor mode defines all the keys necessary to operate the
6053 ;; structure commands, but wraps the commands into a function which
6054 ;; tests if the cursor is currently at a headline or a plain list
6055 ;; item. If that is the case, the structure command is used,
6056 ;; temporarily setting many Org-mode variables like regular
6057 ;; expressions for filling etc. However, when any of those keys is
6058 ;; used at a different location, function uses `key-binding' to look
6059 ;; up if the key has an associated command in another currently active
6060 ;; keymap (minor modes, major mode, global), and executes that
6061 ;; command. There might be problems if any of the keys is otherwise
6062 ;; used as a prefix key.
6064 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6065 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6066 ;; addresses this by checking explicitly for both bindings.
6068 (defvar orgstruct-mode-map (make-sparse-keymap)
6069 "Keymap for the minor `orgstruct-mode'.")
6071 (defvar org-local-vars nil
6072 "List of local variables, for use by `orgstruct-mode'")
6074 ;;;###autoload
6075 (define-minor-mode orgstruct-mode
6076 "Toggle the minor more `orgstruct-mode'.
6077 This mode is for using Org-mode structure commands in other modes.
6078 The following key behave as if Org-mode was active, if the cursor
6079 is on a headline, or on a plain list item (both in the definition
6080 of Org-mode).
6082 M-up Move entry/item up
6083 M-down Move entry/item down
6084 M-left Promote
6085 M-right Demote
6086 M-S-up Move entry/item up
6087 M-S-down Move entry/item down
6088 M-S-left Promote subtree
6089 M-S-right Demote subtree
6090 M-q Fill paragraph and items like in Org-mode
6091 C-c ^ Sort entries
6092 C-c - Cycle list bullet
6093 TAB Cycle item visibility
6094 M-RET Insert new heading/item
6095 S-M-RET Insert new TODO heading / Checkbox item
6096 C-c C-c Set tags / toggle checkbox"
6097 nil " OrgStruct" nil
6098 (org-load-modules-maybe)
6099 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6101 ;;;###autoload
6102 (defun turn-on-orgstruct ()
6103 "Unconditionally turn on `orgstruct-mode'."
6104 (orgstruct-mode 1))
6106 ;;;###autoload
6107 (defun turn-on-orgstruct++ ()
6108 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6109 In addition to setting orgstruct-mode, this also exports all indentation and
6110 autofilling variables from org-mode into the buffer. Note that turning
6111 off orgstruct-mode will *not* remove these additional settings."
6112 (orgstruct-mode 1)
6113 (let (var val)
6114 (mapc
6115 (lambda (x)
6116 (when (string-match
6117 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6118 (symbol-name (car x)))
6119 (setq var (car x) val (nth 1 x))
6120 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6121 org-local-vars)))
6123 (defun orgstruct-error ()
6124 "Error when there is no default binding for a structure key."
6125 (interactive)
6126 (error "This key has no function outside structure elements"))
6128 (defun orgstruct-setup ()
6129 "Setup orgstruct keymaps."
6130 (let ((nfunc 0)
6131 (bindings
6132 (list
6133 '([(meta up)] org-metaup)
6134 '([(meta down)] org-metadown)
6135 '([(meta left)] org-metaleft)
6136 '([(meta right)] org-metaright)
6137 '([(meta shift up)] org-shiftmetaup)
6138 '([(meta shift down)] org-shiftmetadown)
6139 '([(meta shift left)] org-shiftmetaleft)
6140 '([(meta shift right)] org-shiftmetaright)
6141 '([(shift up)] org-shiftup)
6142 '([(shift down)] org-shiftdown)
6143 '([(shift left)] org-shiftleft)
6144 '([(shift right)] org-shiftright)
6145 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6146 '("\M-q" fill-paragraph)
6147 '("\C-c^" org-sort)
6148 '("\C-c-" org-cycle-list-bullet)))
6149 elt key fun cmd)
6150 (while (setq elt (pop bindings))
6151 (setq nfunc (1+ nfunc))
6152 (setq key (org-key (car elt))
6153 fun (nth 1 elt)
6154 cmd (orgstruct-make-binding fun nfunc key))
6155 (org-defkey orgstruct-mode-map key cmd))
6157 ;; Special treatment needed for TAB and RET
6158 (org-defkey orgstruct-mode-map [(tab)]
6159 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6160 (org-defkey orgstruct-mode-map "\C-i"
6161 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6163 (org-defkey orgstruct-mode-map "\M-\C-m"
6164 (orgstruct-make-binding 'org-insert-heading 105
6165 "\M-\C-m" [(meta return)]))
6166 (org-defkey orgstruct-mode-map [(meta return)]
6167 (orgstruct-make-binding 'org-insert-heading 106
6168 [(meta return)] "\M-\C-m"))
6170 (org-defkey orgstruct-mode-map [(shift meta return)]
6171 (orgstruct-make-binding 'org-insert-todo-heading 107
6172 [(meta return)] "\M-\C-m"))
6174 (unless org-local-vars
6175 (setq org-local-vars (org-get-local-variables)))
6179 (defun orgstruct-make-binding (fun n &rest keys)
6180 "Create a function for binding in the structure minor mode.
6181 FUN is the command to call inside a table. N is used to create a unique
6182 command name. KEYS are keys that should be checked in for a command
6183 to execute outside of tables."
6184 (eval
6185 (list 'defun
6186 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6187 '(arg)
6188 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6189 "Outside of structure, run the binding of `"
6190 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6191 "'.")
6192 '(interactive "p")
6193 (list 'if
6194 '(org-context-p 'headline 'item)
6195 (list 'org-run-like-in-org-mode (list 'quote fun))
6196 (list 'let '(orgstruct-mode)
6197 (list 'call-interactively
6198 (append '(or)
6199 (mapcar (lambda (k)
6200 (list 'key-binding k))
6201 keys)
6202 '('orgstruct-error))))))))
6204 (defun org-context-p (&rest contexts)
6205 "Check if local context is any of CONTEXTS.
6206 Possible values in the list of contexts are `table', `headline', and `item'."
6207 (let ((pos (point)))
6208 (goto-char (point-at-bol))
6209 (prog1 (or (and (memq 'table contexts)
6210 (looking-at "[ \t]*|"))
6211 (and (memq 'headline contexts)
6212 ;;????????? (looking-at "\\*+"))
6213 (looking-at outline-regexp))
6214 (and (memq 'item contexts)
6215 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6216 (goto-char pos))))
6218 (defun org-get-local-variables ()
6219 "Return a list of all local variables in an org-mode buffer."
6220 (let (varlist)
6221 (with-current-buffer (get-buffer-create "*Org tmp*")
6222 (erase-buffer)
6223 (org-mode)
6224 (setq varlist (buffer-local-variables)))
6225 (kill-buffer "*Org tmp*")
6226 (delq nil
6227 (mapcar
6228 (lambda (x)
6229 (setq x
6230 (if (symbolp x)
6231 (list x)
6232 (list (car x) (list 'quote (cdr x)))))
6233 (if (string-match
6234 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6235 (symbol-name (car x)))
6236 x nil))
6237 varlist))))
6239 ;;;###autoload
6240 (defun org-run-like-in-org-mode (cmd)
6241 (org-load-modules-maybe)
6242 (unless org-local-vars
6243 (setq org-local-vars (org-get-local-variables)))
6244 (eval (list 'let org-local-vars
6245 (list 'call-interactively (list 'quote cmd)))))
6247 ;;;; Archiving
6249 (defun org-get-category (&optional pos)
6250 "Get the category applying to position POS."
6251 (get-text-property (or pos (point)) 'org-category))
6253 (defun org-refresh-category-properties ()
6254 "Refresh category text properties in the buffer."
6255 (let ((def-cat (cond
6256 ((null org-category)
6257 (if buffer-file-name
6258 (file-name-sans-extension
6259 (file-name-nondirectory buffer-file-name))
6260 "???"))
6261 ((symbolp org-category) (symbol-name org-category))
6262 (t org-category)))
6263 beg end cat pos optionp)
6264 (org-unmodified
6265 (save-excursion
6266 (save-restriction
6267 (widen)
6268 (goto-char (point-min))
6269 (put-text-property (point) (point-max) 'org-category def-cat)
6270 (while (re-search-forward
6271 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6272 (setq pos (match-end 0)
6273 optionp (equal (char-after (match-beginning 0)) ?#)
6274 cat (org-trim (match-string 2)))
6275 (if optionp
6276 (setq beg (point-at-bol) end (point-max))
6277 (org-back-to-heading t)
6278 (setq beg (point) end (org-end-of-subtree t t)))
6279 (put-text-property beg end 'org-category cat)
6280 (goto-char pos)))))))
6283 ;;;; Link Stuff
6285 ;;; Link abbreviations
6287 (defun org-link-expand-abbrev (link)
6288 "Apply replacements as defined in `org-link-abbrev-alist."
6289 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6290 (let* ((key (match-string 1 link))
6291 (as (or (assoc key org-link-abbrev-alist-local)
6292 (assoc key org-link-abbrev-alist)))
6293 (tag (and (match-end 2) (match-string 3 link)))
6294 rpl)
6295 (if (not as)
6296 link
6297 (setq rpl (cdr as))
6298 (cond
6299 ((symbolp rpl) (funcall rpl tag))
6300 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6301 ((string-match "%h" rpl)
6302 (replace-match (url-hexify-string (or tag "")) t t rpl))
6303 (t (concat rpl tag)))))
6304 link))
6306 ;;; Storing and inserting links
6308 (defvar org-insert-link-history nil
6309 "Minibuffer history for links inserted with `org-insert-link'.")
6311 (defvar org-stored-links nil
6312 "Contains the links stored with `org-store-link'.")
6314 (defvar org-store-link-plist nil
6315 "Plist with info about the most recently link created with `org-store-link'.")
6317 (defvar org-link-protocols nil
6318 "Link protocols added to Org-mode using `org-add-link-type'.")
6320 (defvar org-store-link-functions nil
6321 "List of functions that are called to create and store a link.
6322 Each function will be called in turn until one returns a non-nil
6323 value. Each function should check if it is responsible for creating
6324 this link (for example by looking at the major mode).
6325 If not, it must exit and return nil.
6326 If yes, it should return a non-nil value after a calling
6327 `org-store-link-props' with a list of properties and values.
6328 Special properties are:
6330 :type The link prefix. like \"http\". This must be given.
6331 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6332 This is obligatory as well.
6333 :description Optional default description for the second pair
6334 of brackets in an Org-mode link. The user can still change
6335 this when inserting this link into an Org-mode buffer.
6337 In addition to these, any additional properties can be specified
6338 and then used in remember templates.")
6340 (defun org-add-link-type (type &optional follow export)
6341 "Add TYPE to the list of `org-link-types'.
6342 Re-compute all regular expressions depending on `org-link-types'
6344 FOLLOW and EXPORT are two functions.
6346 FOLLOW should take the link path as the single argument and do whatever
6347 is necessary to follow the link, for example find a file or display
6348 a mail message.
6350 EXPORT should format the link path for export to one of the export formats.
6351 It should be a function accepting three arguments:
6353 path the path of the link, the text after the prefix (like \"http:\")
6354 desc the description of the link, if any, nil if there was no description
6355 format the export format, a symbol like `html' or `latex'.
6357 The function may use the FORMAT information to return different values
6358 depending on the format. The return value will be put literally into
6359 the exported file.
6360 Org-mode has a built-in default for exporting links. If you are happy with
6361 this default, there is no need to define an export function for the link
6362 type. For a simple example of an export function, see `org-bbdb.el'."
6363 (add-to-list 'org-link-types type t)
6364 (org-make-link-regexps)
6365 (if (assoc type org-link-protocols)
6366 (setcdr (assoc type org-link-protocols) (list follow export))
6367 (push (list type follow export) org-link-protocols)))
6369 ;;;###autoload
6370 (defun org-store-link (arg)
6371 "\\<org-mode-map>Store an org-link to the current location.
6372 This link is added to `org-stored-links' and can later be inserted
6373 into an org-buffer with \\[org-insert-link].
6375 For some link types, a prefix arg is interpreted:
6376 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6377 For file links, arg negates `org-context-in-file-links'."
6378 (interactive "P")
6379 (org-load-modules-maybe)
6380 (setq org-store-link-plist nil) ; reset
6381 (let (link cpltxt desc description search txt)
6382 (cond
6384 ((run-hook-with-args-until-success 'org-store-link-functions)
6385 (setq link (plist-get org-store-link-plist :link)
6386 desc (or (plist-get org-store-link-plist :description) link)))
6388 ((equal (buffer-name) "*Org Edit Src Example*")
6389 (let (label gc)
6390 (while (or (not label)
6391 (save-excursion
6392 (save-restriction
6393 (widen)
6394 (goto-char (point-min))
6395 (re-search-forward
6396 (regexp-quote (format org-coderef-label-format label))
6397 nil t))))
6398 (when label (message "Label exists already") (sit-for 2))
6399 (setq label (read-string "Code line label: " label)))
6400 (end-of-line 1)
6401 (setq link (format org-coderef-label-format label))
6402 (setq gc (- 79 (length link)))
6403 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6404 (insert link)
6405 (setq link (concat "(" label ")") desc nil)))
6407 ((eq major-mode 'calendar-mode)
6408 (let ((cd (calendar-cursor-to-date)))
6409 (setq link
6410 (format-time-string
6411 (car org-time-stamp-formats)
6412 (apply 'encode-time
6413 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6414 nil nil nil))))
6415 (org-store-link-props :type "calendar" :date cd)))
6417 ((eq major-mode 'w3-mode)
6418 (setq cpltxt (url-view-url t)
6419 link (org-make-link cpltxt))
6420 (org-store-link-props :type "w3" :url (url-view-url t)))
6422 ((eq major-mode 'w3m-mode)
6423 (setq cpltxt (or w3m-current-title w3m-current-url)
6424 link (org-make-link w3m-current-url))
6425 (org-store-link-props :type "w3m" :url (url-view-url t)))
6427 ((setq search (run-hook-with-args-until-success
6428 'org-create-file-search-functions))
6429 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6430 "::" search))
6431 (setq cpltxt (or description link)))
6433 ((eq major-mode 'image-mode)
6434 (setq cpltxt (concat "file:"
6435 (abbreviate-file-name buffer-file-name))
6436 link (org-make-link cpltxt))
6437 (org-store-link-props :type "image" :file buffer-file-name))
6439 ((eq major-mode 'dired-mode)
6440 ;; link to the file in the current line
6441 (setq cpltxt (concat "file:"
6442 (abbreviate-file-name
6443 (expand-file-name
6444 (dired-get-filename nil t))))
6445 link (org-make-link cpltxt)))
6447 ((and buffer-file-name (org-mode-p))
6448 (cond
6449 ((org-in-regexp "<<\\(.*?\\)>>")
6450 (setq cpltxt
6451 (concat "file:"
6452 (abbreviate-file-name buffer-file-name)
6453 "::" (match-string 1))
6454 link (org-make-link cpltxt)))
6455 ((and (featurep 'org-id)
6456 (or (eq org-link-to-org-use-id t)
6457 (and (eq org-link-to-org-use-id 'create-if-interactive)
6458 (interactive-p))
6459 (and org-link-to-org-use-id
6460 (condition-case nil
6461 (org-entry-get nil "ID")
6462 (error nil)))))
6463 ;; We can make a link using the ID.
6464 (setq link (condition-case nil
6465 (prog1 (org-id-store-link)
6466 (setq desc (plist-get org-store-link-plist
6467 :description)))
6468 (error
6469 ;; probably before first headline, link to file only
6470 (concat "file:"
6471 (abbreviate-file-name buffer-file-name))))))
6473 ;; Just link to current headline
6474 (setq cpltxt (concat "file:"
6475 (abbreviate-file-name buffer-file-name)))
6476 ;; Add a context search string
6477 (when (org-xor org-context-in-file-links arg)
6478 (setq txt (cond
6479 ((org-on-heading-p) nil)
6480 ((org-region-active-p)
6481 (buffer-substring (region-beginning) (region-end)))
6482 (t nil)))
6483 (when (or (null txt) (string-match "\\S-" txt))
6484 (setq cpltxt
6485 (concat cpltxt "::"
6486 (condition-case nil
6487 (org-make-org-heading-search-string txt)
6488 (error "")))
6489 desc "NONE")))
6490 (if (string-match "::\\'" cpltxt)
6491 (setq cpltxt (substring cpltxt 0 -2)))
6492 (setq link (org-make-link cpltxt)))))
6494 ((buffer-file-name (buffer-base-buffer))
6495 ;; Just link to this file here.
6496 (setq cpltxt (concat "file:"
6497 (abbreviate-file-name
6498 (buffer-file-name (buffer-base-buffer)))))
6499 ;; Add a context string
6500 (when (org-xor org-context-in-file-links arg)
6501 (setq txt (if (org-region-active-p)
6502 (buffer-substring (region-beginning) (region-end))
6503 (buffer-substring (point-at-bol) (point-at-eol))))
6504 ;; Only use search option if there is some text.
6505 (when (string-match "\\S-" txt)
6506 (setq cpltxt
6507 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6508 desc "NONE")))
6509 (setq link (org-make-link cpltxt)))
6511 ((interactive-p)
6512 (error "Cannot link to a buffer which is not visiting a file"))
6514 (t (setq link nil)))
6516 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6517 (setq link (or link cpltxt)
6518 desc (or desc cpltxt))
6519 (if (equal desc "NONE") (setq desc nil))
6521 (if (and (interactive-p) link)
6522 (progn
6523 (setq org-stored-links
6524 (cons (list link desc) org-stored-links))
6525 (message "Stored: %s" (or desc link)))
6526 (and link (org-make-link-string link desc)))))
6528 (defun org-store-link-props (&rest plist)
6529 "Store link properties, extract names and addresses."
6530 (let (x adr)
6531 (when (setq x (plist-get plist :from))
6532 (setq adr (mail-extract-address-components x))
6533 (setq plist (plist-put plist :fromname (car adr)))
6534 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6535 (when (setq x (plist-get plist :to))
6536 (setq adr (mail-extract-address-components x))
6537 (setq plist (plist-put plist :toname (car adr)))
6538 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6539 (let ((from (plist-get plist :from))
6540 (to (plist-get plist :to)))
6541 (when (and from to org-from-is-user-regexp)
6542 (setq plist
6543 (plist-put plist :fromto
6544 (if (string-match org-from-is-user-regexp from)
6545 (concat "to %t")
6546 (concat "from %f"))))))
6547 (setq org-store-link-plist plist))
6549 (defun org-add-link-props (&rest plist)
6550 "Add these properties to the link property list."
6551 (let (key value)
6552 (while plist
6553 (setq key (pop plist) value (pop plist))
6554 (setq org-store-link-plist
6555 (plist-put org-store-link-plist key value)))))
6557 (defun org-email-link-description (&optional fmt)
6558 "Return the description part of an email link.
6559 This takes information from `org-store-link-plist' and formats it
6560 according to FMT (default from `org-email-link-description-format')."
6561 (setq fmt (or fmt org-email-link-description-format))
6562 (let* ((p org-store-link-plist)
6563 (to (plist-get p :toaddress))
6564 (from (plist-get p :fromaddress))
6565 (table
6566 (list
6567 (cons "%c" (plist-get p :fromto))
6568 (cons "%F" (plist-get p :from))
6569 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6570 (cons "%T" (plist-get p :to))
6571 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6572 (cons "%s" (plist-get p :subject))
6573 (cons "%m" (plist-get p :message-id)))))
6574 (when (string-match "%c" fmt)
6575 ;; Check if the user wrote this message
6576 (if (and org-from-is-user-regexp from to
6577 (save-match-data (string-match org-from-is-user-regexp from)))
6578 (setq fmt (replace-match "to %t" t t fmt))
6579 (setq fmt (replace-match "from %f" t t fmt))))
6580 (org-replace-escapes fmt table)))
6582 (defun org-make-org-heading-search-string (&optional string heading)
6583 "Make search string for STRING or current headline."
6584 (interactive)
6585 (let ((s (or string (org-get-heading))))
6586 (unless (and string (not heading))
6587 ;; We are using a headline, clean up garbage in there.
6588 (if (string-match org-todo-regexp s)
6589 (setq s (replace-match "" t t s)))
6590 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6591 (setq s (replace-match "" t t s)))
6592 (setq s (org-trim s))
6593 (if (string-match (concat "^\\(" org-quote-string "\\|"
6594 org-comment-string "\\)") s)
6595 (setq s (replace-match "" t t s)))
6596 (while (string-match org-ts-regexp s)
6597 (setq s (replace-match "" t t s))))
6598 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6599 (setq s (replace-match " " t t s)))
6600 (or string (setq s (concat "*" s))) ; Add * for headlines
6601 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6603 (defun org-make-link (&rest strings)
6604 "Concatenate STRINGS."
6605 (apply 'concat strings))
6607 (defun org-make-link-string (link &optional description)
6608 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6609 (unless (string-match "\\S-" link)
6610 (error "Empty link"))
6611 (when (stringp description)
6612 ;; Remove brackets from the description, they are fatal.
6613 (while (string-match "\\[" description)
6614 (setq description (replace-match "{" t t description)))
6615 (while (string-match "\\]" description)
6616 (setq description (replace-match "}" t t description))))
6617 (when (equal (org-link-escape link) description)
6618 ;; No description needed, it is identical
6619 (setq description nil))
6620 (when (and (not description)
6621 (not (equal link (org-link-escape link))))
6622 (setq description (org-extract-attributes link)))
6623 (concat "[[" (org-link-escape link) "]"
6624 (if description (concat "[" description "]") "")
6625 "]"))
6627 (defconst org-link-escape-chars
6628 '((?\ . "%20")
6629 (?\[ . "%5B")
6630 (?\] . "%5D")
6631 (?\340 . "%E0") ; `a
6632 (?\342 . "%E2") ; ^a
6633 (?\347 . "%E7") ; ,c
6634 (?\350 . "%E8") ; `e
6635 (?\351 . "%E9") ; 'e
6636 (?\352 . "%EA") ; ^e
6637 (?\356 . "%EE") ; ^i
6638 (?\364 . "%F4") ; ^o
6639 (?\371 . "%F9") ; `u
6640 (?\373 . "%FB") ; ^u
6641 (?\; . "%3B")
6642 (?? . "%3F")
6643 (?= . "%3D")
6644 (?+ . "%2B")
6646 "Association list of escapes for some characters problematic in links.
6647 This is the list that is used for internal purposes.")
6649 (defconst org-link-escape-chars-browser
6650 '((?\ . "%20")) ; 32 for the SPC char
6651 "Association list of escapes for some characters problematic in links.
6652 This is the list that is used before handing over to the browser.")
6654 (defun org-link-escape (text &optional table)
6655 "Escape characters in TEXT that are problematic for links."
6656 (setq table (or table org-link-escape-chars))
6657 (when text
6658 (let ((re (mapconcat (lambda (x) (regexp-quote
6659 (char-to-string (car x))))
6660 table "\\|")))
6661 (while (string-match re text)
6662 (setq text
6663 (replace-match
6664 (cdr (assoc (string-to-char (match-string 0 text))
6665 table))
6666 t t text)))
6667 text)))
6669 (defun org-link-unescape (text &optional table)
6670 "Reverse the action of `org-link-escape'."
6671 (setq table (or table org-link-escape-chars))
6672 (when text
6673 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6674 table "\\|")))
6675 (while (string-match re text)
6676 (setq text
6677 (replace-match
6678 (char-to-string (car (rassoc (match-string 0 text) table)))
6679 t t text)))
6680 text)))
6682 (defun org-xor (a b)
6683 "Exclusive or."
6684 (if a (not b) b))
6686 (defun org-fixup-message-id-for-http (s)
6687 "Replace special characters in a message id, so it can be used in an http query."
6688 (while (string-match "<" s)
6689 (setq s (replace-match "%3C" t t s)))
6690 (while (string-match ">" s)
6691 (setq s (replace-match "%3E" t t s)))
6692 (while (string-match "@" s)
6693 (setq s (replace-match "%40" t t s)))
6696 ;;;###autoload
6697 (defun org-insert-link-global ()
6698 "Insert a link like Org-mode does.
6699 This command can be called in any mode to insert a link in Org-mode syntax."
6700 (interactive)
6701 (org-load-modules-maybe)
6702 (org-run-like-in-org-mode 'org-insert-link))
6704 (defun org-insert-link (&optional complete-file link-location)
6705 "Insert a link. At the prompt, enter the link.
6707 Completion can be used to insert any of the link protocol prefixes like
6708 http or ftp in use.
6710 The history can be used to select a link previously stored with
6711 `org-store-link'. When the empty string is entered (i.e. if you just
6712 press RET at the prompt), the link defaults to the most recently
6713 stored link. As SPC triggers completion in the minibuffer, you need to
6714 use M-SPC or C-q SPC to force the insertion of a space character.
6716 You will also be prompted for a description, and if one is given, it will
6717 be displayed in the buffer instead of the link.
6719 If there is already a link at point, this command will allow you to edit link
6720 and description parts.
6722 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6723 be selected using completion. The path to the file will be relative to the
6724 current directory if the file is in the current directory or a subdirectory.
6725 Otherwise, the link will be the absolute path as completed in the minibuffer
6726 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6727 option `org-link-file-path-type'.
6729 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6730 the current directory or below.
6732 With three \\[universal-argument] prefixes, negate the meaning of
6733 `org-keep-stored-link-after-insertion'.
6735 If `org-make-link-description-function' is non-nil, this function will be
6736 called with the link target, and the result will be the default
6737 link description.
6739 If the LINK-LOCATION parameter is non-nil, this value will be
6740 used as the link location instead of reading one interactively."
6741 (interactive "P")
6742 (let* ((wcf (current-window-configuration))
6743 (region (if (org-region-active-p)
6744 (buffer-substring (region-beginning) (region-end))))
6745 (remove (and region (list (region-beginning) (region-end))))
6746 (desc region)
6747 tmphist ; byte-compile incorrectly complains about this
6748 (link link-location)
6749 entry file)
6750 (cond
6751 (link-location) ; specified by arg, just use it.
6752 ((org-in-regexp org-bracket-link-regexp 1)
6753 ;; We do have a link at point, and we are going to edit it.
6754 (setq remove (list (match-beginning 0) (match-end 0)))
6755 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6756 (setq link (read-string "Link: "
6757 (org-link-unescape
6758 (org-match-string-no-properties 1)))))
6759 ((or (org-in-regexp org-angle-link-re)
6760 (org-in-regexp org-plain-link-re))
6761 ;; Convert to bracket link
6762 (setq remove (list (match-beginning 0) (match-end 0))
6763 link (read-string "Link: "
6764 (org-remove-angle-brackets (match-string 0)))))
6765 ((member complete-file '((4) (16)))
6766 ;; Completing read for file names.
6767 (setq file (read-file-name "File: "))
6768 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6769 (pwd1 (file-name-as-directory (abbreviate-file-name
6770 (expand-file-name ".")))))
6771 (cond
6772 ((equal complete-file '(16))
6773 (setq link (org-make-link
6774 "file:"
6775 (abbreviate-file-name (expand-file-name file)))))
6776 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6777 (setq link (org-make-link "file:" (match-string 1 file))))
6778 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6779 (expand-file-name file))
6780 (setq link (org-make-link
6781 "file:" (match-string 1 (expand-file-name file)))))
6782 (t (setq link (org-make-link "file:" file))))))
6784 ;; Read link, with completion for stored links.
6785 (with-output-to-temp-buffer "*Org Links*"
6786 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6787 (when org-stored-links
6788 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6789 (princ (mapconcat
6790 (lambda (x)
6791 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6792 (reverse org-stored-links) "\n"))))
6793 (let ((cw (selected-window)))
6794 (select-window (get-buffer-window "*Org Links*"))
6795 (setq truncate-lines t)
6796 (org-fit-window-to-buffer)
6797 (select-window cw))
6798 ;; Fake a link history, containing the stored links.
6799 (setq tmphist (append (mapcar 'car org-stored-links)
6800 org-insert-link-history))
6801 (unwind-protect
6802 (setq link
6803 (let ((org-completion-use-ido nil))
6804 (org-completing-read
6805 "Link: "
6806 (append
6807 (mapcar (lambda (x) (list (concat (car x) ":")))
6808 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6809 (mapcar (lambda (x) (list (concat x ":")))
6810 org-link-types))
6811 nil nil nil
6812 'tmphist
6813 (or (car (car org-stored-links))))))
6814 (set-window-configuration wcf)
6815 (kill-buffer "*Org Links*"))
6816 (setq entry (assoc link org-stored-links))
6817 (or entry (push link org-insert-link-history))
6818 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6819 (not org-keep-stored-link-after-insertion))
6820 (setq org-stored-links (delq (assoc link org-stored-links)
6821 org-stored-links)))
6822 (setq desc (or desc (nth 1 entry)))))
6824 (if (string-match org-plain-link-re link)
6825 ;; URL-like link, normalize the use of angular brackets.
6826 (setq link (org-make-link (org-remove-angle-brackets link))))
6828 ;; Check if we are linking to the current file with a search option
6829 ;; If yes, simplify the link by using only the search option.
6830 (when (and buffer-file-name
6831 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6832 (let* ((path (match-string 1 link))
6833 (case-fold-search nil)
6834 (search (match-string 2 link)))
6835 (save-match-data
6836 (if (equal (file-truename buffer-file-name) (file-truename path))
6837 ;; We are linking to this same file, with a search option
6838 (setq link search)))))
6840 ;; Check if we can/should use a relative path. If yes, simplify the link
6841 (when (string-match "^file:\\(.*\\)" link)
6842 (let* ((path (match-string 1 link))
6843 (origpath path)
6844 (case-fold-search nil))
6845 (cond
6846 ((or (eq org-link-file-path-type 'absolute)
6847 (equal complete-file '(16)))
6848 (setq path (abbreviate-file-name (expand-file-name path))))
6849 ((eq org-link-file-path-type 'noabbrev)
6850 (setq path (expand-file-name path)))
6851 ((eq org-link-file-path-type 'relative)
6852 (setq path (file-relative-name path)))
6854 (save-match-data
6855 (if (string-match (concat "^" (regexp-quote
6856 (file-name-as-directory
6857 (expand-file-name "."))))
6858 (expand-file-name path))
6859 ;; We are linking a file with relative path name.
6860 (setq path (substring (expand-file-name path)
6861 (match-end 0)))
6862 (setq path (abbreviate-file-name (expand-file-name path)))))))
6863 (setq link (concat "file:" path))
6864 (if (equal desc origpath)
6865 (setq desc path))))
6867 (if org-make-link-description-function
6868 (setq desc (funcall org-make-link-description-function link desc)))
6870 (setq desc (read-string "Description: " desc))
6871 (unless (string-match "\\S-" desc) (setq desc nil))
6872 (if remove (apply 'delete-region remove))
6873 (insert (org-make-link-string link desc))))
6875 (defun org-completing-read (&rest args)
6876 "Completing-read with SPACE being a normal character."
6877 (let ((minibuffer-local-completion-map
6878 (copy-keymap minibuffer-local-completion-map)))
6879 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6880 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6881 (apply 'org-ido-completing-read args)))
6883 (defun org-ido-completing-read (&rest args)
6884 "Completing-read using `ido-mode' speedups if available"
6885 (if (and org-completion-use-ido
6886 (fboundp 'ido-completing-read)
6887 (boundp 'ido-mode) ido-mode
6888 (listp (second args)))
6889 (apply 'ido-completing-read (concat (car args)) (cdr args))
6890 (apply 'completing-read args)))
6892 (defun org-extract-attributes (s)
6893 "Extract the attributes cookie from a string and set as text property."
6894 (let (a attr (start 0) key value)
6895 (save-match-data
6896 (when (string-match "{{\\([^}]+\\)}}$" s)
6897 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6898 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6899 (setq key (match-string 1 a) value (match-string 2 a)
6900 start (match-end 0)
6901 attr (plist-put attr (intern key) value))))
6902 (org-add-props s nil 'org-attr attr))
6905 (defun org-attributes-to-string (plist)
6906 "Format a property list into an HTML attribute list."
6907 (let ((s "") key value)
6908 (while plist
6909 (setq key (pop plist) value (pop plist))
6910 (and value
6911 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6914 ;;; Opening/following a link
6916 (defvar org-link-search-failed nil)
6918 (defun org-next-link ()
6919 "Move forward to the next link.
6920 If the link is in hidden text, expose it."
6921 (interactive)
6922 (when (and org-link-search-failed (eq this-command last-command))
6923 (goto-char (point-min))
6924 (message "Link search wrapped back to beginning of buffer"))
6925 (setq org-link-search-failed nil)
6926 (let* ((pos (point))
6927 (ct (org-context))
6928 (a (assoc :link ct)))
6929 (if a (goto-char (nth 2 a)))
6930 (if (re-search-forward org-any-link-re nil t)
6931 (progn
6932 (goto-char (match-beginning 0))
6933 (if (org-invisible-p) (org-show-context)))
6934 (goto-char pos)
6935 (setq org-link-search-failed t)
6936 (error "No further link found"))))
6938 (defun org-previous-link ()
6939 "Move backward to the previous link.
6940 If the link is in hidden text, expose it."
6941 (interactive)
6942 (when (and org-link-search-failed (eq this-command last-command))
6943 (goto-char (point-max))
6944 (message "Link search wrapped back to end of buffer"))
6945 (setq org-link-search-failed nil)
6946 (let* ((pos (point))
6947 (ct (org-context))
6948 (a (assoc :link ct)))
6949 (if a (goto-char (nth 1 a)))
6950 (if (re-search-backward org-any-link-re nil t)
6951 (progn
6952 (goto-char (match-beginning 0))
6953 (if (org-invisible-p) (org-show-context)))
6954 (goto-char pos)
6955 (setq org-link-search-failed t)
6956 (error "No further link found"))))
6958 (defun org-translate-link (s)
6959 "Translate a link string if a translation function has been defined."
6960 (if (and org-link-translation-function
6961 (fboundp org-link-translation-function)
6962 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6963 (progn
6964 (setq s (funcall org-link-translation-function
6965 (match-string 1) (match-string 2)))
6966 (concat (car s) ":" (cdr s)))
6969 (defun org-translate-link-from-planner (type path)
6970 "Translate a link from Emacs Planner syntax so that Org can follow it.
6971 This is still an experimental function, your mileage may vary."
6972 (cond
6973 ((member type '("http" "https" "news" "ftp"))
6974 ;; standard Internet links are the same.
6975 nil)
6976 ((and (equal type "irc") (string-match "^//" path))
6977 ;; Planner has two / at the beginning of an irc link, we have 1.
6978 ;; We should have zero, actually....
6979 (setq path (substring path 1)))
6980 ((and (equal type "lisp") (string-match "^/" path))
6981 ;; Planner has a slash, we do not.
6982 (setq type "elisp" path (substring path 1)))
6983 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6984 ;; A typical message link. Planner has the id after the fina slash,
6985 ;; we separate it with a hash mark
6986 (setq path (concat (match-string 1 path) "#"
6987 (org-remove-angle-brackets (match-string 2 path)))))
6989 (cons type path))
6991 (defun org-find-file-at-mouse (ev)
6992 "Open file link or URL at mouse."
6993 (interactive "e")
6994 (mouse-set-point ev)
6995 (org-open-at-point 'in-emacs))
6997 (defun org-open-at-mouse (ev)
6998 "Open file link or URL at mouse."
6999 (interactive "e")
7000 (mouse-set-point ev)
7001 (if (eq major-mode 'org-agenda-mode)
7002 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7003 (org-open-at-point))
7005 (defvar org-window-config-before-follow-link nil
7006 "The window configuration before following a link.
7007 This is saved in case the need arises to restore it.")
7009 (defvar org-open-link-marker (make-marker)
7010 "Marker pointing to the location where `org-open-at-point; was called.")
7012 ;;;###autoload
7013 (defun org-open-at-point-global ()
7014 "Follow a link like Org-mode does.
7015 This command can be called in any mode to follow a link that has
7016 Org-mode syntax."
7017 (interactive)
7018 (org-run-like-in-org-mode 'org-open-at-point))
7020 ;;;###autoload
7021 (defun org-open-link-from-string (s &optional arg)
7022 "Open a link in the string S, as if it was in Org-mode."
7023 (interactive "sLink: \nP")
7024 (with-temp-buffer
7025 (let ((org-inhibit-startup t))
7026 (org-mode)
7027 (insert s)
7028 (goto-char (point-min))
7029 (org-open-at-point arg))))
7031 (defun org-open-at-point (&optional in-emacs)
7032 "Open link at or after point.
7033 If there is no link at point, this function will search forward up to
7034 the end of the current subtree.
7035 Normally, files will be opened by an appropriate application. If the
7036 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7037 With a double prefix argument, try to open outside of Emacs, in the
7038 application the system uses for this file type."
7039 (interactive "P")
7040 (org-load-modules-maybe)
7041 (move-marker org-open-link-marker (point))
7042 (setq org-window-config-before-follow-link (current-window-configuration))
7043 (org-remove-occur-highlights nil nil t)
7044 (cond
7045 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7046 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7047 (org-footnote-action))
7049 (let (type path link line search (pos (point)))
7050 (catch 'match
7051 (save-excursion
7052 (skip-chars-forward "^]\n\r")
7053 (when (org-in-regexp org-bracket-link-regexp)
7054 (setq link (org-extract-attributes
7055 (org-link-unescape (org-match-string-no-properties 1))))
7056 (while (string-match " *\n *" link)
7057 (setq link (replace-match " " t t link)))
7058 (setq link (org-link-expand-abbrev link))
7059 (cond
7060 ((or (file-name-absolute-p link)
7061 (string-match "^\\.\\.?/" link))
7062 (setq type "file" path link))
7063 ((string-match org-link-re-with-space3 link)
7064 (setq type (match-string 1 link) path (match-string 2 link)))
7065 (t (setq type "thisfile" path link)))
7066 (throw 'match t)))
7068 (when (get-text-property (point) 'org-linked-text)
7069 (setq type "thisfile"
7070 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7071 (1+ (point)) (point))
7072 path (buffer-substring
7073 (previous-single-property-change pos 'org-linked-text)
7074 (next-single-property-change pos 'org-linked-text)))
7075 (throw 'match t))
7077 (save-excursion
7078 (when (or (org-in-regexp org-angle-link-re)
7079 (org-in-regexp org-plain-link-re))
7080 (setq type (match-string 1) path (match-string 2))
7081 (throw 'match t)))
7082 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7083 (setq type "tree-match"
7084 path (match-string 1))
7085 (throw 'match t))
7086 (save-excursion
7087 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7088 (setq type "tags"
7089 path (match-string 1))
7090 (while (string-match ":" path)
7091 (setq path (replace-match "+" t t path)))
7092 (throw 'match t))))
7093 (unless path
7094 (error "No link found"))
7095 ;; Remove any trailing spaces in path
7096 (if (string-match " +\\'" path)
7097 (setq path (replace-match "" t t path)))
7098 (if (and org-link-translation-function
7099 (fboundp org-link-translation-function))
7100 ;; Check if we need to translate the link
7101 (let ((tmp (funcall org-link-translation-function type path)))
7102 (setq type (car tmp) path (cdr tmp))))
7104 (cond
7106 ((assoc type org-link-protocols)
7107 (funcall (nth 1 (assoc type org-link-protocols)) path))
7109 ((equal type "mailto")
7110 (let ((cmd (car org-link-mailto-program))
7111 (args (cdr org-link-mailto-program)) args1
7112 (address path) (subject "") a)
7113 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7114 (setq address (match-string 1 path)
7115 subject (org-link-escape (match-string 2 path))))
7116 (while args
7117 (cond
7118 ((not (stringp (car args))) (push (pop args) args1))
7119 (t (setq a (pop args))
7120 (if (string-match "%a" a)
7121 (setq a (replace-match address t t a)))
7122 (if (string-match "%s" a)
7123 (setq a (replace-match subject t t a)))
7124 (push a args1))))
7125 (apply cmd (nreverse args1))))
7127 ((member type '("http" "https" "ftp" "news"))
7128 (browse-url (concat type ":" (org-link-escape
7129 path org-link-escape-chars-browser))))
7131 ((member type '("message"))
7132 (browse-url (concat type ":" path)))
7134 ((string= type "tags")
7135 (org-tags-view in-emacs path))
7136 ((string= type "thisfile")
7137 (if in-emacs
7138 (switch-to-buffer-other-window
7139 (org-get-buffer-for-internal-link (current-buffer)))
7140 (org-mark-ring-push))
7141 (let ((cmd `(org-link-search
7142 ,path
7143 ,(cond ((equal in-emacs '(4)) 'occur)
7144 ((equal in-emacs '(16)) 'org-occur)
7145 (t nil))
7146 ,pos)))
7147 (condition-case nil (eval cmd)
7148 (error (progn (widen) (eval cmd))))))
7150 ((string= type "tree-match")
7151 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7153 ((string= type "file")
7154 (if (string-match "::\\([0-9]+\\)\\'" path)
7155 (setq line (string-to-number (match-string 1 path))
7156 path (substring path 0 (match-beginning 0)))
7157 (if (string-match "::\\(.+\\)\\'" path)
7158 (setq search (match-string 1 path)
7159 path (substring path 0 (match-beginning 0)))))
7160 (if (string-match "[*?{]" (file-name-nondirectory path))
7161 (dired path)
7162 (org-open-file path in-emacs line search)))
7164 ((string= type "news")
7165 (require 'org-gnus)
7166 (org-gnus-follow-link path))
7168 ((string= type "shell")
7169 (let ((cmd path))
7170 (if (or (not org-confirm-shell-link-function)
7171 (funcall org-confirm-shell-link-function
7172 (format "Execute \"%s\" in shell? "
7173 (org-add-props cmd nil
7174 'face 'org-warning))))
7175 (progn
7176 (message "Executing %s" cmd)
7177 (shell-command cmd))
7178 (error "Abort"))))
7180 ((string= type "elisp")
7181 (let ((cmd path))
7182 (if (or (not org-confirm-elisp-link-function)
7183 (funcall org-confirm-elisp-link-function
7184 (format "Execute \"%s\" as elisp? "
7185 (org-add-props cmd nil
7186 'face 'org-warning))))
7187 (message "%s => %s" cmd
7188 (if (equal (string-to-char cmd) ?\()
7189 (eval (read cmd))
7190 (call-interactively (read cmd))))
7191 (error "Abort"))))
7194 (browse-url-at-point))))))
7195 (move-marker org-open-link-marker nil)
7196 (run-hook-with-args 'org-follow-link-hook))
7198 ;;;; Time estimates
7200 (defun org-get-effort (&optional pom)
7201 "Get the effort estimate for the current entry."
7202 (org-entry-get pom org-effort-property))
7204 ;;; File search
7206 (defvar org-create-file-search-functions nil
7207 "List of functions to construct the right search string for a file link.
7208 These functions are called in turn with point at the location to
7209 which the link should point.
7211 A function in the hook should first test if it would like to
7212 handle this file type, for example by checking the major-mode or
7213 the file extension. If it decides not to handle this file, it
7214 should just return nil to give other functions a chance. If it
7215 does handle the file, it must return the search string to be used
7216 when following the link. The search string will be part of the
7217 file link, given after a double colon, and `org-open-at-point'
7218 will automatically search for it. If special measures must be
7219 taken to make the search successful, another function should be
7220 added to the companion hook `org-execute-file-search-functions',
7221 which see.
7223 A function in this hook may also use `setq' to set the variable
7224 `description' to provide a suggestion for the descriptive text to
7225 be used for this link when it gets inserted into an Org-mode
7226 buffer with \\[org-insert-link].")
7228 (defvar org-execute-file-search-functions nil
7229 "List of functions to execute a file search triggered by a link.
7231 Functions added to this hook must accept a single argument, the
7232 search string that was part of the file link, the part after the
7233 double colon. The function must first check if it would like to
7234 handle this search, for example by checking the major-mode or the
7235 file extension. If it decides not to handle this search, it
7236 should just return nil to give other functions a chance. If it
7237 does handle the search, it must return a non-nil value to keep
7238 other functions from trying.
7240 Each function can access the current prefix argument through the
7241 variable `current-prefix-argument'. Note that a single prefix is
7242 used to force opening a link in Emacs, so it may be good to only
7243 use a numeric or double prefix to guide the search function.
7245 In case this is needed, a function in this hook can also restore
7246 the window configuration before `org-open-at-point' was called using:
7248 (set-window-configuration org-window-config-before-follow-link)")
7250 (defun org-link-search (s &optional type avoid-pos)
7251 "Search for a link search option.
7252 If S is surrounded by forward slashes, it is interpreted as a
7253 regular expression. In org-mode files, this will create an `org-occur'
7254 sparse tree. In ordinary files, `occur' will be used to list matches.
7255 If the current buffer is in `dired-mode', grep will be used to search
7256 in all files. If AVOID-POS is given, ignore matches near that position."
7257 (let ((case-fold-search t)
7258 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7259 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7260 (append '(("") (" ") ("\t") ("\n"))
7261 org-emphasis-alist)
7262 "\\|") "\\)"))
7263 (pos (point))
7264 (pre nil) (post nil)
7265 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7266 (cond
7267 ;; First check if there are any special
7268 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7269 ;; Now try the builtin stuff
7270 ((save-excursion
7271 (goto-char (point-min))
7272 (and
7273 (re-search-forward
7274 (concat "<<" (regexp-quote s0) ">>") nil t)
7275 (setq type 'dedicated
7276 pos (match-beginning 0))))
7277 ;; There is an exact target for this
7278 (goto-char pos))
7279 ((and (string-match "^(\\(.*\\))$" s0)
7280 (save-excursion
7281 (goto-char (point-min))
7282 (and
7283 (re-search-forward
7284 (concat "[^[]" (regexp-quote
7285 (format org-coderef-label-format
7286 (match-string 1 s0))))
7287 nil t)
7288 (setq type 'dedicated
7289 pos (1+ (match-beginning 0))))))
7290 ;; There is a coderef target for this
7291 (goto-char pos))
7292 ((string-match "^/\\(.*\\)/$" s)
7293 ;; A regular expression
7294 (cond
7295 ((org-mode-p)
7296 (org-occur (match-string 1 s)))
7297 ;;((eq major-mode 'dired-mode)
7298 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7299 (t (org-do-occur (match-string 1 s)))))
7301 ;; A normal search strings
7302 (when (equal (string-to-char s) ?*)
7303 ;; Anchor on headlines, post may include tags.
7304 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7305 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7306 s (substring s 1)))
7307 (remove-text-properties
7308 0 (length s)
7309 '(face nil mouse-face nil keymap nil fontified nil) s)
7310 ;; Make a series of regular expressions to find a match
7311 (setq words (org-split-string s "[ \n\r\t]+")
7313 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7314 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7315 "\\)" markers)
7316 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7317 re2a (concat "[ \t\r\n]" re2a_)
7318 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7319 re4 (concat "[^a-zA-Z_]" re4_)
7321 re1 (concat pre re2 post)
7322 re3 (concat pre (if pre re4_ re4) post)
7323 re5 (concat pre ".*" re4)
7324 re2 (concat pre re2)
7325 re2a (concat pre (if pre re2a_ re2a))
7326 re4 (concat pre (if pre re4_ re4))
7327 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7328 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7329 re5 "\\)"
7331 (cond
7332 ((eq type 'org-occur) (org-occur reall))
7333 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7334 (t (goto-char (point-min))
7335 (setq type 'fuzzy)
7336 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7337 (org-search-not-self 1 re1 nil t)
7338 (org-search-not-self 1 re2 nil t)
7339 (org-search-not-self 1 re2a nil t)
7340 (org-search-not-self 1 re3 nil t)
7341 (org-search-not-self 1 re4 nil t)
7342 (org-search-not-self 1 re5 nil t)
7344 (goto-char (match-beginning 1))
7345 (goto-char pos)
7346 (error "No match")))))
7348 ;; Normal string-search
7349 (goto-char (point-min))
7350 (if (search-forward s nil t)
7351 (goto-char (match-beginning 0))
7352 (error "No match"))))
7353 (and (org-mode-p) (org-show-context 'link-search))
7354 type))
7356 (defun org-search-not-self (group &rest args)
7357 "Execute `re-search-forward', but only accept matches that do not
7358 enclose the position of `org-open-link-marker'."
7359 (let ((m org-open-link-marker))
7360 (catch 'exit
7361 (while (apply 're-search-forward args)
7362 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7363 (goto-char (match-end group))
7364 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7365 (> (match-beginning 0) (marker-position m))
7366 (< (match-end 0) (marker-position m)))
7367 (save-match-data
7368 (or (not (org-in-regexp
7369 org-bracket-link-analytic-regexp 1))
7370 (not (match-end 4)) ; no description
7371 (and (<= (match-beginning 4) (point))
7372 (>= (match-end 4) (point))))))
7373 (throw 'exit (point))))))))
7375 (defun org-get-buffer-for-internal-link (buffer)
7376 "Return a buffer to be used for displaying the link target of internal links."
7377 (cond
7378 ((not org-display-internal-link-with-indirect-buffer)
7379 buffer)
7380 ((string-match "(Clone)$" (buffer-name buffer))
7381 (message "Buffer is already a clone, not making another one")
7382 ;; we also do not modify visibility in this case
7383 buffer)
7384 (t ; make a new indirect buffer for displaying the link
7385 (let* ((bn (buffer-name buffer))
7386 (ibn (concat bn "(Clone)"))
7387 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7388 (with-current-buffer ib (org-overview))
7389 ib))))
7391 (defun org-do-occur (regexp &optional cleanup)
7392 "Call the Emacs command `occur'.
7393 If CLEANUP is non-nil, remove the printout of the regular expression
7394 in the *Occur* buffer. This is useful if the regex is long and not useful
7395 to read."
7396 (occur regexp)
7397 (when cleanup
7398 (let ((cwin (selected-window)) win beg end)
7399 (when (setq win (get-buffer-window "*Occur*"))
7400 (select-window win))
7401 (goto-char (point-min))
7402 (when (re-search-forward "match[a-z]+" nil t)
7403 (setq beg (match-end 0))
7404 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7405 (setq end (1- (match-beginning 0)))))
7406 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7407 (goto-char (point-min))
7408 (select-window cwin))))
7410 ;;; The mark ring for links jumps
7412 (defvar org-mark-ring nil
7413 "Mark ring for positions before jumps in Org-mode.")
7414 (defvar org-mark-ring-last-goto nil
7415 "Last position in the mark ring used to go back.")
7416 ;; Fill and close the ring
7417 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7418 (loop for i from 1 to org-mark-ring-length do
7419 (push (make-marker) org-mark-ring))
7420 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7421 org-mark-ring)
7423 (defun org-mark-ring-push (&optional pos buffer)
7424 "Put the current position or POS into the mark ring and rotate it."
7425 (interactive)
7426 (setq pos (or pos (point)))
7427 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7428 (move-marker (car org-mark-ring)
7429 (or pos (point))
7430 (or buffer (current-buffer)))
7431 (message "%s"
7432 (substitute-command-keys
7433 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7435 (defun org-mark-ring-goto (&optional n)
7436 "Jump to the previous position in the mark ring.
7437 With prefix arg N, jump back that many stored positions. When
7438 called several times in succession, walk through the entire ring.
7439 Org-mode commands jumping to a different position in the current file,
7440 or to another Org-mode file, automatically push the old position
7441 onto the ring."
7442 (interactive "p")
7443 (let (p m)
7444 (if (eq last-command this-command)
7445 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7446 (setq p org-mark-ring))
7447 (setq org-mark-ring-last-goto p)
7448 (setq m (car p))
7449 (switch-to-buffer (marker-buffer m))
7450 (goto-char m)
7451 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7453 (defun org-remove-angle-brackets (s)
7454 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7455 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7457 (defun org-add-angle-brackets (s)
7458 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7459 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7461 (defun org-remove-double-quotes (s)
7462 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7463 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7466 ;;; Following specific links
7468 (defun org-follow-timestamp-link ()
7469 (cond
7470 ((org-at-date-range-p t)
7471 (let ((org-agenda-start-on-weekday)
7472 (t1 (match-string 1))
7473 (t2 (match-string 2)))
7474 (setq t1 (time-to-days (org-time-string-to-time t1))
7475 t2 (time-to-days (org-time-string-to-time t2)))
7476 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7477 ((org-at-timestamp-p t)
7478 (org-agenda-list nil (time-to-days (org-time-string-to-time
7479 (substring (match-string 1) 0 10)))
7481 (t (error "This should not happen"))))
7484 ;;; Following file links
7485 (defvar org-wait nil)
7486 (defun org-open-file (path &optional in-emacs line search)
7487 "Open the file at PATH.
7488 First, this expands any special file name abbreviations. Then the
7489 configuration variable `org-file-apps' is checked if it contains an
7490 entry for this file type, and if yes, the corresponding command is launched.
7492 If no application is found, Emacs simply visits the file.
7494 With optional prefix argument IN-EMACS, Emacs will visit the file.
7495 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7496 and o use an external application to visit the file.
7498 Optional LINE specifies a line to go to, optional SEARCH a string to
7499 search for. If LINE or SEARCH is given, the file will always be
7500 opened in Emacs.
7501 If the file does not exist, an error is thrown."
7502 (setq in-emacs (or in-emacs line search))
7503 (let* ((file (if (equal path "")
7504 buffer-file-name
7505 (substitute-in-file-name (expand-file-name path))))
7506 (apps (append org-file-apps (org-default-apps)))
7507 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7508 (dirp (if remp nil (file-directory-p file)))
7509 (file (if (and dirp org-open-directory-means-index-dot-org)
7510 (concat (file-name-as-directory file) "index.org")
7511 file))
7512 (a-m-a-p (assq 'auto-mode apps))
7513 (dfile (downcase file))
7514 (old-buffer (current-buffer))
7515 (old-pos (point))
7516 (old-mode major-mode)
7517 ext cmd)
7518 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7519 (setq ext (match-string 1 dfile))
7520 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7521 (setq ext (match-string 1 dfile))))
7522 (cond
7523 ((equal in-emacs '(16))
7524 (setq cmd (cdr (assoc 'system apps))))
7525 (in-emacs (setq cmd 'emacs))
7527 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7528 (and dirp (cdr (assoc 'directory apps)))
7529 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7530 'string-match)
7531 (cdr (assoc ext apps))
7532 (cdr (assoc t apps))))))
7533 (when (eq cmd 'system)
7534 (setq cmd (cdr (assoc 'system apps))))
7535 (when (eq cmd 'default)
7536 (setq cmd (cdr (assoc t apps))))
7537 (when (eq cmd 'mailcap)
7538 (require 'mailcap)
7539 (mailcap-parse-mailcaps)
7540 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7541 (command (mailcap-mime-info mime-type)))
7542 (if (stringp command)
7543 (setq cmd command)
7544 (setq cmd 'emacs))))
7545 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7546 (not (file-exists-p file))
7547 (not org-open-non-existing-files))
7548 (error "No such file: %s" file))
7549 (cond
7550 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7551 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7552 (while (string-match "['\"]%s['\"]" cmd)
7553 (setq cmd (replace-match "%s" t t cmd)))
7554 (while (string-match "%s" cmd)
7555 (setq cmd (replace-match
7556 (save-match-data
7557 (shell-quote-argument
7558 (convert-standard-filename file)))
7559 t t cmd)))
7560 (save-window-excursion
7561 (start-process-shell-command cmd nil cmd)
7562 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7564 ((or (stringp cmd)
7565 (eq cmd 'emacs))
7566 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7567 (widen)
7568 (if line (goto-line line)
7569 (if search (org-link-search search))))
7570 ((consp cmd)
7571 (let ((file (convert-standard-filename file)))
7572 (eval cmd)))
7573 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7574 (and (org-mode-p) (eq old-mode 'org-mode)
7575 (or (not (equal old-buffer (current-buffer)))
7576 (not (equal old-pos (point))))
7577 (org-mark-ring-push old-pos old-buffer))))
7579 (defun org-default-apps ()
7580 "Return the default applications for this operating system."
7581 (cond
7582 ((eq system-type 'darwin)
7583 org-file-apps-defaults-macosx)
7584 ((eq system-type 'windows-nt)
7585 org-file-apps-defaults-windowsnt)
7586 (t org-file-apps-defaults-gnu)))
7588 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7589 "Convert extensions to regular expressions in the cars of LIST.
7590 Also, weed out any non-string entries, because the return value is used
7591 only for regexp matching.
7592 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7593 point to the symbol `emacs', indicating that the file should
7594 be opened in Emacs."
7595 (append
7596 (delq nil
7597 (mapcar (lambda (x)
7598 (if (not (stringp (car x)))
7600 (if (string-match "\\W" (car x))
7602 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7603 list))
7604 (if add-auto-mode
7605 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7607 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7608 (defun org-file-remote-p (file)
7609 "Test whether FILE specifies a location on a remote system.
7610 Return non-nil if the location is indeed remote.
7612 For example, the filename \"/user@host:/foo\" specifies a location
7613 on the system \"/user@host:\"."
7614 (cond ((fboundp 'file-remote-p)
7615 (file-remote-p file))
7616 ((fboundp 'tramp-handle-file-remote-p)
7617 (tramp-handle-file-remote-p file))
7618 ((and (boundp 'ange-ftp-name-format)
7619 (string-match (car ange-ftp-name-format) file))
7621 (t nil)))
7624 ;;;; Refiling
7626 (defun org-get-org-file ()
7627 "Read a filename, with default directory `org-directory'."
7628 (let ((default (or org-default-notes-file remember-data-file)))
7629 (read-file-name (format "File name [%s]: " default)
7630 (file-name-as-directory org-directory)
7631 default)))
7633 (defun org-notes-order-reversed-p ()
7634 "Check if the current file should receive notes in reversed order."
7635 (cond
7636 ((not org-reverse-note-order) nil)
7637 ((eq t org-reverse-note-order) t)
7638 ((not (listp org-reverse-note-order)) nil)
7639 (t (catch 'exit
7640 (let ((all org-reverse-note-order)
7641 entry)
7642 (while (setq entry (pop all))
7643 (if (string-match (car entry) buffer-file-name)
7644 (throw 'exit (cdr entry))))
7645 nil)))))
7647 (defvar org-refile-target-table nil
7648 "The list of refile targets, created by `org-refile'.")
7650 (defvar org-agenda-new-buffers nil
7651 "Buffers created to visit agenda files.")
7653 (defun org-get-refile-targets (&optional default-buffer)
7654 "Produce a table with refile targets."
7655 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7656 targets txt re files f desc descre fast-path-p level)
7657 (message "Getting targets...")
7658 (with-current-buffer (or default-buffer (current-buffer))
7659 (while (setq entry (pop entries))
7660 (setq files (car entry) desc (cdr entry))
7661 (setq fast-path-p nil)
7662 (cond
7663 ((null files) (setq files (list (current-buffer))))
7664 ((eq files 'org-agenda-files)
7665 (setq files (org-agenda-files 'unrestricted)))
7666 ((and (symbolp files) (fboundp files))
7667 (setq files (funcall files)))
7668 ((and (symbolp files) (boundp files))
7669 (setq files (symbol-value files))))
7670 (if (stringp files) (setq files (list files)))
7671 (cond
7672 ((eq (car desc) :tag)
7673 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7674 ((eq (car desc) :todo)
7675 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7676 ((eq (car desc) :regexp)
7677 (setq descre (cdr desc)))
7678 ((eq (car desc) :level)
7679 (setq descre (concat "^\\*\\{" (number-to-string
7680 (if org-odd-levels-only
7681 (1- (* 2 (cdr desc)))
7682 (cdr desc)))
7683 "\\}[ \t]")))
7684 ((eq (car desc) :maxlevel)
7685 (setq fast-path-p t)
7686 (setq descre (concat "^\\*\\{1," (number-to-string
7687 (if org-odd-levels-only
7688 (1- (* 2 (cdr desc)))
7689 (cdr desc)))
7690 "\\}[ \t]")))
7691 (t (error "Bad refiling target description %s" desc)))
7692 (while (setq f (pop files))
7693 (save-excursion
7694 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7695 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7696 (setq f (expand-file-name f))
7697 (save-excursion
7698 (save-restriction
7699 (widen)
7700 (goto-char (point-min))
7701 (while (re-search-forward descre nil t)
7702 (goto-char (point-at-bol))
7703 (when (looking-at org-complex-heading-regexp)
7704 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7705 txt (org-link-display-format (match-string 4))
7706 re (concat "^" (regexp-quote
7707 (buffer-substring (match-beginning 1)
7708 (match-end 4)))))
7709 (if (match-end 5) (setq re (concat re "[ \t]+"
7710 (regexp-quote
7711 (match-string 5)))))
7712 (setq re (concat re "[ \t]*$"))
7713 (when org-refile-use-outline-path
7714 (setq txt (mapconcat 'org-protect-slash
7715 (append
7716 (if (eq org-refile-use-outline-path 'file)
7717 (list (file-name-nondirectory
7718 (buffer-file-name (buffer-base-buffer))))
7719 (if (eq org-refile-use-outline-path 'full-file-path)
7720 (list (buffer-file-name (buffer-base-buffer)))))
7721 (org-get-outline-path fast-path-p level txt)
7722 (list txt))
7723 "/")))
7724 (push (list txt f re (point)) targets))
7725 (goto-char (point-at-eol))))))))
7726 (message "Getting targets...done")
7727 (nreverse targets))))
7729 (defun org-protect-slash (s)
7730 (while (string-match "/" s)
7731 (setq s (replace-match "\\" t t s)))
7734 (defvar org-olpa (make-vector 20 nil))
7736 (defun org-get-outline-path (&optional fastp level heading)
7737 "Return the outline path to the current entry, as a list."
7738 (if fastp
7739 (progn
7740 (if (> level 19)
7741 (error "Outline path failure, more than 19 levels."))
7742 (loop for i from level upto 19 do
7743 (aset org-olpa i nil))
7744 (prog1
7745 (delq nil (append org-olpa nil))
7746 (aset org-olpa level heading)))
7747 (let (rtn)
7748 (save-excursion
7749 (while (org-up-heading-safe)
7750 (when (looking-at org-complex-heading-regexp)
7751 (push (org-match-string-no-properties 4) rtn)))
7752 rtn))))
7754 (defvar org-refile-history nil
7755 "History for refiling operations.")
7757 (defun org-refile (&optional goto default-buffer)
7758 "Move the entry at point to another heading.
7759 The list of target headings is compiled using the information in
7760 `org-refile-targets', which see. This list is created before each use
7761 and will therefore always be up-to-date.
7763 At the target location, the entry is filed as a subitem of the target heading.
7764 Depending on `org-reverse-note-order', the new subitem will either be the
7765 first or the last subitem.
7767 If there is an active region, all entries in that region will be moved.
7768 However, the region must fulfil the requirement that the first heading
7769 is the first one sets the top-level of the moved text - at most siblings
7770 below it are allowed.
7772 With prefix arg GOTO, the command will only visit the target location,
7773 not actually move anything.
7774 With a double prefix `C-u C-u', go to the location where the last refiling
7775 operation has put the subtree."
7776 (interactive "P")
7777 (let* ((cbuf (current-buffer))
7778 (regionp (org-region-active-p))
7779 (region-start (and regionp (region-beginning)))
7780 (region-end (and regionp (region-end)))
7781 (region-length (and regionp (- region-end region-start)))
7782 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7783 pos it nbuf file re level reversed)
7784 (when regionp (goto-char region-start)
7785 (unless (org-kill-is-subtree-p
7786 (buffer-substring region-start region-end))
7787 (error "The region is not a (sequence of) subtree(s)")))
7788 (if (equal goto '(16))
7789 (org-refile-goto-last-stored)
7790 (when (setq it (org-refile-get-location
7791 (if goto "Goto: " "Refile to: ") default-buffer))
7792 (setq file (nth 1 it)
7793 re (nth 2 it)
7794 pos (nth 3 it))
7795 (if (and (equal (buffer-file-name) file)
7796 (if regionp
7797 (and (>= pos region-start)
7798 (<= pos region-end))
7799 (and (>= pos (point))
7800 (< pos (save-excursion
7801 (org-end-of-subtree t t))))))
7802 (error "Cannot refile to position inside the tree or region"))
7804 (setq nbuf (or (find-buffer-visiting file)
7805 (find-file-noselect file)))
7806 (if goto
7807 (progn
7808 (switch-to-buffer nbuf)
7809 (goto-char pos)
7810 (org-show-context 'org-goto))
7811 (if regionp
7812 (progn
7813 (kill-new (buffer-substring region-start region-end))
7814 (org-save-markers-in-region region-start region-end))
7815 (org-copy-subtree 1 nil t))
7816 (save-excursion
7817 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7818 (find-file-noselect file))))
7819 (setq reversed (org-notes-order-reversed-p))
7820 (save-excursion
7821 (save-restriction
7822 (widen)
7823 (goto-char pos)
7824 (looking-at outline-regexp)
7825 (setq level (org-get-valid-level (funcall outline-level) 1))
7826 (goto-char
7827 (if reversed
7828 (or (outline-next-heading) (point-max))
7829 (or (save-excursion (outline-get-next-sibling))
7830 (org-end-of-subtree t t)
7831 (point-max))))
7832 (if (not (bolp)) (newline))
7833 (bookmark-set "org-refile-last-stored")
7834 (org-paste-subtree level))))
7835 (if regionp
7836 (delete-region (point) (+ (point) region-length))
7837 (org-cut-subtree))
7838 (setq org-markers-to-move nil)
7839 (message "Refiled to \"%s\"" (car it)))))))
7841 (defun org-refile-goto-last-stored ()
7842 "Go to the location where the last refile was stored."
7843 (interactive)
7844 (bookmark-jump "org-refile-last-stored")
7845 (message "This is the location of the last refile"))
7847 (defun org-refile-get-location (&optional prompt default-buffer)
7848 "Prompt the user for a refile location, using PROMPT."
7849 (let ((org-refile-targets org-refile-targets)
7850 (org-refile-use-outline-path org-refile-use-outline-path))
7851 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7852 (unless org-refile-target-table
7853 (error "No refile targets"))
7854 (let* ((cbuf (current-buffer))
7855 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7856 (cfunc (if (and org-refile-use-outline-path
7857 org-outline-path-complete-in-steps)
7858 'org-olpath-completing-read
7859 'org-ido-completing-read))
7860 (extra (if org-refile-use-outline-path "/" ""))
7861 (filename (and cfn (expand-file-name cfn)))
7862 (tbl (mapcar
7863 (lambda (x)
7864 (if (not (equal filename (nth 1 x)))
7865 (cons (concat (car x) extra " ("
7866 (file-name-nondirectory (nth 1 x)) ")")
7867 (cdr x))
7868 (cons (concat (car x) extra) (cdr x))))
7869 org-refile-target-table))
7870 (completion-ignore-case t))
7871 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7872 tbl)))
7874 (defun org-olpath-completing-read (prompt collection &rest args)
7875 "Read an outline path like a file name."
7876 (let ((thetable collection))
7877 (apply
7878 'org-ido-completing-read prompt
7879 (lambda (string predicate &optional flag)
7880 (let (rtn r f (l (length string)))
7881 (cond
7882 ((eq flag nil)
7883 ;; try completion
7884 (try-completion string thetable))
7885 ((eq flag t)
7886 ;; all-completions
7887 (setq rtn (all-completions string thetable predicate))
7888 (mapcar
7889 (lambda (x)
7890 (setq r (substring x l))
7891 (if (string-match " ([^)]*)$" x)
7892 (setq f (match-string 0 x))
7893 (setq f ""))
7894 (if (string-match "/" r)
7895 (concat string (substring r 0 (match-end 0)) f)
7897 rtn))
7898 ((eq flag 'lambda)
7899 ;; exact match?
7900 (assoc string thetable)))
7902 args)))
7904 ;;;; Dynamic blocks
7906 (defun org-find-dblock (name)
7907 "Find the first dynamic block with name NAME in the buffer.
7908 If not found, stay at current position and return nil."
7909 (let (pos)
7910 (save-excursion
7911 (goto-char (point-min))
7912 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7913 nil t)
7914 (match-beginning 0))))
7915 (if pos (goto-char pos))
7916 pos))
7918 (defconst org-dblock-start-re
7919 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7920 "Matches the startline of a dynamic block, with parameters.")
7922 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7923 "Matches the end of a dynamic block.")
7925 (defun org-create-dblock (plist)
7926 "Create a dynamic block section, with parameters taken from PLIST.
7927 PLIST must contain a :name entry which is used as name of the block."
7928 (unless (bolp) (newline))
7929 (let ((name (plist-get plist :name)))
7930 (insert "#+BEGIN: " name)
7931 (while plist
7932 (if (eq (car plist) :name)
7933 (setq plist (cddr plist))
7934 (insert " " (prin1-to-string (pop plist)))))
7935 (insert "\n\n#+END:\n")
7936 (beginning-of-line -2)))
7938 (defun org-prepare-dblock ()
7939 "Prepare dynamic block for refresh.
7940 This empties the block, puts the cursor at the insert position and returns
7941 the property list including an extra property :name with the block name."
7942 (unless (looking-at org-dblock-start-re)
7943 (error "Not at a dynamic block"))
7944 (let* ((begdel (1+ (match-end 0)))
7945 (name (org-no-properties (match-string 1)))
7946 (params (append (list :name name)
7947 (read (concat "(" (match-string 3) ")")))))
7948 (unless (re-search-forward org-dblock-end-re nil t)
7949 (error "Dynamic block not terminated"))
7950 (setq params
7951 (append params
7952 (list :content (buffer-substring
7953 begdel (match-beginning 0)))))
7954 (delete-region begdel (match-beginning 0))
7955 (goto-char begdel)
7956 (open-line 1)
7957 params))
7959 (defun org-map-dblocks (&optional command)
7960 "Apply COMMAND to all dynamic blocks in the current buffer.
7961 If COMMAND is not given, use `org-update-dblock'."
7962 (let ((cmd (or command 'org-update-dblock))
7963 pos)
7964 (save-excursion
7965 (goto-char (point-min))
7966 (while (re-search-forward org-dblock-start-re nil t)
7967 (goto-char (setq pos (match-beginning 0)))
7968 (condition-case nil
7969 (funcall cmd)
7970 (error (message "Error during update of dynamic block")))
7971 (goto-char pos)
7972 (unless (re-search-forward org-dblock-end-re nil t)
7973 (error "Dynamic block not terminated"))))))
7975 (defun org-dblock-update (&optional arg)
7976 "User command for updating dynamic blocks.
7977 Update the dynamic block at point. With prefix ARG, update all dynamic
7978 blocks in the buffer."
7979 (interactive "P")
7980 (if arg
7981 (org-update-all-dblocks)
7982 (or (looking-at org-dblock-start-re)
7983 (org-beginning-of-dblock))
7984 (org-update-dblock)))
7986 (defun org-update-dblock ()
7987 "Update the dynamic block at point
7988 This means to empty the block, parse for parameters and then call
7989 the correct writing function."
7990 (save-window-excursion
7991 (let* ((pos (point))
7992 (line (org-current-line))
7993 (params (org-prepare-dblock))
7994 (name (plist-get params :name))
7995 (cmd (intern (concat "org-dblock-write:" name))))
7996 (message "Updating dynamic block `%s' at line %d..." name line)
7997 (funcall cmd params)
7998 (message "Updating dynamic block `%s' at line %d...done" name line)
7999 (goto-char pos))))
8001 (defun org-beginning-of-dblock ()
8002 "Find the beginning of the dynamic block at point.
8003 Error if there is no such block at point."
8004 (let ((pos (point))
8005 beg)
8006 (end-of-line 1)
8007 (if (and (re-search-backward org-dblock-start-re nil t)
8008 (setq beg (match-beginning 0))
8009 (re-search-forward org-dblock-end-re nil t)
8010 (> (match-end 0) pos))
8011 (goto-char beg)
8012 (goto-char pos)
8013 (error "Not in a dynamic block"))))
8015 (defun org-update-all-dblocks ()
8016 "Update all dynamic blocks in the buffer.
8017 This function can be used in a hook."
8018 (when (org-mode-p)
8019 (org-map-dblocks 'org-update-dblock)))
8022 ;;;; Completion
8024 (defconst org-additional-option-like-keywords
8025 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8026 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8027 "BEGIN_EXAMPLE" "END_EXAMPLE"
8028 "BEGIN_QUOTE" "END_QUOTE"
8029 "BEGIN_VERSE" "END_VERSE"
8030 "BEGIN_SRC" "END_SRC"
8031 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8033 (defcustom org-structure-template-alist
8035 ("s" "#+begin_src ?\n\n#+end_src"
8036 "<src lang=\"?\">\n\n</src>")
8037 ("e" "#+begin_example\n?\n#+end_example"
8038 "<example>\n?\n</example>")
8039 ("q" "#+begin_quote\n?\n#+end_quote"
8040 "<quote>\n?\n</quote>")
8041 ("v" "#+begin_verse\n?\n#+end_verse"
8042 "<verse>\n?\n/verse>")
8043 ("l" "#+begin_latex\n?\n#+end_latex"
8044 "<literal style=\"latex\">\n?\n</literal>")
8045 ("L" "#+latex: "
8046 "<literal style=\"latex\">?</literal>")
8047 ("h" "#+begin_html\n?\n#+end_html"
8048 "<literal style=\"html\">\n?\n</literal>")
8049 ("H" "#+html: "
8050 "<literal style=\"html\">?</literal>")
8051 ("a" "#+begin_ascii\n?\n#+end_ascii")
8052 ("A" "#+ascii: ")
8053 ("i" "#+include %file ?"
8054 "<include file=%file markup=\"?\">")
8056 "Structure completion elements.
8057 This is a list of abbreviation keys and values. The value gets inserted
8058 it you type @samp{.} followed by the key and then the completion key,
8059 usually `M-TAB'. %file will be replaced by a file name after prompting
8060 for the file using completion.
8061 There are two templates for each key, the first uses the original Org syntax,
8062 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8063 the default when the /org-mtags.el/ module has been loaded. See also the
8064 variable `org-mtags-prefer-muse-templates'.
8065 This is an experimental feature, it is undecided if it is going to stay in."
8066 :group 'org-completion
8067 :type '(repeat
8068 (string :tag "Key")
8069 (string :tag "Template")
8070 (string :tag "Muse Template")))
8072 (defun org-try-structure-completion ()
8073 "Try to complete a structure template before point.
8074 This looks for strings like \"<e\" on an otherwise empty line and
8075 expands them."
8076 (let ((l (buffer-substring (point-at-bol) (point)))
8078 (when (and (looking-at "[ \t]*$")
8079 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8080 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8081 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8082 (match-beginning 1)) a)
8083 t)))
8085 (defun org-complete-expand-structure-template (start cell)
8086 "Expand a structure template."
8087 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8088 (rpl (nth (if musep 2 1) cell)))
8089 (delete-region start (point))
8090 (when (string-match "\\`#\\+" rpl)
8091 (cond
8092 ((bolp))
8093 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8094 (delete-region (point-at-bol) (point)))
8095 (t (newline))))
8096 (setq start (point))
8097 (if (string-match "%file" rpl)
8098 (setq rpl (replace-match
8099 (concat
8100 "\""
8101 (save-match-data
8102 (abbreviate-file-name (read-file-name "Include file: ")))
8103 "\"")
8104 t t rpl)))
8105 (insert rpl)
8106 (if (re-search-backward "\\?" start t) (delete-char 1))))
8109 (defun org-complete (&optional arg)
8110 "Perform completion on word at point.
8111 At the beginning of a headline, this completes TODO keywords as given in
8112 `org-todo-keywords'.
8113 If the current word is preceded by a backslash, completes the TeX symbols
8114 that are supported for HTML support.
8115 If the current word is preceded by \"#+\", completes special words for
8116 setting file options.
8117 In the line after \"#+STARTUP:, complete valid keywords.\"
8118 At all other locations, this simply calls the value of
8119 `org-completion-fallback-command'."
8120 (interactive "P")
8121 (org-without-partial-completion
8122 (catch 'exit
8123 (let* ((a nil)
8124 (end (point))
8125 (beg1 (save-excursion
8126 (skip-chars-backward (org-re "[:alnum:]_@"))
8127 (point)))
8128 (beg (save-excursion
8129 (skip-chars-backward "a-zA-Z0-9_:$")
8130 (point)))
8131 (confirm (lambda (x) (stringp (car x))))
8132 (searchhead (equal (char-before beg) ?*))
8133 (struct
8134 (when (and (member (char-before beg1) '(?. ?<))
8135 (setq a (assoc (buffer-substring beg1 (point))
8136 org-structure-template-alist)))
8137 (org-complete-expand-structure-template (1- beg1) a)
8138 (throw 'exit t)))
8139 (tag (and (equal (char-before beg1) ?:)
8140 (equal (char-after (point-at-bol)) ?*)))
8141 (prop (and (equal (char-before beg1) ?:)
8142 (not (equal (char-after (point-at-bol)) ?*))))
8143 (texp (equal (char-before beg) ?\\))
8144 (link (equal (char-before beg) ?\[))
8145 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8146 beg)
8147 "#+"))
8148 (startup (string-match "^#\\+STARTUP:.*"
8149 (buffer-substring (point-at-bol) (point))))
8150 (completion-ignore-case opt)
8151 (type nil)
8152 (tbl nil)
8153 (table (cond
8154 (opt
8155 (setq type :opt)
8156 (require 'org-exp)
8157 (append
8158 (mapcar
8159 (lambda (x)
8160 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8161 (cons (match-string 2 x) (match-string 1 x)))
8162 (org-split-string (org-get-current-options) "\n"))
8163 (mapcar 'list org-additional-option-like-keywords)))
8164 (startup
8165 (setq type :startup)
8166 org-startup-options)
8167 (link (append org-link-abbrev-alist-local
8168 org-link-abbrev-alist))
8169 (texp
8170 (setq type :tex)
8171 org-html-entities)
8172 ((string-match "\\`\\*+[ \t]+\\'"
8173 (buffer-substring (point-at-bol) beg))
8174 (setq type :todo)
8175 (mapcar 'list org-todo-keywords-1))
8176 (searchhead
8177 (setq type :searchhead)
8178 (save-excursion
8179 (goto-char (point-min))
8180 (while (re-search-forward org-todo-line-regexp nil t)
8181 (push (list
8182 (org-make-org-heading-search-string
8183 (match-string 3) t))
8184 tbl)))
8185 tbl)
8186 (tag (setq type :tag beg beg1)
8187 (or org-tag-alist (org-get-buffer-tags)))
8188 (prop (setq type :prop beg beg1)
8189 (mapcar 'list (org-buffer-property-keys nil t t)))
8190 (t (progn
8191 (call-interactively org-completion-fallback-command)
8192 (throw 'exit nil)))))
8193 (pattern (buffer-substring-no-properties beg end))
8194 (completion (try-completion pattern table confirm)))
8195 (cond ((eq completion t)
8196 (if (not (assoc (upcase pattern) table))
8197 (message "Already complete")
8198 (if (and (equal type :opt)
8199 (not (member (car (assoc (upcase pattern) table))
8200 org-additional-option-like-keywords)))
8201 (insert (substring (cdr (assoc (upcase pattern) table))
8202 (length pattern)))
8203 (if (memq type '(:tag :prop)) (insert ":")))))
8204 ((null completion)
8205 (message "Can't find completion for \"%s\"" pattern)
8206 (ding))
8207 ((not (string= pattern completion))
8208 (delete-region beg end)
8209 (if (string-match " +$" completion)
8210 (setq completion (replace-match "" t t completion)))
8211 (insert completion)
8212 (if (get-buffer-window "*Completions*")
8213 (delete-window (get-buffer-window "*Completions*")))
8214 (if (assoc completion table)
8215 (if (eq type :todo) (insert " ")
8216 (if (memq type '(:tag :prop)) (insert ":"))))
8217 (if (and (equal type :opt) (assoc completion table))
8218 (message "%s" (substitute-command-keys
8219 "Press \\[org-complete] again to insert example settings"))))
8221 (message "Making completion list...")
8222 (let ((list (sort (all-completions pattern table confirm)
8223 'string<)))
8224 (with-output-to-temp-buffer "*Completions*"
8225 (condition-case nil
8226 ;; Protection needed for XEmacs and emacs 21
8227 (display-completion-list list pattern)
8228 (error (display-completion-list list)))))
8229 (message "Making completion list...%s" "done")))))))
8231 ;;;; TODO, DEADLINE, Comments
8233 (defun org-toggle-comment ()
8234 "Change the COMMENT state of an entry."
8235 (interactive)
8236 (save-excursion
8237 (org-back-to-heading)
8238 (let (case-fold-search)
8239 (if (looking-at (concat outline-regexp
8240 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8241 (replace-match "" t t nil 1)
8242 (if (looking-at outline-regexp)
8243 (progn
8244 (goto-char (match-end 0))
8245 (insert org-comment-string " ")))))))
8247 (defvar org-last-todo-state-is-todo nil
8248 "This is non-nil when the last TODO state change led to a TODO state.
8249 If the last change removed the TODO tag or switched to DONE, then
8250 this is nil.")
8252 (defvar org-setting-tags nil) ; dynamically skipped
8254 (defun org-parse-local-options (string var)
8255 "Parse STRING for startup setting relevant for variable VAR."
8256 (let ((rtn (symbol-value var))
8257 e opts)
8258 (save-match-data
8259 (if (or (not string) (not (string-match "\\S-" string)))
8261 (setq opts (delq nil (mapcar (lambda (x)
8262 (setq e (assoc x org-startup-options))
8263 (if (eq (nth 1 e) var) e nil))
8264 (org-split-string string "[ \t]+"))))
8265 (if (not opts)
8267 (setq rtn nil)
8268 (while (setq e (pop opts))
8269 (if (not (nth 3 e))
8270 (setq rtn (nth 2 e))
8271 (if (not (listp rtn)) (setq rtn nil))
8272 (push (nth 2 e) rtn)))
8273 rtn)))))
8275 (defvar org-blocker-hook nil
8276 "Hook for functions that are allowed to block a state change.
8278 Each function gets as its single argument a property list, see
8279 `org-trigger-hook' for more information about this list.
8281 If any of the functions in this hook returns nil, the state change
8282 is blocked.")
8284 (defvar org-trigger-hook nil
8285 "Hook for functions that are triggered by a state change.
8287 Each function gets as its single argument a property list with at least
8288 the following elements:
8290 (:type type-of-change :position pos-at-entry-start
8291 :from old-state :to new-state)
8293 Depending on the type, more properties may be present.
8295 This mechanism is currently implemented for:
8297 TODO state changes
8298 ------------------
8299 :type todo-state-change
8300 :from previous state (keyword as a string), or nil
8301 :to new state (keyword as a string), or nil")
8303 (defvar org-agenda-headline-snapshot-before-repeat)
8304 (defun org-todo (&optional arg)
8305 "Change the TODO state of an item.
8306 The state of an item is given by a keyword at the start of the heading,
8307 like
8308 *** TODO Write paper
8309 *** DONE Call mom
8311 The different keywords are specified in the variable `org-todo-keywords'.
8312 By default the available states are \"TODO\" and \"DONE\".
8313 So for this example: when the item starts with TODO, it is changed to DONE.
8314 When it starts with DONE, the DONE is removed. And when neither TODO nor
8315 DONE are present, add TODO at the beginning of the heading.
8317 With C-u prefix arg, use completion to determine the new state.
8318 With numeric prefix arg, switch to that state.
8319 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8321 For calling through lisp, arg is also interpreted in the following way:
8322 'none -> empty state
8323 \"\"(empty string) -> switch to empty state
8324 'done -> switch to DONE
8325 'nextset -> switch to the next set of keywords
8326 'previousset -> switch to the previous set of keywords
8327 \"WAITING\" -> switch to the specified keyword, but only if it
8328 really is a member of `org-todo-keywords'."
8329 (interactive "P")
8330 (if (equal arg '(16)) (setq arg 'nextset))
8331 (save-excursion
8332 (catch 'exit
8333 (org-back-to-heading)
8334 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8335 (or (looking-at (concat " +" org-todo-regexp " *"))
8336 (looking-at " *"))
8337 (let* ((match-data (match-data))
8338 (startpos (point-at-bol))
8339 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8340 (org-log-done org-log-done)
8341 (org-log-repeat org-log-repeat)
8342 (org-todo-log-states org-todo-log-states)
8343 (this (match-string 1))
8344 (hl-pos (match-beginning 0))
8345 (head (org-get-todo-sequence-head this))
8346 (ass (assoc head org-todo-kwd-alist))
8347 (interpret (nth 1 ass))
8348 (done-word (nth 3 ass))
8349 (final-done-word (nth 4 ass))
8350 (last-state (or this ""))
8351 (completion-ignore-case t)
8352 (member (member this org-todo-keywords-1))
8353 (tail (cdr member))
8354 (state (cond
8355 ((and org-todo-key-trigger
8356 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8357 (and (not arg) org-use-fast-todo-selection
8358 (not (eq org-use-fast-todo-selection 'prefix)))))
8359 ;; Use fast selection
8360 (org-fast-todo-selection))
8361 ((and (equal arg '(4))
8362 (or (not org-use-fast-todo-selection)
8363 (not org-todo-key-trigger)))
8364 ;; Read a state with completion
8365 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8366 org-todo-keywords-1)
8367 nil t))
8368 ((eq arg 'right)
8369 (if this
8370 (if tail (car tail) nil)
8371 (car org-todo-keywords-1)))
8372 ((eq arg 'left)
8373 (if (equal member org-todo-keywords-1)
8375 (if this
8376 (nth (- (length org-todo-keywords-1) (length tail) 2)
8377 org-todo-keywords-1)
8378 (org-last org-todo-keywords-1))))
8379 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8380 (setq arg nil))) ; hack to fall back to cycling
8381 (arg
8382 ;; user or caller requests a specific state
8383 (cond
8384 ((equal arg "") nil)
8385 ((eq arg 'none) nil)
8386 ((eq arg 'done) (or done-word (car org-done-keywords)))
8387 ((eq arg 'nextset)
8388 (or (car (cdr (member head org-todo-heads)))
8389 (car org-todo-heads)))
8390 ((eq arg 'previousset)
8391 (let ((org-todo-heads (reverse org-todo-heads)))
8392 (or (car (cdr (member head org-todo-heads)))
8393 (car org-todo-heads))))
8394 ((car (member arg org-todo-keywords-1)))
8395 ((nth (1- (prefix-numeric-value arg))
8396 org-todo-keywords-1))))
8397 ((null member) (or head (car org-todo-keywords-1)))
8398 ((equal this final-done-word) nil) ;; -> make empty
8399 ((null tail) nil) ;; -> first entry
8400 ((eq interpret 'sequence)
8401 (car tail))
8402 ((memq interpret '(type priority))
8403 (if (eq this-command last-command)
8404 (car tail)
8405 (if (> (length tail) 0)
8406 (or done-word (car org-done-keywords))
8407 nil)))
8408 (t nil)))
8409 (next (if state (concat " " state " ") " "))
8410 (change-plist (list :type 'todo-state-change :from this :to state
8411 :position startpos))
8412 dolog now-done-p)
8413 (when org-blocker-hook
8414 (unless (save-excursion
8415 (save-match-data
8416 (run-hook-with-args-until-failure
8417 'org-blocker-hook change-plist)))
8418 (if (interactive-p)
8419 (error "TODO state change from %s to %s blocked" this state)
8420 ;; fail silently
8421 (message "TODO state change from %s to %s blocked" this state)
8422 (throw 'exit nil))))
8423 (store-match-data match-data)
8424 (replace-match next t t)
8425 (unless (pos-visible-in-window-p hl-pos)
8426 (message "TODO state changed to %s" (org-trim next)))
8427 (unless head
8428 (setq head (org-get-todo-sequence-head state)
8429 ass (assoc head org-todo-kwd-alist)
8430 interpret (nth 1 ass)
8431 done-word (nth 3 ass)
8432 final-done-word (nth 4 ass)))
8433 (when (memq arg '(nextset previousset))
8434 (message "Keyword-Set %d/%d: %s"
8435 (- (length org-todo-sets) -1
8436 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8437 (length org-todo-sets)
8438 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8439 (setq org-last-todo-state-is-todo
8440 (not (member state org-done-keywords)))
8441 (setq now-done-p (and (member state org-done-keywords)
8442 (not (member this org-done-keywords))))
8443 (and logging (org-local-logging logging))
8444 (when (and (or org-todo-log-states org-log-done)
8445 (not (memq arg '(nextset previousset))))
8446 ;; we need to look at recording a time and note
8447 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8448 (nth 2 (assoc this org-todo-log-states))))
8449 (when (and state
8450 (member state org-not-done-keywords)
8451 (not (member this org-not-done-keywords)))
8452 ;; This is now a todo state and was not one before
8453 ;; If there was a CLOSED time stamp, get rid of it.
8454 (org-add-planning-info nil nil 'closed))
8455 (when (and now-done-p org-log-done)
8456 ;; It is now done, and it was not done before
8457 (org-add-planning-info 'closed (org-current-time))
8458 (if (and (not dolog) (eq 'note org-log-done))
8459 (org-add-log-setup 'done state 'findpos 'note)))
8460 (when (and state dolog)
8461 ;; This is a non-nil state, and we need to log it
8462 (org-add-log-setup 'state state 'findpos dolog)))
8463 ;; Fixup tag positioning
8464 (org-todo-trigger-tag-changes state)
8465 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8466 (when org-provide-todo-statistics
8467 (org-update-parent-todo-statistics))
8468 (run-hooks 'org-after-todo-state-change-hook)
8469 (if (and arg (not (member state org-done-keywords)))
8470 (setq head (org-get-todo-sequence-head state)))
8471 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8472 ;; Do we need to trigger a repeat?
8473 (when now-done-p
8474 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8475 ;; This is for the agenda, take a snapshot of the headline.
8476 (save-match-data
8477 (setq org-agenda-headline-snapshot-before-repeat
8478 (org-get-heading))))
8479 (org-auto-repeat-maybe state))
8480 ;; Fixup cursor location if close to the keyword
8481 (if (and (outline-on-heading-p)
8482 (not (bolp))
8483 (save-excursion (beginning-of-line 1)
8484 (looking-at org-todo-line-regexp))
8485 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8486 (progn
8487 (goto-char (or (match-end 2) (match-end 1)))
8488 (just-one-space)))
8489 (when org-trigger-hook
8490 (save-excursion
8491 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8493 (defun org-update-parent-todo-statistics ()
8494 "Update any statistics cookie in the parent of the current headline."
8495 (interactive)
8496 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8497 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8498 (catch 'exit
8499 (save-excursion
8500 (setq level (org-up-heading-safe))
8501 (unless (and level
8502 (re-search-forward box-re (point-at-eol) t))
8503 (throw 'exit nil))
8504 (setq is-percent (match-end 2))
8505 (save-match-data
8506 (unless (outline-next-heading) (throw 'exit nil))
8507 (while (looking-at org-todo-line-regexp)
8508 (setq kwd (match-string 2))
8509 (and kwd (setq cnt-all (1+ cnt-all)))
8510 (and (member kwd org-done-keywords)
8511 (setq cnt-done (1+ cnt-done)))
8512 (condition-case nil
8513 (org-forward-same-level 1)
8514 (error (end-of-line 1)))))
8515 (replace-match
8516 (if is-percent
8517 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8518 (format "[%d/%d]" cnt-done cnt-all)))
8519 (run-hook-with-args 'org-after-todo-statistics-hook
8520 cnt-done (- cnt-all cnt-done))))))
8522 (defvar org-after-todo-statistics-hook nil
8523 "Hook that is called after a TODO statistics cookie has been updated.
8524 Each function is called with two arguments: the number of not-done entries
8525 and the number of done entries.
8527 For example, the following function, when added to this hook, will switch
8528 an entry to DONE when all children are done, and back to TODO when new
8529 entries are set to a TODO status. Note that this hook is only called
8530 when there is a statistics cookie in the headline!
8532 (defun org-summary-todo (n-done n-not-done)
8533 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8534 (let (org-log-done org-log-states) ; turn off logging
8535 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8538 (defun org-todo-trigger-tag-changes (state)
8539 "Apply the changes defined in `org-todo-state-tags-triggers'."
8540 (let ((l org-todo-state-tags-triggers)
8541 changes)
8542 (when (or (not state) (equal state ""))
8543 (setq changes (append changes (cdr (assoc "" l)))))
8544 (when (and (stringp state) (> (length state) 0))
8545 (setq changes (append changes (cdr (assoc state l)))))
8546 (when (member state org-not-done-keywords)
8547 (setq changes (append changes (cdr (assoc 'todo l)))))
8548 (when (member state org-done-keywords)
8549 (setq changes (append changes (cdr (assoc 'done l)))))
8550 (dolist (c changes)
8551 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8553 (defun org-local-logging (value)
8554 "Get logging settings from a property VALUE."
8555 (let* (words w a)
8556 ;; directly set the variables, they are already local.
8557 (setq org-log-done nil
8558 org-log-repeat nil
8559 org-todo-log-states nil)
8560 (setq words (org-split-string value))
8561 (while (setq w (pop words))
8562 (cond
8563 ((setq a (assoc w org-startup-options))
8564 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8565 (set (nth 1 a) (nth 2 a))))
8566 ((setq a (org-extract-log-state-settings w))
8567 (and (member (car a) org-todo-keywords-1)
8568 (push a org-todo-log-states)))))))
8570 (defun org-get-todo-sequence-head (kwd)
8571 "Return the head of the TODO sequence to which KWD belongs.
8572 If KWD is not set, check if there is a text property remembering the
8573 right sequence."
8574 (let (p)
8575 (cond
8576 ((not kwd)
8577 (or (get-text-property (point-at-bol) 'org-todo-head)
8578 (progn
8579 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8580 nil (point-at-eol)))
8581 (get-text-property p 'org-todo-head))))
8582 ((not (member kwd org-todo-keywords-1))
8583 (car org-todo-keywords-1))
8584 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8586 (defun org-fast-todo-selection ()
8587 "Fast TODO keyword selection with single keys.
8588 Returns the new TODO keyword, or nil if no state change should occur."
8589 (let* ((fulltable org-todo-key-alist)
8590 (done-keywords org-done-keywords) ;; needed for the faces.
8591 (maxlen (apply 'max (mapcar
8592 (lambda (x)
8593 (if (stringp (car x)) (string-width (car x)) 0))
8594 fulltable)))
8595 (expert nil)
8596 (fwidth (+ maxlen 3 1 3))
8597 (ncol (/ (- (window-width) 4) fwidth))
8598 tg cnt e c tbl
8599 groups ingroup)
8600 (save-window-excursion
8601 (if expert
8602 (set-buffer (get-buffer-create " *Org todo*"))
8603 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8604 (erase-buffer)
8605 (org-set-local 'org-done-keywords done-keywords)
8606 (setq tbl fulltable cnt 0)
8607 (while (setq e (pop tbl))
8608 (cond
8609 ((equal e '(:startgroup))
8610 (push '() groups) (setq ingroup t)
8611 (when (not (= cnt 0))
8612 (setq cnt 0)
8613 (insert "\n"))
8614 (insert "{ "))
8615 ((equal e '(:endgroup))
8616 (setq ingroup nil cnt 0)
8617 (insert "}\n"))
8619 (setq tg (car e) c (cdr e))
8620 (if ingroup (push tg (car groups)))
8621 (setq tg (org-add-props tg nil 'face
8622 (org-get-todo-face tg)))
8623 (if (and (= cnt 0) (not ingroup)) (insert " "))
8624 (insert "[" c "] " tg (make-string
8625 (- fwidth 4 (length tg)) ?\ ))
8626 (when (= (setq cnt (1+ cnt)) ncol)
8627 (insert "\n")
8628 (if ingroup (insert " "))
8629 (setq cnt 0)))))
8630 (insert "\n")
8631 (goto-char (point-min))
8632 (if (not expert) (org-fit-window-to-buffer))
8633 (message "[a-z..]:Set [SPC]:clear")
8634 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8635 (cond
8636 ((or (= c ?\C-g)
8637 (and (= c ?q) (not (rassoc c fulltable))))
8638 (setq quit-flag t))
8639 ((= c ?\ ) nil)
8640 ((setq e (rassoc c fulltable) tg (car e))
8642 (t (setq quit-flag t))))))
8644 (defun org-entry-is-todo-p ()
8645 (member (org-get-todo-state) org-not-done-keywords))
8647 (defun org-entry-is-done-p ()
8648 (member (org-get-todo-state) org-done-keywords))
8650 (defun org-get-todo-state ()
8651 (save-excursion
8652 (org-back-to-heading t)
8653 (and (looking-at org-todo-line-regexp)
8654 (match-end 2)
8655 (match-string 2))))
8657 (defun org-at-date-range-p (&optional inactive-ok)
8658 "Is the cursor inside a date range?"
8659 (interactive)
8660 (save-excursion
8661 (catch 'exit
8662 (let ((pos (point)))
8663 (skip-chars-backward "^[<\r\n")
8664 (skip-chars-backward "<[")
8665 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8666 (>= (match-end 0) pos)
8667 (throw 'exit t))
8668 (skip-chars-backward "^<[\r\n")
8669 (skip-chars-backward "<[")
8670 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8671 (>= (match-end 0) pos)
8672 (throw 'exit t)))
8673 nil)))
8675 (defun org-get-repeat ()
8676 "Check if there is a deadline/schedule with repeater in this entry."
8677 (save-match-data
8678 (save-excursion
8679 (org-back-to-heading t)
8680 (if (re-search-forward
8681 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8682 (match-string 1)))))
8684 (defvar org-last-changed-timestamp)
8685 (defvar org-last-inserted-timestamp)
8686 (defvar org-log-post-message)
8687 (defvar org-log-note-purpose)
8688 (defvar org-log-note-how)
8689 (defvar org-log-note-extra)
8690 (defun org-auto-repeat-maybe (done-word)
8691 "Check if the current headline contains a repeated deadline/schedule.
8692 If yes, set TODO state back to what it was and change the base date
8693 of repeating deadline/scheduled time stamps to new date.
8694 This function is run automatically after each state change to a DONE state."
8695 ;; last-state is dynamically scoped into this function
8696 (let* ((repeat (org-get-repeat))
8697 (aa (assoc last-state org-todo-kwd-alist))
8698 (interpret (nth 1 aa))
8699 (head (nth 2 aa))
8700 (whata '(("d" . day) ("m" . month) ("y" . year)))
8701 (msg "Entry repeats: ")
8702 (org-log-done nil)
8703 (org-todo-log-states nil)
8704 (nshiftmax 10) (nshift 0)
8705 re type n what ts time)
8706 (when repeat
8707 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8708 (org-todo (if (eq interpret 'type) last-state head))
8709 (when org-log-repeat
8710 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8711 (memq 'org-add-log-note post-command-hook))
8712 ;; OK, we are already setup for some record
8713 (if (eq org-log-repeat 'note)
8714 ;; make sure we take a note, not only a time stamp
8715 (setq org-log-note-how 'note))
8716 ;; Set up for taking a record
8717 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8718 'findpos org-log-repeat)))
8719 (org-back-to-heading t)
8720 (org-add-planning-info nil nil 'closed)
8721 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8722 org-deadline-time-regexp "\\)\\|\\("
8723 org-ts-regexp "\\)"))
8724 (while (re-search-forward
8725 re (save-excursion (outline-next-heading) (point)) t)
8726 (setq type (if (match-end 1) org-scheduled-string
8727 (if (match-end 3) org-deadline-string "Plain:"))
8728 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8729 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8730 (setq n (string-to-number (match-string 2 ts))
8731 what (match-string 3 ts))
8732 (if (equal what "w") (setq n (* n 7) what "d"))
8733 ;; Preparation, see if we need to modify the start date for the change
8734 (when (match-end 1)
8735 (setq time (save-match-data (org-time-string-to-time ts)))
8736 (cond
8737 ((equal (match-string 1 ts) ".")
8738 ;; Shift starting date to today
8739 (org-timestamp-change
8740 (- (time-to-days (current-time)) (time-to-days time))
8741 'day))
8742 ((equal (match-string 1 ts) "+")
8743 (while (or (= nshift 0)
8744 (<= (time-to-days time) (time-to-days (current-time))))
8745 (when (= (incf nshift) nshiftmax)
8746 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8747 (error "Abort")))
8748 (org-timestamp-change n (cdr (assoc what whata)))
8749 (org-at-timestamp-p t)
8750 (setq ts (match-string 1))
8751 (setq time (save-match-data (org-time-string-to-time ts))))
8752 (org-timestamp-change (- n) (cdr (assoc what whata)))
8753 ;; rematch, so that we have everything in place for the real shift
8754 (org-at-timestamp-p t)
8755 (setq ts (match-string 1))
8756 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8757 (org-timestamp-change n (cdr (assoc what whata)))
8758 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8759 (setq org-log-post-message msg)
8760 (message "%s" msg))))
8762 (defun org-show-todo-tree (arg)
8763 "Make a compact tree which shows all headlines marked with TODO.
8764 The tree will show the lines where the regexp matches, and all higher
8765 headlines above the match.
8766 With a \\[universal-argument] prefix, also show the DONE entries.
8767 With a numeric prefix N, construct a sparse tree for the Nth element
8768 of `org-todo-keywords-1'."
8769 (interactive "P")
8770 (let ((case-fold-search nil)
8771 (kwd-re
8772 (cond ((null arg) org-not-done-regexp)
8773 ((equal arg '(4))
8774 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8775 (mapcar 'list org-todo-keywords-1))))
8776 (concat "\\("
8777 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8778 "\\)\\>")))
8779 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8780 (regexp-quote (nth (1- (prefix-numeric-value arg))
8781 org-todo-keywords-1)))
8782 (t (error "Invalid prefix argument: %s" arg)))))
8783 (message "%d TODO entries found"
8784 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8786 (defun org-deadline (&optional remove time)
8787 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8788 With argument REMOVE, remove any deadline from the item.
8789 When TIME is set, it should be an internal time specification, and the
8790 scheduling will use the corresponding date."
8791 (interactive "P")
8792 (if remove
8793 (progn
8794 (org-remove-timestamp-with-keyword org-deadline-string)
8795 (message "Item no longer has a deadline."))
8796 (if (org-get-repeat)
8797 (error "Cannot change deadline on task with repeater, please do that by hand")
8798 (org-add-planning-info 'deadline time 'closed)
8799 (message "Deadline on %s" org-last-inserted-timestamp))))
8801 (defun org-schedule (&optional remove time)
8802 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8803 With argument REMOVE, remove any scheduling date from the item.
8804 When TIME is set, it should be an internal time specification, and the
8805 scheduling will use the corresponding date."
8806 (interactive "P")
8807 (if remove
8808 (progn
8809 (org-remove-timestamp-with-keyword org-scheduled-string)
8810 (message "Item is no longer scheduled."))
8811 (if (org-get-repeat)
8812 (error "Cannot reschedule task with repeater, please do that by hand")
8813 (org-add-planning-info 'scheduled time 'closed)
8814 (message "Scheduled to %s" org-last-inserted-timestamp))))
8816 (defun org-remove-timestamp-with-keyword (keyword)
8817 "Remove all time stamps with KEYWORD in the current entry."
8818 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8819 beg)
8820 (save-excursion
8821 (org-back-to-heading t)
8822 (setq beg (point))
8823 (org-end-of-subtree t t)
8824 (while (re-search-backward re beg t)
8825 (replace-match "")
8826 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8827 (equal (char-before) ?\ ))
8828 (backward-delete-char 1)
8829 (if (string-match "^[ \t]*$" (buffer-substring
8830 (point-at-bol) (point-at-eol)))
8831 (delete-region (point-at-bol)
8832 (min (point-max) (1+ (point-at-eol))))))))))
8834 (defun org-add-planning-info (what &optional time &rest remove)
8835 "Insert new timestamp with keyword in the line directly after the headline.
8836 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8837 If non is given, the user is prompted for a date.
8838 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8839 be removed."
8840 (interactive)
8841 (let (org-time-was-given org-end-time-was-given ts
8842 end default-time default-input)
8844 (when (and (not time) (memq what '(scheduled deadline)))
8845 ;; Try to get a default date/time from existing timestamp
8846 (save-excursion
8847 (org-back-to-heading t)
8848 (setq end (save-excursion (outline-next-heading) (point)))
8849 (when (re-search-forward (if (eq what 'scheduled)
8850 org-scheduled-time-regexp
8851 org-deadline-time-regexp)
8852 end t)
8853 (setq ts (match-string 1)
8854 default-time
8855 (apply 'encode-time (org-parse-time-string ts))
8856 default-input (and ts (org-get-compact-tod ts))))))
8857 (when what
8858 ;; If necessary, get the time from the user
8859 (setq time (or time (org-read-date nil 'to-time nil nil
8860 default-time default-input))))
8862 (when (and org-insert-labeled-timestamps-at-point
8863 (member what '(scheduled deadline)))
8864 (insert
8865 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8866 (org-insert-time-stamp time org-time-was-given
8867 nil nil nil (list org-end-time-was-given))
8868 (setq what nil))
8869 (save-excursion
8870 (save-restriction
8871 (let (col list elt ts buffer-invisibility-spec)
8872 (org-back-to-heading t)
8873 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8874 (goto-char (match-end 1))
8875 (setq col (current-column))
8876 (goto-char (match-end 0))
8877 (if (eobp) (insert "\n") (forward-char 1))
8878 (if (and (not (looking-at outline-regexp))
8879 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8880 "[^\r\n]*"))
8881 (not (equal (match-string 1) org-clock-string)))
8882 (narrow-to-region (match-beginning 0) (match-end 0))
8883 (insert-before-markers "\n")
8884 (backward-char 1)
8885 (narrow-to-region (point) (point))
8886 (and org-adapt-indentation (org-indent-to-column col)))
8887 ;; Check if we have to remove something.
8888 (setq list (cons what remove))
8889 (while list
8890 (setq elt (pop list))
8891 (goto-char (point-min))
8892 (when (or (and (eq elt 'scheduled)
8893 (re-search-forward org-scheduled-time-regexp nil t))
8894 (and (eq elt 'deadline)
8895 (re-search-forward org-deadline-time-regexp nil t))
8896 (and (eq elt 'closed)
8897 (re-search-forward org-closed-time-regexp nil t)))
8898 (replace-match "")
8899 (if (looking-at "--+<[^>]+>") (replace-match ""))
8900 (if (looking-at " +") (replace-match ""))))
8901 (goto-char (point-max))
8902 (when what
8903 (insert
8904 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8905 (cond ((eq what 'scheduled) org-scheduled-string)
8906 ((eq what 'deadline) org-deadline-string)
8907 ((eq what 'closed) org-closed-string))
8908 " ")
8909 (setq ts (org-insert-time-stamp
8910 time
8911 (or org-time-was-given
8912 (and (eq what 'closed) org-log-done-with-time))
8913 (eq what 'closed)
8914 nil nil (list org-end-time-was-given)))
8915 (end-of-line 1))
8916 (goto-char (point-min))
8917 (widen)
8918 (if (and (looking-at "[ \t]+\n")
8919 (equal (char-before) ?\n))
8920 (delete-region (1- (point)) (point-at-eol)))
8921 ts)))))
8923 (defvar org-log-note-marker (make-marker))
8924 (defvar org-log-note-purpose nil)
8925 (defvar org-log-note-state nil)
8926 (defvar org-log-note-how nil)
8927 (defvar org-log-note-extra nil)
8928 (defvar org-log-note-window-configuration nil)
8929 (defvar org-log-note-return-to (make-marker))
8930 (defvar org-log-post-message nil
8931 "Message to be displayed after a log note has been stored.
8932 The auto-repeater uses this.")
8934 (defun org-add-note ()
8935 "Add a note to the current entry.
8936 This is done in the same way as adding a state change note."
8937 (interactive)
8938 (org-add-log-setup 'note nil 'findpos nil))
8940 (defvar org-property-end-re)
8941 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8942 "Set up the post command hook to take a note.
8943 If this is about to TODO state change, the new state is expected in STATE.
8944 When FINDPOS is non-nil, find the correct position for the note in
8945 the current entry. If not, assume that it can be inserted at point.
8946 HOW is an indicator what kind of note should be created.
8947 EXTRA is additional text that will be inserted into the notes buffer."
8948 (save-restriction
8949 (save-excursion
8950 (when findpos
8951 (org-back-to-heading t)
8952 (narrow-to-region (point) (save-excursion
8953 (outline-next-heading) (point)))
8954 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8955 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8956 "[^\r\n]*\\)?"))
8957 (goto-char (match-end 0))
8958 (when (and org-log-state-notes-insert-after-drawers
8959 (save-excursion
8960 (forward-line) (looking-at org-drawer-regexp)))
8961 (progn (forward-line)
8962 (while (looking-at org-drawer-regexp)
8963 (goto-char (match-end 0))
8964 (re-search-forward org-property-end-re (point-max) t)
8965 (forward-line))
8966 (forward-line -1)))
8967 (unless org-log-states-order-reversed
8968 (and (= (char-after) ?\n) (forward-char 1))
8969 (org-skip-over-state-notes)
8970 (skip-chars-backward " \t\n\r")))
8971 (move-marker org-log-note-marker (point))
8972 (setq org-log-note-purpose purpose
8973 org-log-note-state state
8974 org-log-note-how how
8975 org-log-note-extra extra)
8976 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8978 (defun org-skip-over-state-notes ()
8979 "Skip past the list of State notes in an entry."
8980 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8981 (while (looking-at "[ \t]*- State")
8982 (condition-case nil
8983 (org-next-item)
8984 (error (org-end-of-item)))))
8986 (defun org-add-log-note (&optional purpose)
8987 "Pop up a window for taking a note, and add this note later at point."
8988 (remove-hook 'post-command-hook 'org-add-log-note)
8989 (setq org-log-note-window-configuration (current-window-configuration))
8990 (delete-other-windows)
8991 (move-marker org-log-note-return-to (point))
8992 (switch-to-buffer (marker-buffer org-log-note-marker))
8993 (goto-char org-log-note-marker)
8994 (org-switch-to-buffer-other-window "*Org Note*")
8995 (erase-buffer)
8996 (if (memq org-log-note-how '(time state))
8997 (let (current-prefix-arg) (org-store-log-note))
8998 (let ((org-inhibit-startup t)) (org-mode))
8999 (insert (format "# Insert note for %s.
9000 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9001 (cond
9002 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9003 ((eq org-log-note-purpose 'done) "closed todo item")
9004 ((eq org-log-note-purpose 'state)
9005 (format "state change to \"%s\"" org-log-note-state))
9006 ((eq org-log-note-purpose 'note)
9007 "this entry")
9008 (t (error "This should not happen")))))
9009 (if org-log-note-extra (insert org-log-note-extra))
9010 (org-set-local 'org-finish-function 'org-store-log-note)))
9012 (defvar org-note-abort nil) ; dynamically scoped
9013 (defun org-store-log-note ()
9014 "Finish taking a log note, and insert it to where it belongs."
9015 (let ((txt (buffer-string))
9016 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9017 lines ind)
9018 (kill-buffer (current-buffer))
9019 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9020 (setq txt (replace-match "" t t txt)))
9021 (if (string-match "\\s-+\\'" txt)
9022 (setq txt (replace-match "" t t txt)))
9023 (setq lines (org-split-string txt "\n"))
9024 (when (and note (string-match "\\S-" note))
9025 (setq note
9026 (org-replace-escapes
9027 note
9028 (list (cons "%u" (user-login-name))
9029 (cons "%U" user-full-name)
9030 (cons "%t" (format-time-string
9031 (org-time-stamp-format 'long 'inactive)
9032 (current-time)))
9033 (cons "%s" (if org-log-note-state
9034 (concat "\"" org-log-note-state "\"")
9035 "")))))
9036 (if lines (setq note (concat note " \\\\")))
9037 (push note lines))
9038 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9039 (when lines
9040 (save-excursion
9041 (set-buffer (marker-buffer org-log-note-marker))
9042 (save-excursion
9043 (goto-char org-log-note-marker)
9044 (move-marker org-log-note-marker nil)
9045 (end-of-line 1)
9046 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9047 (indent-relative nil)
9048 (insert "- " (pop lines))
9049 (org-indent-line-function)
9050 (beginning-of-line 1)
9051 (looking-at "[ \t]*")
9052 (setq ind (concat (match-string 0) " "))
9053 (end-of-line 1)
9054 (while lines (insert "\n" ind (pop lines)))))))
9055 (set-window-configuration org-log-note-window-configuration)
9056 (with-current-buffer (marker-buffer org-log-note-return-to)
9057 (goto-char org-log-note-return-to))
9058 (move-marker org-log-note-return-to nil)
9059 (and org-log-post-message (message "%s" org-log-post-message)))
9061 (defun org-sparse-tree (&optional arg)
9062 "Create a sparse tree, prompt for the details.
9063 This command can create sparse trees. You first need to select the type
9064 of match used to create the tree:
9066 t Show entries with a specific TODO keyword.
9067 T Show entries selected by a tags match.
9068 p Enter a property name and its value (both with completion on existing
9069 names/values) and show entries with that property.
9070 r Show entries matching a regular expression
9071 d Show deadlines due within `org-deadline-warning-days'."
9072 (interactive "P")
9073 (let (ans kwd value)
9074 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9075 (setq ans (read-char-exclusive))
9076 (cond
9077 ((equal ans ?d)
9078 (call-interactively 'org-check-deadlines))
9079 ((equal ans ?b)
9080 (call-interactively 'org-check-before-date))
9081 ((equal ans ?t)
9082 (org-show-todo-tree '(4)))
9083 ((equal ans ?T)
9084 (call-interactively 'org-tags-sparse-tree))
9085 ((member ans '(?p ?P))
9086 (setq kwd (org-ido-completing-read "Property: "
9087 (mapcar 'list (org-buffer-property-keys))))
9088 (setq value (org-ido-completing-read "Value: "
9089 (mapcar 'list (org-property-values kwd))))
9090 (unless (string-match "\\`{.*}\\'" value)
9091 (setq value (concat "\"" value "\"")))
9092 (org-tags-sparse-tree arg (concat kwd "=" value)))
9093 ((member ans '(?r ?R ?/))
9094 (call-interactively 'org-occur))
9095 (t (error "No such sparse tree command \"%c\"" ans)))))
9097 (defvar org-occur-highlights nil
9098 "List of overlays used for occur matches.")
9099 (make-variable-buffer-local 'org-occur-highlights)
9100 (defvar org-occur-parameters nil
9101 "Parameters of the active org-occur calls.
9102 This is a list, each call to org-occur pushes as cons cell,
9103 containing the regular expression and the callback, onto the list.
9104 The list can contain several entries if `org-occur' has been called
9105 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9106 will only contain one set of parameters. When the highlights are
9107 removed (for example with `C-c C-c', or with the next edit (depending
9108 on `org-remove-highlights-with-change'), this variable is emptied
9109 as well.")
9110 (make-variable-buffer-local 'org-occur-parameters)
9112 (defun org-occur (regexp &optional keep-previous callback)
9113 "Make a compact tree which shows all matches of REGEXP.
9114 The tree will show the lines where the regexp matches, and all higher
9115 headlines above the match. It will also show the heading after the match,
9116 to make sure editing the matching entry is easy.
9117 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9118 call to `org-occur' will be kept, to allow stacking of calls to this
9119 command.
9120 If CALLBACK is non-nil, it is a function which is called to confirm
9121 that the match should indeed be shown."
9122 (interactive "sRegexp: \nP")
9123 (unless keep-previous
9124 (org-remove-occur-highlights nil nil t))
9125 (push (cons regexp callback) org-occur-parameters)
9126 (let ((cnt 0))
9127 (save-excursion
9128 (goto-char (point-min))
9129 (if (or (not keep-previous) ; do not want to keep
9130 (not org-occur-highlights)) ; no previous matches
9131 ;; hide everything
9132 (org-overview))
9133 (while (re-search-forward regexp nil t)
9134 (when (or (not callback)
9135 (save-match-data (funcall callback)))
9136 (setq cnt (1+ cnt))
9137 (when org-highlight-sparse-tree-matches
9138 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9139 (org-show-context 'occur-tree))))
9140 (when org-remove-highlights-with-change
9141 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9142 nil 'local))
9143 (unless org-sparse-tree-open-archived-trees
9144 (org-hide-archived-subtrees (point-min) (point-max)))
9145 (run-hooks 'org-occur-hook)
9146 (if (interactive-p)
9147 (message "%d match(es) for regexp %s" cnt regexp))
9148 cnt))
9150 (defun org-show-context (&optional key)
9151 "Make sure point and context and visible.
9152 How much context is shown depends upon the variables
9153 `org-show-hierarchy-above', `org-show-following-heading'. and
9154 `org-show-siblings'."
9155 (let ((heading-p (org-on-heading-p t))
9156 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9157 (following-p (org-get-alist-option org-show-following-heading key))
9158 (entry-p (org-get-alist-option org-show-entry-below key))
9159 (siblings-p (org-get-alist-option org-show-siblings key)))
9160 (catch 'exit
9161 ;; Show heading or entry text
9162 (if (and heading-p (not entry-p))
9163 (org-flag-heading nil) ; only show the heading
9164 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9165 (org-show-hidden-entry))) ; show entire entry
9166 (when following-p
9167 ;; Show next sibling, or heading below text
9168 (save-excursion
9169 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9170 (org-flag-heading nil))))
9171 (when siblings-p (org-show-siblings))
9172 (when hierarchy-p
9173 ;; show all higher headings, possibly with siblings
9174 (save-excursion
9175 (while (and (condition-case nil
9176 (progn (org-up-heading-all 1) t)
9177 (error nil))
9178 (not (bobp)))
9179 (org-flag-heading nil)
9180 (when siblings-p (org-show-siblings))))))))
9182 (defun org-reveal (&optional siblings)
9183 "Show current entry, hierarchy above it, and the following headline.
9184 This can be used to show a consistent set of context around locations
9185 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9186 not t for the search context.
9188 With optional argument SIBLINGS, on each level of the hierarchy all
9189 siblings are shown. This repairs the tree structure to what it would
9190 look like when opened with hierarchical calls to `org-cycle'."
9191 (interactive "P")
9192 (let ((org-show-hierarchy-above t)
9193 (org-show-following-heading t)
9194 (org-show-siblings (if siblings t org-show-siblings)))
9195 (org-show-context nil)))
9197 (defun org-highlight-new-match (beg end)
9198 "Highlight from BEG to END and mark the highlight is an occur headline."
9199 (let ((ov (org-make-overlay beg end)))
9200 (org-overlay-put ov 'face 'secondary-selection)
9201 (push ov org-occur-highlights)))
9203 (defun org-remove-occur-highlights (&optional beg end noremove)
9204 "Remove the occur highlights from the buffer.
9205 BEG and END are ignored. If NOREMOVE is nil, remove this function
9206 from the `before-change-functions' in the current buffer."
9207 (interactive)
9208 (unless org-inhibit-highlight-removal
9209 (mapc 'org-delete-overlay org-occur-highlights)
9210 (setq org-occur-highlights nil)
9211 (setq org-occur-parameters nil)
9212 (unless noremove
9213 (remove-hook 'before-change-functions
9214 'org-remove-occur-highlights 'local))))
9216 ;;;; Priorities
9218 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9219 "Regular expression matching the priority indicator.")
9221 (defvar org-remove-priority-next-time nil)
9223 (defun org-priority-up ()
9224 "Increase the priority of the current item."
9225 (interactive)
9226 (org-priority 'up))
9228 (defun org-priority-down ()
9229 "Decrease the priority of the current item."
9230 (interactive)
9231 (org-priority 'down))
9233 (defun org-priority (&optional action)
9234 "Change the priority of an item by ARG.
9235 ACTION can be `set', `up', `down', or a character."
9236 (interactive)
9237 (setq action (or action 'set))
9238 (let (current new news have remove)
9239 (save-excursion
9240 (org-back-to-heading)
9241 (if (looking-at org-priority-regexp)
9242 (setq current (string-to-char (match-string 2))
9243 have t)
9244 (setq current org-default-priority))
9245 (cond
9246 ((or (eq action 'set)
9247 (if (featurep 'xemacs) (characterp action) (integerp action)))
9248 (if (not (eq action 'set))
9249 (setq new action)
9250 (message "Priority %c-%c, SPC to remove: "
9251 org-highest-priority org-lowest-priority)
9252 (setq new (read-char-exclusive)))
9253 (if (and (= (upcase org-highest-priority) org-highest-priority)
9254 (= (upcase org-lowest-priority) org-lowest-priority))
9255 (setq new (upcase new)))
9256 (cond ((equal new ?\ ) (setq remove t))
9257 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9258 (error "Priority must be between `%c' and `%c'"
9259 org-highest-priority org-lowest-priority))))
9260 ((eq action 'up)
9261 (if (and (not have) (eq last-command this-command))
9262 (setq new org-lowest-priority)
9263 (setq new (if (and org-priority-start-cycle-with-default (not have))
9264 org-default-priority (1- current)))))
9265 ((eq action 'down)
9266 (if (and (not have) (eq last-command this-command))
9267 (setq new org-highest-priority)
9268 (setq new (if (and org-priority-start-cycle-with-default (not have))
9269 org-default-priority (1+ current)))))
9270 (t (error "Invalid action")))
9271 (if (or (< (upcase new) org-highest-priority)
9272 (> (upcase new) org-lowest-priority))
9273 (setq remove t))
9274 (setq news (format "%c" new))
9275 (if have
9276 (if remove
9277 (replace-match "" t t nil 1)
9278 (replace-match news t t nil 2))
9279 (if remove
9280 (error "No priority cookie found in line")
9281 (looking-at org-todo-line-regexp)
9282 (if (match-end 2)
9283 (progn
9284 (goto-char (match-end 2))
9285 (insert " [#" news "]"))
9286 (goto-char (match-beginning 3))
9287 (insert "[#" news "] ")))))
9288 (org-preserve-lc (org-set-tags nil 'align))
9289 (if remove
9290 (message "Priority removed")
9291 (message "Priority of current item set to %s" news))))
9294 (defun org-get-priority (s)
9295 "Find priority cookie and return priority."
9296 (save-match-data
9297 (if (not (string-match org-priority-regexp s))
9298 (* 1000 (- org-lowest-priority org-default-priority))
9299 (* 1000 (- org-lowest-priority
9300 (string-to-char (match-string 2 s)))))))
9302 ;;;; Tags
9304 (defvar org-agenda-archives-mode)
9305 (defun org-scan-tags (action matcher &optional todo-only)
9306 "Scan headline tags with inheritance and produce output ACTION.
9308 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9309 or `agenda' to produce an entry list for an agenda view. It can also be
9310 a Lisp form or a function that should be called at each matched headline, in
9311 this case the return value is a list of all return values from these calls.
9313 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9314 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9315 only lines with a TODO keyword are included in the output."
9316 (require 'org-agenda)
9317 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9318 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9319 (org-re
9320 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9321 (props (list 'face 'default
9322 'done-face 'org-done
9323 'undone-face 'default
9324 'mouse-face 'highlight
9325 'org-not-done-regexp org-not-done-regexp
9326 'org-todo-regexp org-todo-regexp
9327 'keymap org-agenda-keymap
9328 'help-echo
9329 (format "mouse-2 or RET jump to org file %s"
9330 (abbreviate-file-name
9331 (or (buffer-file-name (buffer-base-buffer))
9332 (buffer-name (buffer-base-buffer)))))))
9333 (case-fold-search nil)
9334 lspos tags tags-list
9335 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9336 (llast 0) rtn rtn1 level category i txt
9337 todo marker entry priority)
9338 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9339 (setq action (list 'lambda nil action)))
9340 (save-excursion
9341 (goto-char (point-min))
9342 (when (eq action 'sparse-tree)
9343 (org-overview)
9344 (org-remove-occur-highlights))
9345 (while (re-search-forward re nil t)
9346 (catch :skip
9347 (setq todo (if (match-end 1) (match-string 2))
9348 tags (if (match-end 4) (match-string 4)))
9349 (goto-char (setq lspos (1+ (match-beginning 0))))
9350 (setq level (org-reduced-level (funcall outline-level))
9351 category (org-get-category))
9352 (setq i llast llast level)
9353 ;; remove tag lists from same and sublevels
9354 (while (>= i level)
9355 (when (setq entry (assoc i tags-alist))
9356 (setq tags-alist (delete entry tags-alist)))
9357 (setq i (1- i)))
9358 ;; add the next tags
9359 (when tags
9360 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9361 tags-alist
9362 (cons (cons level tags) tags-alist)))
9363 ;; compile tags for current headline
9364 (setq tags-list
9365 (if org-use-tag-inheritance
9366 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9367 tags))
9368 (when org-use-tag-inheritance
9369 (setcdr (car tags-alist)
9370 (mapcar (lambda (x)
9371 (setq x (copy-sequence x))
9372 (org-add-prop-inherited x))
9373 (cdar tags-alist))))
9374 (when (and tags org-use-tag-inheritance
9375 (not (eq t org-use-tag-inheritance)))
9376 ;; selective inheritance, remove uninherited ones
9377 (setcdr (car tags-alist)
9378 (org-remove-uniherited-tags (cdar tags-alist))))
9379 (when (and (or (not todo-only)
9380 (and (member todo org-not-done-keywords)
9381 (or (not org-agenda-tags-todo-honor-ignore-options)
9382 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9383 (let ((case-fold-search t)) (eval matcher))
9385 (not (member org-archive-tag tags-list))
9386 ;; we have an archive tag, should we use this anyway?
9387 (or (not org-agenda-skip-archived-trees)
9388 (and (eq action 'agenda) org-agenda-archives-mode))))
9389 (unless (eq action 'sparse-tree) (org-agenda-skip))
9391 ;; select this headline
9393 (cond
9394 ((eq action 'sparse-tree)
9395 (and org-highlight-sparse-tree-matches
9396 (org-get-heading) (match-end 0)
9397 (org-highlight-new-match
9398 (match-beginning 0) (match-beginning 1)))
9399 (org-show-context 'tags-tree))
9400 ((eq action 'agenda)
9401 (setq txt (org-format-agenda-item
9403 (concat
9404 (if org-tags-match-list-sublevels
9405 (make-string (1- level) ?.) "")
9406 (org-get-heading))
9407 category (org-get-tags-at))
9408 priority (org-get-priority txt))
9409 (goto-char lspos)
9410 (setq marker (org-agenda-new-marker))
9411 (org-add-props txt props
9412 'org-marker marker 'org-hd-marker marker 'org-category category
9413 'priority priority 'type "tagsmatch")
9414 (push txt rtn))
9415 ((functionp action)
9416 (save-excursion
9417 (setq rtn1 (funcall action))
9418 (push rtn1 rtn))
9419 (goto-char (point-at-eol)))
9420 (t (error "Invalid action")))
9422 ;; if we are to skip sublevels, jump to end of subtree
9423 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9424 (when (and (eq action 'sparse-tree)
9425 (not org-sparse-tree-open-archived-trees))
9426 (org-hide-archived-subtrees (point-min) (point-max)))
9427 (nreverse rtn)))
9429 (defun org-remove-uniherited-tags (tags)
9430 "Remove all tags that are not inherited from the list TAGS."
9431 (cond
9432 ((eq org-use-tag-inheritance t)
9433 (if org-tags-exclude-from-inheritance
9434 (org-delete-all org-tags-exclude-from-inheritance tags)
9435 tags))
9436 ((not org-use-tag-inheritance) nil)
9437 ((stringp org-use-tag-inheritance)
9438 (delq nil (mapcar
9439 (lambda (x)
9440 (if (and (string-match org-use-tag-inheritance x)
9441 (not (member x org-tags-exclude-from-inheritance)))
9442 x nil))
9443 tags)))
9444 ((listp org-use-tag-inheritance)
9445 (delq nil (mapcar
9446 (lambda (x)
9447 (if (member x org-use-tag-inheritance) x nil))
9448 tags)))))
9450 (defvar todo-only) ;; dynamically scoped
9452 (defun org-tags-sparse-tree (&optional todo-only match)
9453 "Create a sparse tree according to tags string MATCH.
9454 MATCH can contain positive and negative selection of tags, like
9455 \"+WORK+URGENT-WITHBOSS\".
9456 If optional argument TODO-ONLY is non-nil, only select lines that are
9457 also TODO lines."
9458 (interactive "P")
9459 (org-prepare-agenda-buffers (list (current-buffer)))
9460 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9462 (defvar org-cached-props nil)
9463 (defun org-cached-entry-get (pom property)
9464 (if (or (eq t org-use-property-inheritance)
9465 (and (stringp org-use-property-inheritance)
9466 (string-match org-use-property-inheritance property))
9467 (and (listp org-use-property-inheritance)
9468 (member property org-use-property-inheritance)))
9469 ;; Caching is not possible, check it directly
9470 (org-entry-get pom property 'inherit)
9471 ;; Get all properties, so that we can do complicated checks easily
9472 (cdr (assoc property (or org-cached-props
9473 (setq org-cached-props
9474 (org-entry-properties pom)))))))
9476 (defun org-global-tags-completion-table (&optional files)
9477 "Return the list of all tags in all agenda buffer/files."
9478 (save-excursion
9479 (org-uniquify
9480 (delq nil
9481 (apply 'append
9482 (mapcar
9483 (lambda (file)
9484 (set-buffer (find-file-noselect file))
9485 (append (org-get-buffer-tags)
9486 (mapcar (lambda (x) (if (stringp (car-safe x))
9487 (list (car-safe x)) nil))
9488 org-tag-alist)))
9489 (if (and files (car files))
9490 files
9491 (org-agenda-files))))))))
9493 (defun org-make-tags-matcher (match)
9494 "Create the TAGS//TODO matcher form for the selection string MATCH."
9495 ;; todo-only is scoped dynamically into this function, and the function
9496 ;; may change it if the matcher asks for it.
9497 (unless match
9498 ;; Get a new match request, with completion
9499 (let ((org-last-tags-completion-table
9500 (org-global-tags-completion-table)))
9501 (setq match (org-completing-read
9502 "Match: " 'org-tags-completion-function nil nil nil
9503 'org-tags-history))))
9505 ;; Parse the string and create a lisp form
9506 (let ((match0 match)
9507 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9508 minus tag mm
9509 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9510 orterms term orlist re-p str-p level-p level-op time-p
9511 prop-p pn pv po cat-p gv rest)
9512 (if (string-match "/+" match)
9513 ;; match contains also a todo-matching request
9514 (progn
9515 (setq tagsmatch (substring match 0 (match-beginning 0))
9516 todomatch (substring match (match-end 0)))
9517 (if (string-match "^!" todomatch)
9518 (setq todo-only t todomatch (substring todomatch 1)))
9519 (if (string-match "^\\s-*$" todomatch)
9520 (setq todomatch nil)))
9521 ;; only matching tags
9522 (setq tagsmatch match todomatch nil))
9524 ;; Make the tags matcher
9525 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9526 (setq tagsmatcher t)
9527 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9528 (while (setq term (pop orterms))
9529 (while (and (equal (substring term -1) "\\") orterms)
9530 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9531 (while (string-match re term)
9532 (setq rest (substring term (match-end 0))
9533 minus (and (match-end 1)
9534 (equal (match-string 1 term) "-"))
9535 tag (match-string 2 term)
9536 re-p (equal (string-to-char tag) ?{)
9537 level-p (match-end 4)
9538 prop-p (match-end 5)
9539 mm (cond
9540 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9541 (level-p
9542 (setq level-op (org-op-to-function (match-string 3 term)))
9543 `(,level-op level ,(string-to-number
9544 (match-string 4 term))))
9545 (prop-p
9546 (setq pn (match-string 5 term)
9547 po (match-string 6 term)
9548 pv (match-string 7 term)
9549 cat-p (equal pn "CATEGORY")
9550 re-p (equal (string-to-char pv) ?{)
9551 str-p (equal (string-to-char pv) ?\")
9552 time-p (save-match-data
9553 (string-match "^\"[[<].*[]>]\"$" pv))
9554 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9555 (if time-p (setq pv (org-matcher-time pv)))
9556 (setq po (org-op-to-function po (if time-p 'time str-p)))
9557 (cond
9558 ((equal pn "CATEGORY")
9559 (setq gv '(get-text-property (point) 'org-category)))
9560 ((equal pn "TODO")
9561 (setq gv 'todo))
9563 (setq gv `(org-cached-entry-get nil ,pn))))
9564 (if re-p
9565 (if (eq po 'org<>)
9566 `(not (string-match ,pv (or ,gv "")))
9567 `(string-match ,pv (or ,gv "")))
9568 (if str-p
9569 `(,po (or ,gv "") ,pv)
9570 `(,po (string-to-number (or ,gv ""))
9571 ,(string-to-number pv) ))))
9572 (t `(member ,(downcase tag) tags-list)))
9573 mm (if minus (list 'not mm) mm)
9574 term rest)
9575 (push mm tagsmatcher))
9576 (push (if (> (length tagsmatcher) 1)
9577 (cons 'and tagsmatcher)
9578 (car tagsmatcher))
9579 orlist)
9580 (setq tagsmatcher nil))
9581 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9582 (setq tagsmatcher
9583 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9584 ;; Make the todo matcher
9585 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9586 (setq todomatcher t)
9587 (setq orterms (org-split-string todomatch "|") orlist nil)
9588 (while (setq term (pop orterms))
9589 (while (string-match re term)
9590 (setq minus (and (match-end 1)
9591 (equal (match-string 1 term) "-"))
9592 kwd (match-string 2 term)
9593 re-p (equal (string-to-char kwd) ?{)
9594 term (substring term (match-end 0))
9595 mm (if re-p
9596 `(string-match ,(substring kwd 1 -1) todo)
9597 (list 'equal 'todo kwd))
9598 mm (if minus (list 'not mm) mm))
9599 (push mm todomatcher))
9600 (push (if (> (length todomatcher) 1)
9601 (cons 'and todomatcher)
9602 (car todomatcher))
9603 orlist)
9604 (setq todomatcher nil))
9605 (setq todomatcher (if (> (length orlist) 1)
9606 (cons 'or orlist) (car orlist))))
9608 ;; Return the string and lisp forms of the matcher
9609 (setq matcher (if todomatcher
9610 (list 'and tagsmatcher todomatcher)
9611 tagsmatcher))
9612 (cons match0 matcher)))
9614 (defun org-op-to-function (op &optional stringp)
9615 "Turn an operator into the appropriate function."
9616 (setq op
9617 (cond
9618 ((equal op "<" ) '(< string< org-time<))
9619 ((equal op ">" ) '(> org-string> org-time>))
9620 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9621 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9622 ((member op '("=" "==")) '(= string= org-time=))
9623 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9624 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9626 (defun org<> (a b) (not (= a b)))
9627 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9628 (defun org-string>= (a b) (not (string< a b)))
9629 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9630 (defun org-string<> (a b) (not (string= 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) (< a b)))
9633 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9634 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9635 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9636 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9637 (defun org-2ft (s)
9638 "Convert S to a floating point time.
9639 If S is already a number, just return it. If it is a string, parse
9640 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9641 (cond
9642 ((numberp s) s)
9643 ((stringp s)
9644 (condition-case nil
9645 (float-time (apply 'encode-time (org-parse-time-string s)))
9646 (error 0.)))
9647 (t 0.)))
9649 (defun org-time-today ()
9650 "Time in seconds today at 0:00.
9651 Returns the float number of seconds since the beginning of the
9652 epoch to the beginning of today (00:00)."
9653 (float-time (apply 'encode-time
9654 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9656 (defun org-matcher-time (s)
9657 "Interpret a time comparison value."
9658 (save-match-data
9659 (cond
9660 ((string= s "<now>") (float-time))
9661 ((string= s "<today>") (org-time-today))
9662 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9663 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9664 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9665 (+ (org-time-today)
9666 (* (string-to-number (match-string 1 s))
9667 (cdr (assoc (match-string 2 s)
9668 '(("d" . 86400.0) ("w" . 604800.0)
9669 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9670 (t (org-2ft s)))))
9672 (defun org-match-any-p (re list)
9673 "Does re match any element of list?"
9674 (setq list (mapcar (lambda (x) (string-match re x)) list))
9675 (delq nil list))
9677 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9678 (defvar org-tags-overlay (org-make-overlay 1 1))
9679 (org-detach-overlay org-tags-overlay)
9681 (defun org-get-local-tags-at (&optional pos)
9682 "Get a list of tags defined in the current headline."
9683 (org-get-tags-at pos 'local))
9685 (defun org-get-local-tags ()
9686 "Get a list of tags defined in the current headline."
9687 (org-get-tags-at nil 'local))
9689 (defun org-get-tags-at (&optional pos local)
9690 "Get a list of all headline tags applicable at POS.
9691 POS defaults to point. If tags are inherited, the list contains
9692 the targets in the same sequence as the headlines appear, i.e.
9693 the tags of the current headline come last.
9694 When LOCAL is non-nil, only return tags from the current headline,
9695 ignore inherited ones."
9696 (interactive)
9697 (let (tags ltags lastpos parent)
9698 (save-excursion
9699 (save-restriction
9700 (widen)
9701 (goto-char (or pos (point)))
9702 (save-match-data
9703 (catch 'done
9704 (condition-case nil
9705 (progn
9706 (org-back-to-heading t)
9707 (while (not (equal lastpos (point)))
9708 (setq lastpos (point))
9709 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9710 (setq ltags (org-split-string
9711 (org-match-string-no-properties 1) ":"))
9712 (when parent
9713 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9714 (setq tags (append
9715 (if parent
9716 (org-remove-uniherited-tags ltags)
9717 ltags)
9718 tags)))
9719 (or org-use-tag-inheritance (throw 'done t))
9720 (if local (throw 'done t))
9721 (org-up-heading-all 1)
9722 (setq parent t)))
9723 (error nil)))))
9724 (append (org-remove-uniherited-tags org-file-tags) tags))))
9726 (defun org-add-prop-inherited (s)
9727 (add-text-properties 0 (length s) '(inherited t) s)
9730 (defun org-toggle-tag (tag &optional onoff)
9731 "Toggle the tag TAG for the current line.
9732 If ONOFF is `on' or `off', don't toggle but set to this state."
9733 (let (res current)
9734 (save-excursion
9735 (org-back-to-heading t)
9736 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9737 (point-at-eol) t)
9738 (progn
9739 (setq current (match-string 1))
9740 (replace-match ""))
9741 (setq current ""))
9742 (setq current (nreverse (org-split-string current ":")))
9743 (cond
9744 ((eq onoff 'on)
9745 (setq res t)
9746 (or (member tag current) (push tag current)))
9747 ((eq onoff 'off)
9748 (or (not (member tag current)) (setq current (delete tag current))))
9749 (t (if (member tag current)
9750 (setq current (delete tag current))
9751 (setq res t)
9752 (push tag current))))
9753 (end-of-line 1)
9754 (if current
9755 (progn
9756 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9757 (org-set-tags nil t))
9758 (delete-horizontal-space))
9759 (run-hooks 'org-after-tags-change-hook))
9760 res))
9762 (defun org-align-tags-here (to-col)
9763 ;; Assumes that this is a headline
9764 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9765 (beginning-of-line 1)
9766 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9767 (< pos (match-beginning 2)))
9768 (progn
9769 (setq tags-l (- (match-end 2) (match-beginning 2)))
9770 (goto-char (match-beginning 1))
9771 (insert " ")
9772 (delete-region (point) (1+ (match-beginning 2)))
9773 (setq ncol (max (1+ (current-column))
9774 (1+ col)
9775 (if (> to-col 0)
9776 to-col
9777 (- (abs to-col) tags-l))))
9778 (setq p (point))
9779 (insert (make-string (- ncol (current-column)) ?\ ))
9780 (setq ncol (current-column))
9781 (when indent-tabs-mode (tabify p (point-at-eol)))
9782 (org-move-to-column (min ncol col) t))
9783 (goto-char pos))))
9785 (defun org-set-tags-command (&optional arg just-align)
9786 "Call the set-tags command for the current entry."
9787 (interactive "P")
9788 (if (org-on-heading-p)
9789 (org-set-tags arg just-align)
9790 (save-excursion
9791 (org-back-to-heading t)
9792 (org-set-tags arg just-align))))
9794 (defun org-set-tags (&optional arg just-align)
9795 "Set the tags for the current headline.
9796 With prefix ARG, realign all tags in headings in the current buffer."
9797 (interactive "P")
9798 (let* ((re (concat "^" outline-regexp))
9799 (current (org-get-tags-string))
9800 (col (current-column))
9801 (org-setting-tags t)
9802 table current-tags inherited-tags ; computed below when needed
9803 tags p0 c0 c1 rpl)
9804 (if arg
9805 (save-excursion
9806 (goto-char (point-min))
9807 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9808 (while (re-search-forward re nil t)
9809 (org-set-tags nil t)
9810 (end-of-line 1)))
9811 (message "All tags realigned to column %d" org-tags-column))
9812 (if just-align
9813 (setq tags current)
9814 ;; Get a new set of tags from the user
9815 (save-excursion
9816 (setq table (or org-tag-alist (org-get-buffer-tags))
9817 org-last-tags-completion-table table
9818 current-tags (org-split-string current ":")
9819 inherited-tags (nreverse
9820 (nthcdr (length current-tags)
9821 (nreverse (org-get-tags-at))))
9822 tags
9823 (if (or (eq t org-use-fast-tag-selection)
9824 (and org-use-fast-tag-selection
9825 (delq nil (mapcar 'cdr table))))
9826 (org-fast-tag-selection
9827 current-tags inherited-tags table
9828 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9829 (let ((org-add-colon-after-tag-completion t))
9830 (org-trim
9831 (org-without-partial-completion
9832 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9833 nil nil current 'org-tags-history)))))))
9834 (while (string-match "[-+&]+" tags)
9835 ;; No boolean logic, just a list
9836 (setq tags (replace-match ":" t t tags))))
9838 (if (string-match "\\`[\t ]*\\'" tags)
9839 (setq tags "")
9840 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9841 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9843 ;; Insert new tags at the correct column
9844 (beginning-of-line 1)
9845 (cond
9846 ((and (equal current "") (equal tags "")))
9847 ((re-search-forward
9848 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9849 (point-at-eol) t)
9850 (if (equal tags "")
9851 (setq rpl "")
9852 (goto-char (match-beginning 0))
9853 (setq c0 (current-column) p0 (point)
9854 c1 (max (1+ c0) (if (> org-tags-column 0)
9855 org-tags-column
9856 (- (- org-tags-column) (length tags))))
9857 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9858 (replace-match rpl t t)
9859 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9860 tags)
9861 (t (error "Tags alignment failed")))
9862 (org-move-to-column col)
9863 (unless just-align
9864 (run-hooks 'org-after-tags-change-hook)))))
9866 (defun org-change-tag-in-region (beg end tag off)
9867 "Add or remove TAG for each entry in the region.
9868 This works in the agenda, and also in an org-mode buffer."
9869 (interactive
9870 (list (region-beginning) (region-end)
9871 (let ((org-last-tags-completion-table
9872 (if (org-mode-p)
9873 (org-get-buffer-tags)
9874 (org-global-tags-completion-table))))
9875 (org-ido-completing-read
9876 "Tag: " 'org-tags-completion-function nil nil nil
9877 'org-tags-history))
9878 (progn
9879 (message "[s]et or [r]emove? ")
9880 (equal (read-char-exclusive) ?r))))
9881 (if (fboundp 'deactivate-mark) (deactivate-mark))
9882 (let ((agendap (equal major-mode 'org-agenda-mode))
9883 l1 l2 m buf pos newhead (cnt 0))
9884 (goto-char end)
9885 (setq l2 (1- (org-current-line)))
9886 (goto-char beg)
9887 (setq l1 (org-current-line))
9888 (loop for l from l1 to l2 do
9889 (goto-line l)
9890 (setq m (get-text-property (point) 'org-hd-marker))
9891 (when (or (and (org-mode-p) (org-on-heading-p))
9892 (and agendap m))
9893 (setq buf (if agendap (marker-buffer m) (current-buffer))
9894 pos (if agendap m (point)))
9895 (with-current-buffer buf
9896 (save-excursion
9897 (save-restriction
9898 (goto-char pos)
9899 (setq cnt (1+ cnt))
9900 (org-toggle-tag tag (if off 'off 'on))
9901 (setq newhead (org-get-heading)))))
9902 (and agendap (org-agenda-change-all-lines newhead m))))
9903 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9905 (defun org-tags-completion-function (string predicate &optional flag)
9906 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9907 (confirm (lambda (x) (stringp (car x)))))
9908 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9909 (setq s1 (match-string 1 string)
9910 s2 (match-string 2 string))
9911 (setq s1 "" s2 string))
9912 (cond
9913 ((eq flag nil)
9914 ;; try completion
9915 (setq rtn (try-completion s2 ctable confirm))
9916 (if (stringp rtn)
9917 (setq rtn
9918 (concat s1 s2 (substring rtn (length s2))
9919 (if (and org-add-colon-after-tag-completion
9920 (assoc rtn ctable))
9921 ":" ""))))
9922 rtn)
9923 ((eq flag t)
9924 ;; all-completions
9925 (all-completions s2 ctable confirm)
9927 ((eq flag 'lambda)
9928 ;; exact match?
9929 (assoc s2 ctable)))
9932 (defun org-fast-tag-insert (kwd tags face &optional end)
9933 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9934 (insert (format "%-12s" (concat kwd ":"))
9935 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9936 (or end "")))
9938 (defun org-fast-tag-show-exit (flag)
9939 (save-excursion
9940 (goto-line 3)
9941 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9942 (replace-match ""))
9943 (when flag
9944 (end-of-line 1)
9945 (org-move-to-column (- (window-width) 19) t)
9946 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9948 (defun org-set-current-tags-overlay (current prefix)
9949 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9950 (if (featurep 'xemacs)
9951 (org-overlay-display org-tags-overlay (concat prefix s)
9952 'secondary-selection)
9953 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9954 (org-overlay-display org-tags-overlay (concat prefix s)))))
9956 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9957 "Fast tag selection with single keys.
9958 CURRENT is the current list of tags in the headline, INHERITED is the
9959 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9960 possibly with grouping information. TODO-TABLE is a similar table with
9961 TODO keywords, should these have keys assigned to them.
9962 If the keys are nil, a-z are automatically assigned.
9963 Returns the new tags string, or nil to not change the current settings."
9964 (let* ((fulltable (append table todo-table))
9965 (maxlen (apply 'max (mapcar
9966 (lambda (x)
9967 (if (stringp (car x)) (string-width (car x)) 0))
9968 fulltable)))
9969 (buf (current-buffer))
9970 (expert (eq org-fast-tag-selection-single-key 'expert))
9971 (buffer-tags nil)
9972 (fwidth (+ maxlen 3 1 3))
9973 (ncol (/ (- (window-width) 4) fwidth))
9974 (i-face 'org-done)
9975 (c-face 'org-todo)
9976 tg cnt e c char c1 c2 ntable tbl rtn
9977 ov-start ov-end ov-prefix
9978 (exit-after-next org-fast-tag-selection-single-key)
9979 (done-keywords org-done-keywords)
9980 groups ingroup)
9981 (save-excursion
9982 (beginning-of-line 1)
9983 (if (looking-at
9984 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9985 (setq ov-start (match-beginning 1)
9986 ov-end (match-end 1)
9987 ov-prefix "")
9988 (setq ov-start (1- (point-at-eol))
9989 ov-end (1+ ov-start))
9990 (skip-chars-forward "^\n\r")
9991 (setq ov-prefix
9992 (concat
9993 (buffer-substring (1- (point)) (point))
9994 (if (> (current-column) org-tags-column)
9996 (make-string (- org-tags-column (current-column)) ?\ ))))))
9997 (org-move-overlay org-tags-overlay ov-start ov-end)
9998 (save-window-excursion
9999 (if expert
10000 (set-buffer (get-buffer-create " *Org tags*"))
10001 (delete-other-windows)
10002 (split-window-vertically)
10003 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10004 (erase-buffer)
10005 (org-set-local 'org-done-keywords done-keywords)
10006 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10007 (org-fast-tag-insert "Current" current c-face "\n\n")
10008 (org-fast-tag-show-exit exit-after-next)
10009 (org-set-current-tags-overlay current ov-prefix)
10010 (setq tbl fulltable char ?a cnt 0)
10011 (while (setq e (pop tbl))
10012 (cond
10013 ((equal e '(:startgroup))
10014 (push '() groups) (setq ingroup t)
10015 (when (not (= cnt 0))
10016 (setq cnt 0)
10017 (insert "\n"))
10018 (insert "{ "))
10019 ((equal e '(:endgroup))
10020 (setq ingroup nil cnt 0)
10021 (insert "}\n"))
10023 (setq tg (car e) c2 nil)
10024 (if (cdr e)
10025 (setq c (cdr e))
10026 ;; automatically assign a character.
10027 (setq c1 (string-to-char
10028 (downcase (substring
10029 tg (if (= (string-to-char tg) ?@) 1 0)))))
10030 (if (or (rassoc c1 ntable) (rassoc c1 table))
10031 (while (or (rassoc char ntable) (rassoc char table))
10032 (setq char (1+ char)))
10033 (setq c2 c1))
10034 (setq c (or c2 char)))
10035 (if ingroup (push tg (car groups)))
10036 (setq tg (org-add-props tg nil 'face
10037 (cond
10038 ((not (assoc tg table))
10039 (org-get-todo-face tg))
10040 ((member tg current) c-face)
10041 ((member tg inherited) i-face)
10042 (t nil))))
10043 (if (and (= cnt 0) (not ingroup)) (insert " "))
10044 (insert "[" c "] " tg (make-string
10045 (- fwidth 4 (length tg)) ?\ ))
10046 (push (cons tg c) ntable)
10047 (when (= (setq cnt (1+ cnt)) ncol)
10048 (insert "\n")
10049 (if ingroup (insert " "))
10050 (setq cnt 0)))))
10051 (setq ntable (nreverse ntable))
10052 (insert "\n")
10053 (goto-char (point-min))
10054 (if (not expert) (org-fit-window-to-buffer))
10055 (setq rtn
10056 (catch 'exit
10057 (while t
10058 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10059 (if groups " [!] no groups" " [!]groups")
10060 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10061 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10062 (cond
10063 ((= c ?\r) (throw 'exit t))
10064 ((= c ?!)
10065 (setq groups (not groups))
10066 (goto-char (point-min))
10067 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10068 ((= c ?\C-c)
10069 (if (not expert)
10070 (org-fast-tag-show-exit
10071 (setq exit-after-next (not exit-after-next)))
10072 (setq expert nil)
10073 (delete-other-windows)
10074 (split-window-vertically)
10075 (org-switch-to-buffer-other-window " *Org tags*")
10076 (org-fit-window-to-buffer)))
10077 ((or (= c ?\C-g)
10078 (and (= c ?q) (not (rassoc c ntable))))
10079 (org-detach-overlay org-tags-overlay)
10080 (setq quit-flag t))
10081 ((= c ?\ )
10082 (setq current nil)
10083 (if exit-after-next (setq exit-after-next 'now)))
10084 ((= c ?\t)
10085 (condition-case nil
10086 (setq tg (org-ido-completing-read
10087 "Tag: "
10088 (or buffer-tags
10089 (with-current-buffer buf
10090 (org-get-buffer-tags)))))
10091 (quit (setq tg "")))
10092 (when (string-match "\\S-" tg)
10093 (add-to-list 'buffer-tags (list tg))
10094 (if (member tg current)
10095 (setq current (delete tg current))
10096 (push tg current)))
10097 (if exit-after-next (setq exit-after-next 'now)))
10098 ((setq e (rassoc c todo-table) tg (car e))
10099 (with-current-buffer buf
10100 (save-excursion (org-todo tg)))
10101 (if exit-after-next (setq exit-after-next 'now)))
10102 ((setq e (rassoc c ntable) tg (car e))
10103 (if (member tg current)
10104 (setq current (delete tg current))
10105 (loop for g in groups do
10106 (if (member tg g)
10107 (mapc (lambda (x)
10108 (setq current (delete x current)))
10109 g)))
10110 (push tg current))
10111 (if exit-after-next (setq exit-after-next 'now))))
10113 ;; Create a sorted list
10114 (setq current
10115 (sort current
10116 (lambda (a b)
10117 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10118 (if (eq exit-after-next 'now) (throw 'exit t))
10119 (goto-char (point-min))
10120 (beginning-of-line 2)
10121 (delete-region (point) (point-at-eol))
10122 (org-fast-tag-insert "Current" current c-face)
10123 (org-set-current-tags-overlay current ov-prefix)
10124 (while (re-search-forward
10125 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10126 (setq tg (match-string 1))
10127 (add-text-properties
10128 (match-beginning 1) (match-end 1)
10129 (list 'face
10130 (cond
10131 ((member tg current) c-face)
10132 ((member tg inherited) i-face)
10133 (t (get-text-property (match-beginning 1) 'face))))))
10134 (goto-char (point-min)))))
10135 (org-detach-overlay org-tags-overlay)
10136 (if rtn
10137 (mapconcat 'identity current ":")
10138 nil))))
10140 (defun org-get-tags-string ()
10141 "Get the TAGS string in the current headline."
10142 (unless (org-on-heading-p t)
10143 (error "Not on a heading"))
10144 (save-excursion
10145 (beginning-of-line 1)
10146 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10147 (org-match-string-no-properties 1)
10148 "")))
10150 (defun org-get-tags ()
10151 "Get the list of tags specified in the current headline."
10152 (org-split-string (org-get-tags-string) ":"))
10154 (defun org-get-buffer-tags ()
10155 "Get a table of all tags used in the buffer, for completion."
10156 (let (tags)
10157 (save-excursion
10158 (goto-char (point-min))
10159 (while (re-search-forward
10160 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10161 (when (equal (char-after (point-at-bol 0)) ?*)
10162 (mapc (lambda (x) (add-to-list 'tags x))
10163 (org-split-string (org-match-string-no-properties 1) ":")))))
10164 (mapcar 'list tags)))
10166 ;;;; The mapping API
10168 ;;;###autoload
10169 (defun org-map-entries (func &optional match scope &rest skip)
10170 "Call FUNC at each headline selected by MATCH in SCOPE.
10172 FUNC is a function or a lisp form. The function will be called without
10173 arguments, with the cursor positioned at the beginning of the headline.
10174 The return values of all calls to the function will be collected and
10175 returned as a list.
10177 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10178 Only headlines that are matched by this query will be considered during
10179 the iteration. When MATCH is nil or t, all headlines will be
10180 visited by the iteration.
10182 SCOPE determines the scope of this command. It can be any of:
10184 nil The current buffer, respecting the restriction if any
10185 tree The subtree started with the entry at point
10186 file The current buffer, without restriction
10187 file-with-archives
10188 The current buffer, and any archives associated with it
10189 agenda All agenda files
10190 agenda-with-archives
10191 All agenda files with any archive files associated with them
10192 \(file1 file2 ...)
10193 If this is a list, all files in the list will be scanned
10195 The remaining args are treated as settings for the skipping facilities of
10196 the scanner. The following items can be given here:
10198 archive skip trees with the archive tag.
10199 comment skip trees with the COMMENT keyword
10200 function or Emacs Lisp form:
10201 will be used as value for `org-agenda-skip-function', so whenever
10202 the the function returns t, FUNC will not be called for that
10203 entry and search will continue from the point where the
10204 function leaves it."
10205 (let* ((org-agenda-archives-mode nil) ; just to make sure
10206 (org-agenda-skip-archived-trees (memq 'archive skip))
10207 (org-agenda-skip-comment-trees (memq 'comment skip))
10208 (org-agenda-skip-function
10209 (car (org-delete-all '(comment archive) skip)))
10210 (org-tags-match-list-sublevels t)
10211 matcher file res
10212 org-todo-keywords-for-agenda
10213 org-done-keywords-for-agenda
10214 org-todo-keyword-alist-for-agenda
10215 org-tag-alist-for-agenda)
10217 (cond
10218 ((eq match t) (setq matcher t))
10219 ((eq match nil) (setq matcher t))
10220 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10222 (save-excursion
10223 (save-restriction
10224 (when (eq scope 'tree)
10225 (org-back-to-heading t)
10226 (org-narrow-to-subtree)
10227 (setq scope nil))
10229 (if (not scope)
10230 (progn
10231 (org-prepare-agenda-buffers
10232 (list (buffer-file-name (current-buffer))))
10233 (setq res (org-scan-tags func matcher)))
10234 ;; Get the right scope
10235 (cond
10236 ((and scope (listp scope) (symbolp (car scope)))
10237 (setq scope (eval scope)))
10238 ((eq scope 'agenda)
10239 (setq scope (org-agenda-files t)))
10240 ((eq scope 'agenda-with-archives)
10241 (setq scope (org-agenda-files t))
10242 (setq scope (org-add-archive-files scope)))
10243 ((eq scope 'file)
10244 (setq scope (list (buffer-file-name))))
10245 ((eq scope 'file-with-archives)
10246 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10247 (org-prepare-agenda-buffers scope)
10248 (while (setq file (pop scope))
10249 (with-current-buffer (org-find-base-buffer-visiting file)
10250 (save-excursion
10251 (save-restriction
10252 (widen)
10253 (goto-char (point-min))
10254 (setq res (append res (org-scan-tags func matcher))))))))))
10255 res))
10257 ;;;; Properties
10259 ;;; Setting and retrieving properties
10261 (defconst org-special-properties
10262 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10263 "TIMESTAMP" "TIMESTAMP_IA")
10264 "The special properties valid in Org-mode.
10266 These are properties that are not defined in the property drawer,
10267 but in some other way.")
10269 (defconst org-default-properties
10270 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10271 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10272 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10273 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10274 "Some properties that are used by Org-mode for various purposes.
10275 Being in this list makes sure that they are offered for completion.")
10277 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10278 "Regular expression matching the first line of a property drawer.")
10280 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10281 "Regular expression matching the first line of a property drawer.")
10283 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10284 "Regular expression matching the first line of a property drawer.")
10286 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10287 "Regular expression matching the first line of a property drawer.")
10289 (defconst org-property-drawer-re
10290 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10291 org-property-end-re "\\)\n?")
10292 "Matches an entire property drawer.")
10294 (defconst org-clock-drawer-re
10295 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10296 org-property-end-re "\\)\n?")
10297 "Matches an entire clock drawer.")
10299 (defun org-property-action ()
10300 "Do an action on properties."
10301 (interactive)
10302 (let (c)
10303 (org-at-property-p)
10304 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10305 (setq c (read-char-exclusive))
10306 (cond
10307 ((equal c ?s)
10308 (call-interactively 'org-set-property))
10309 ((equal c ?d)
10310 (call-interactively 'org-delete-property))
10311 ((equal c ?D)
10312 (call-interactively 'org-delete-property-globally))
10313 ((equal c ?c)
10314 (call-interactively 'org-compute-property-at-point))
10315 (t (error "No such property action %c" c)))))
10317 (defun org-at-property-p ()
10318 "Is the cursor in a property line?"
10319 ;; FIXME: Does not check if we are actually in the drawer.
10320 ;; FIXME: also returns true on any drawers.....
10321 ;; This is used by C-c C-c for property action.
10322 (save-excursion
10323 (beginning-of-line 1)
10324 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10326 (defun org-get-property-block (&optional beg end force)
10327 "Return the (beg . end) range of the body of the property drawer.
10328 BEG and END can be beginning and end of subtree, if not given
10329 they will be found.
10330 If the drawer does not exist and FORCE is non-nil, create the drawer."
10331 (catch 'exit
10332 (save-excursion
10333 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10334 (end (or end (progn (outline-next-heading) (point)))))
10335 (goto-char beg)
10336 (if (re-search-forward org-property-start-re end t)
10337 (setq beg (1+ (match-end 0)))
10338 (if force
10339 (save-excursion
10340 (org-insert-property-drawer)
10341 (setq end (progn (outline-next-heading) (point))))
10342 (throw 'exit nil))
10343 (goto-char beg)
10344 (if (re-search-forward org-property-start-re end t)
10345 (setq beg (1+ (match-end 0)))))
10346 (if (re-search-forward org-property-end-re end t)
10347 (setq end (match-beginning 0))
10348 (or force (throw 'exit nil))
10349 (goto-char beg)
10350 (setq end beg)
10351 (org-indent-line-function)
10352 (insert ":END:\n"))
10353 (cons beg end)))))
10355 (defun org-entry-properties (&optional pom which)
10356 "Get all properties of the entry at point-or-marker POM.
10357 This includes the TODO keyword, the tags, time strings for deadline,
10358 scheduled, and clocking, and any additional properties defined in the
10359 entry. The return value is an alist, keys may occur multiple times
10360 if the property key was used several times.
10361 POM may also be nil, in which case the current entry is used.
10362 If WHICH is nil or `all', get all properties. If WHICH is
10363 `special' or `standard', only get that subclass."
10364 (setq which (or which 'all))
10365 (org-with-point-at pom
10366 (let ((clockstr (substring org-clock-string 0 -1))
10367 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10368 beg end range props sum-props key value string clocksum)
10369 (save-excursion
10370 (when (condition-case nil
10371 (and (org-mode-p) (org-back-to-heading t))
10372 (error nil))
10373 (setq beg (point))
10374 (setq sum-props (get-text-property (point) 'org-summaries))
10375 (setq clocksum (get-text-property (point) :org-clock-minutes))
10376 (outline-next-heading)
10377 (setq end (point))
10378 (when (memq which '(all special))
10379 ;; Get the special properties, like TODO and tags
10380 (goto-char beg)
10381 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10382 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10383 (when (looking-at org-priority-regexp)
10384 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10385 (when (and (setq value (org-get-tags-string))
10386 (string-match "\\S-" value))
10387 (push (cons "TAGS" value) props))
10388 (when (setq value (org-get-tags-at))
10389 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10390 props))
10391 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10392 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10393 string (if (equal key clockstr)
10394 (org-no-properties
10395 (org-trim
10396 (buffer-substring
10397 (match-beginning 3) (goto-char (point-at-eol)))))
10398 (substring (org-match-string-no-properties 3) 1 -1)))
10399 (unless key
10400 (if (= (char-after (match-beginning 3)) ?\[)
10401 (setq key "TIMESTAMP_IA")
10402 (setq key "TIMESTAMP")))
10403 (when (or (equal key clockstr) (not (assoc key props)))
10404 (push (cons key string) props)))
10408 (when (memq which '(all standard))
10409 ;; Get the standard properties, like :PORP: ...
10410 (setq range (org-get-property-block beg end))
10411 (when range
10412 (goto-char (car range))
10413 (while (re-search-forward
10414 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10415 (cdr range) t)
10416 (setq key (org-match-string-no-properties 1)
10417 value (org-trim (or (org-match-string-no-properties 2) "")))
10418 (unless (member key excluded)
10419 (push (cons key (or value "")) props)))))
10420 (if clocksum
10421 (push (cons "CLOCKSUM"
10422 (org-columns-number-to-string (/ (float clocksum) 60.)
10423 'add_times))
10424 props))
10425 (unless (assoc "CATEGORY" props)
10426 (setq value (or (org-get-category)
10427 (progn (org-refresh-category-properties)
10428 (org-get-category))))
10429 (push (cons "CATEGORY" value) props))
10430 (append sum-props (nreverse props)))))))
10432 (defun org-entry-get (pom property &optional inherit)
10433 "Get value of PROPERTY for entry at point-or-marker POM.
10434 If INHERIT is non-nil and the entry does not have the property,
10435 then also check higher levels of the hierarchy.
10436 If INHERIT is the symbol `selective', use inheritance only if the setting
10437 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10438 If the property is present but empty, the return value is the empty string.
10439 If the property is not present at all, nil is returned."
10440 (org-with-point-at pom
10441 (if (and inherit (if (eq inherit 'selective)
10442 (org-property-inherit-p property)
10444 (org-entry-get-with-inheritance property)
10445 (if (member property org-special-properties)
10446 ;; We need a special property. Use brute force, get all properties.
10447 (cdr (assoc property (org-entry-properties nil 'special)))
10448 (let ((range (org-get-property-block)))
10449 (if (and range
10450 (goto-char (car range))
10451 (re-search-forward
10452 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10453 (cdr range) t))
10454 ;; Found the property, return it.
10455 (if (match-end 1)
10456 (org-match-string-no-properties 1)
10457 "")))))))
10459 (defun org-property-or-variable-value (var &optional inherit)
10460 "Check if there is a property fixing the value of VAR.
10461 If yes, return this value. If not, return the current value of the variable."
10462 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10463 (if (and prop (stringp prop) (string-match "\\S-" prop))
10464 (read prop)
10465 (symbol-value var))))
10467 (defun org-entry-delete (pom property)
10468 "Delete the property PROPERTY from entry at point-or-marker POM."
10469 (org-with-point-at pom
10470 (if (member property org-special-properties)
10471 nil ; cannot delete these properties.
10472 (let ((range (org-get-property-block)))
10473 (if (and range
10474 (goto-char (car range))
10475 (re-search-forward
10476 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10477 (cdr range) t))
10478 (progn
10479 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10481 nil)))))
10483 ;; Multi-values properties are properties that contain multiple values
10484 ;; These values are assumed to be single words, separated by whitespace.
10485 (defun org-entry-add-to-multivalued-property (pom property value)
10486 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10487 (let* ((old (org-entry-get pom property))
10488 (values (and old (org-split-string old "[ \t]"))))
10489 (setq value (org-entry-protect-space value))
10490 (unless (member value values)
10491 (setq values (cons value values))
10492 (org-entry-put pom property
10493 (mapconcat 'identity values " ")))))
10495 (defun org-entry-remove-from-multivalued-property (pom property value)
10496 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10497 (let* ((old (org-entry-get pom property))
10498 (values (and old (org-split-string old "[ \t]"))))
10499 (setq value (org-entry-protect-space value))
10500 (when (member value values)
10501 (setq values (delete value values))
10502 (org-entry-put pom property
10503 (mapconcat 'identity values " ")))))
10505 (defun org-entry-member-in-multivalued-property (pom property value)
10506 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10507 (let* ((old (org-entry-get pom property))
10508 (values (and old (org-split-string old "[ \t]"))))
10509 (setq value (org-entry-protect-space value))
10510 (member value values)))
10512 (defun org-entry-get-multivalued-property (pom property)
10513 "Return a list of values in a multivalued property."
10514 (let* ((value (org-entry-get pom property))
10515 (values (and value (org-split-string value "[ \t]"))))
10516 (mapcar 'org-entry-restore-space values)))
10518 (defun org-entry-put-multivalued-property (pom property &rest values)
10519 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10520 VALUES should be a list of strings. Spaces will be protected."
10521 (org-entry-put pom property
10522 (mapconcat 'org-entry-protect-space values " "))
10523 (let* ((value (org-entry-get pom property))
10524 (values (and value (org-split-string value "[ \t]"))))
10525 (mapcar 'org-entry-restore-space values)))
10527 (defun org-entry-protect-space (s)
10528 "Protect spaces and newline in string S."
10529 (while (string-match " " s)
10530 (setq s (replace-match "%20" t t s)))
10531 (while (string-match "\n" s)
10532 (setq s (replace-match "%0A" t t s)))
10535 (defun org-entry-restore-space (s)
10536 "Restore spaces and newline in string S."
10537 (while (string-match "%20" s)
10538 (setq s (replace-match " " t t s)))
10539 (while (string-match "%0A" s)
10540 (setq s (replace-match "\n" t t s)))
10543 (defvar org-entry-property-inherited-from (make-marker)
10544 "Marker pointing to the entry from where a property was inherited.
10545 Each call to `org-entry-get-with-inheritance' will set this marker to the
10546 location of the entry where the inheritance search matched. If there was
10547 no match, the marker will point nowhere.
10548 Note that also `org-entry-get' calls this function, if the INHERIT flag
10549 is set.")
10551 (defun org-entry-get-with-inheritance (property)
10552 "Get entry property, and search higher levels if not present."
10553 (move-marker org-entry-property-inherited-from nil)
10554 (let (tmp)
10555 (save-excursion
10556 (save-restriction
10557 (widen)
10558 (catch 'ex
10559 (while t
10560 (when (setq tmp (org-entry-get nil property))
10561 (org-back-to-heading t)
10562 (move-marker org-entry-property-inherited-from (point))
10563 (throw 'ex tmp))
10564 (or (org-up-heading-safe) (throw 'ex nil)))))
10565 (or tmp
10566 (cdr (assoc property org-file-properties))
10567 (cdr (assoc property org-global-properties))
10568 (cdr (assoc property org-global-properties-fixed))))))
10570 (defun org-entry-put (pom property value)
10571 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10572 (org-with-point-at pom
10573 (org-back-to-heading t)
10574 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10575 range)
10576 (cond
10577 ((equal property "TODO")
10578 (when (and (stringp value) (string-match "\\S-" value)
10579 (not (member value org-todo-keywords-1)))
10580 (error "\"%s\" is not a valid TODO state" value))
10581 (if (or (not value)
10582 (not (string-match "\\S-" value)))
10583 (setq value 'none))
10584 (org-todo value)
10585 (org-set-tags nil 'align))
10586 ((equal property "PRIORITY")
10587 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10588 (string-to-char value) ?\ ))
10589 (org-set-tags nil 'align))
10590 ((equal property "SCHEDULED")
10591 (if (re-search-forward org-scheduled-time-regexp end t)
10592 (cond
10593 ((eq value 'earlier) (org-timestamp-change -1 'day))
10594 ((eq value 'later) (org-timestamp-change 1 'day))
10595 (t (call-interactively 'org-schedule)))
10596 (call-interactively 'org-schedule)))
10597 ((equal property "DEADLINE")
10598 (if (re-search-forward org-deadline-time-regexp end t)
10599 (cond
10600 ((eq value 'earlier) (org-timestamp-change -1 'day))
10601 ((eq value 'later) (org-timestamp-change 1 'day))
10602 (t (call-interactively 'org-deadline)))
10603 (call-interactively 'org-deadline)))
10604 ((member property org-special-properties)
10605 (error "The %s property can not yet be set with `org-entry-put'"
10606 property))
10607 (t ; a non-special property
10608 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10609 (setq range (org-get-property-block beg end 'force))
10610 (goto-char (car range))
10611 (if (re-search-forward
10612 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10613 (progn
10614 (delete-region (match-beginning 1) (match-end 1))
10615 (goto-char (match-beginning 1)))
10616 (goto-char (cdr range))
10617 (insert "\n")
10618 (backward-char 1)
10619 (org-indent-line-function)
10620 (insert ":" property ":"))
10621 (and value (insert " " value))
10622 (org-indent-line-function)))))))
10624 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10625 "Get all property keys in the current buffer.
10626 With INCLUDE-SPECIALS, also list the special properties that reflect things
10627 like tags and TODO state.
10628 With INCLUDE-DEFAULTS, also include properties that has special meaning
10629 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10630 With INCLUDE-COLUMNS, also include property names given in COLUMN
10631 formats in the current buffer."
10632 (let (rtn range cfmt s p)
10633 (save-excursion
10634 (save-restriction
10635 (widen)
10636 (goto-char (point-min))
10637 (while (re-search-forward org-property-start-re nil t)
10638 (setq range (org-get-property-block))
10639 (goto-char (car range))
10640 (while (re-search-forward
10641 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10642 (cdr range) t)
10643 (add-to-list 'rtn (org-match-string-no-properties 1)))
10644 (outline-next-heading))))
10646 (when include-specials
10647 (setq rtn (append org-special-properties rtn)))
10649 (when include-defaults
10650 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10652 (when include-columns
10653 (save-excursion
10654 (save-restriction
10655 (widen)
10656 (goto-char (point-min))
10657 (while (re-search-forward
10658 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10659 nil t)
10660 (setq cfmt (match-string 2) s 0)
10661 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10662 cfmt s)
10663 (setq s (match-end 0)
10664 p (match-string 1 cfmt))
10665 (unless (or (equal p "ITEM")
10666 (member p org-special-properties))
10667 (add-to-list 'rtn (match-string 1 cfmt))))))))
10669 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10671 (defun org-property-values (key)
10672 "Return a list of all values of property KEY."
10673 (save-excursion
10674 (save-restriction
10675 (widen)
10676 (goto-char (point-min))
10677 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10678 values)
10679 (while (re-search-forward re nil t)
10680 (add-to-list 'values (org-trim (match-string 1))))
10681 (delete "" values)))))
10683 (defun org-insert-property-drawer ()
10684 "Insert a property drawer into the current entry."
10685 (interactive)
10686 (org-back-to-heading t)
10687 (looking-at outline-regexp)
10688 (let ((indent (- (match-end 0)(match-beginning 0)))
10689 (beg (point))
10690 (re (concat "^[ \t]*" org-keyword-time-regexp))
10691 end hiddenp)
10692 (outline-next-heading)
10693 (setq end (point))
10694 (goto-char beg)
10695 (while (re-search-forward re end t))
10696 (setq hiddenp (org-invisible-p))
10697 (end-of-line 1)
10698 (and (equal (char-after) ?\n) (forward-char 1))
10699 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10700 (beginning-of-line 2))
10701 (org-skip-over-state-notes)
10702 (skip-chars-backward " \t\n\r")
10703 (if (eq (char-before) ?*) (forward-char 1))
10704 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10705 (beginning-of-line 0)
10706 (org-indent-to-column indent)
10707 (beginning-of-line 2)
10708 (org-indent-to-column indent)
10709 (beginning-of-line 0)
10710 (if hiddenp
10711 (save-excursion
10712 (org-back-to-heading t)
10713 (hide-entry))
10714 (org-flag-drawer t))))
10716 (defun org-set-property (property value)
10717 "In the current entry, set PROPERTY to VALUE.
10718 When called interactively, this will prompt for a property name, offering
10719 completion on existing and default properties. And then it will prompt
10720 for a value, offering completion either on allowed values (via an inherited
10721 xxx_ALL property) or on existing values in other instances of this property
10722 in the current file."
10723 (interactive
10724 (let* ((completion-ignore-case t)
10725 (keys (org-buffer-property-keys nil t t))
10726 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10727 (prop (if (member prop0 keys)
10728 prop0
10729 (or (cdr (assoc (downcase prop0)
10730 (mapcar (lambda (x) (cons (downcase x) x))
10731 keys)))
10732 prop0)))
10733 (cur (org-entry-get nil prop))
10734 (allowed (org-property-get-allowed-values nil prop 'table))
10735 (existing (mapcar 'list (org-property-values prop)))
10736 (val (if allowed
10737 (org-completing-read "Value: " allowed nil 'req-match)
10738 (org-completing-read
10739 (concat "Value" (if (and cur (string-match "\\S-" cur))
10740 (concat "[" cur "]") "")
10741 ": ")
10742 existing nil nil "" nil cur))))
10743 (list prop (if (equal val "") cur val))))
10744 (unless (equal (org-entry-get nil property) value)
10745 (org-entry-put nil property value)))
10747 (defun org-delete-property (property)
10748 "In the current entry, delete PROPERTY."
10749 (interactive
10750 (let* ((completion-ignore-case t)
10751 (prop (org-ido-completing-read
10752 "Property: " (org-entry-properties nil 'standard))))
10753 (list prop)))
10754 (message "Property %s %s" property
10755 (if (org-entry-delete nil property)
10756 "deleted"
10757 "was not present in the entry")))
10759 (defun org-delete-property-globally (property)
10760 "Remove PROPERTY globally, from all entries."
10761 (interactive
10762 (let* ((completion-ignore-case t)
10763 (prop (org-ido-completing-read
10764 "Globally remove property: "
10765 (mapcar 'list (org-buffer-property-keys)))))
10766 (list prop)))
10767 (save-excursion
10768 (save-restriction
10769 (widen)
10770 (goto-char (point-min))
10771 (let ((cnt 0))
10772 (while (re-search-forward
10773 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10774 nil t)
10775 (setq cnt (1+ cnt))
10776 (replace-match ""))
10777 (message "Property \"%s\" removed from %d entries" property cnt)))))
10779 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10781 (defun org-compute-property-at-point ()
10782 "Compute the property at point.
10783 This looks for an enclosing column format, extracts the operator and
10784 then applies it to the property in the column format's scope."
10785 (interactive)
10786 (unless (org-at-property-p)
10787 (error "Not at a property"))
10788 (let ((prop (org-match-string-no-properties 2)))
10789 (org-columns-get-format-and-top-level)
10790 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10791 (error "No operator defined for property %s" prop))
10792 (org-columns-compute prop)))
10794 (defun org-property-get-allowed-values (pom property &optional table)
10795 "Get allowed values for the property PROPERTY.
10796 When TABLE is non-nil, return an alist that can directly be used for
10797 completion."
10798 (let (vals)
10799 (cond
10800 ((equal property "TODO")
10801 (setq vals (org-with-point-at pom
10802 (append org-todo-keywords-1 '("")))))
10803 ((equal property "PRIORITY")
10804 (let ((n org-lowest-priority))
10805 (while (>= n org-highest-priority)
10806 (push (char-to-string n) vals)
10807 (setq n (1- n)))))
10808 ((member property org-special-properties))
10810 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10812 (when (and vals (string-match "\\S-" vals))
10813 (setq vals (car (read-from-string (concat "(" vals ")"))))
10814 (setq vals (mapcar (lambda (x)
10815 (cond ((stringp x) x)
10816 ((numberp x) (number-to-string x))
10817 ((symbolp x) (symbol-name x))
10818 (t "???")))
10819 vals)))))
10820 (if table (mapcar 'list vals) vals)))
10822 (defun org-property-previous-allowed-value (&optional previous)
10823 "Switch to the next allowed value for this property."
10824 (interactive)
10825 (org-property-next-allowed-value t))
10827 (defun org-property-next-allowed-value (&optional previous)
10828 "Switch to the next allowed value for this property."
10829 (interactive)
10830 (unless (org-at-property-p)
10831 (error "Not at a property"))
10832 (let* ((key (match-string 2))
10833 (value (match-string 3))
10834 (allowed (or (org-property-get-allowed-values (point) key)
10835 (and (member value '("[ ]" "[-]" "[X]"))
10836 '("[ ]" "[X]"))))
10837 nval)
10838 (unless allowed
10839 (error "Allowed values for this property have not been defined"))
10840 (if previous (setq allowed (reverse allowed)))
10841 (if (member value allowed)
10842 (setq nval (car (cdr (member value allowed)))))
10843 (setq nval (or nval (car allowed)))
10844 (if (equal nval value)
10845 (error "Only one allowed value for this property"))
10846 (org-at-property-p)
10847 (replace-match (concat " :" key ": " nval) t t)
10848 (org-indent-line-function)
10849 (beginning-of-line 1)
10850 (skip-chars-forward " \t")))
10852 (defun org-find-entry-with-id (ident)
10853 "Locate the entry that contains the ID property with exact value IDENT.
10854 IDENT can be a string, a symbol or a number, this function will search for
10855 the string representation of it.
10856 Return the position where this entry starts, or nil if there is no such entry."
10857 (interactive "sID: ")
10858 (let ((id (cond
10859 ((stringp ident) ident)
10860 ((symbol-name ident) (symbol-name ident))
10861 ((numberp ident) (number-to-string ident))
10862 (t (error "IDENT %s must be a string, symbol or number" ident))))
10863 (case-fold-search nil))
10864 (save-excursion
10865 (save-restriction
10866 (widen)
10867 (goto-char (point-min))
10868 (when (re-search-forward
10869 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10870 nil t)
10871 (org-back-to-heading)
10872 (point))))))
10874 ;;;; Timestamps
10876 (defvar org-last-changed-timestamp nil)
10877 (defvar org-last-inserted-timestamp nil
10878 "The last time stamp inserted with `org-insert-time-stamp'.")
10879 (defvar org-time-was-given) ; dynamically scoped parameter
10880 (defvar org-end-time-was-given) ; dynamically scoped parameter
10881 (defvar org-ts-what) ; dynamically scoped parameter
10883 (defun org-time-stamp (arg &optional inactive)
10884 "Prompt for a date/time and insert a time stamp.
10885 If the user specifies a time like HH:MM, or if this command is called
10886 with a prefix argument, the time stamp will contain date and time.
10887 Otherwise, only the date will be included. All parts of a date not
10888 specified by the user will be filled in from the current date/time.
10889 So if you press just return without typing anything, the time stamp
10890 will represent the current date/time. If there is already a timestamp
10891 at the cursor, it will be modified."
10892 (interactive "P")
10893 (let* ((ts nil)
10894 (default-time
10895 ;; Default time is either today, or, when entering a range,
10896 ;; the range start.
10897 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10898 (save-excursion
10899 (re-search-backward
10900 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10901 (- (point) 20) t)))
10902 (apply 'encode-time (org-parse-time-string (match-string 1)))
10903 (current-time)))
10904 (default-input (and ts (org-get-compact-tod ts)))
10905 org-time-was-given org-end-time-was-given time)
10906 (cond
10907 ((and (org-at-timestamp-p t)
10908 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10909 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10910 (insert "--")
10911 (setq time (let ((this-command this-command))
10912 (org-read-date arg 'totime nil nil
10913 default-time default-input)))
10914 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10915 ((org-at-timestamp-p t)
10916 (setq time (let ((this-command this-command))
10917 (org-read-date arg 'totime nil nil default-time default-input)))
10918 (when (org-at-timestamp-p t) ; just to get the match data
10919 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10920 (replace-match "")
10921 (setq org-last-changed-timestamp
10922 (org-insert-time-stamp
10923 time (or org-time-was-given arg)
10924 inactive nil nil (list org-end-time-was-given))))
10925 (message "Timestamp updated"))
10927 (setq time (let ((this-command this-command))
10928 (org-read-date arg 'totime nil nil default-time default-input)))
10929 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10930 nil nil (list org-end-time-was-given))))))
10932 ;; FIXME: can we use this for something else, like computing time differences?
10933 (defun org-get-compact-tod (s)
10934 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10935 (let* ((t1 (match-string 1 s))
10936 (h1 (string-to-number (match-string 2 s)))
10937 (m1 (string-to-number (match-string 3 s)))
10938 (t2 (and (match-end 4) (match-string 5 s)))
10939 (h2 (and t2 (string-to-number (match-string 6 s))))
10940 (m2 (and t2 (string-to-number (match-string 7 s))))
10941 dh dm)
10942 (if (not t2)
10944 (setq dh (- h2 h1) dm (- m2 m1))
10945 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10946 (concat t1 "+" (number-to-string dh)
10947 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10949 (defun org-time-stamp-inactive (&optional arg)
10950 "Insert an inactive time stamp.
10951 An inactive time stamp is enclosed in square brackets instead of angle
10952 brackets. It is inactive in the sense that it does not trigger agenda entries,
10953 does not link to the calendar and cannot be changed with the S-cursor keys.
10954 So these are more for recording a certain time/date."
10955 (interactive "P")
10956 (org-time-stamp arg 'inactive))
10958 (defvar org-date-ovl (org-make-overlay 1 1))
10959 (org-overlay-put org-date-ovl 'face 'org-warning)
10960 (org-detach-overlay org-date-ovl)
10962 (defvar org-ans1) ; dynamically scoped parameter
10963 (defvar org-ans2) ; dynamically scoped parameter
10965 (defvar org-plain-time-of-day-regexp) ; defined below
10967 (defvar org-overriding-default-time nil) ; dynamically scoped
10968 (defvar org-read-date-overlay nil)
10969 (defvar org-dcst nil) ; dynamically scoped
10971 (defun org-read-date (&optional with-time to-time from-string prompt
10972 default-time default-input)
10973 "Read a date, possibly a time, and make things smooth for the user.
10974 The prompt will suggest to enter an ISO date, but you can also enter anything
10975 which will at least partially be understood by `parse-time-string'.
10976 Unrecognized parts of the date will default to the current day, month, year,
10977 hour and minute. If this command is called to replace a timestamp at point,
10978 of to enter the second timestamp of a range, the default time is taken from the
10979 existing stamp. For example,
10980 3-2-5 --> 2003-02-05
10981 feb 15 --> currentyear-02-15
10982 sep 12 9 --> 2009-09-12
10983 12:45 --> today 12:45
10984 22 sept 0:34 --> currentyear-09-22 0:34
10985 12 --> currentyear-currentmonth-12
10986 Fri --> nearest Friday (today or later)
10987 etc.
10989 Furthermore you can specify a relative date by giving, as the *first* thing
10990 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10991 change in days weeks, months, years.
10992 With a single plus or minus, the date is relative to today. With a double
10993 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10994 +4d --> four days from today
10995 +4 --> same as above
10996 +2w --> two weeks from today
10997 ++5 --> five days from default date
10999 The function understands only English month and weekday abbreviations,
11000 but this can be configured with the variables `parse-time-months' and
11001 `parse-time-weekdays'.
11003 While prompting, a calendar is popped up - you can also select the
11004 date with the mouse (button 1). The calendar shows a period of three
11005 months. To scroll it to other months, use the keys `>' and `<'.
11006 If you don't like the calendar, turn it off with
11007 \(setq org-read-date-popup-calendar nil)
11009 With optional argument TO-TIME, the date will immediately be converted
11010 to an internal time.
11011 With an optional argument WITH-TIME, the prompt will suggest to also
11012 insert a time. Note that when WITH-TIME is not set, you can still
11013 enter a time, and this function will inform the calling routine about
11014 this change. The calling routine may then choose to change the format
11015 used to insert the time stamp into the buffer to include the time.
11016 With optional argument FROM-STRING, read from this string instead from
11017 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11018 the time/date that is used for everything that is not specified by the
11019 user."
11020 (require 'parse-time)
11021 (let* ((org-time-stamp-rounding-minutes
11022 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11023 (org-dcst org-display-custom-times)
11024 (ct (org-current-time))
11025 (def (or org-overriding-default-time default-time ct))
11026 (defdecode (decode-time def))
11027 (dummy (progn
11028 (when (< (nth 2 defdecode) org-extend-today-until)
11029 (setcar (nthcdr 2 defdecode) -1)
11030 (setcar (nthcdr 1 defdecode) 59)
11031 (setq def (apply 'encode-time defdecode)
11032 defdecode (decode-time def)))))
11033 (calendar-move-hook nil)
11034 (calendar-view-diary-initially-flag nil)
11035 (view-diary-entries-initially nil)
11036 (calendar-view-holidays-initially-flag nil)
11037 (view-calendar-holidays-initially nil)
11038 (timestr (format-time-string
11039 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11040 (prompt (concat (if prompt (concat prompt " ") "")
11041 (format "Date+time [%s]: " timestr)))
11042 ans (org-ans0 "") org-ans1 org-ans2 final)
11044 (cond
11045 (from-string (setq ans from-string))
11046 (org-read-date-popup-calendar
11047 (save-excursion
11048 (save-window-excursion
11049 (calendar)
11050 (calendar-forward-day (- (time-to-days def)
11051 (calendar-absolute-from-gregorian
11052 (calendar-current-date))))
11053 (org-eval-in-calendar nil t)
11054 (let* ((old-map (current-local-map))
11055 (map (copy-keymap calendar-mode-map))
11056 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11057 (org-defkey map (kbd "RET") 'org-calendar-select)
11058 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11059 'org-calendar-select-mouse)
11060 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11061 'org-calendar-select-mouse)
11062 (org-defkey minibuffer-local-map [(meta shift left)]
11063 (lambda () (interactive)
11064 (org-eval-in-calendar '(calendar-backward-month 1))))
11065 (org-defkey minibuffer-local-map [(meta shift right)]
11066 (lambda () (interactive)
11067 (org-eval-in-calendar '(calendar-forward-month 1))))
11068 (org-defkey minibuffer-local-map [(meta shift up)]
11069 (lambda () (interactive)
11070 (org-eval-in-calendar '(calendar-backward-year 1))))
11071 (org-defkey minibuffer-local-map [(meta shift down)]
11072 (lambda () (interactive)
11073 (org-eval-in-calendar '(calendar-forward-year 1))))
11074 (org-defkey minibuffer-local-map [(shift up)]
11075 (lambda () (interactive)
11076 (org-eval-in-calendar '(calendar-backward-week 1))))
11077 (org-defkey minibuffer-local-map [(shift down)]
11078 (lambda () (interactive)
11079 (org-eval-in-calendar '(calendar-forward-week 1))))
11080 (org-defkey minibuffer-local-map [(shift left)]
11081 (lambda () (interactive)
11082 (org-eval-in-calendar '(calendar-backward-day 1))))
11083 (org-defkey minibuffer-local-map [(shift right)]
11084 (lambda () (interactive)
11085 (org-eval-in-calendar '(calendar-forward-day 1))))
11086 (org-defkey minibuffer-local-map ">"
11087 (lambda () (interactive)
11088 (org-eval-in-calendar '(scroll-calendar-left 1))))
11089 (org-defkey minibuffer-local-map "<"
11090 (lambda () (interactive)
11091 (org-eval-in-calendar '(scroll-calendar-right 1))))
11092 (unwind-protect
11093 (progn
11094 (use-local-map map)
11095 (add-hook 'post-command-hook 'org-read-date-display)
11096 (setq org-ans0 (read-string prompt default-input nil nil))
11097 ;; org-ans0: from prompt
11098 ;; org-ans1: from mouse click
11099 ;; org-ans2: from calendar motion
11100 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11101 (remove-hook 'post-command-hook 'org-read-date-display)
11102 (use-local-map old-map)
11103 (when org-read-date-overlay
11104 (org-delete-overlay org-read-date-overlay)
11105 (setq org-read-date-overlay nil)))))))
11107 (t ; Naked prompt only
11108 (unwind-protect
11109 (setq ans (read-string prompt default-input nil timestr))
11110 (when org-read-date-overlay
11111 (org-delete-overlay org-read-date-overlay)
11112 (setq org-read-date-overlay nil)))))
11114 (setq final (org-read-date-analyze ans def defdecode))
11116 (if to-time
11117 (apply 'encode-time final)
11118 (if (and (boundp 'org-time-was-given) org-time-was-given)
11119 (format "%04d-%02d-%02d %02d:%02d"
11120 (nth 5 final) (nth 4 final) (nth 3 final)
11121 (nth 2 final) (nth 1 final))
11122 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11123 (defvar def)
11124 (defvar defdecode)
11125 (defvar with-time)
11126 (defun org-read-date-display ()
11127 "Display the current date prompt interpretation in the minibuffer."
11128 (when org-read-date-display-live
11129 (when org-read-date-overlay
11130 (org-delete-overlay org-read-date-overlay))
11131 (let ((p (point)))
11132 (end-of-line 1)
11133 (while (not (equal (buffer-substring
11134 (max (point-min) (- (point) 4)) (point))
11135 " "))
11136 (insert " "))
11137 (goto-char p))
11138 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11139 " " (or org-ans1 org-ans2)))
11140 (org-end-time-was-given nil)
11141 (f (org-read-date-analyze ans def defdecode))
11142 (fmts (if org-dcst
11143 org-time-stamp-custom-formats
11144 org-time-stamp-formats))
11145 (fmt (if (or with-time
11146 (and (boundp 'org-time-was-given) org-time-was-given))
11147 (cdr fmts)
11148 (car fmts)))
11149 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11150 (when (and org-end-time-was-given
11151 (string-match org-plain-time-of-day-regexp txt))
11152 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11153 org-end-time-was-given
11154 (substring txt (match-end 0)))))
11155 (setq org-read-date-overlay
11156 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11157 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11159 (defun org-read-date-analyze (ans def defdecode)
11160 "Analyse the combined answer of the date prompt."
11161 ;; FIXME: cleanup and comment
11162 (let (delta deltan deltaw deltadef year month day
11163 hour minute second wday pm h2 m2 tl wday1
11164 iso-year iso-weekday iso-week iso-year iso-date)
11166 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11167 (setq ans "+0"))
11169 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11170 (setq ans (replace-match "" t t ans)
11171 deltan (car delta)
11172 deltaw (nth 1 delta)
11173 deltadef (nth 2 delta)))
11175 ;; Check if there is an iso week date in there
11176 ;; If yes, sore the info and postpone interpreting it until the rest
11177 ;; of the parsing is done
11178 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11179 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11180 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11181 iso-week (string-to-number (match-string 2 ans)))
11182 (setq ans (replace-match "" t t ans)))
11184 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11185 (when (string-match
11186 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11187 (setq year (if (match-end 2)
11188 (string-to-number (match-string 2 ans))
11189 (string-to-number (format-time-string "%Y")))
11190 month (string-to-number (match-string 3 ans))
11191 day (string-to-number (match-string 4 ans)))
11192 (if (< year 100) (setq year (+ 2000 year)))
11193 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11194 t nil ans)))
11195 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11196 ;; If there is a time with am/pm, and *no* time without it, we convert
11197 ;; so that matching will be successful.
11198 (loop for i from 1 to 2 do ; twice, for end time as well
11199 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11200 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11201 (setq hour (string-to-number (match-string 1 ans))
11202 minute (if (match-end 3)
11203 (string-to-number (match-string 3 ans))
11205 pm (equal ?p
11206 (string-to-char (downcase (match-string 4 ans)))))
11207 (if (and (= hour 12) (not pm))
11208 (setq hour 0)
11209 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11210 (setq ans (replace-match (format "%02d:%02d" hour minute)
11211 t t ans))))
11213 ;; Check if a time range is given as a duration
11214 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11215 (setq hour (string-to-number (match-string 1 ans))
11216 h2 (+ hour (string-to-number (match-string 3 ans)))
11217 minute (string-to-number (match-string 2 ans))
11218 m2 (+ minute (if (match-end 5) (string-to-number
11219 (match-string 5 ans))0)))
11220 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11221 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11222 t t ans)))
11224 ;; Check if there is a time range
11225 (when (boundp 'org-end-time-was-given)
11226 (setq org-time-was-given nil)
11227 (when (and (string-match org-plain-time-of-day-regexp ans)
11228 (match-end 8))
11229 (setq org-end-time-was-given (match-string 8 ans))
11230 (setq ans (concat (substring ans 0 (match-beginning 7))
11231 (substring ans (match-end 7))))))
11233 (setq tl (parse-time-string ans)
11234 day (or (nth 3 tl) (nth 3 defdecode))
11235 month (or (nth 4 tl)
11236 (if (and org-read-date-prefer-future
11237 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11238 (1+ (nth 4 defdecode))
11239 (nth 4 defdecode)))
11240 year (or (nth 5 tl)
11241 (if (and org-read-date-prefer-future
11242 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11243 (1+ (nth 5 defdecode))
11244 (nth 5 defdecode)))
11245 hour (or (nth 2 tl) (nth 2 defdecode))
11246 minute (or (nth 1 tl) (nth 1 defdecode))
11247 second (or (nth 0 tl) 0)
11248 wday (nth 6 tl))
11250 ;; Special date definitions below
11251 (cond
11252 (iso-week
11253 ;; There was an iso week
11254 (setq year (or iso-year year)
11255 day (or iso-weekday wday 1)
11256 wday nil ; to make sure that the trigger below does not match
11257 iso-date (calendar-gregorian-from-absolute
11258 (calendar-absolute-from-iso
11259 (list iso-week day year))))
11260 ; FIXME: Should we also push ISO weeks into the future?
11261 ; (when (and org-read-date-prefer-future
11262 ; (not iso-year)
11263 ; (< (calendar-absolute-from-gregorian iso-date)
11264 ; (time-to-days (current-time))))
11265 ; (setq year (1+ year)
11266 ; iso-date (calendar-gregorian-from-absolute
11267 ; (calendar-absolute-from-iso
11268 ; (list iso-week day year)))))
11269 (setq month (car iso-date)
11270 year (nth 2 iso-date)
11271 day (nth 1 iso-date)))
11272 (deltan
11273 (unless deltadef
11274 (let ((now (decode-time (current-time))))
11275 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11276 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11277 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11278 ((equal deltaw "m") (setq month (+ month deltan)))
11279 ((equal deltaw "y") (setq year (+ year deltan)))))
11280 ((and wday (not (nth 3 tl)))
11281 ;; Weekday was given, but no day, so pick that day in the week
11282 ;; on or after the derived date.
11283 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11284 (unless (equal wday wday1)
11285 (setq day (+ day (% (- wday wday1 -7) 7))))))
11286 (if (and (boundp 'org-time-was-given)
11287 (nth 2 tl))
11288 (setq org-time-was-given t))
11289 (if (< year 100) (setq year (+ 2000 year)))
11290 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11291 (list second minute hour day month year)))
11293 (defvar parse-time-weekdays)
11295 (defun org-read-date-get-relative (s today default)
11296 "Check string S for special relative date string.
11297 TODAY and DEFAULT are internal times, for today and for a default.
11298 Return shift list (N what def-flag)
11299 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11300 N is the number of WHATs to shift.
11301 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11302 the DEFAULT date rather than TODAY."
11303 (when (and
11304 (string-match
11305 (concat
11306 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11307 "\\([0-9]+\\)?"
11308 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11309 "\\([ \t]\\|$\\)") s)
11310 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11311 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11312 (string-to-char (substring (match-string 1 s) -1))
11313 ?+))
11314 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11315 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11316 (what (if (match-end 3) (match-string 3 s) "d"))
11317 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11318 (date (if rel default today))
11319 (wday (nth 6 (decode-time date)))
11320 delta)
11321 (if wday1
11322 (progn
11323 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11324 (if (= dir ?-) (setq delta (- delta 7)))
11325 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11326 (list delta "d" rel))
11327 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11329 (defun org-eval-in-calendar (form &optional keepdate)
11330 "Eval FORM in the calendar window and return to current window.
11331 Also, store the cursor date in variable org-ans2."
11332 (let ((sw (selected-window)))
11333 (select-window (get-buffer-window "*Calendar*"))
11334 (eval form)
11335 (when (and (not keepdate) (calendar-cursor-to-date))
11336 (let* ((date (calendar-cursor-to-date))
11337 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11338 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11339 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11340 (select-window sw)))
11342 (defun org-calendar-select ()
11343 "Return to `org-read-date' with the date currently selected.
11344 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11345 (interactive)
11346 (when (calendar-cursor-to-date)
11347 (let* ((date (calendar-cursor-to-date))
11348 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11349 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11350 (if (active-minibuffer-window) (exit-minibuffer))))
11352 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11353 "Insert a date stamp for the date given by the internal TIME.
11354 WITH-HM means, use the stamp format that includes the time of the day.
11355 INACTIVE means use square brackets instead of angular ones, so that the
11356 stamp will not contribute to the agenda.
11357 PRE and POST are optional strings to be inserted before and after the
11358 stamp.
11359 The command returns the inserted time stamp."
11360 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11361 stamp)
11362 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11363 (insert-before-markers (or pre ""))
11364 (insert-before-markers (setq stamp (format-time-string fmt time)))
11365 (when (listp extra)
11366 (setq extra (car extra))
11367 (if (and (stringp extra)
11368 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11369 (setq extra (format "-%02d:%02d"
11370 (string-to-number (match-string 1 extra))
11371 (string-to-number (match-string 2 extra))))
11372 (setq extra nil)))
11373 (when extra
11374 (backward-char 1)
11375 (insert-before-markers extra)
11376 (forward-char 1))
11377 (insert-before-markers (or post ""))
11378 (setq org-last-inserted-timestamp stamp)))
11380 (defun org-toggle-time-stamp-overlays ()
11381 "Toggle the use of custom time stamp formats."
11382 (interactive)
11383 (setq org-display-custom-times (not org-display-custom-times))
11384 (unless org-display-custom-times
11385 (let ((p (point-min)) (bmp (buffer-modified-p)))
11386 (while (setq p (next-single-property-change p 'display))
11387 (if (and (get-text-property p 'display)
11388 (eq (get-text-property p 'face) 'org-date))
11389 (remove-text-properties
11390 p (setq p (next-single-property-change p 'display))
11391 '(display t))))
11392 (set-buffer-modified-p bmp)))
11393 (if (featurep 'xemacs)
11394 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11395 (org-restart-font-lock)
11396 (setq org-table-may-need-update t)
11397 (if org-display-custom-times
11398 (message "Time stamps are overlayed with custom format")
11399 (message "Time stamp overlays removed")))
11401 (defun org-display-custom-time (beg end)
11402 "Overlay modified time stamp format over timestamp between BEG and END."
11403 (let* ((ts (buffer-substring beg end))
11404 t1 w1 with-hm tf time str w2 (off 0))
11405 (save-match-data
11406 (setq t1 (org-parse-time-string ts t))
11407 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11408 (setq off (- (match-end 0) (match-beginning 0)))))
11409 (setq end (- end off))
11410 (setq w1 (- end beg)
11411 with-hm (and (nth 1 t1) (nth 2 t1))
11412 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11413 time (org-fix-decoded-time t1)
11414 str (org-add-props
11415 (format-time-string
11416 (substring tf 1 -1) (apply 'encode-time time))
11417 nil 'mouse-face 'highlight)
11418 w2 (length str))
11419 (if (not (= w2 w1))
11420 (add-text-properties (1+ beg) (+ 2 beg)
11421 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11422 (if (featurep 'xemacs)
11423 (progn
11424 (put-text-property beg end 'invisible t)
11425 (put-text-property beg end 'end-glyph (make-glyph str)))
11426 (put-text-property beg end 'display str))))
11428 (defun org-translate-time (string)
11429 "Translate all timestamps in STRING to custom format.
11430 But do this only if the variable `org-display-custom-times' is set."
11431 (when org-display-custom-times
11432 (save-match-data
11433 (let* ((start 0)
11434 (re org-ts-regexp-both)
11435 t1 with-hm inactive tf time str beg end)
11436 (while (setq start (string-match re string start))
11437 (setq beg (match-beginning 0)
11438 end (match-end 0)
11439 t1 (save-match-data
11440 (org-parse-time-string (substring string beg end) t))
11441 with-hm (and (nth 1 t1) (nth 2 t1))
11442 inactive (equal (substring string beg (1+ beg)) "[")
11443 tf (funcall (if with-hm 'cdr 'car)
11444 org-time-stamp-custom-formats)
11445 time (org-fix-decoded-time t1)
11446 str (format-time-string
11447 (concat
11448 (if inactive "[" "<") (substring tf 1 -1)
11449 (if inactive "]" ">"))
11450 (apply 'encode-time time))
11451 string (replace-match str t t string)
11452 start (+ start (length str)))))))
11453 string)
11455 (defun org-fix-decoded-time (time)
11456 "Set 0 instead of nil for the first 6 elements of time.
11457 Don't touch the rest."
11458 (let ((n 0))
11459 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11461 (defun org-days-to-time (timestamp-string)
11462 "Difference between TIMESTAMP-STRING and now in days."
11463 (- (time-to-days (org-time-string-to-time timestamp-string))
11464 (time-to-days (current-time))))
11466 (defun org-deadline-close (timestamp-string &optional ndays)
11467 "Is the time in TIMESTAMP-STRING close to the current date?"
11468 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11469 (and (< (org-days-to-time timestamp-string) ndays)
11470 (not (org-entry-is-done-p))))
11472 (defun org-get-wdays (ts)
11473 "Get the deadline lead time appropriate for timestring TS."
11474 (cond
11475 ((<= org-deadline-warning-days 0)
11476 ;; 0 or negative, enforce this value no matter what
11477 (- org-deadline-warning-days))
11478 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11479 ;; lead time is specified.
11480 (floor (* (string-to-number (match-string 1 ts))
11481 (cdr (assoc (match-string 2 ts)
11482 '(("d" . 1) ("w" . 7)
11483 ("m" . 30.4) ("y" . 365.25)))))))
11484 ;; go for the default.
11485 (t org-deadline-warning-days)))
11487 (defun org-calendar-select-mouse (ev)
11488 "Return to `org-read-date' with the date currently selected.
11489 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11490 (interactive "e")
11491 (mouse-set-point ev)
11492 (when (calendar-cursor-to-date)
11493 (let* ((date (calendar-cursor-to-date))
11494 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11495 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11496 (if (active-minibuffer-window) (exit-minibuffer))))
11498 (defun org-check-deadlines (ndays)
11499 "Check if there are any deadlines due or past due.
11500 A deadline is considered due if it happens within `org-deadline-warning-days'
11501 days from today's date. If the deadline appears in an entry marked DONE,
11502 it is not shown. The prefix arg NDAYS can be used to test that many
11503 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11504 (interactive "P")
11505 (let* ((org-warn-days
11506 (cond
11507 ((equal ndays '(4)) 100000)
11508 (ndays (prefix-numeric-value ndays))
11509 (t (abs org-deadline-warning-days))))
11510 (case-fold-search nil)
11511 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11512 (callback
11513 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11515 (message "%d deadlines past-due or due within %d days"
11516 (org-occur regexp nil callback)
11517 org-warn-days)))
11519 (defun org-check-before-date (date)
11520 "Check if there are deadlines or scheduled entries before DATE."
11521 (interactive (list (org-read-date)))
11522 (let ((case-fold-search nil)
11523 (regexp (concat "\\<\\(" org-deadline-string
11524 "\\|" org-scheduled-string
11525 "\\) *<\\([^>]+\\)>"))
11526 (callback
11527 (lambda () (time-less-p
11528 (org-time-string-to-time (match-string 2))
11529 (org-time-string-to-time date)))))
11530 (message "%d entries before %s"
11531 (org-occur regexp nil callback) date)))
11533 (defun org-evaluate-time-range (&optional to-buffer)
11534 "Evaluate a time range by computing the difference between start and end.
11535 Normally the result is just printed in the echo area, but with prefix arg
11536 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11537 If the time range is actually in a table, the result is inserted into the
11538 next column.
11539 For time difference computation, a year is assumed to be exactly 365
11540 days in order to avoid rounding problems."
11541 (interactive "P")
11543 (org-clock-update-time-maybe)
11544 (save-excursion
11545 (unless (org-at-date-range-p t)
11546 (goto-char (point-at-bol))
11547 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11548 (if (not (org-at-date-range-p t))
11549 (error "Not at a time-stamp range, and none found in current line")))
11550 (let* ((ts1 (match-string 1))
11551 (ts2 (match-string 2))
11552 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11553 (match-end (match-end 0))
11554 (time1 (org-time-string-to-time ts1))
11555 (time2 (org-time-string-to-time ts2))
11556 (t1 (time-to-seconds time1))
11557 (t2 (time-to-seconds time2))
11558 (diff (abs (- t2 t1)))
11559 (negative (< (- t2 t1) 0))
11560 ;; (ys (floor (* 365 24 60 60)))
11561 (ds (* 24 60 60))
11562 (hs (* 60 60))
11563 (fy "%dy %dd %02d:%02d")
11564 (fy1 "%dy %dd")
11565 (fd "%dd %02d:%02d")
11566 (fd1 "%dd")
11567 (fh "%02d:%02d")
11568 y d h m align)
11569 (if havetime
11570 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11572 d (floor (/ diff ds)) diff (mod diff ds)
11573 h (floor (/ diff hs)) diff (mod diff hs)
11574 m (floor (/ diff 60)))
11575 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11577 d (floor (+ (/ diff ds) 0.5))
11578 h 0 m 0))
11579 (if (not to-buffer)
11580 (message "%s" (org-make-tdiff-string y d h m))
11581 (if (org-at-table-p)
11582 (progn
11583 (goto-char match-end)
11584 (setq align t)
11585 (and (looking-at " *|") (goto-char (match-end 0))))
11586 (goto-char match-end))
11587 (if (looking-at
11588 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11589 (replace-match ""))
11590 (if negative (insert " -"))
11591 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11592 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11593 (insert " " (format fh h m))))
11594 (if align (org-table-align))
11595 (message "Time difference inserted")))))
11597 (defun org-make-tdiff-string (y d h m)
11598 (let ((fmt "")
11599 (l nil))
11600 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11601 l (push y l)))
11602 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11603 l (push d l)))
11604 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11605 l (push h l)))
11606 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11607 l (push m l)))
11608 (apply 'format fmt (nreverse l))))
11610 (defun org-time-string-to-time (s)
11611 (apply 'encode-time (org-parse-time-string s)))
11613 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11614 "Convert a time stamp to an absolute day number.
11615 If there is a specifyer for a cyclic time stamp, get the closest date to
11616 DAYNR.
11617 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11618 (cond
11619 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11620 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11621 daynr
11622 (+ daynr 1000)))
11623 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11624 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11625 (time-to-days (current-time))) (match-string 0 s)
11626 prefer show-all))
11627 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11629 (defun org-days-to-iso-week (days)
11630 "Return the iso week number."
11631 (require 'cal-iso)
11632 (car (calendar-iso-from-absolute days)))
11634 (defun org-small-year-to-year (year)
11635 "Convert 2-digit years into 4-digit years.
11636 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11637 The year 2000 cannot be abbreviated. Any year larger than 99
11638 is returned unchanged."
11639 (if (< year 38)
11640 (setq year (+ 2000 year))
11641 (if (< year 100)
11642 (setq year (+ 1900 year))))
11643 year)
11645 (defun org-time-from-absolute (d)
11646 "Return the time corresponding to date D.
11647 D may be an absolute day number, or a calendar-type list (month day year)."
11648 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11649 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11651 (defun org-calendar-holiday ()
11652 "List of holidays, for Diary display in Org-mode."
11653 (require 'holidays)
11654 (let ((hl (funcall
11655 (if (fboundp 'calendar-check-holidays)
11656 'calendar-check-holidays 'check-calendar-holidays) date)))
11657 (if hl (mapconcat 'identity hl "; "))))
11659 (defun org-diary-sexp-entry (sexp entry date)
11660 "Process a SEXP diary ENTRY for DATE."
11661 (require 'diary-lib)
11662 (let ((result (if calendar-debug-sexp
11663 (let ((stack-trace-on-error t))
11664 (eval (car (read-from-string sexp))))
11665 (condition-case nil
11666 (eval (car (read-from-string sexp)))
11667 (error
11668 (beep)
11669 (message "Bad sexp at line %d in %s: %s"
11670 (org-current-line)
11671 (buffer-file-name) sexp)
11672 (sleep-for 2))))))
11673 (cond ((stringp result) result)
11674 ((and (consp result)
11675 (stringp (cdr result))) (cdr result))
11676 (result entry)
11677 (t nil))))
11679 (defun org-diary-to-ical-string (frombuf)
11680 "Get iCalendar entries from diary entries in buffer FROMBUF.
11681 This uses the icalendar.el library."
11682 (let* ((tmpdir (if (featurep 'xemacs)
11683 (temp-directory)
11684 temporary-file-directory))
11685 (tmpfile (make-temp-name
11686 (expand-file-name "orgics" tmpdir)))
11687 buf rtn b e)
11688 (save-excursion
11689 (set-buffer frombuf)
11690 (icalendar-export-region (point-min) (point-max) tmpfile)
11691 (setq buf (find-buffer-visiting tmpfile))
11692 (set-buffer buf)
11693 (goto-char (point-min))
11694 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11695 (setq b (match-beginning 0)))
11696 (goto-char (point-max))
11697 (if (re-search-backward "^END:VEVENT" nil t)
11698 (setq e (match-end 0)))
11699 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11700 (kill-buffer buf)
11701 (delete-file tmpfile)
11702 rtn))
11704 (defun org-closest-date (start current change prefer show-all)
11705 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11706 When PREFER is `past' return a date that is either CURRENT or past.
11707 When PREFER is `future', return a date that is either CURRENT or future.
11708 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11709 ;; Make the proper lists from the dates
11710 (catch 'exit
11711 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11712 dn dw sday cday n1 n2 n0
11713 d m y y1 y2 date1 date2 nmonths nm ny m2)
11715 (setq start (org-date-to-gregorian start)
11716 current (org-date-to-gregorian
11717 (if show-all
11718 current
11719 (time-to-days (current-time))))
11720 sday (calendar-absolute-from-gregorian start)
11721 cday (calendar-absolute-from-gregorian current))
11723 (if (<= cday sday) (throw 'exit sday))
11725 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11726 (setq dn (string-to-number (match-string 1 change))
11727 dw (cdr (assoc (match-string 2 change) a1)))
11728 (error "Invalid change specifyer: %s" change))
11729 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11730 (cond
11731 ((eq dw 'day)
11732 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11733 n2 (+ n1 dn)))
11734 ((eq dw 'year)
11735 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11736 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11737 (setq date1 (list m d y1)
11738 n1 (calendar-absolute-from-gregorian date1)
11739 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11740 n2 (calendar-absolute-from-gregorian date2)))
11741 ((eq dw 'month)
11742 ;; approx number of month between the two dates
11743 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11744 ;; How often does dn fit in there?
11745 (setq d (nth 1 start) m (car start) y (nth 2 start)
11746 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11747 m (+ m nm)
11748 ny (floor (/ m 12))
11749 y (+ y ny)
11750 m (- m (* ny 12)))
11751 (while (> m 12) (setq m (- m 12) y (1+ y)))
11752 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11753 (setq m2 (+ m dn) y2 y)
11754 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11755 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11756 (while (<= n2 cday)
11757 (setq n1 n2 m m2 y y2)
11758 (setq m2 (+ m dn) y2 y)
11759 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11760 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11761 ;; Make sure n1 is the earlier date
11762 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11763 (if show-all
11764 (cond
11765 ((eq prefer 'past) n1)
11766 ((eq prefer 'future) (if (= cday n1) n1 n2))
11767 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11768 (cond
11769 ((eq prefer 'past) n1)
11770 ((eq prefer 'future) (if (= cday n1) n1 n2))
11771 (t (if (= cday n1) n1 n2)))))))
11773 (defun org-date-to-gregorian (date)
11774 "Turn any specification of DATE into a gregorian date for the calendar."
11775 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11776 ((and (listp date) (= (length date) 3)) date)
11777 ((stringp date)
11778 (setq date (org-parse-time-string date))
11779 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11780 ((listp date)
11781 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11783 (defun org-parse-time-string (s &optional nodefault)
11784 "Parse the standard Org-mode time string.
11785 This should be a lot faster than the normal `parse-time-string'.
11786 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11787 hour and minute fields will be nil if not given."
11788 (if (string-match org-ts-regexp0 s)
11789 (list 0
11790 (if (or (match-beginning 8) (not nodefault))
11791 (string-to-number (or (match-string 8 s) "0")))
11792 (if (or (match-beginning 7) (not nodefault))
11793 (string-to-number (or (match-string 7 s) "0")))
11794 (string-to-number (match-string 4 s))
11795 (string-to-number (match-string 3 s))
11796 (string-to-number (match-string 2 s))
11797 nil nil nil)
11798 (make-list 9 0)))
11800 (defun org-timestamp-up (&optional arg)
11801 "Increase the date item at the cursor by one.
11802 If the cursor is on the year, change the year. If it is on the month or
11803 the day, change that.
11804 With prefix ARG, change by that many units."
11805 (interactive "p")
11806 (org-timestamp-change (prefix-numeric-value arg)))
11808 (defun org-timestamp-down (&optional arg)
11809 "Decrease the date item at the cursor by one.
11810 If the cursor is on the year, change the year. If it is on the month or
11811 the day, change that.
11812 With prefix ARG, change by that many units."
11813 (interactive "p")
11814 (org-timestamp-change (- (prefix-numeric-value arg))))
11816 (defun org-timestamp-up-day (&optional arg)
11817 "Increase the date in the time stamp by one day.
11818 With prefix ARG, change that many days."
11819 (interactive "p")
11820 (if (and (not (org-at-timestamp-p t))
11821 (org-on-heading-p))
11822 (org-todo 'up)
11823 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11825 (defun org-timestamp-down-day (&optional arg)
11826 "Decrease the date in the time stamp by one day.
11827 With prefix ARG, change that many days."
11828 (interactive "p")
11829 (if (and (not (org-at-timestamp-p t))
11830 (org-on-heading-p))
11831 (org-todo 'down)
11832 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11834 (defun org-at-timestamp-p (&optional inactive-ok)
11835 "Determine if the cursor is in or at a timestamp."
11836 (interactive)
11837 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11838 (pos (point))
11839 (ans (or (looking-at tsr)
11840 (save-excursion
11841 (skip-chars-backward "^[<\n\r\t")
11842 (if (> (point) (point-min)) (backward-char 1))
11843 (and (looking-at tsr)
11844 (> (- (match-end 0) pos) -1))))))
11845 (and ans
11846 (boundp 'org-ts-what)
11847 (setq org-ts-what
11848 (cond
11849 ((= pos (match-beginning 0)) 'bracket)
11850 ((= pos (1- (match-end 0))) 'bracket)
11851 ((org-pos-in-match-range pos 2) 'year)
11852 ((org-pos-in-match-range pos 3) 'month)
11853 ((org-pos-in-match-range pos 7) 'hour)
11854 ((org-pos-in-match-range pos 8) 'minute)
11855 ((or (org-pos-in-match-range pos 4)
11856 (org-pos-in-match-range pos 5)) 'day)
11857 ((and (> pos (or (match-end 8) (match-end 5)))
11858 (< pos (match-end 0)))
11859 (- pos (or (match-end 8) (match-end 5))))
11860 (t 'day))))
11861 ans))
11863 (defun org-toggle-timestamp-type ()
11864 "Toggle the type (<active> or [inactive]) of a time stamp."
11865 (interactive)
11866 (when (org-at-timestamp-p t)
11867 (let ((beg (match-beginning 0)) (end (match-end 0))
11868 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11869 (save-excursion
11870 (goto-char beg)
11871 (while (re-search-forward "[][<>]" end t)
11872 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11873 t t)))
11874 (message "Timestamp is now %sactive"
11875 (if (equal (char-after beg) ?<) "" "in")))))
11877 (defun org-timestamp-change (n &optional what)
11878 "Change the date in the time stamp at point.
11879 The date will be changed by N times WHAT. WHAT can be `day', `month',
11880 `year', `minute', `second'. If WHAT is not given, the cursor position
11881 in the timestamp determines what will be changed."
11882 (let ((pos (point))
11883 with-hm inactive
11884 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11885 org-ts-what
11886 extra rem
11887 ts time time0)
11888 (if (not (org-at-timestamp-p t))
11889 (error "Not at a timestamp"))
11890 (if (and (not what) (eq org-ts-what 'bracket))
11891 (org-toggle-timestamp-type)
11892 (if (and (not what) (not (eq org-ts-what 'day))
11893 org-display-custom-times
11894 (get-text-property (point) 'display)
11895 (not (get-text-property (1- (point)) 'display)))
11896 (setq org-ts-what 'day))
11897 (setq org-ts-what (or what org-ts-what)
11898 inactive (= (char-after (match-beginning 0)) ?\[)
11899 ts (match-string 0))
11900 (replace-match "")
11901 (if (string-match
11902 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11904 (setq extra (match-string 1 ts)))
11905 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11906 (setq with-hm t))
11907 (setq time0 (org-parse-time-string ts))
11908 (when (and (eq org-ts-what 'minute)
11909 (eq current-prefix-arg nil))
11910 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11911 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11912 (setcar (cdr time0) (+ (nth 1 time0)
11913 (if (> n 0) (- rem) (- dm rem))))))
11914 (setq time
11915 (encode-time (or (car time0) 0)
11916 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11917 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11918 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11919 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11920 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11921 (nthcdr 6 time0)))
11922 (when (integerp org-ts-what)
11923 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11924 (if (eq what 'calendar)
11925 (let ((cal-date (org-get-date-from-calendar)))
11926 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11927 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11928 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11929 (setcar time0 (or (car time0) 0))
11930 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11931 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11932 (setq time (apply 'encode-time time0))))
11933 (setq org-last-changed-timestamp
11934 (org-insert-time-stamp time with-hm inactive nil nil extra))
11935 (org-clock-update-time-maybe)
11936 (goto-char pos)
11937 ;; Try to recenter the calendar window, if any
11938 (if (and org-calendar-follow-timestamp-change
11939 (get-buffer-window "*Calendar*" t)
11940 (memq org-ts-what '(day month year)))
11941 (org-recenter-calendar (time-to-days time))))))
11943 (defun org-modify-ts-extra (s pos n dm)
11944 "Change the different parts of the lead-time and repeat fields in timestamp."
11945 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11946 ng h m new rem)
11947 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11948 (cond
11949 ((or (org-pos-in-match-range pos 2)
11950 (org-pos-in-match-range pos 3))
11951 (setq m (string-to-number (match-string 3 s))
11952 h (string-to-number (match-string 2 s)))
11953 (if (org-pos-in-match-range pos 2)
11954 (setq h (+ h n))
11955 (setq n (* dm (org-no-warnings (signum n))))
11956 (when (not (= 0 (setq rem (% m dm))))
11957 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11958 (setq m (+ m n)))
11959 (if (< m 0) (setq m (+ m 60) h (1- h)))
11960 (if (> m 59) (setq m (- m 60) h (1+ h)))
11961 (setq h (min 24 (max 0 h)))
11962 (setq ng 1 new (format "-%02d:%02d" h m)))
11963 ((org-pos-in-match-range pos 6)
11964 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11965 ((org-pos-in-match-range pos 5)
11966 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11968 ((org-pos-in-match-range pos 9)
11969 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11970 ((org-pos-in-match-range pos 8)
11971 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11973 (when ng
11974 (setq s (concat
11975 (substring s 0 (match-beginning ng))
11977 (substring s (match-end ng))))))
11980 (defun org-recenter-calendar (date)
11981 "If the calendar is visible, recenter it to DATE."
11982 (let* ((win (selected-window))
11983 (cwin (get-buffer-window "*Calendar*" t))
11984 (calendar-move-hook nil))
11985 (when cwin
11986 (select-window cwin)
11987 (calendar-goto-date (if (listp date) date
11988 (calendar-gregorian-from-absolute date)))
11989 (select-window win))))
11991 (defun org-goto-calendar (&optional arg)
11992 "Go to the Emacs calendar at the current date.
11993 If there is a time stamp in the current line, go to that date.
11994 A prefix ARG can be used to force the current date."
11995 (interactive "P")
11996 (let ((tsr org-ts-regexp) diff
11997 (calendar-move-hook nil)
11998 (calendar-view-holidays-initially-flag nil)
11999 (view-calendar-holidays-initially nil)
12000 (calendar-view-diary-initially-flag nil)
12001 (view-diary-entries-initially nil))
12002 (if (or (org-at-timestamp-p)
12003 (save-excursion
12004 (beginning-of-line 1)
12005 (looking-at (concat ".*" tsr))))
12006 (let ((d1 (time-to-days (current-time)))
12007 (d2 (time-to-days
12008 (org-time-string-to-time (match-string 1)))))
12009 (setq diff (- d2 d1))))
12010 (calendar)
12011 (calendar-goto-today)
12012 (if (and diff (not arg)) (calendar-forward-day diff))))
12014 (defun org-get-date-from-calendar ()
12015 "Return a list (month day year) of date at point in calendar."
12016 (with-current-buffer "*Calendar*"
12017 (save-match-data
12018 (calendar-cursor-to-date))))
12020 (defun org-date-from-calendar ()
12021 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12022 If there is already a time stamp at the cursor position, update it."
12023 (interactive)
12024 (if (org-at-timestamp-p t)
12025 (org-timestamp-change 0 'calendar)
12026 (let ((cal-date (org-get-date-from-calendar)))
12027 (org-insert-time-stamp
12028 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12030 (defun org-minutes-to-hh:mm-string (m)
12031 "Compute H:MM from a number of minutes."
12032 (let ((h (/ m 60)))
12033 (setq m (- m (* 60 h)))
12034 (format org-time-clocksum-format h m)))
12036 (defun org-hh:mm-string-to-minutes (s)
12037 "Convert a string H:MM to a number of minutes."
12038 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12039 (+ (* (string-to-number (match-string 1 s)) 60)
12040 (string-to-number (match-string 2 s)))
12043 ;;;; Agenda files
12045 ;;;###autoload
12046 (defun org-iswitchb (&optional arg)
12047 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12048 With a prefix argument, restrict available to files.
12049 With two prefix arguments, restrict available buffers to agenda files.
12051 Due to some yet unresolved reason, the global function
12052 `iswitchb-mode' needs to be active for this function to work."
12053 (interactive "P")
12054 (require 'iswitchb)
12055 (let ((enabled iswitchb-mode) blist)
12056 (or enabled (iswitchb-mode 1))
12057 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12058 ((equal arg '(16)) (org-buffer-list 'agenda))
12059 (t (org-buffer-list))))
12060 (unwind-protect
12061 (let ((iswitchb-make-buflist-hook
12062 (lambda ()
12063 (setq iswitchb-temp-buflist
12064 (mapcar 'buffer-name blist)))))
12065 (switch-to-buffer
12066 (iswitchb-read-buffer
12067 "Switch-to: " nil t))
12068 (or enabled (iswitchb-mode -1))))))
12070 ;;;###autoload
12071 (defun org-ido-switchb (&optional arg)
12072 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12073 With a prefix argument, restrict available to files.
12074 With two prefix arguments, restrict available buffers to agenda files."
12075 (interactive "P")
12076 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12077 ((equal arg '(16)) (org-buffer-list 'agenda))
12078 (t (org-buffer-list)))))
12079 (switch-to-buffer
12080 (org-ido-completing-read "Org buffer: "
12081 (mapcar 'buffer-name blist)
12082 nil t))))
12084 (defun org-buffer-list (&optional predicate exclude-tmp)
12085 "Return a list of Org buffers.
12086 PREDICATE can be `export', `files' or `agenda'.
12088 export restrict the list to Export buffers.
12089 files restrict the list to buffers visiting Org files.
12090 agenda restrict the list to buffers visiting agenda files.
12092 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12093 (let* ((bfn nil)
12094 (agenda-files (and (eq predicate 'agenda)
12095 (mapcar 'file-truename (org-agenda-files t))))
12096 (filter
12097 (cond
12098 ((eq predicate 'files)
12099 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12100 ((eq predicate 'export)
12101 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12102 ((eq predicate 'agenda)
12103 (lambda (b)
12104 (with-current-buffer b
12105 (and (eq major-mode 'org-mode)
12106 (setq bfn (buffer-file-name b))
12107 (member (file-truename bfn) agenda-files)))))
12108 (t (lambda (b) (with-current-buffer b
12109 (or (eq major-mode 'org-mode)
12110 (string-match "\*Org .*Export"
12111 (buffer-name b)))))))))
12112 (delq nil
12113 (mapcar
12114 (lambda(b)
12115 (if (and (funcall filter b)
12116 (or (not exclude-tmp)
12117 (not (string-match "tmp" (buffer-name b)))))
12119 nil))
12120 (buffer-list)))))
12122 (defun org-agenda-files (&optional unrestricted archives)
12123 "Get the list of agenda files.
12124 Optional UNRESTRICTED means return the full list even if a restriction
12125 is currently in place.
12126 When ARCHIVES is t, include all archive files hat are really being
12127 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12128 `org-agenda-archives-mode' is t."
12129 (let ((files
12130 (cond
12131 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12132 ((stringp org-agenda-files) (org-read-agenda-file-list))
12133 ((listp org-agenda-files) org-agenda-files)
12134 (t (error "Invalid value of `org-agenda-files'")))))
12135 (setq files (apply 'append
12136 (mapcar (lambda (f)
12137 (if (file-directory-p f)
12138 (directory-files
12139 f t org-agenda-file-regexp)
12140 (list f)))
12141 files)))
12142 (when org-agenda-skip-unavailable-files
12143 (setq files (delq nil
12144 (mapcar (function
12145 (lambda (file)
12146 (and (file-readable-p file) file)))
12147 files))))
12148 (when (or (eq archives t)
12149 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12150 (setq files (org-add-archive-files files)))
12151 files))
12153 (defun org-edit-agenda-file-list ()
12154 "Edit the list of agenda files.
12155 Depending on setup, this either uses customize to edit the variable
12156 `org-agenda-files', or it visits the file that is holding the list. In the
12157 latter case, the buffer is set up in a way that saving it automatically kills
12158 the buffer and restores the previous window configuration."
12159 (interactive)
12160 (if (stringp org-agenda-files)
12161 (let ((cw (current-window-configuration)))
12162 (find-file org-agenda-files)
12163 (org-set-local 'org-window-configuration cw)
12164 (org-add-hook 'after-save-hook
12165 (lambda ()
12166 (set-window-configuration
12167 (prog1 org-window-configuration
12168 (kill-buffer (current-buffer))))
12169 (org-install-agenda-files-menu)
12170 (message "New agenda file list installed"))
12171 nil 'local)
12172 (message "%s" (substitute-command-keys
12173 "Edit list and finish with \\[save-buffer]")))
12174 (customize-variable 'org-agenda-files)))
12176 (defun org-store-new-agenda-file-list (list)
12177 "Set new value for the agenda file list and save it correctly."
12178 (if (stringp org-agenda-files)
12179 (let ((f org-agenda-files) b)
12180 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12181 (with-temp-file f
12182 (insert (mapconcat 'identity list "\n") "\n")))
12183 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12184 (setq org-agenda-files list)
12185 (customize-save-variable 'org-agenda-files org-agenda-files))))
12187 (defun org-read-agenda-file-list ()
12188 "Read the list of agenda files from a file."
12189 (when (file-directory-p org-agenda-files)
12190 (error "`org-agenda-files' cannot be a single directory"))
12191 (when (stringp org-agenda-files)
12192 (with-temp-buffer
12193 (insert-file-contents org-agenda-files)
12194 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12197 ;;;###autoload
12198 (defun org-cycle-agenda-files ()
12199 "Cycle through the files in `org-agenda-files'.
12200 If the current buffer visits an agenda file, find the next one in the list.
12201 If the current buffer does not, find the first agenda file."
12202 (interactive)
12203 (let* ((fs (org-agenda-files t))
12204 (files (append fs (list (car fs))))
12205 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12206 file)
12207 (unless files (error "No agenda files"))
12208 (catch 'exit
12209 (while (setq file (pop files))
12210 (if (equal (file-truename file) tcf)
12211 (when (car files)
12212 (find-file (car files))
12213 (throw 'exit t))))
12214 (find-file (car fs)))
12215 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12217 (defun org-agenda-file-to-front (&optional to-end)
12218 "Move/add the current file to the top of the agenda file list.
12219 If the file is not present in the list, it is added to the front. If it is
12220 present, it is moved there. With optional argument TO-END, add/move to the
12221 end of the list."
12222 (interactive "P")
12223 (let ((org-agenda-skip-unavailable-files nil)
12224 (file-alist (mapcar (lambda (x)
12225 (cons (file-truename x) x))
12226 (org-agenda-files t)))
12227 (ctf (file-truename buffer-file-name))
12228 x had)
12229 (setq x (assoc ctf file-alist) had x)
12231 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12232 (if to-end
12233 (setq file-alist (append (delq x file-alist) (list x)))
12234 (setq file-alist (cons x (delq x file-alist))))
12235 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12236 (org-install-agenda-files-menu)
12237 (message "File %s to %s of agenda file list"
12238 (if had "moved" "added") (if to-end "end" "front"))))
12240 (defun org-remove-file (&optional file)
12241 "Remove current file from the list of files in variable `org-agenda-files'.
12242 These are the files which are being checked for agenda entries.
12243 Optional argument FILE means, use this file instead of the current."
12244 (interactive)
12245 (let* ((org-agenda-skip-unavailable-files nil)
12246 (file (or file buffer-file-name))
12247 (true-file (file-truename file))
12248 (afile (abbreviate-file-name file))
12249 (files (delq nil (mapcar
12250 (lambda (x)
12251 (if (equal true-file
12252 (file-truename x))
12253 nil x))
12254 (org-agenda-files t)))))
12255 (if (not (= (length files) (length (org-agenda-files t))))
12256 (progn
12257 (org-store-new-agenda-file-list files)
12258 (org-install-agenda-files-menu)
12259 (message "Removed file: %s" afile))
12260 (message "File was not in list: %s (not removed)" afile))))
12262 (defun org-file-menu-entry (file)
12263 (vector file (list 'find-file file) t))
12265 (defun org-check-agenda-file (file)
12266 "Make sure FILE exists. If not, ask user what to do."
12267 (when (not (file-exists-p file))
12268 (message "non-existent file %s. [R]emove from list or [A]bort?"
12269 (abbreviate-file-name file))
12270 (let ((r (downcase (read-char-exclusive))))
12271 (cond
12272 ((equal r ?r)
12273 (org-remove-file file)
12274 (throw 'nextfile t))
12275 (t (error "Abort"))))))
12277 (defun org-get-agenda-file-buffer (file)
12278 "Get a buffer visiting FILE. If the buffer needs to be created, add
12279 it to the list of buffers which might be released later."
12280 (let ((buf (org-find-base-buffer-visiting file)))
12281 (if buf
12282 buf ; just return it
12283 ;; Make a new buffer and remember it
12284 (setq buf (find-file-noselect file))
12285 (if buf (push buf org-agenda-new-buffers))
12286 buf)))
12288 (defun org-release-buffers (blist)
12289 "Release all buffers in list, asking the user for confirmation when needed.
12290 When a buffer is unmodified, it is just killed. When modified, it is saved
12291 \(if the user agrees) and then killed."
12292 (let (buf file)
12293 (while (setq buf (pop blist))
12294 (setq file (buffer-file-name buf))
12295 (when (and (buffer-modified-p buf)
12296 file
12297 (y-or-n-p (format "Save file %s? " file)))
12298 (with-current-buffer buf (save-buffer)))
12299 (kill-buffer buf))))
12301 (defun org-prepare-agenda-buffers (files)
12302 "Create buffers for all agenda files, protect archived trees and comments."
12303 (interactive)
12304 (let ((pa '(:org-archived t))
12305 (pc '(:org-comment t))
12306 (pall '(:org-archived t :org-comment t))
12307 (inhibit-read-only t)
12308 (rea (concat ":" org-archive-tag ":"))
12309 bmp file re)
12310 (save-excursion
12311 (save-restriction
12312 (while (setq file (pop files))
12313 (if (bufferp file)
12314 (set-buffer file)
12315 (org-check-agenda-file file)
12316 (set-buffer (org-get-agenda-file-buffer file)))
12317 (widen)
12318 (setq bmp (buffer-modified-p))
12319 (org-refresh-category-properties)
12320 (setq org-todo-keywords-for-agenda
12321 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12322 (setq org-done-keywords-for-agenda
12323 (append org-done-keywords-for-agenda org-done-keywords))
12324 (setq org-todo-keyword-alist-for-agenda
12325 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12326 (setq org-tag-alist-for-agenda
12327 (append org-tag-alist-for-agenda org-tag-alist))
12329 (save-excursion
12330 (remove-text-properties (point-min) (point-max) pall)
12331 (when org-agenda-skip-archived-trees
12332 (goto-char (point-min))
12333 (while (re-search-forward rea nil t)
12334 (if (org-on-heading-p t)
12335 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12336 (goto-char (point-min))
12337 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12338 (while (re-search-forward re nil t)
12339 (add-text-properties
12340 (match-beginning 0) (org-end-of-subtree t) pc)))
12341 (set-buffer-modified-p bmp))))
12342 (setq org-todo-keyword-alist-for-agenda
12343 (org-uniquify org-todo-keyword-alist-for-agenda)
12344 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12346 ;;;; Embedded LaTeX
12348 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12349 "Keymap for the minor `org-cdlatex-mode'.")
12351 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12352 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12353 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12354 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12355 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12357 (defvar org-cdlatex-texmathp-advice-is-done nil
12358 "Flag remembering if we have applied the advice to texmathp already.")
12360 (define-minor-mode org-cdlatex-mode
12361 "Toggle the minor `org-cdlatex-mode'.
12362 This mode supports entering LaTeX environment and math in LaTeX fragments
12363 in Org-mode.
12364 \\{org-cdlatex-mode-map}"
12365 nil " OCDL" nil
12366 (when org-cdlatex-mode (require 'cdlatex))
12367 (unless org-cdlatex-texmathp-advice-is-done
12368 (setq org-cdlatex-texmathp-advice-is-done t)
12369 (defadvice texmathp (around org-math-always-on activate)
12370 "Always return t in org-mode buffers.
12371 This is because we want to insert math symbols without dollars even outside
12372 the LaTeX math segments. If Orgmode thinks that point is actually inside
12373 an embedded LaTeX fragment, let texmathp do its job.
12374 \\[org-cdlatex-mode-map]"
12375 (interactive)
12376 (let (p)
12377 (cond
12378 ((not (org-mode-p)) ad-do-it)
12379 ((eq this-command 'cdlatex-math-symbol)
12380 (setq ad-return-value t
12381 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12383 (let ((p (org-inside-LaTeX-fragment-p)))
12384 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12385 (setq ad-return-value t
12386 texmathp-why '("Org-mode embedded math" . 0))
12387 (if p ad-do-it)))))))))
12389 (defun turn-on-org-cdlatex ()
12390 "Unconditionally turn on `org-cdlatex-mode'."
12391 (org-cdlatex-mode 1))
12393 (defun org-inside-LaTeX-fragment-p ()
12394 "Test if point is inside a LaTeX fragment.
12395 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12396 sequence appearing also before point.
12397 Even though the matchers for math are configurable, this function assumes
12398 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12399 delimiters are skipped when they have been removed by customization.
12400 The return value is nil, or a cons cell with the delimiter and
12401 and the position of this delimiter.
12403 This function does a reasonably good job, but can locally be fooled by
12404 for example currency specifications. For example it will assume being in
12405 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12406 fragments that are properly closed, but during editing, we have to live
12407 with the uncertainty caused by missing closing delimiters. This function
12408 looks only before point, not after."
12409 (catch 'exit
12410 (let ((pos (point))
12411 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12412 (lim (progn
12413 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12414 (point)))
12415 dd-on str (start 0) m re)
12416 (goto-char pos)
12417 (when dodollar
12418 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12419 re (nth 1 (assoc "$" org-latex-regexps)))
12420 (while (string-match re str start)
12421 (cond
12422 ((= (match-end 0) (length str))
12423 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12424 ((= (match-end 0) (- (length str) 5))
12425 (throw 'exit nil))
12426 (t (setq start (match-end 0))))))
12427 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12428 (goto-char pos)
12429 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12430 (and (match-beginning 2) (throw 'exit nil))
12431 ;; count $$
12432 (while (re-search-backward "\\$\\$" lim t)
12433 (setq dd-on (not dd-on)))
12434 (goto-char pos)
12435 (if dd-on (cons "$$" m))))))
12438 (defun org-try-cdlatex-tab ()
12439 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12440 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12441 - inside a LaTeX fragment, or
12442 - after the first word in a line, where an abbreviation expansion could
12443 insert a LaTeX environment."
12444 (when org-cdlatex-mode
12445 (cond
12446 ((save-excursion
12447 (skip-chars-backward "a-zA-Z0-9*")
12448 (skip-chars-backward " \t")
12449 (bolp))
12450 (cdlatex-tab) t)
12451 ((org-inside-LaTeX-fragment-p)
12452 (cdlatex-tab) t)
12453 (t nil))))
12455 (defun org-cdlatex-underscore-caret (&optional arg)
12456 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12457 Revert to the normal definition outside of these fragments."
12458 (interactive "P")
12459 (if (org-inside-LaTeX-fragment-p)
12460 (call-interactively 'cdlatex-sub-superscript)
12461 (let (org-cdlatex-mode)
12462 (call-interactively (key-binding (vector last-input-event))))))
12464 (defun org-cdlatex-math-modify (&optional arg)
12465 "Execute `cdlatex-math-modify' in LaTeX fragments.
12466 Revert to the normal definition outside of these fragments."
12467 (interactive "P")
12468 (if (org-inside-LaTeX-fragment-p)
12469 (call-interactively 'cdlatex-math-modify)
12470 (let (org-cdlatex-mode)
12471 (call-interactively (key-binding (vector last-input-event))))))
12473 (defvar org-latex-fragment-image-overlays nil
12474 "List of overlays carrying the images of latex fragments.")
12475 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12477 (defun org-remove-latex-fragment-image-overlays ()
12478 "Remove all overlays with LaTeX fragment images in current buffer."
12479 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12480 (setq org-latex-fragment-image-overlays nil))
12482 (defun org-preview-latex-fragment (&optional subtree)
12483 "Preview the LaTeX fragment at point, or all locally or globally.
12484 If the cursor is in a LaTeX fragment, create the image and overlay
12485 it over the source code. If there is no fragment at point, display
12486 all fragments in the current text, from one headline to the next. With
12487 prefix SUBTREE, display all fragments in the current subtree. With a
12488 double prefix `C-u C-u', or when the cursor is before the first headline,
12489 display all fragments in the buffer.
12490 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12491 (interactive "P")
12492 (org-remove-latex-fragment-image-overlays)
12493 (save-excursion
12494 (save-restriction
12495 (let (beg end at msg)
12496 (cond
12497 ((or (equal subtree '(16))
12498 (not (save-excursion
12499 (re-search-backward (concat "^" outline-regexp) nil t))))
12500 (setq beg (point-min) end (point-max)
12501 msg "Creating images for buffer...%s"))
12502 ((equal subtree '(4))
12503 (org-back-to-heading)
12504 (setq beg (point) end (org-end-of-subtree t)
12505 msg "Creating images for subtree...%s"))
12507 (if (setq at (org-inside-LaTeX-fragment-p))
12508 (goto-char (max (point-min) (- (cdr at) 2)))
12509 (org-back-to-heading))
12510 (setq beg (point) end (progn (outline-next-heading) (point))
12511 msg (if at "Creating image...%s"
12512 "Creating images for entry...%s"))))
12513 (message msg "")
12514 (narrow-to-region beg end)
12515 (goto-char beg)
12516 (org-format-latex
12517 (concat "ltxpng/" (file-name-sans-extension
12518 (file-name-nondirectory
12519 buffer-file-name)))
12520 default-directory 'overlays msg at 'forbuffer)
12521 (message msg "done. Use `C-c C-c' to remove images.")))))
12523 (defvar org-latex-regexps
12524 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12525 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12526 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12527 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12528 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12529 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12530 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12531 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12532 "Regular expressions for matching embedded LaTeX.")
12534 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12535 "Replace LaTeX fragments with links to an image, and produce images."
12536 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12537 (let* ((prefixnodir (file-name-nondirectory prefix))
12538 (absprefix (expand-file-name prefix dir))
12539 (todir (file-name-directory absprefix))
12540 (opt org-format-latex-options)
12541 (matchers (plist-get opt :matchers))
12542 (re-list org-latex-regexps)
12543 (cnt 0) txt link beg end re e checkdir
12544 m n block linkfile movefile ov)
12545 ;; Check if there are old images files with this prefix, and remove them
12546 (when (file-directory-p todir)
12547 (mapc 'delete-file
12548 (directory-files
12549 todir 'full
12550 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12551 ;; Check the different regular expressions
12552 (while (setq e (pop re-list))
12553 (setq m (car e) re (nth 1 e) n (nth 2 e)
12554 block (if (nth 3 e) "\n\n" ""))
12555 (when (member m matchers)
12556 (goto-char (point-min))
12557 (while (re-search-forward re nil t)
12558 (when (or (not at) (equal (cdr at) (match-beginning n)))
12559 (setq txt (match-string n)
12560 beg (match-beginning n) end (match-end n)
12561 cnt (1+ cnt)
12562 linkfile (format "%s_%04d.png" prefix cnt)
12563 movefile (format "%s_%04d.png" absprefix cnt)
12564 link (concat block "[[file:" linkfile "]]" block))
12565 (if msg (message msg cnt))
12566 (goto-char beg)
12567 (unless checkdir ; make sure the directory exists
12568 (setq checkdir t)
12569 (or (file-directory-p todir) (make-directory todir)))
12570 (org-create-formula-image
12571 txt movefile opt forbuffer)
12572 (if overlays
12573 (progn
12574 (setq ov (org-make-overlay beg end))
12575 (if (featurep 'xemacs)
12576 (progn
12577 (org-overlay-put ov 'invisible t)
12578 (org-overlay-put
12579 ov 'end-glyph
12580 (make-glyph (vector 'png :file movefile))))
12581 (org-overlay-put
12582 ov 'display
12583 (list 'image :type 'png :file movefile :ascent 'center)))
12584 (push ov org-latex-fragment-image-overlays)
12585 (goto-char end))
12586 (delete-region beg end)
12587 (insert link))))))))
12589 ;; This function borrows from Ganesh Swami's latex2png.el
12590 (defun org-create-formula-image (string tofile options buffer)
12591 (let* ((tmpdir (if (featurep 'xemacs)
12592 (temp-directory)
12593 temporary-file-directory))
12594 (texfilebase (make-temp-name
12595 (expand-file-name "orgtex" tmpdir)))
12596 (texfile (concat texfilebase ".tex"))
12597 (dvifile (concat texfilebase ".dvi"))
12598 (pngfile (concat texfilebase ".png"))
12599 (fnh (if (featurep 'xemacs)
12600 (font-height (get-face-font 'default))
12601 (face-attribute 'default :height nil)))
12602 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12603 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12604 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12605 "Black"))
12606 (bg (or (plist-get options (if buffer :background :html-background))
12607 "Transparent")))
12608 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12609 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12610 (with-temp-file texfile
12611 (insert org-format-latex-header
12612 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12613 (let ((dir default-directory))
12614 (condition-case nil
12615 (progn
12616 (cd tmpdir)
12617 (call-process "latex" nil nil nil texfile))
12618 (error nil))
12619 (cd dir))
12620 (if (not (file-exists-p dvifile))
12621 (progn (message "Failed to create dvi file from %s" texfile) nil)
12622 (condition-case nil
12623 (call-process "dvipng" nil nil nil
12624 "-E" "-fg" fg "-bg" bg
12625 "-D" dpi
12626 ;;"-x" scale "-y" scale
12627 "-T" "tight"
12628 "-o" pngfile
12629 dvifile)
12630 (error nil))
12631 (if (not (file-exists-p pngfile))
12632 (progn (message "Failed to create png file from %s" texfile) nil)
12633 ;; Use the requested file name and clean up
12634 (copy-file pngfile tofile 'replace)
12635 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12636 (delete-file (concat texfilebase e)))
12637 pngfile))))
12639 (defun org-dvipng-color (attr)
12640 "Return an rgb color specification for dvipng."
12641 (apply 'format "rgb %s %s %s"
12642 (mapcar 'org-normalize-color
12643 (color-values (face-attribute 'default attr nil)))))
12645 (defun org-normalize-color (value)
12646 "Return string to be used as color value for an RGB component."
12647 (format "%g" (/ value 65535.0)))
12649 ;;;; Key bindings
12651 ;; Make `C-c C-x' a prefix key
12652 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12654 ;; TAB key with modifiers
12655 (org-defkey org-mode-map "\C-i" 'org-cycle)
12656 (org-defkey org-mode-map [(tab)] 'org-cycle)
12657 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12658 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12659 (org-defkey org-mode-map "\M-\t" 'org-complete)
12660 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12661 ;; The following line is necessary under Suse GNU/Linux
12662 (unless (featurep 'xemacs)
12663 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12664 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12665 (define-key org-mode-map [backtab] 'org-shifttab)
12667 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12668 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12669 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12671 ;; Cursor keys with modifiers
12672 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12673 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12674 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12675 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12677 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12678 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12679 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12680 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12682 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12683 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12684 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12685 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12687 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12688 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12690 ;;; Extra keys for tty access.
12691 ;; We only set them when really needed because otherwise the
12692 ;; menus don't show the simple keys
12694 (when (or org-use-extra-keys
12695 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12696 (not window-system))
12697 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12698 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12699 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12700 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12701 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12702 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12703 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12704 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12705 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12706 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12707 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12708 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12709 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12710 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12711 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12712 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12713 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12714 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12715 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12716 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12717 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12718 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12720 ;; All the other keys
12722 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12723 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12724 (if (boundp 'narrow-map)
12725 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12726 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12727 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12728 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12729 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12730 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12731 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12732 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12733 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12734 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12735 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12736 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12737 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12738 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12739 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12740 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12741 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12742 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12743 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12744 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12745 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12746 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12747 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12748 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12749 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12750 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12751 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12752 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12753 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12754 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12755 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12756 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12757 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12758 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12759 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12760 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12761 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12762 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12763 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12764 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12765 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12766 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12767 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12768 (org-defkey org-mode-map "\C-c^" 'org-sort)
12769 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12770 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12771 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12772 (org-defkey org-mode-map "\C-m" 'org-return)
12773 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12774 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12775 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12776 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12777 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12778 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12779 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12780 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12781 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12782 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12783 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12784 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12785 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12786 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12787 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12788 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12789 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12791 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12792 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12793 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12794 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12796 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12797 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12798 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12799 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12800 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12801 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12802 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12803 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12804 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12805 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12806 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12807 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12809 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12810 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12811 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12812 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12814 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12816 (when (featurep 'xemacs)
12817 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12819 (defvar org-table-auto-blank-field) ; defined in org-table.el
12820 (defun org-self-insert-command (N)
12821 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12822 If the cursor is in a table looking at whitespace, the whitespace is
12823 overwritten, and the table is not marked as requiring realignment."
12824 (interactive "p")
12825 (if (and (org-table-p)
12826 (progn
12827 ;; check if we blank the field, and if that triggers align
12828 (and (featurep 'org-table) org-table-auto-blank-field
12829 (member last-command
12830 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12831 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12832 ;; got extra space, this field does not determine column width
12833 (let (org-table-may-need-update) (org-table-blank-field))
12834 ;; no extra space, this field may determine column width
12835 (org-table-blank-field)))
12837 (eq N 1)
12838 (looking-at "[^|\n]* |"))
12839 (let (org-table-may-need-update)
12840 (goto-char (1- (match-end 0)))
12841 (delete-backward-char 1)
12842 (goto-char (match-beginning 0))
12843 (self-insert-command N))
12844 (setq org-table-may-need-update t)
12845 (self-insert-command N)
12846 (org-fix-tags-on-the-fly)))
12848 (defun org-fix-tags-on-the-fly ()
12849 (when (and (equal (char-after (point-at-bol)) ?*)
12850 (org-on-heading-p))
12851 (org-align-tags-here org-tags-column)))
12853 (defun org-delete-backward-char (N)
12854 "Like `delete-backward-char', insert whitespace at field end in tables.
12855 When deleting backwards, in tables this function will insert whitespace in
12856 front of the next \"|\" separator, to keep the table aligned. The table will
12857 still be marked for re-alignment if the field did fill the entire column,
12858 because, in this case the deletion might narrow the column."
12859 (interactive "p")
12860 (if (and (org-table-p)
12861 (eq N 1)
12862 (string-match "|" (buffer-substring (point-at-bol) (point)))
12863 (looking-at ".*?|"))
12864 (let ((pos (point))
12865 (noalign (looking-at "[^|\n\r]* |"))
12866 (c org-table-may-need-update))
12867 (backward-delete-char N)
12868 (skip-chars-forward "^|")
12869 (insert " ")
12870 (goto-char (1- pos))
12871 ;; noalign: if there were two spaces at the end, this field
12872 ;; does not determine the width of the column.
12873 (if noalign (setq org-table-may-need-update c)))
12874 (backward-delete-char N)
12875 (org-fix-tags-on-the-fly)))
12877 (defun org-delete-char (N)
12878 "Like `delete-char', but insert whitespace at field end in tables.
12879 When deleting characters, in tables this function will insert whitespace in
12880 front of the next \"|\" separator, to keep the table aligned. The table will
12881 still be marked for re-alignment if the field did fill the entire column,
12882 because, in this case the deletion might narrow the column."
12883 (interactive "p")
12884 (if (and (org-table-p)
12885 (not (bolp))
12886 (not (= (char-after) ?|))
12887 (eq N 1))
12888 (if (looking-at ".*?|")
12889 (let ((pos (point))
12890 (noalign (looking-at "[^|\n\r]* |"))
12891 (c org-table-may-need-update))
12892 (replace-match (concat
12893 (substring (match-string 0) 1 -1)
12894 " |"))
12895 (goto-char pos)
12896 ;; noalign: if there were two spaces at the end, this field
12897 ;; does not determine the width of the column.
12898 (if noalign (setq org-table-may-need-update c)))
12899 (delete-char N))
12900 (delete-char N)
12901 (org-fix-tags-on-the-fly)))
12903 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12904 (put 'org-self-insert-command 'delete-selection t)
12905 (put 'orgtbl-self-insert-command 'delete-selection t)
12906 (put 'org-delete-char 'delete-selection 'supersede)
12907 (put 'org-delete-backward-char 'delete-selection 'supersede)
12908 (put 'org-yank 'delete-selection 'yank)
12910 ;; Make `flyspell-mode' delay after some commands
12911 (put 'org-self-insert-command 'flyspell-delayed t)
12912 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12913 (put 'org-delete-char 'flyspell-delayed t)
12914 (put 'org-delete-backward-char 'flyspell-delayed t)
12916 ;; Make pabbrev-mode expand after org-mode commands
12917 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12918 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12920 ;; How to do this: Measure non-white length of current string
12921 ;; If equal to column width, we should realign.
12923 (defun org-remap (map &rest commands)
12924 "In MAP, remap the functions given in COMMANDS.
12925 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12926 (let (new old)
12927 (while commands
12928 (setq old (pop commands) new (pop commands))
12929 (if (fboundp 'command-remapping)
12930 (org-defkey map (vector 'remap old) new)
12931 (substitute-key-definition old new map global-map)))))
12933 (when (eq org-enable-table-editor 'optimized)
12934 ;; If the user wants maximum table support, we need to hijack
12935 ;; some standard editing functions
12936 (org-remap org-mode-map
12937 'self-insert-command 'org-self-insert-command
12938 'delete-char 'org-delete-char
12939 'delete-backward-char 'org-delete-backward-char)
12940 (org-defkey org-mode-map "|" 'org-force-self-insert))
12942 (defun org-shiftcursor-error ()
12943 "Throw an error, a modified cursor command was applied in wrong context."
12944 (error "This command is active in special context like tables, headlines or items"))
12946 (defun org-shiftselect-error ()
12947 "Throw an error because Shift-Cursor command was applied in wrong context."
12948 (if (and (boundp 'shift-select-mode) shift-select-mode)
12949 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
12950 (error "This command works only in special context like headlines or timestamps.")))
12952 (defun org-call-for-shift-select (cmd)
12953 (let ((this-command-keys-shift-translated t))
12954 (call-interactively cmd)))
12956 (defun org-shifttab (&optional arg)
12957 "Global visibility cycling or move to previous table field.
12958 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12959 on context.
12960 See the individual commands for more information."
12961 (interactive "P")
12962 (cond
12963 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12964 ((integerp arg)
12965 (message "Content view to level: %d" arg)
12966 (org-content (prefix-numeric-value arg))
12967 (setq org-cycle-global-status 'overview))
12968 (t (call-interactively 'org-global-cycle))))
12970 (defun org-shiftmetaleft ()
12971 "Promote subtree or delete table column.
12972 Calls `org-promote-subtree', `org-outdent-item',
12973 or `org-table-delete-column', depending on context.
12974 See the individual commands for more information."
12975 (interactive)
12976 (cond
12977 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12978 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12979 ((org-at-item-p) (call-interactively 'org-outdent-item))
12980 (t (org-shiftcursor-error))))
12982 (defun org-shiftmetaright ()
12983 "Demote subtree or insert table column.
12984 Calls `org-demote-subtree', `org-indent-item',
12985 or `org-table-insert-column', depending on context.
12986 See the individual commands for more information."
12987 (interactive)
12988 (cond
12989 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12990 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12991 ((org-at-item-p) (call-interactively 'org-indent-item))
12992 (t (org-shiftcursor-error))))
12994 (defun org-shiftmetaup (&optional arg)
12995 "Move subtree up or kill table row.
12996 Calls `org-move-subtree-up' or `org-table-kill-row' or
12997 `org-move-item-up' depending on context. See the individual commands
12998 for more information."
12999 (interactive "P")
13000 (cond
13001 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13002 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13003 ((org-at-item-p) (call-interactively 'org-move-item-up))
13004 (t (org-shiftcursor-error))))
13005 (defun org-shiftmetadown (&optional arg)
13006 "Move subtree down or insert table row.
13007 Calls `org-move-subtree-down' or `org-table-insert-row' or
13008 `org-move-item-down', depending on context. See the individual
13009 commands for more information."
13010 (interactive "P")
13011 (cond
13012 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13013 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13014 ((org-at-item-p) (call-interactively 'org-move-item-down))
13015 (t (org-shiftcursor-error))))
13017 (defun org-metaleft (&optional arg)
13018 "Promote heading or move table column to left.
13019 Calls `org-do-promote' or `org-table-move-column', depending on context.
13020 With no specific context, calls the Emacs default `backward-word'.
13021 See the individual commands for more information."
13022 (interactive "P")
13023 (cond
13024 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13025 ((or (org-on-heading-p) (org-region-active-p))
13026 (call-interactively 'org-do-promote))
13027 ((org-at-item-p) (call-interactively 'org-outdent-item))
13028 (t (call-interactively 'backward-word))))
13030 (defun org-metaright (&optional arg)
13031 "Demote subtree or move table column to right.
13032 Calls `org-do-demote' or `org-table-move-column', depending on context.
13033 With no specific context, calls the Emacs default `forward-word'.
13034 See the individual commands for more information."
13035 (interactive "P")
13036 (cond
13037 ((org-at-table-p) (call-interactively 'org-table-move-column))
13038 ((or (org-on-heading-p) (org-region-active-p))
13039 (call-interactively 'org-do-demote))
13040 ((org-at-item-p) (call-interactively 'org-indent-item))
13041 (t (call-interactively 'forward-word))))
13043 (defun org-metaup (&optional arg)
13044 "Move subtree up or move table row up.
13045 Calls `org-move-subtree-up' or `org-table-move-row' or
13046 `org-move-item-up', depending on context. See the individual commands
13047 for more information."
13048 (interactive "P")
13049 (cond
13050 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13051 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13052 ((org-at-item-p) (call-interactively 'org-move-item-up))
13053 (t (transpose-lines 1) (beginning-of-line -1))))
13055 (defun org-metadown (&optional arg)
13056 "Move subtree down or move table row down.
13057 Calls `org-move-subtree-down' or `org-table-move-row' or
13058 `org-move-item-down', depending on context. See the individual
13059 commands for more information."
13060 (interactive "P")
13061 (cond
13062 ((org-at-table-p) (call-interactively 'org-table-move-row))
13063 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13064 ((org-at-item-p) (call-interactively 'org-move-item-down))
13065 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13067 (defun org-shiftup (&optional arg)
13068 "Increase item in timestamp or increase priority of current headline.
13069 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13070 depending on context. See the individual commands for more information."
13071 (interactive "P")
13072 (cond
13073 ((and org-support-shift-select (org-region-active-p))
13074 (org-call-for-shift-select 'previous-line))
13075 ((org-at-timestamp-p t)
13076 (call-interactively (if org-edit-timestamp-down-means-later
13077 'org-timestamp-down 'org-timestamp-up)))
13078 ((and (not (eq org-support-shift-select 'always))
13079 (org-on-heading-p))
13080 (call-interactively 'org-priority-up))
13081 ((and (not org-support-shift-select) (org-at-item-p))
13082 (call-interactively 'org-previous-item))
13083 ((org-clocktable-try-shift 'up arg))
13084 (org-support-shift-select
13085 (org-call-for-shift-select 'previous-line))
13086 (t (org-shiftselect-error))))
13088 (defun org-shiftdown (&optional arg)
13089 "Decrease item in timestamp or decrease priority of current headline.
13090 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13091 depending on context. See the individual commands for more information."
13092 (interactive "P")
13093 (cond
13094 ((and org-support-shift-select (org-region-active-p))
13095 (org-call-for-shift-select 'next-line))
13096 ((org-at-timestamp-p t)
13097 (call-interactively (if org-edit-timestamp-down-means-later
13098 'org-timestamp-up 'org-timestamp-down)))
13099 ((and (not (eq org-support-shift-select 'always))
13100 (org-on-heading-p))
13101 (call-interactively 'org-priority-down))
13102 ((and (not org-support-shift-select) (org-at-item-p))
13103 (call-interactively 'org-next-item))
13104 ((org-clocktable-try-shift 'down arg))
13105 (org-support-shift-select
13106 (org-call-for-shift-select 'next-line))
13107 (t (org-shiftselect-error))))
13109 (defun org-shiftright (&optional arg)
13110 "Cycle the thing at point or in the current line, depending on context.
13111 Depending on context, this does one of the following:
13113 - switch a timestamp at point one day into the future
13114 - on a headline, switch to the next TODO keyword.
13115 - on an item, switch entire list to the next bullet type
13116 - on a property line, switch to the next allowed value
13117 - on a clocktable definition line, move time block into the future"
13118 (interactive "P")
13119 (cond
13120 ((and org-support-shift-select (org-region-active-p))
13121 (org-call-for-shift-select 'forward-char))
13122 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13123 ((and (not (eq org-support-shift-select 'always))
13124 (org-on-heading-p))
13125 (org-call-with-arg 'org-todo 'right))
13126 ((or (and org-support-shift-select
13127 (not (eq org-support-shift-select 'always))
13128 (org-at-item-bullet-p))
13129 (and (not org-support-shift-select) (org-at-item-p)))
13130 (org-call-with-arg 'org-cycle-list-bullet nil))
13131 ((and (not (eq org-support-shift-select 'always))
13132 (org-at-property-p))
13133 (call-interactively 'org-property-next-allowed-value))
13134 ((org-clocktable-try-shift 'right arg))
13135 (org-support-shift-select
13136 (org-call-for-shift-select 'forward-char))
13137 (t (org-shiftselect-error))))
13139 (defun org-shiftleft (&optional arg)
13140 "Cycle the thing at point or in the current line, depending on context.
13141 Depending on context, this does one of the following:
13143 - switch a timestamp at point one day into the past
13144 - on a headline, switch to the previous TODO keyword.
13145 - on an item, switch entire list to the previous bullet type
13146 - on a property line, switch to the previous allowed value
13147 - on a clocktable definition line, move time block into the past"
13148 (interactive "P")
13149 (cond
13150 ((and org-support-shift-select (org-region-active-p))
13151 (org-call-for-shift-select 'backward-char))
13152 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13153 ((and (not (eq org-support-shift-select 'always))
13154 (org-on-heading-p))
13155 (org-call-with-arg 'org-todo 'left))
13156 ((or (and org-support-shift-select
13157 (not (eq org-support-shift-select 'always))
13158 (org-at-item-bullet-p))
13159 (and (not org-support-shift-select) (org-at-item-p)))
13160 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13161 ((and (not (eq org-support-shift-select 'always))
13162 (org-at-property-p))
13163 (call-interactively 'org-property-previous-allowed-value))
13164 ((org-clocktable-try-shift 'left arg))
13165 (org-support-shift-select
13166 (org-call-for-shift-select 'backward-char))
13167 (t (org-shiftselect-error))))
13169 (defun org-shiftcontrolright ()
13170 "Switch to next TODO set."
13171 (interactive)
13172 (cond
13173 ((and org-support-shift-select (org-region-active-p))
13174 (org-call-for-shift-select 'forward-word))
13175 ((and (not (eq org-support-shift-select 'always))
13176 (org-on-heading-p))
13177 (org-call-with-arg 'org-todo 'nextset))
13178 (org-support-shift-select
13179 (org-call-for-shift-select 'forward-word))
13180 (t (org-shiftselect-error))))
13182 (defun org-shiftcontrolleft ()
13183 "Switch to previous TODO set."
13184 (interactive)
13185 (cond
13186 ((and org-support-shift-select (org-region-active-p))
13187 (org-call-for-shift-select 'backward-word))
13188 ((and (not (eq org-support-shift-select 'always))
13189 (org-on-heading-p))
13190 (org-call-with-arg 'org-todo 'previousset))
13191 (org-support-shift-select
13192 (org-call-for-shift-select 'backward-word))
13193 (t (org-shiftselect-error))))
13195 (defun org-ctrl-c-ret ()
13196 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13197 (interactive)
13198 (cond
13199 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13200 (t (call-interactively 'org-insert-heading))))
13202 (defun org-copy-special ()
13203 "Copy region in table or copy current subtree.
13204 Calls `org-table-copy' or `org-copy-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-copy-region 'org-copy-subtree)))
13210 (defun org-cut-special ()
13211 "Cut region in table or cut current subtree.
13212 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13213 See the individual commands for more information."
13214 (interactive)
13215 (call-interactively
13216 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13218 (defun org-paste-special (arg)
13219 "Paste rectangular region into table, or past subtree relative to level.
13220 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13221 See the individual commands for more information."
13222 (interactive "P")
13223 (if (org-at-table-p)
13224 (org-table-paste-rectangle)
13225 (org-paste-subtree arg)))
13227 (defun org-edit-special ()
13228 "Call a special editor for the stuff at point.
13229 When at a table, call the formula editor with `org-table-edit-formulas'.
13230 When at the first line of an src example, call `org-edit-src-code'.
13231 When in an #+include line, visit the include file. Otherwise call
13232 `ffap' to visit the file at point."
13233 (interactive)
13234 (cond
13235 ((org-at-table-p)
13236 (call-interactively 'org-table-edit-formulas))
13237 ((save-excursion
13238 (beginning-of-line 1)
13239 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13240 (find-file (org-trim (match-string 1))))
13241 ((org-edit-src-code))
13242 ((org-edit-fixed-width-region))
13243 (t (call-interactively 'ffap))))
13245 (defun org-ctrl-c-ctrl-c (&optional arg)
13246 "Set tags in headline, or update according to changed information at point.
13248 This command does many different things, depending on context:
13250 - If the cursor is in a headline, prompt for tags and insert them
13251 into the current line, aligned to `org-tags-column'. When called
13252 with prefix arg, realign all tags in the current buffer.
13254 - If the cursor is in one of the special #+KEYWORD lines, this
13255 triggers scanning the buffer for these lines and updating the
13256 information.
13258 - If the cursor is inside a table, realign the table. This command
13259 works even if the automatic table editor has been turned off.
13261 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13262 the entire table.
13264 - If the cursor is at a footnote reference or definition, jump to
13265 the corresponding definition or references, respectively.
13267 - If the cursor is a the beginning of a dynamic block, update it.
13269 - If the cursor is inside a table created by the table.el package,
13270 activate that table.
13272 - If the current buffer is a remember buffer, close note and file
13273 it. A prefix argument of 1 files to the default location
13274 without further interaction. A prefix argument of 2 files to
13275 the currently clocking task.
13277 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13278 links in this buffer.
13280 - If the cursor is on a numbered item in a plain list, renumber the
13281 ordered list.
13283 - If the cursor is on a checkbox, toggle it."
13284 (interactive "P")
13285 (let ((org-enable-table-editor t))
13286 (cond
13287 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13288 org-occur-highlights
13289 org-latex-fragment-image-overlays)
13290 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13291 (org-remove-occur-highlights)
13292 (org-remove-latex-fragment-image-overlays)
13293 (message "Temporary highlights/overlays removed from current buffer"))
13294 ((and (local-variable-p 'org-finish-function (current-buffer))
13295 (fboundp org-finish-function))
13296 (funcall org-finish-function))
13297 ((org-at-property-p)
13298 (call-interactively 'org-property-action))
13299 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13300 ((org-on-heading-p) (call-interactively 'org-set-tags))
13301 ((org-at-table.el-p)
13302 (require 'table)
13303 (beginning-of-line 1)
13304 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13305 (call-interactively 'table-recognize-table))
13306 ((org-at-table-p)
13307 (org-table-maybe-eval-formula)
13308 (if arg
13309 (call-interactively 'org-table-recalculate)
13310 (org-table-maybe-recalculate-line))
13311 (call-interactively 'org-table-align))
13312 ((or (org-footnote-at-reference-p)
13313 (org-footnote-at-definition-p))
13314 (call-interactively 'org-footnote-action))
13315 ((org-at-item-checkbox-p)
13316 (call-interactively 'org-toggle-checkbox))
13317 ((org-at-item-p)
13318 (call-interactively 'org-maybe-renumber-ordered-list))
13319 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13320 ;; Dynamic block
13321 (beginning-of-line 1)
13322 (save-excursion (org-update-dblock)))
13323 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13324 (cond
13325 ((equal (match-string 1) "TBLFM")
13326 ;; Recalculate the table before this line
13327 (save-excursion
13328 (beginning-of-line 1)
13329 (skip-chars-backward " \r\n\t")
13330 (if (org-at-table-p)
13331 (org-call-with-arg 'org-table-recalculate t))))
13333 ; (org-set-regexps-and-options)
13334 ; (org-restart-font-lock)
13335 (let ((org-inhibit-startup t)) (org-mode-restart))
13336 (message "Local setup has been refreshed"))))
13337 (t (error "C-c C-c can do nothing useful at this location.")))))
13339 (defun org-mode-restart ()
13340 "Restart Org-mode, to scan again for special lines.
13341 Also updates the keyword regular expressions."
13342 (interactive)
13343 (org-mode)
13344 (message "Org-mode restarted"))
13346 (defun org-kill-note-or-show-branches ()
13347 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13348 (interactive)
13349 (if (not org-finish-function)
13350 (call-interactively 'show-branches)
13351 (let ((org-note-abort t))
13352 (funcall org-finish-function))))
13354 (defun org-return (&optional indent)
13355 "Goto next table row or insert a newline.
13356 Calls `org-table-next-row' or `newline', depending on context.
13357 See the individual commands for more information."
13358 (interactive)
13359 (cond
13360 ((bobp) (if indent (newline-and-indent) (newline)))
13361 ((and (org-at-heading-p)
13362 (looking-at
13363 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13364 (org-show-entry)
13365 (end-of-line 1)
13366 (newline))
13367 ((org-at-table-p)
13368 (org-table-justify-field-maybe)
13369 (call-interactively 'org-table-next-row))
13370 (t (if indent (newline-and-indent) (newline)))))
13372 (defun org-return-indent ()
13373 "Goto next table row or insert a newline and indent.
13374 Calls `org-table-next-row' or `newline-and-indent', depending on
13375 context. See the individual commands for more information."
13376 (interactive)
13377 (org-return t))
13379 (defun org-ctrl-c-star ()
13380 "Compute table, or change heading status of lines.
13381 Calls `org-table-recalculate' or `org-toggle-heading',
13382 depending on context."
13383 (interactive)
13384 (cond
13385 ((org-at-table-p)
13386 (call-interactively 'org-table-recalculate))
13388 ;; Convert all lines in region to list items
13389 (call-interactively 'org-toggle-heading))))
13391 (defun org-ctrl-c-minus ()
13392 "Insert separator line in table or modify bullet status of line.
13393 Also turns a plain line or a region of lines into list items.
13394 Calls `org-table-insert-hline', `org-toggle-item', or
13395 `org-cycle-list-bullet', depending on context."
13396 (interactive)
13397 (cond
13398 ((org-at-table-p)
13399 (call-interactively 'org-table-insert-hline))
13400 ((org-region-active-p)
13401 (call-interactively 'org-toggle-item))
13402 ((org-in-item-p)
13403 (call-interactively 'org-cycle-list-bullet))
13405 (call-interactively 'org-toggle-item))))
13407 (defun org-toggle-item ()
13408 "Convert headings or normal lines to items, items to normal lines.
13409 If there is no active region, only the current line is considered.
13411 If the first line in the region is a headline, convert all headlines to items.
13413 If the first line in the region is an item, convert all items to normal lines.
13415 If the first line is normal text, add an item bullet to each line."
13416 (interactive)
13417 (let (l2 l beg end)
13418 (if (org-region-active-p)
13419 (setq beg (region-beginning) end (region-end))
13420 (setq beg (point-at-bol)
13421 end (min (1+ (point-at-eol)) (point-max))))
13422 (save-excursion
13423 (goto-char end)
13424 (setq l2 (org-current-line))
13425 (goto-char beg)
13426 (beginning-of-line 1)
13427 (setq l (1- (org-current-line)))
13428 (if (org-at-item-p)
13429 ;; We already have items, de-itemize
13430 (while (< (setq l (1+ l)) l2)
13431 (when (org-at-item-p)
13432 (goto-char (match-beginning 2))
13433 (delete-region (match-beginning 2) (match-end 2))
13434 (and (looking-at "[ \t]+") (replace-match "")))
13435 (beginning-of-line 2))
13436 (if (org-on-heading-p)
13437 ;; Headings, convert to items
13438 (while (< (setq l (1+ l)) l2)
13439 (if (looking-at org-outline-regexp)
13440 (replace-match "- " t t))
13441 (beginning-of-line 2))
13442 ;; normal lines, turn them into items
13443 (while (< (setq l (1+ l)) l2)
13444 (unless (org-at-item-p)
13445 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13446 (replace-match "\\1- \\2")))
13447 (beginning-of-line 2)))))))
13449 (defun org-toggle-heading (&optional nstars)
13450 "Convert headings to normal text, or items or text to headings.
13451 If there is no active region, only the current line is considered.
13453 If the first line is a heading, remove the stars from all headlines
13454 in the region.
13456 If the first line is a plain list item, turn all plain list items into
13457 headings.
13459 If the first line is a normal line, turn each and every line in the region
13460 into a heading.
13462 When converting a line into a heading, the number of stars is chosen
13463 such that the lines become children of the current entry. However, when
13464 a prefix argument is given, its value determines the number of stars to add."
13465 (interactive "P")
13466 (let (l2 l itemp beg end)
13467 (if (org-region-active-p)
13468 (setq beg (region-beginning) end (region-end))
13469 (setq beg (point-at-bol)
13470 end (min (1+ (point-at-eol)) (point-max))))
13471 (save-excursion
13472 (goto-char end)
13473 (setq l2 (org-current-line))
13474 (goto-char beg)
13475 (beginning-of-line 1)
13476 (setq l (1- (org-current-line)))
13477 (if (org-on-heading-p)
13478 ;; We already have headlines, de-star them
13479 (while (< (setq l (1+ l)) l2)
13480 (when (org-on-heading-p t)
13481 (and (looking-at outline-regexp) (replace-match "")))
13482 (beginning-of-line 2))
13483 (setq itemp (org-at-item-p))
13484 (let* ((stars
13485 (if nstars
13486 (make-string (prefix-numeric-value current-prefix-arg)
13488 (save-excursion
13489 (re-search-backward org-complex-heading-regexp nil t)
13490 (or (match-string 1) "*"))))
13491 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13492 (rpl (concat stars add-stars " ")))
13493 (while (< (setq l (1+ l)) l2)
13494 (if itemp
13495 (and (org-at-item-p) (replace-match rpl t t))
13496 (unless (org-on-heading-p)
13497 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13498 (replace-match (concat rpl (match-string 2))))))
13499 (beginning-of-line 2)))))))
13501 (defun org-meta-return (&optional arg)
13502 "Insert a new heading or wrap a region in a table.
13503 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13504 See the individual commands for more information."
13505 (interactive "P")
13506 (cond
13507 ((org-at-table-p)
13508 (call-interactively 'org-table-wrap-region))
13509 (t (call-interactively 'org-insert-heading))))
13511 ;;; Menu entries
13513 ;; Define the Org-mode menus
13514 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13515 '("Tbl"
13516 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13517 ["Next Field" org-cycle (org-at-table-p)]
13518 ["Previous Field" org-shifttab (org-at-table-p)]
13519 ["Next Row" org-return (org-at-table-p)]
13520 "--"
13521 ["Blank Field" org-table-blank-field (org-at-table-p)]
13522 ["Edit Field" org-table-edit-field (org-at-table-p)]
13523 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13524 "--"
13525 ("Column"
13526 ["Move Column Left" org-metaleft (org-at-table-p)]
13527 ["Move Column Right" org-metaright (org-at-table-p)]
13528 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13529 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13530 ("Row"
13531 ["Move Row Up" org-metaup (org-at-table-p)]
13532 ["Move Row Down" org-metadown (org-at-table-p)]
13533 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13534 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13535 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13536 "--"
13537 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13538 ("Rectangle"
13539 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13540 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13541 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13542 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13543 "--"
13544 ("Calculate"
13545 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13546 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13547 ["Edit Formulas" org-edit-special (org-at-table-p)]
13548 "--"
13549 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13550 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13551 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13552 "--"
13553 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13554 "--"
13555 ["Sum Column/Rectangle" org-table-sum
13556 (or (org-at-table-p) (org-region-active-p))]
13557 ["Which Column?" org-table-current-column (org-at-table-p)])
13558 ["Debug Formulas"
13559 org-table-toggle-formula-debugger
13560 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13561 ["Show Col/Row Numbers"
13562 org-table-toggle-coordinate-overlays
13563 :style toggle
13564 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13565 "--"
13566 ["Create" org-table-create (and (not (org-at-table-p))
13567 org-enable-table-editor)]
13568 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13569 ["Import from File" org-table-import (not (org-at-table-p))]
13570 ["Export to File" org-table-export (org-at-table-p)]
13571 "--"
13572 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13574 (easy-menu-define org-org-menu org-mode-map "Org menu"
13575 '("Org"
13576 ("Show/Hide"
13577 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13578 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13579 ["Sparse Tree..." org-sparse-tree t]
13580 ["Reveal Context" org-reveal t]
13581 ["Show All" show-all t]
13582 "--"
13583 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13584 "--"
13585 ["New Heading" org-insert-heading t]
13586 ("Navigate Headings"
13587 ["Up" outline-up-heading t]
13588 ["Next" outline-next-visible-heading t]
13589 ["Previous" outline-previous-visible-heading t]
13590 ["Next Same Level" outline-forward-same-level t]
13591 ["Previous Same Level" outline-backward-same-level t]
13592 "--"
13593 ["Jump" org-goto t])
13594 ("Edit Structure"
13595 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13596 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13597 "--"
13598 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13599 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13600 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13601 "--"
13602 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13603 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13604 ["Demote Heading" org-metaright (not (org-at-table-p))]
13605 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13606 "--"
13607 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13608 "--"
13609 ["Convert to odd levels" org-convert-to-odd-levels t]
13610 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13611 ("Editing"
13612 ["Emphasis..." org-emphasize t]
13613 ["Edit Source Example" org-edit-special t]
13614 "--"
13615 ["Footnote new/jump" org-footnote-action t]
13616 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13617 ("Archive"
13618 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13619 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13620 ; :active t :keys "C-u C-c C-x C-a"]
13621 ["Sparse trees open ARCHIVE trees"
13622 (setq org-sparse-tree-open-archived-trees
13623 (not org-sparse-tree-open-archived-trees))
13624 :style toggle :selected org-sparse-tree-open-archived-trees]
13625 ["Cycling opens ARCHIVE trees"
13626 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13627 :style toggle :selected org-cycle-open-archived-trees]
13628 "--"
13629 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13630 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13631 ; ["Check and Move Children" (org-archive-subtree '(4))
13632 ; :active t :keys "C-u C-c C-x C-s"]
13634 "--"
13635 ("TODO Lists"
13636 ["TODO/DONE/-" org-todo t]
13637 ("Select keyword"
13638 ["Next keyword" org-shiftright (org-on-heading-p)]
13639 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13640 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13641 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13642 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13643 ["Show TODO Tree" org-show-todo-tree t]
13644 ["Global TODO list" org-todo-list t]
13645 "--"
13646 ["Set Priority" org-priority t]
13647 ["Priority Up" org-shiftup t]
13648 ["Priority Down" org-shiftdown t])
13649 ("TAGS and Properties"
13650 ["Set Tags" org-set-tags-command t]
13651 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13652 "--"
13653 ["Set property" org-set-property t]
13654 ["Column view of properties" org-columns t]
13655 ["Insert Column View DBlock" org-insert-columns-dblock t])
13656 ("Dates and Scheduling"
13657 ["Timestamp" org-time-stamp t]
13658 ["Timestamp (inactive)" org-time-stamp-inactive t]
13659 ("Change Date"
13660 ["1 Day Later" org-shiftright t]
13661 ["1 Day Earlier" org-shiftleft t]
13662 ["1 ... Later" org-shiftup t]
13663 ["1 ... Earlier" org-shiftdown t])
13664 ["Compute Time Range" org-evaluate-time-range t]
13665 ["Schedule Item" org-schedule t]
13666 ["Deadline" org-deadline t]
13667 "--"
13668 ["Custom time format" org-toggle-time-stamp-overlays
13669 :style radio :selected org-display-custom-times]
13670 "--"
13671 ["Goto Calendar" org-goto-calendar t]
13672 ["Date from Calendar" org-date-from-calendar t]
13673 "--"
13674 ["Start/Restart Timer" org-timer-start t]
13675 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13676 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13677 ["Insert Timer String" org-timer t]
13678 ["Insert Timer Item" org-timer-item t])
13679 ("Logging work"
13680 ["Clock in" org-clock-in t]
13681 ["Clock out" org-clock-out t]
13682 ["Clock cancel" org-clock-cancel t]
13683 ["Goto running clock" org-clock-goto t]
13684 ["Display times" org-clock-display t]
13685 ["Create clock table" org-clock-report t]
13686 "--"
13687 ["Record DONE time"
13688 (progn (setq org-log-done (not org-log-done))
13689 (message "Switching to %s will %s record a timestamp"
13690 (car org-done-keywords)
13691 (if org-log-done "automatically" "not")))
13692 :style toggle :selected org-log-done])
13693 "--"
13694 ["Agenda Command..." org-agenda t]
13695 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13696 ("File List for Agenda")
13697 ("Special views current file"
13698 ["TODO Tree" org-show-todo-tree t]
13699 ["Check Deadlines" org-check-deadlines t]
13700 ["Timeline" org-timeline t]
13701 ["Tags Tree" org-tags-sparse-tree t])
13702 "--"
13703 ("Hyperlinks"
13704 ["Store Link (Global)" org-store-link t]
13705 ["Insert Link" org-insert-link t]
13706 ["Follow Link" org-open-at-point t]
13707 "--"
13708 ["Next link" org-next-link t]
13709 ["Previous link" org-previous-link t]
13710 "--"
13711 ["Descriptive Links"
13712 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13713 :style radio
13714 :selected (member '(org-link) buffer-invisibility-spec)]
13715 ["Literal Links"
13716 (progn
13717 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13718 :style radio
13719 :selected (not (member '(org-link) buffer-invisibility-spec))])
13720 "--"
13721 ["Export/Publish..." org-export t]
13722 ("LaTeX"
13723 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13724 :selected org-cdlatex-mode]
13725 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13726 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13727 ["Modify math symbol" org-cdlatex-math-modify
13728 (org-inside-LaTeX-fragment-p)]
13729 ["Export LaTeX fragments as images"
13730 (if (featurep 'org-exp)
13731 (setq org-export-with-LaTeX-fragments
13732 (not org-export-with-LaTeX-fragments))
13733 (require 'org-exp))
13734 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13735 org-export-with-LaTeX-fragments)])
13736 "--"
13737 ("Documentation"
13738 ["Show Version" org-version t]
13739 ["Info Documentation" org-info t])
13740 ("Customize"
13741 ["Browse Org Group" org-customize t]
13742 "--"
13743 ["Expand This Menu" org-create-customize-menu
13744 (fboundp 'customize-menu-create)])
13745 "--"
13746 ["Refresh setup" org-mode-restart t]
13749 (defun org-info (&optional node)
13750 "Read documentation for Org-mode in the info system.
13751 With optional NODE, go directly to that node."
13752 (interactive)
13753 (info (format "(org)%s" (or node ""))))
13755 (defun org-install-agenda-files-menu ()
13756 (let ((bl (buffer-list)))
13757 (save-excursion
13758 (while bl
13759 (set-buffer (pop bl))
13760 (if (org-mode-p) (setq bl nil)))
13761 (when (org-mode-p)
13762 (easy-menu-change
13763 '("Org") "File List for Agenda"
13764 (append
13765 (list
13766 ["Edit File List" (org-edit-agenda-file-list) t]
13767 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13768 ["Remove Current File from List" org-remove-file t]
13769 ["Cycle through agenda files" org-cycle-agenda-files t]
13770 ["Occur in all agenda files" org-occur-in-agenda-files t]
13771 "--")
13772 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13774 ;;;; Documentation
13776 ;;;###autoload
13777 (defun org-require-autoloaded-modules ()
13778 (interactive)
13779 (mapc 'require
13780 '(org-agenda org-archive org-clock org-colview
13781 org-exp org-id org-export-latex org-publish
13782 org-remember org-table)))
13784 ;;;###autoload
13785 (defun org-customize ()
13786 "Call the customize function with org as argument."
13787 (interactive)
13788 (org-load-modules-maybe)
13789 (org-require-autoloaded-modules)
13790 (customize-browse 'org))
13792 (defun org-create-customize-menu ()
13793 "Create a full customization menu for Org-mode, insert it into the menu."
13794 (interactive)
13795 (org-load-modules-maybe)
13796 (org-require-autoloaded-modules)
13797 (if (fboundp 'customize-menu-create)
13798 (progn
13799 (easy-menu-change
13800 '("Org") "Customize"
13801 `(["Browse Org group" org-customize t]
13802 "--"
13803 ,(customize-menu-create 'org)
13804 ["Set" Custom-set t]
13805 ["Save" Custom-save t]
13806 ["Reset to Current" Custom-reset-current t]
13807 ["Reset to Saved" Custom-reset-saved t]
13808 ["Reset to Standard Settings" Custom-reset-standard t]))
13809 (message "\"Org\"-menu now contains full customization menu"))
13810 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13812 ;;;; Miscellaneous stuff
13814 ;;; Generally useful functions
13816 (defun org-find-text-property-in-string (prop s)
13817 "Return the first non-nil value of property PROP in string S."
13818 (or (get-text-property 0 prop s)
13819 (get-text-property (or (next-single-property-change 0 prop s) 0)
13820 prop s)))
13822 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13823 "Display the given MESSAGE as a warning."
13824 (if (fboundp 'display-warning)
13825 (display-warning 'org message
13826 (if (featurep 'xemacs)
13827 'warning
13828 :warning))
13829 (let ((buf (get-buffer-create "*Org warnings*")))
13830 (with-current-buffer buf
13831 (goto-char (point-max))
13832 (insert "Warning (Org): " message)
13833 (unless (bolp)
13834 (newline)))
13835 (display-buffer buf)
13836 (sit-for 0))))
13838 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13839 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13840 (if (and marker (marker-buffer marker)
13841 (buffer-live-p (marker-buffer marker)))
13842 (progn
13843 (switch-to-buffer (marker-buffer marker))
13844 (if (or (> marker (point-max)) (< marker (point-min)))
13845 (widen))
13846 (goto-char marker)
13847 (org-show-context 'org-goto))
13848 (if bookmark
13849 (bookmark-jump bookmark)
13850 (error "Cannot find location"))))
13852 (defun org-quote-csv-field (s)
13853 "Quote field for inclusion in CSV material."
13854 (if (string-match "[\",]" s)
13855 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13858 (defun org-plist-delete (plist property)
13859 "Delete PROPERTY from PLIST.
13860 This is in contrast to merely setting it to 0."
13861 (let (p)
13862 (while plist
13863 (if (not (eq property (car plist)))
13864 (setq p (plist-put p (car plist) (nth 1 plist))))
13865 (setq plist (cddr plist)))
13868 (defun org-force-self-insert (N)
13869 "Needed to enforce self-insert under remapping."
13870 (interactive "p")
13871 (self-insert-command N))
13873 (defun org-string-width (s)
13874 "Compute width of string, ignoring invisible characters.
13875 This ignores character with invisibility property `org-link', and also
13876 characters with property `org-cwidth', because these will become invisible
13877 upon the next fontification round."
13878 (let (b l)
13879 (when (or (eq t buffer-invisibility-spec)
13880 (assq 'org-link buffer-invisibility-spec))
13881 (while (setq b (text-property-any 0 (length s)
13882 'invisible 'org-link s))
13883 (setq s (concat (substring s 0 b)
13884 (substring s (or (next-single-property-change
13885 b 'invisible s) (length s)))))))
13886 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13887 (setq s (concat (substring s 0 b)
13888 (substring s (or (next-single-property-change
13889 b 'org-cwidth s) (length s))))))
13890 (setq l (string-width s) b -1)
13891 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13892 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13895 (defun org-get-indentation (&optional line)
13896 "Get the indentation of the current line, interpreting tabs.
13897 When LINE is given, assume it represents a line and compute its indentation."
13898 (if line
13899 (if (string-match "^ *" (org-remove-tabs line))
13900 (match-end 0))
13901 (save-excursion
13902 (beginning-of-line 1)
13903 (skip-chars-forward " \t")
13904 (current-column))))
13906 (defun org-remove-tabs (s &optional width)
13907 "Replace tabulators in S with spaces.
13908 Assumes that s is a single line, starting in column 0."
13909 (setq width (or width tab-width))
13910 (while (string-match "\t" s)
13911 (setq s (replace-match
13912 (make-string
13913 (- (* width (/ (+ (match-beginning 0) width) width))
13914 (match-beginning 0)) ?\ )
13915 t t s)))
13918 (defun org-fix-indentation (line ind)
13919 "Fix indentation in LINE.
13920 IND is a cons cell with target and minimum indentation.
13921 If the current indentation in LINE is smaller than the minimum,
13922 leave it alone. If it is larger than ind, set it to the target."
13923 (let* ((l (org-remove-tabs line))
13924 (i (org-get-indentation l))
13925 (i1 (car ind)) (i2 (cdr ind)))
13926 (if (>= i i2) (setq l (substring line i2)))
13927 (if (> i1 0)
13928 (concat (make-string i1 ?\ ) l)
13929 l)))
13931 (defun org-base-buffer (buffer)
13932 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13933 (if (not buffer)
13934 buffer
13935 (or (buffer-base-buffer buffer)
13936 buffer)))
13938 (defun org-trim (s)
13939 "Remove whitespace at beginning and end of string."
13940 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13941 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13944 (defun org-wrap (string &optional width lines)
13945 "Wrap string to either a number of lines, or a width in characters.
13946 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13947 that costs. If there is a word longer than WIDTH, the text is actually
13948 wrapped to the length of that word.
13949 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13950 many lines, whatever width that takes.
13951 The return value is a list of lines, without newlines at the end."
13952 (let* ((words (org-split-string string "[ \t\n]+"))
13953 (maxword (apply 'max (mapcar 'org-string-width words)))
13954 w ll)
13955 (cond (width
13956 (org-do-wrap words (max maxword width)))
13957 (lines
13958 (setq w maxword)
13959 (setq ll (org-do-wrap words maxword))
13960 (if (<= (length ll) lines)
13962 (setq ll words)
13963 (while (> (length ll) lines)
13964 (setq w (1+ w))
13965 (setq ll (org-do-wrap words w)))
13966 ll))
13967 (t (error "Cannot wrap this")))))
13969 (defun org-do-wrap (words width)
13970 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13971 (let (lines line)
13972 (while words
13973 (setq line (pop words))
13974 (while (and words (< (+ (length line) (length (car words))) width))
13975 (setq line (concat line " " (pop words))))
13976 (setq lines (push line lines)))
13977 (nreverse lines)))
13979 (defun org-split-string (string &optional separators)
13980 "Splits STRING into substrings at SEPARATORS.
13981 No empty strings are returned if there are matches at the beginning
13982 and end of string."
13983 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13984 (start 0)
13985 notfirst
13986 (list nil))
13987 (while (and (string-match rexp string
13988 (if (and notfirst
13989 (= start (match-beginning 0))
13990 (< start (length string)))
13991 (1+ start) start))
13992 (< (match-beginning 0) (length string)))
13993 (setq notfirst t)
13994 (or (eq (match-beginning 0) 0)
13995 (and (eq (match-beginning 0) (match-end 0))
13996 (eq (match-beginning 0) start))
13997 (setq list
13998 (cons (substring string start (match-beginning 0))
13999 list)))
14000 (setq start (match-end 0)))
14001 (or (eq start (length string))
14002 (setq list
14003 (cons (substring string start)
14004 list)))
14005 (nreverse list)))
14007 (defun org-context ()
14008 "Return a list of contexts of the current cursor position.
14009 If several contexts apply, all are returned.
14010 Each context entry is a list with a symbol naming the context, and
14011 two positions indicating start and end of the context. Possible
14012 contexts are:
14014 :headline anywhere in a headline
14015 :headline-stars on the leading stars in a headline
14016 :todo-keyword on a TODO keyword (including DONE) in a headline
14017 :tags on the TAGS in a headline
14018 :priority on the priority cookie in a headline
14019 :item on the first line of a plain list item
14020 :item-bullet on the bullet/number of a plain list item
14021 :checkbox on the checkbox in a plain list item
14022 :table in an org-mode table
14023 :table-special on a special filed in a table
14024 :table-table in a table.el table
14025 :link on a hyperlink
14026 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14027 :target on a <<target>>
14028 :radio-target on a <<<radio-target>>>
14029 :latex-fragment on a LaTeX fragment
14030 :latex-preview on a LaTeX fragment with overlayed preview image
14032 This function expects the position to be visible because it uses font-lock
14033 faces as a help to recognize the following contexts: :table-special, :link,
14034 and :keyword."
14035 (let* ((f (get-text-property (point) 'face))
14036 (faces (if (listp f) f (list f)))
14037 (p (point)) clist o)
14038 ;; First the large context
14039 (cond
14040 ((org-on-heading-p t)
14041 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14042 (when (progn
14043 (beginning-of-line 1)
14044 (looking-at org-todo-line-tags-regexp))
14045 (push (org-point-in-group p 1 :headline-stars) clist)
14046 (push (org-point-in-group p 2 :todo-keyword) clist)
14047 (push (org-point-in-group p 4 :tags) clist))
14048 (goto-char p)
14049 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14050 (if (looking-at "\\[#[A-Z0-9]\\]")
14051 (push (org-point-in-group p 0 :priority) clist)))
14053 ((org-at-item-p)
14054 (push (org-point-in-group p 2 :item-bullet) clist)
14055 (push (list :item (point-at-bol)
14056 (save-excursion (org-end-of-item) (point)))
14057 clist)
14058 (and (org-at-item-checkbox-p)
14059 (push (org-point-in-group p 0 :checkbox) clist)))
14061 ((org-at-table-p)
14062 (push (list :table (org-table-begin) (org-table-end)) clist)
14063 (if (memq 'org-formula faces)
14064 (push (list :table-special
14065 (previous-single-property-change p 'face)
14066 (next-single-property-change p 'face)) clist)))
14067 ((org-at-table-p 'any)
14068 (push (list :table-table) clist)))
14069 (goto-char p)
14071 ;; Now the small context
14072 (cond
14073 ((org-at-timestamp-p)
14074 (push (org-point-in-group p 0 :timestamp) clist))
14075 ((memq 'org-link faces)
14076 (push (list :link
14077 (previous-single-property-change p 'face)
14078 (next-single-property-change p 'face)) clist))
14079 ((memq 'org-special-keyword faces)
14080 (push (list :keyword
14081 (previous-single-property-change p 'face)
14082 (next-single-property-change p 'face)) clist))
14083 ((org-on-target-p)
14084 (push (org-point-in-group p 0 :target) clist)
14085 (goto-char (1- (match-beginning 0)))
14086 (if (looking-at org-radio-target-regexp)
14087 (push (org-point-in-group p 0 :radio-target) clist))
14088 (goto-char p))
14089 ((setq o (car (delq nil
14090 (mapcar
14091 (lambda (x)
14092 (if (memq x org-latex-fragment-image-overlays) x))
14093 (org-overlays-at (point))))))
14094 (push (list :latex-fragment
14095 (org-overlay-start o) (org-overlay-end o)) clist)
14096 (push (list :latex-preview
14097 (org-overlay-start o) (org-overlay-end o)) clist))
14098 ((org-inside-LaTeX-fragment-p)
14099 ;; FIXME: positions wrong.
14100 (push (list :latex-fragment (point) (point)) clist)))
14102 (setq clist (nreverse (delq nil clist)))
14103 clist))
14105 ;; FIXME: Compare with at-regexp-p Do we need both?
14106 (defun org-in-regexp (re &optional nlines visually)
14107 "Check if point is inside a match of regexp.
14108 Normally only the current line is checked, but you can include NLINES extra
14109 lines both before and after point into the search.
14110 If VISUALLY is set, require that the cursor is not after the match but
14111 really on, so that the block visually is on the match."
14112 (catch 'exit
14113 (let ((pos (point))
14114 (eol (point-at-eol (+ 1 (or nlines 0))))
14115 (inc (if visually 1 0)))
14116 (save-excursion
14117 (beginning-of-line (- 1 (or nlines 0)))
14118 (while (re-search-forward re eol t)
14119 (if (and (<= (match-beginning 0) pos)
14120 (>= (+ inc (match-end 0)) pos))
14121 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14123 (defun org-at-regexp-p (regexp)
14124 "Is point inside a match of REGEXP in the current line?"
14125 (catch 'exit
14126 (save-excursion
14127 (let ((pos (point)) (end (point-at-eol)))
14128 (beginning-of-line 1)
14129 (while (re-search-forward regexp end t)
14130 (if (and (<= (match-beginning 0) pos)
14131 (>= (match-end 0) pos))
14132 (throw 'exit t)))
14133 nil))))
14135 (defun org-occur-in-agenda-files (regexp &optional nlines)
14136 "Call `multi-occur' with buffers for all agenda files."
14137 (interactive "sOrg-files matching: \np")
14138 (let* ((files (org-agenda-files))
14139 (tnames (mapcar 'file-truename files))
14140 (extra org-agenda-text-search-extra-files)
14142 (when (eq (car extra) 'agenda-archives)
14143 (setq extra (cdr extra))
14144 (setq files (org-add-archive-files files)))
14145 (while (setq f (pop extra))
14146 (unless (member (file-truename f) tnames)
14147 (add-to-list 'files f 'append)
14148 (add-to-list 'tnames (file-truename f) 'append)))
14149 (multi-occur
14150 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14151 regexp)))
14153 (if (boundp 'occur-mode-find-occurrence-hook)
14154 ;; Emacs 23
14155 (add-hook 'occur-mode-find-occurrence-hook
14156 (lambda ()
14157 (when (org-mode-p)
14158 (org-reveal))))
14159 ;; Emacs 22
14160 (defadvice occur-mode-goto-occurrence
14161 (after org-occur-reveal activate)
14162 (and (org-mode-p) (org-reveal)))
14163 (defadvice occur-mode-goto-occurrence-other-window
14164 (after org-occur-reveal activate)
14165 (and (org-mode-p) (org-reveal)))
14166 (defadvice occur-mode-display-occurrence
14167 (after org-occur-reveal activate)
14168 (when (org-mode-p)
14169 (let ((pos (occur-mode-find-occurrence)))
14170 (with-current-buffer (marker-buffer pos)
14171 (save-excursion
14172 (goto-char pos)
14173 (org-reveal)))))))
14175 (defun org-uniquify (list)
14176 "Remove duplicate elements from LIST."
14177 (let (res)
14178 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14179 res))
14181 (defun org-delete-all (elts list)
14182 "Remove all elements in ELTS from LIST."
14183 (while elts
14184 (setq list (delete (pop elts) list)))
14185 list)
14187 (defun org-back-over-empty-lines ()
14188 "Move backwards over whitespace, to the beginning of the first empty line.
14189 Returns the number of empty lines passed."
14190 (let ((pos (point)))
14191 (skip-chars-backward " \t\n\r")
14192 (beginning-of-line 2)
14193 (goto-char (min (point) pos))
14194 (count-lines (point) pos)))
14196 (defun org-skip-whitespace ()
14197 (skip-chars-forward " \t\n\r"))
14199 (defun org-point-in-group (point group &optional context)
14200 "Check if POINT is in match-group GROUP.
14201 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14202 match. If the match group does ot exist or point is not inside it,
14203 return nil."
14204 (and (match-beginning group)
14205 (>= point (match-beginning group))
14206 (<= point (match-end group))
14207 (if context
14208 (list context (match-beginning group) (match-end group))
14209 t)))
14211 (defun org-switch-to-buffer-other-window (&rest args)
14212 "Switch to buffer in a second window on the current frame.
14213 In particular, do not allow pop-up frames."
14214 (let (pop-up-frames special-display-buffer-names special-display-regexps
14215 special-display-function)
14216 (apply 'switch-to-buffer-other-window args)))
14218 (defun org-combine-plists (&rest plists)
14219 "Create a single property list from all plists in PLISTS.
14220 The process starts by copying the first list, and then setting properties
14221 from the other lists. Settings in the last list are the most significant
14222 ones and overrule settings in the other lists."
14223 (let ((rtn (copy-sequence (pop plists)))
14224 p v ls)
14225 (while plists
14226 (setq ls (pop plists))
14227 (while ls
14228 (setq p (pop ls) v (pop ls))
14229 (setq rtn (plist-put rtn p v))))
14230 rtn))
14232 (defun org-move-line-down (arg)
14233 "Move the current line down. With prefix argument, move it past ARG lines."
14234 (interactive "p")
14235 (let ((col (current-column))
14236 beg end pos)
14237 (beginning-of-line 1) (setq beg (point))
14238 (beginning-of-line 2) (setq end (point))
14239 (beginning-of-line (+ 1 arg))
14240 (setq pos (move-marker (make-marker) (point)))
14241 (insert (delete-and-extract-region beg end))
14242 (goto-char pos)
14243 (org-move-to-column col)))
14245 (defun org-move-line-up (arg)
14246 "Move the current line up. With prefix argument, move it past ARG lines."
14247 (interactive "p")
14248 (let ((col (current-column))
14249 beg end pos)
14250 (beginning-of-line 1) (setq beg (point))
14251 (beginning-of-line 2) (setq end (point))
14252 (beginning-of-line (- arg))
14253 (setq pos (move-marker (make-marker) (point)))
14254 (insert (delete-and-extract-region beg end))
14255 (goto-char pos)
14256 (org-move-to-column col)))
14258 (defun org-replace-escapes (string table)
14259 "Replace %-escapes in STRING with values in TABLE.
14260 TABLE is an association list with keys like \"%a\" and string values.
14261 The sequences in STRING may contain normal field width and padding information,
14262 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14263 so values can contain further %-escapes if they are define later in TABLE."
14264 (let ((case-fold-search nil)
14265 e re rpl)
14266 (while (setq e (pop table))
14267 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14268 (while (string-match re string)
14269 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14270 (cdr e)))
14271 (setq string (replace-match rpl t t string))))
14272 string))
14275 (defun org-sublist (list start end)
14276 "Return a section of LIST, from START to END.
14277 Counting starts at 1."
14278 (let (rtn (c start))
14279 (setq list (nthcdr (1- start) list))
14280 (while (and list (<= c end))
14281 (push (pop list) rtn)
14282 (setq c (1+ c)))
14283 (nreverse rtn)))
14285 (defun org-find-base-buffer-visiting (file)
14286 "Like `find-buffer-visiting' but alway return the base buffer and
14287 not an indirect buffer."
14288 (let ((buf (find-buffer-visiting file)))
14289 (if buf
14290 (or (buffer-base-buffer buf) buf)
14291 nil)))
14293 (defun org-image-file-name-regexp (&optional extensions)
14294 "Return regexp matching the file names of images.
14295 If EXTENSIONS is given, only match these."
14296 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14297 (image-file-name-regexp)
14298 (let ((image-file-name-extensions
14299 (or extensions
14300 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14301 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14302 (concat "\\."
14303 (regexp-opt (nconc (mapcar 'upcase
14304 image-file-name-extensions)
14305 image-file-name-extensions)
14307 "\\'"))))
14309 (defun org-file-image-p (file &optional extensions)
14310 "Return non-nil if FILE is an image."
14311 (save-match-data
14312 (string-match (org-image-file-name-regexp extensions) file)))
14314 (defun org-get-cursor-date ()
14315 "Return the date at cursor in as a time.
14316 This works in the calendar and in the agenda, anywhere else it just
14317 returns the current time."
14318 (let (date day defd)
14319 (cond
14320 ((eq major-mode 'calendar-mode)
14321 (setq date (calendar-cursor-to-date)
14322 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14323 ((eq major-mode 'org-agenda-mode)
14324 (setq day (get-text-property (point) 'day))
14325 (if day
14326 (setq date (calendar-gregorian-from-absolute day)
14327 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14328 (nth 2 date))))))
14329 (or defd (current-time))))
14331 (defvar org-agenda-action-marker (make-marker)
14332 "Marker pointing to the entry for the next agenda action.")
14334 (defun org-mark-entry-for-agenda-action ()
14335 "Mark the current entry as target of an agenda action.
14336 Agenda actions are actions executed from the agenda with the key `k',
14337 which make use of the date at the cursor."
14338 (interactive)
14339 (move-marker org-agenda-action-marker
14340 (save-excursion (org-back-to-heading t) (point))
14341 (current-buffer))
14342 (message
14343 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14345 ;;; Paragraph filling stuff.
14346 ;; We want this to be just right, so use the full arsenal.
14348 (defun org-indent-line-function ()
14349 "Indent line like previous, but further if previous was headline or item."
14350 (interactive)
14351 (let* ((pos (point))
14352 (itemp (org-at-item-p))
14353 column bpos bcol tpos tcol bullet btype bullet-type)
14354 ;; Find the previous relevant line
14355 (beginning-of-line 1)
14356 (cond
14357 ((looking-at "#") (setq column 0))
14358 ((looking-at "\\*+ ") (setq column 0))
14360 (beginning-of-line 0)
14361 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14362 (beginning-of-line 0))
14363 (cond
14364 ((looking-at "\\*+[ \t]+")
14365 (if (not org-adapt-indentation)
14366 (setq column 0)
14367 (goto-char (match-end 0))
14368 (setq column (current-column))))
14369 ((org-in-item-p)
14370 (org-beginning-of-item)
14371 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14372 (setq bpos (match-beginning 1) tpos (match-end 0)
14373 bcol (progn (goto-char bpos) (current-column))
14374 tcol (progn (goto-char tpos) (current-column))
14375 bullet (match-string 1)
14376 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14377 (if (> tcol (+ bcol org-description-max-indent))
14378 (setq tcol (+ bcol 5)))
14379 (if (not itemp)
14380 (setq column tcol)
14381 (goto-char pos)
14382 (beginning-of-line 1)
14383 (if (looking-at "\\S-")
14384 (progn
14385 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14386 (setq bullet (match-string 1)
14387 btype (if (string-match "[0-9]" bullet) "n" bullet))
14388 (setq column (if (equal btype bullet-type) bcol tcol)))
14389 (setq column (org-get-indentation)))))
14390 (t (setq column (org-get-indentation))))))
14391 (goto-char pos)
14392 (if (<= (current-column) (current-indentation))
14393 (org-indent-line-to column)
14394 (save-excursion (org-indent-line-to column)))
14395 (setq column (current-column))
14396 (beginning-of-line 1)
14397 (if (looking-at
14398 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14399 (replace-match (concat "\\1" (format org-property-format
14400 (match-string 2) (match-string 3)))
14401 t nil))
14402 (org-move-to-column column)))
14404 (defun org-set-autofill-regexps ()
14405 (interactive)
14406 ;; In the paragraph separator we include headlines, because filling
14407 ;; text in a line directly attached to a headline would otherwise
14408 ;; fill the headline as well.
14409 (org-set-local 'comment-start-skip "^#+[ \t]*")
14410 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14411 ;; The paragraph starter includes hand-formatted lists.
14412 (org-set-local 'paragraph-start
14413 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14414 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14415 ;; But only if the user has not turned off tables or fixed-width regions
14416 (org-set-local
14417 'auto-fill-inhibit-regexp
14418 (concat "\\*+ \\|#\\+"
14419 "\\|[ \t]*" org-keyword-time-regexp
14420 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14421 (concat
14422 "\\|[ \t]*["
14423 (if org-enable-table-editor "|" "")
14424 (if org-enable-fixed-width-editor ":" "")
14425 "]"))))
14426 ;; We use our own fill-paragraph function, to make sure that tables
14427 ;; and fixed-width regions are not wrapped. That function will pass
14428 ;; through to `fill-paragraph' when appropriate.
14429 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14430 ; Adaptive filling: To get full control, first make sure that
14431 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14432 (org-set-local 'adaptive-fill-regexp "\000")
14433 (org-set-local 'adaptive-fill-function
14434 'org-adaptive-fill-function)
14435 (org-set-local
14436 'align-mode-rules-list
14437 '((org-in-buffer-settings
14438 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14439 (modes . '(org-mode))))))
14441 (defun org-fill-paragraph (&optional justify)
14442 "Re-align a table, pass through to fill-paragraph if no table."
14443 (let ((table-p (org-at-table-p))
14444 (table.el-p (org-at-table.el-p)))
14445 (cond ((and (equal (char-after (point-at-bol)) ?*)
14446 (save-excursion (goto-char (point-at-bol))
14447 (looking-at outline-regexp)))
14448 t) ; skip headlines
14449 (table.el-p t) ; skip table.el tables
14450 (table-p (org-table-align) t) ; align org-mode tables
14451 (t nil)))) ; call paragraph-fill
14453 ;; For reference, this is the default value of adaptive-fill-regexp
14454 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14456 (defun org-adaptive-fill-function ()
14457 "Return a fill prefix for org-mode files.
14458 In particular, this makes sure hanging paragraphs for hand-formatted lists
14459 work correctly."
14460 (cond ((looking-at "#[ \t]+")
14461 (match-string 0))
14462 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14463 (save-excursion
14464 (if (> (match-end 1) (+ (match-beginning 1)
14465 org-description-max-indent))
14466 (goto-char (+ (match-beginning 1) 5))
14467 (goto-char (match-end 0)))
14468 (make-string (current-column) ?\ )))
14469 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14470 (save-excursion
14471 (goto-char (match-end 0))
14472 (make-string (current-column) ?\ )))
14473 (t nil)))
14475 ;;; Other stuff.
14477 (defun org-toggle-fixed-width-section (arg)
14478 "Toggle the fixed-width export.
14479 If there is no active region, the QUOTE keyword at the current headline is
14480 inserted or removed. When present, it causes the text between this headline
14481 and the next to be exported as fixed-width text, and unmodified.
14482 If there is an active region, this command adds or removes a colon as the
14483 first character of this line. If the first character of a line is a colon,
14484 this line is also exported in fixed-width font."
14485 (interactive "P")
14486 (let* ((cc 0)
14487 (regionp (org-region-active-p))
14488 (beg (if regionp (region-beginning) (point)))
14489 (end (if regionp (region-end)))
14490 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14491 (case-fold-search nil)
14492 (re "[ \t]*\\(:\\)")
14493 off)
14494 (if regionp
14495 (save-excursion
14496 (goto-char beg)
14497 (setq cc (current-column))
14498 (beginning-of-line 1)
14499 (setq off (looking-at re))
14500 (while (> nlines 0)
14501 (setq nlines (1- nlines))
14502 (beginning-of-line 1)
14503 (cond
14504 (arg
14505 (org-move-to-column cc t)
14506 (insert ":\n")
14507 (forward-line -1))
14508 ((and off (looking-at re))
14509 (replace-match "" t t nil 1))
14510 ((not off) (org-move-to-column cc t) (insert ":")))
14511 (forward-line 1)))
14512 (save-excursion
14513 (org-back-to-heading)
14514 (if (looking-at (concat outline-regexp
14515 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14516 (replace-match "" t t nil 1)
14517 (if (looking-at outline-regexp)
14518 (progn
14519 (goto-char (match-end 0))
14520 (insert org-quote-string " "))))))))
14522 ;;;; Functions extending outline functionality
14524 (defun org-beginning-of-line (&optional arg)
14525 "Go to the beginning of the current line. If that is invisible, continue
14526 to a visible line beginning. This makes the function of C-a more intuitive.
14527 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14528 first attempt, and only move to after the tags when the cursor is already
14529 beyond the end of the headline."
14530 (interactive "P")
14531 (let ((pos (point)) refpos)
14532 (beginning-of-line 1)
14533 (if (bobp)
14535 (backward-char 1)
14536 (if (org-invisible-p)
14537 (while (and (not (bobp)) (org-invisible-p))
14538 (backward-char 1)
14539 (beginning-of-line 1))
14540 (forward-char 1)))
14541 (when org-special-ctrl-a/e
14542 (cond
14543 ((and (looking-at org-complex-heading-regexp)
14544 (= (char-after (match-end 1)) ?\ ))
14545 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14546 (point-at-eol)))
14547 (goto-char
14548 (if (eq org-special-ctrl-a/e t)
14549 (cond ((> pos refpos) refpos)
14550 ((= pos (point)) refpos)
14551 (t (point)))
14552 (cond ((> pos (point)) (point))
14553 ((not (eq last-command this-command)) (point))
14554 (t refpos)))))
14555 ((org-at-item-p)
14556 (goto-char
14557 (if (eq org-special-ctrl-a/e t)
14558 (cond ((> pos (match-end 4)) (match-end 4))
14559 ((= pos (point)) (match-end 4))
14560 (t (point)))
14561 (cond ((> pos (point)) (point))
14562 ((not (eq last-command this-command)) (point))
14563 (t (match-end 4))))))))
14564 (org-no-warnings
14565 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14567 (defun org-end-of-line (&optional arg)
14568 "Go to the end of the line.
14569 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14570 first attempt, and only move to after the tags when the cursor is already
14571 beyond the end of the headline."
14572 (interactive "P")
14573 (if (or (not org-special-ctrl-a/e)
14574 (not (org-on-heading-p)))
14575 (end-of-line arg)
14576 (let ((pos (point)))
14577 (beginning-of-line 1)
14578 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14579 (if (eq org-special-ctrl-a/e t)
14580 (if (or (< pos (match-beginning 1))
14581 (= pos (match-end 0)))
14582 (goto-char (match-beginning 1))
14583 (goto-char (match-end 0)))
14584 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14585 (goto-char (match-end 0))
14586 (goto-char (match-beginning 1))))
14587 (end-of-line arg))))
14588 (org-no-warnings
14589 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14592 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14593 (define-key org-mode-map "\C-e" 'org-end-of-line)
14595 (defun org-kill-line (&optional arg)
14596 "Kill line, to tags or end of line."
14597 (interactive "P")
14598 (cond
14599 ((or (not org-special-ctrl-k)
14600 (bolp)
14601 (not (org-on-heading-p)))
14602 (call-interactively 'kill-line))
14603 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14604 (kill-region (point) (match-beginning 1))
14605 (org-set-tags nil t))
14606 (t (kill-region (point) (point-at-eol)))))
14608 (define-key org-mode-map "\C-k" 'org-kill-line)
14610 (defun org-yank (&optional arg)
14611 "Yank. If the kill is a subtree, treat it specially.
14612 This command will look at the current kill and check if is a single
14613 subtree, or a series of subtrees[1]. If it passes the test, and if the
14614 cursor is at the beginning of a line or after the stars of a currently
14615 empty headline, then the yank is handled specially. How exactly depends
14616 on the value of the following variables, both set by default.
14618 org-yank-folded-subtrees
14619 When set, the subtree(s) will be folded after insertion, but only
14620 if doing so would now swallow text after the yanked text.
14622 org-yank-adjusted-subtrees
14623 When set, the subtree will be promoted or demoted in order to
14624 fit into the local outline tree structure, which means that the level
14625 will be adjusted so that it becomes the smaller one of the two
14626 *visible* surrounding headings.
14628 Any prefix to this command will cause `yank' to be called directly with
14629 no special treatment. In particular, a simple `C-u' prefix will just
14630 plainly yank the text as it is.
14632 \[1] Basically, the test checks if the first non-white line is a heading
14633 and if there are no other headings with fewer stars."
14634 (interactive "P")
14635 (setq this-command 'yank)
14636 (if arg
14637 (call-interactively 'yank)
14638 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14639 (and (org-kill-is-subtree-p)
14640 (or (bolp)
14641 (and (looking-at "[ \t]*$")
14642 (string-match
14643 "\\`\\*+\\'"
14644 (buffer-substring (point-at-bol) (point)))))))
14645 swallowp)
14646 (cond
14647 ((and subtreep org-yank-folded-subtrees)
14648 (let ((beg (point))
14649 end)
14650 (if (and subtreep org-yank-adjusted-subtrees)
14651 (org-paste-subtree nil nil 'for-yank)
14652 (call-interactively 'yank))
14653 (setq end (point))
14654 (goto-char beg)
14655 (when (and (bolp) subtreep
14656 (not (setq swallowp
14657 (org-yank-folding-would-swallow-text beg end))))
14658 (or (looking-at outline-regexp)
14659 (re-search-forward (concat "^" outline-regexp) end t))
14660 (while (and (< (point) end) (looking-at outline-regexp))
14661 (hide-subtree)
14662 (org-cycle-show-empty-lines 'folded)
14663 (condition-case nil
14664 (outline-forward-same-level 1)
14665 (error (goto-char end)))))
14666 (when swallowp
14667 (message
14668 "Yanked text not folded because that would swallow text"))
14669 (goto-char end)
14670 (skip-chars-forward " \t\n\r")
14671 (beginning-of-line 1)
14672 (push-mark beg 'nomsg)))
14673 ((and subtreep org-yank-adjusted-subtrees)
14674 (let ((beg (point-at-bol)))
14675 (org-paste-subtree nil nil 'for-yank)
14676 (push-mark beg 'nomsg)))
14678 (call-interactively 'yank))))))
14680 (defun org-yank-folding-would-swallow-text (beg end)
14681 "Would hide-subtree at BEG swallow any text after END?"
14682 (let (level)
14683 (save-excursion
14684 (goto-char beg)
14685 (when (or (looking-at outline-regexp)
14686 (re-search-forward (concat "^" outline-regexp) end t))
14687 (setq level (org-outline-level)))
14688 (goto-char end)
14689 (skip-chars-forward " \t\r\n\v\f")
14690 (if (or (eobp)
14691 (and (bolp) (looking-at org-outline-regexp)
14692 (<= (org-outline-level) level)))
14693 nil ; Nothing would be swallowed
14694 t)))) ; something would swallow
14696 (define-key org-mode-map "\C-y" 'org-yank)
14698 (defun org-invisible-p ()
14699 "Check if point is at a character currently not visible."
14700 ;; Early versions of noutline don't have `outline-invisible-p'.
14701 (if (fboundp 'outline-invisible-p)
14702 (outline-invisible-p)
14703 (get-char-property (point) 'invisible)))
14705 (defun org-invisible-p2 ()
14706 "Check if point is at a character currently not visible."
14707 (save-excursion
14708 (if (and (eolp) (not (bobp))) (backward-char 1))
14709 ;; Early versions of noutline don't have `outline-invisible-p'.
14710 (if (fboundp 'outline-invisible-p)
14711 (outline-invisible-p)
14712 (get-char-property (point) 'invisible))))
14714 (defun org-back-to-heading (&optional invisible-ok)
14715 "Call `outline-back-to-heading', but provide a better error message."
14716 (condition-case nil
14717 (outline-back-to-heading invisible-ok)
14718 (error (error "Before first headline at position %d in buffer %s"
14719 (point) (current-buffer)))))
14721 (defun org-before-first-heading-p ()
14722 "Before first heading?"
14723 (save-excursion
14724 (null (re-search-backward "^\\*+ " nil t))))
14726 (defalias 'org-on-heading-p 'outline-on-heading-p)
14727 (defalias 'org-at-heading-p 'outline-on-heading-p)
14728 (defun org-at-heading-or-item-p ()
14729 (or (org-on-heading-p) (org-at-item-p)))
14731 (defun org-on-target-p ()
14732 (or (org-in-regexp org-radio-target-regexp)
14733 (org-in-regexp org-target-regexp)))
14735 (defun org-up-heading-all (arg)
14736 "Move to the heading line of which the present line is a subheading.
14737 This function considers both visible and invisible heading lines.
14738 With argument, move up ARG levels."
14739 (if (fboundp 'outline-up-heading-all)
14740 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14741 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14743 (defun org-up-heading-safe ()
14744 "Move to the heading line of which the present line is a subheading.
14745 This version will not throw an error. It will return the level of the
14746 headline found, or nil if no higher level is found."
14747 (let (start-level re)
14748 (org-back-to-heading t)
14749 (setq start-level (funcall outline-level))
14750 (if (equal start-level 1)
14752 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14753 (if (re-search-backward re nil t)
14754 (funcall outline-level)))))
14756 (defun org-first-sibling-p ()
14757 "Is this heading the first child of its parents?"
14758 (interactive)
14759 (let ((re (concat "^" outline-regexp))
14760 level l)
14761 (unless (org-at-heading-p t)
14762 (error "Not at a heading"))
14763 (setq level (funcall outline-level))
14764 (save-excursion
14765 (if (not (re-search-backward re nil t))
14767 (setq l (funcall outline-level))
14768 (< l level)))))
14770 (defun org-goto-sibling (&optional previous)
14771 "Goto the next sibling, even if it is invisible.
14772 When PREVIOUS is set, go to the previous sibling instead. Returns t
14773 when a sibling was found. When none is found, return nil and don't
14774 move point."
14775 (let ((fun (if previous 're-search-backward 're-search-forward))
14776 (pos (point))
14777 (re (concat "^" outline-regexp))
14778 level l)
14779 (when (condition-case nil (org-back-to-heading t) (error nil))
14780 (setq level (funcall outline-level))
14781 (catch 'exit
14782 (or previous (forward-char 1))
14783 (while (funcall fun re nil t)
14784 (setq l (funcall outline-level))
14785 (when (< l level) (goto-char pos) (throw 'exit nil))
14786 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14787 (goto-char pos)
14788 nil))))
14790 (defun org-show-siblings ()
14791 "Show all siblings of the current headline."
14792 (save-excursion
14793 (while (org-goto-sibling) (org-flag-heading nil)))
14794 (save-excursion
14795 (while (org-goto-sibling 'previous)
14796 (org-flag-heading nil))))
14798 (defun org-show-hidden-entry ()
14799 "Show an entry where even the heading is hidden."
14800 (save-excursion
14801 (org-show-entry)))
14803 (defun org-flag-heading (flag &optional entry)
14804 "Flag the current heading. FLAG non-nil means make invisible.
14805 When ENTRY is non-nil, show the entire entry."
14806 (save-excursion
14807 (org-back-to-heading t)
14808 ;; Check if we should show the entire entry
14809 (if entry
14810 (progn
14811 (org-show-entry)
14812 (save-excursion
14813 (and (outline-next-heading)
14814 (org-flag-heading nil))))
14815 (outline-flag-region (max (point-min) (1- (point)))
14816 (save-excursion (outline-end-of-heading) (point))
14817 flag))))
14819 (defun org-forward-same-level (arg)
14820 "Move forward to the ARG'th subheading at same level as this one.
14821 Stop at the first and last subheadings of a superior heading.
14822 This is like outline-forward-same-level, but invisible headings are ok."
14823 (interactive "p")
14824 (org-back-to-heading t)
14825 (while (> arg 0)
14826 (let ((point-to-move-to (save-excursion
14827 (org-get-next-sibling))))
14828 (if point-to-move-to
14829 (progn
14830 (goto-char point-to-move-to)
14831 (setq arg (1- arg)))
14832 (progn
14833 (setq arg 0)
14834 (error "No following same-level heading"))))))
14836 (defun org-get-next-sibling ()
14837 "Move to next heading of the same level, and return point.
14838 If there is no such heading, return nil.
14839 This is like outline-next-sibling, but invisible headings are ok."
14840 (let ((level (funcall outline-level)))
14841 (outline-next-heading)
14842 (while (and (not (eobp)) (> (funcall outline-level) level))
14843 (outline-next-heading))
14844 (if (or (eobp) (< (funcall outline-level) level))
14846 (point))))
14848 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14849 ;; This is an exact copy of the original function, but it uses
14850 ;; `org-back-to-heading', to make it work also in invisible
14851 ;; trees. And is uses an invisible-OK argument.
14852 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14853 (org-back-to-heading invisible-OK)
14854 (let ((first t)
14855 (level (funcall outline-level)))
14856 (while (and (not (eobp))
14857 (or first (> (funcall outline-level) level)))
14858 (setq first nil)
14859 (outline-next-heading))
14860 (unless to-heading
14861 (if (memq (preceding-char) '(?\n ?\^M))
14862 (progn
14863 ;; Go to end of line before heading
14864 (forward-char -1)
14865 (if (memq (preceding-char) '(?\n ?\^M))
14866 ;; leave blank line before heading
14867 (forward-char -1))))))
14868 (point))
14870 (defun org-show-subtree ()
14871 "Show everything after this heading at deeper levels."
14872 (outline-flag-region
14873 (point)
14874 (save-excursion
14875 (outline-end-of-subtree) (outline-next-heading) (point))
14876 nil))
14878 (defun org-show-entry ()
14879 "Show the body directly following this heading.
14880 Show the heading too, if it is currently invisible."
14881 (interactive)
14882 (save-excursion
14883 (condition-case nil
14884 (progn
14885 (org-back-to-heading t)
14886 (outline-flag-region
14887 (max (point-min) (1- (point)))
14888 (save-excursion
14889 (re-search-forward
14890 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14891 (or (match-beginning 1) (point-max)))
14892 nil))
14893 (error nil))))
14895 (defun org-make-options-regexp (kwds)
14896 "Make a regular expression for keyword lines."
14897 (concat
14899 "#?[ \t]*\\+\\("
14900 (mapconcat 'regexp-quote kwds "\\|")
14901 "\\):[ \t]*"
14902 "\\(.+\\)"))
14904 ;; Make isearch reveal the necessary context
14905 (defun org-isearch-end ()
14906 "Reveal context after isearch exits."
14907 (when isearch-success ; only if search was successful
14908 (if (featurep 'xemacs)
14909 ;; Under XEmacs, the hook is run in the correct place,
14910 ;; we directly show the context.
14911 (org-show-context 'isearch)
14912 ;; In Emacs the hook runs *before* restoring the overlays.
14913 ;; So we have to use a one-time post-command-hook to do this.
14914 ;; (Emacs 22 has a special variable, see function `org-mode')
14915 (unless (and (boundp 'isearch-mode-end-hook-quit)
14916 isearch-mode-end-hook-quit)
14917 ;; Only when the isearch was not quitted.
14918 (org-add-hook 'post-command-hook 'org-isearch-post-command
14919 'append 'local)))))
14921 (defun org-isearch-post-command ()
14922 "Remove self from hook, and show context."
14923 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14924 (org-show-context 'isearch))
14927 ;;;; Integration with and fixes for other packages
14929 ;;; Imenu support
14931 (defvar org-imenu-markers nil
14932 "All markers currently used by Imenu.")
14933 (make-variable-buffer-local 'org-imenu-markers)
14935 (defun org-imenu-new-marker (&optional pos)
14936 "Return a new marker for use by Imenu, and remember the marker."
14937 (let ((m (make-marker)))
14938 (move-marker m (or pos (point)))
14939 (push m org-imenu-markers)
14942 (defun org-imenu-get-tree ()
14943 "Produce the index for Imenu."
14944 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14945 (setq org-imenu-markers nil)
14946 (let* ((n org-imenu-depth)
14947 (re (concat "^" outline-regexp))
14948 (subs (make-vector (1+ n) nil))
14949 (last-level 0)
14950 m level head)
14951 (save-excursion
14952 (save-restriction
14953 (widen)
14954 (goto-char (point-max))
14955 (while (re-search-backward re nil t)
14956 (setq level (org-reduced-level (funcall outline-level)))
14957 (when (<= level n)
14958 (looking-at org-complex-heading-regexp)
14959 (setq head (org-link-display-format
14960 (org-match-string-no-properties 4))
14961 m (org-imenu-new-marker))
14962 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14963 (if (>= level last-level)
14964 (push (cons head m) (aref subs level))
14965 (push (cons head (aref subs (1+ level))) (aref subs level))
14966 (loop for i from (1+ level) to n do (aset subs i nil)))
14967 (setq last-level level)))))
14968 (aref subs 1)))
14970 (eval-after-load "imenu"
14971 '(progn
14972 (add-hook 'imenu-after-jump-hook
14973 (lambda ()
14974 (if (eq major-mode 'org-mode)
14975 (org-show-context 'org-goto))))))
14977 (defun org-link-display-format (link)
14978 "Replace a link with either the description, or the link target
14979 if no description is present"
14980 (save-match-data
14981 (if (string-match org-bracket-link-analytic-regexp link)
14982 (replace-match (or (match-string 5 link)
14983 (concat (match-string 1 link)
14984 (match-string 3 link)))
14985 nil nil link)
14986 link)))
14988 ;; Speedbar support
14990 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14991 "Overlay marking the agenda restriction line in speedbar.")
14992 (org-overlay-put org-speedbar-restriction-lock-overlay
14993 'face 'org-agenda-restriction-lock)
14994 (org-overlay-put org-speedbar-restriction-lock-overlay
14995 'help-echo "Agendas are currently limited to this item.")
14996 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14998 (defun org-speedbar-set-agenda-restriction ()
14999 "Restrict future agenda commands to the location at point in speedbar.
15000 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15001 (interactive)
15002 (require 'org-agenda)
15003 (let (p m tp np dir txt)
15004 (cond
15005 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15006 'org-imenu t))
15007 (setq m (get-text-property p 'org-imenu-marker))
15008 (save-excursion
15009 (save-restriction
15010 (set-buffer (marker-buffer m))
15011 (goto-char m)
15012 (org-agenda-set-restriction-lock 'subtree))))
15013 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15014 'speedbar-function 'speedbar-find-file))
15015 (setq tp (previous-single-property-change
15016 (1+ p) 'speedbar-function)
15017 np (next-single-property-change
15018 tp 'speedbar-function)
15019 dir (speedbar-line-directory)
15020 txt (buffer-substring-no-properties (or tp (point-min))
15021 (or np (point-max))))
15022 (save-excursion
15023 (save-restriction
15024 (set-buffer (find-file-noselect
15025 (let ((default-directory dir))
15026 (expand-file-name txt))))
15027 (unless (org-mode-p)
15028 (error "Cannot restrict to non-Org-mode file"))
15029 (org-agenda-set-restriction-lock 'file))))
15030 (t (error "Don't know how to restrict Org-mode's agenda")))
15031 (org-move-overlay org-speedbar-restriction-lock-overlay
15032 (point-at-bol) (point-at-eol))
15033 (setq current-prefix-arg nil)
15034 (org-agenda-maybe-redo)))
15036 (eval-after-load "speedbar"
15037 '(progn
15038 (speedbar-add-supported-extension ".org")
15039 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15040 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15041 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15042 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15043 (add-hook 'speedbar-visiting-tag-hook
15044 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15047 ;;; Fixes and Hacks for problems with other packages
15049 ;; Make flyspell not check words in links, to not mess up our keymap
15050 (defun org-mode-flyspell-verify ()
15051 "Don't let flyspell put overlays at active buttons."
15052 (not (get-text-property (point) 'keymap)))
15054 ;; Make `bookmark-jump' show the jump location if it was hidden.
15055 (eval-after-load "bookmark"
15056 '(if (boundp 'bookmark-after-jump-hook)
15057 ;; We can use the hook
15058 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15059 ;; Hook not available, use advice
15060 (defadvice bookmark-jump (after org-make-visible activate)
15061 "Make the position visible."
15062 (org-bookmark-jump-unhide))))
15064 ;; Make sure saveplace show the location if it was hidden
15065 (eval-after-load "saveplace"
15066 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15067 "Make the position visible."
15068 (org-bookmark-jump-unhide)))
15070 (defun org-bookmark-jump-unhide ()
15071 "Unhide the current position, to show the bookmark location."
15072 (and (org-mode-p)
15073 (or (org-invisible-p)
15074 (save-excursion (goto-char (max (point-min) (1- (point))))
15075 (org-invisible-p)))
15076 (org-show-context 'bookmark-jump)))
15078 ;; Make session.el ignore our circular variable
15079 (eval-after-load "session"
15080 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15082 ;;;; Experimental code
15084 (defun org-closed-in-range ()
15085 "Sparse tree of items closed in a certain time range.
15086 Still experimental, may disappear in the future."
15087 (interactive)
15088 ;; Get the time interval from the user.
15089 (let* ((time1 (time-to-seconds
15090 (org-read-date nil 'to-time nil "Starting date: ")))
15091 (time2 (time-to-seconds
15092 (org-read-date nil 'to-time nil "End date:")))
15093 ;; callback function
15094 (callback (lambda ()
15095 (let ((time
15096 (time-to-seconds
15097 (apply 'encode-time
15098 (org-parse-time-string
15099 (match-string 1))))))
15100 ;; check if time in interval
15101 (and (>= time time1) (<= time time2))))))
15102 ;; make tree, check each match with the callback
15103 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15106 ;;;; Finish up
15108 (provide 'org)
15110 (run-hooks 'org-load-hook)
15112 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15114 ;;; org.el ends here