Release 6.21a
[org-mode/org-tableheadings.git] / lisp / org.el
blobb47667b533f2eac5f2bf5fb79965170648e3fca3
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.21a
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.21a"
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 nil
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 t
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 t
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 (defvar org-blocker-hook nil
1607 "Hook for functions that are allowed to block a state change.
1609 Each function gets as its single argument a property list, see
1610 `org-trigger-hook' for more information about this list.
1612 If any of the functions in this hook returns nil, the state change
1613 is blocked.")
1615 (defvar org-trigger-hook nil
1616 "Hook for functions that are triggered by a state change.
1618 Each function gets as its single argument a property list with at least
1619 the following elements:
1621 (:type type-of-change :position pos-at-entry-start
1622 :from old-state :to new-state)
1624 Depending on the type, more properties may be present.
1626 This mechanism is currently implemented for:
1628 TODO state changes
1629 ------------------
1630 :type todo-state-change
1631 :from previous state (keyword as a string), or nil, or a symbol
1632 'todo' or 'done', to indicate the general type of state.
1633 :to new state, like in :from")
1635 (defcustom org-enforce-todo-dependencies nil
1636 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1637 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1638 be blocked if any prior sibling is not yet done.
1639 This variable needs to be set before org.el is loaded, and you need to
1640 restart Emacs after a change to make the change effective. The only way
1641 to change is while Emacs is running is through the customize interface."
1642 :set (lambda (var val)
1643 (set var val)
1644 (if val
1645 (add-hook 'org-blocker-hook
1646 'org-block-todo-from-children-or-siblings)
1647 (remove-hook 'org-blocker-hook
1648 'org-block-todo-from-children-or-siblings)))
1649 :group 'org-todo
1650 :type 'boolean)
1652 (defcustom org-enforce-todo-checkbox-dependencies nil
1653 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1654 When this is nil, checkboxes have no influence on switching TODO states.
1655 When non-nil, you first need to check off all check boxes before the TODO
1656 entry can be switched to DONE.
1657 This variable needs to be set before org.el is loaded, and you need to
1658 restart Emacs after a change to make the change effective. The only way
1659 to change is while Emacs is running is through the customize interface."
1660 :set (lambda (var val)
1661 (set var val)
1662 (if val
1663 (add-hook 'org-blocker-hook
1664 'org-block-todo-from-checkboxes)
1665 (remove-hook 'org-blocker-hook
1666 'org-block-todo-from-checkboxes)))
1667 :group 'org-todo
1668 :type 'boolean)
1670 (defcustom org-todo-state-tags-triggers nil
1671 "Tag changes that should be triggered by TODO state changes.
1672 This is a list. Each entry is
1674 (state-change (tag . flag) .......)
1676 State-change can be a string with a state, and empty string to indicate the
1677 state that has no TODO keyword, or it can be one of the symbols `todo'
1678 or `done', meaning any not-done or done state, respectively."
1679 :group 'org-todo
1680 :group 'org-tags
1681 :type '(repeat
1682 (cons (choice :tag "When changing to"
1683 (const :tag "Not-done state" todo)
1684 (const :tag "Done state" done)
1685 (string :tag "State"))
1686 (repeat
1687 (cons :tag "Tag action"
1688 (string :tag "Tag")
1689 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1691 (defcustom org-log-done nil
1692 "Information to record when a task moves to the DONE state.
1694 Possible values are:
1696 nil Don't add anything, just change the keyword
1697 time Add a time stamp to the task
1698 note Prompt a closing note and add it with template `org-log-note-headings'
1700 This option can also be set with on a per-file-basis with
1702 #+STARTUP: nologdone
1703 #+STARTUP: logdone
1704 #+STARTUP: lognotedone
1706 You can have local logging settings for a subtree by setting the LOGGING
1707 property to one or more of these keywords."
1708 :group 'org-todo
1709 :group 'org-progress
1710 :type '(choice
1711 (const :tag "No logging" nil)
1712 (const :tag "Record CLOSED timestamp" time)
1713 (const :tag "Record CLOSED timestamp with closing note." note)))
1715 ;; Normalize old uses of org-log-done.
1716 (cond
1717 ((eq org-log-done t) (setq org-log-done 'time))
1718 ((and (listp org-log-done) (memq 'done org-log-done))
1719 (setq org-log-done 'note)))
1721 (defcustom org-log-note-clock-out nil
1722 "Non-nil means, record a note when clocking out of an item.
1723 This can also be configured on a per-file basis by adding one of
1724 the following lines anywhere in the buffer:
1726 #+STARTUP: lognoteclock-out
1727 #+STARTUP: nolognoteclock-out"
1728 :group 'org-todo
1729 :group 'org-progress
1730 :type 'boolean)
1732 (defcustom org-log-done-with-time t
1733 "Non-nil means, the CLOSED time stamp will contain date and time.
1734 When nil, only the date will be recorded."
1735 :group 'org-progress
1736 :type 'boolean)
1738 (defcustom org-log-note-headings
1739 '((done . "CLOSING NOTE %t")
1740 (state . "State %-12s %t")
1741 (note . "Note taken on %t")
1742 (clock-out . ""))
1743 "Headings for notes added to entries.
1744 The value is an alist, with the car being a symbol indicating the note
1745 context, and the cdr is the heading to be used. The heading may also be the
1746 empty string.
1747 %t in the heading will be replaced by a time stamp.
1748 %s will be replaced by the new TODO state, in double quotes.
1749 %u will be replaced by the user name.
1750 %U will be replaced by the full user name."
1751 :group 'org-todo
1752 :group 'org-progress
1753 :type '(list :greedy t
1754 (cons (const :tag "Heading when closing an item" done) string)
1755 (cons (const :tag
1756 "Heading when changing todo state (todo sequence only)"
1757 state) string)
1758 (cons (const :tag "Heading when just taking a note" note) string)
1759 (cons (const :tag "Heading when clocking out" clock-out) string)))
1761 (unless (assq 'note org-log-note-headings)
1762 (push '(note . "%t") org-log-note-headings))
1764 (defcustom org-log-state-notes-insert-after-drawers nil
1765 "Non-nil means, insert state change notes after any drawers in entry.
1766 Only the drawers that *immediately* follow the headline and the
1767 deadline/scheduled line are skipped.
1768 When nil, insert notes right after the heading and perhaps the line
1769 with deadline/scheduling if present."
1770 :group 'org-todo
1771 :group 'org-progress
1772 :type 'boolean)
1774 (defcustom org-log-states-order-reversed t
1775 "Non-nil means, the latest state change note will be directly after heading.
1776 When nil, the notes will be orderer according to time."
1777 :group 'org-todo
1778 :group 'org-progress
1779 :type 'boolean)
1781 (defcustom org-log-repeat 'time
1782 "Non-nil means, record moving through the DONE state when triggering repeat.
1783 An auto-repeating tasks is immediately switched back to TODO when marked
1784 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1785 the TODO keyword definition, or recording a closing note by setting
1786 `org-log-done', there will be no record of the task moving through DONE.
1787 This variable forces taking a note anyway. Possible values are:
1789 nil Don't force a record
1790 time Record a time stamp
1791 note Record a note
1793 This option can also be set with on a per-file-basis with
1795 #+STARTUP: logrepeat
1796 #+STARTUP: lognoterepeat
1797 #+STARTUP: nologrepeat
1799 You can have local logging settings for a subtree by setting the LOGGING
1800 property to one or more of these keywords."
1801 :group 'org-todo
1802 :group 'org-progress
1803 :type '(choice
1804 (const :tag "Don't force a record" nil)
1805 (const :tag "Force recording the DONE state" time)
1806 (const :tag "Force recording a note with the DONE state" note)))
1809 (defgroup org-priorities nil
1810 "Priorities in Org-mode."
1811 :tag "Org Priorities"
1812 :group 'org-todo)
1814 (defcustom org-highest-priority ?A
1815 "The highest priority of TODO items. A character like ?A, ?B etc.
1816 Must have a smaller ASCII number than `org-lowest-priority'."
1817 :group 'org-priorities
1818 :type 'character)
1820 (defcustom org-lowest-priority ?C
1821 "The lowest priority of TODO items. A character like ?A, ?B etc.
1822 Must have a larger ASCII number than `org-highest-priority'."
1823 :group 'org-priorities
1824 :type 'character)
1826 (defcustom org-default-priority ?B
1827 "The default priority of TODO items.
1828 This is the priority an item get if no explicit priority is given."
1829 :group 'org-priorities
1830 :type 'character)
1832 (defcustom org-priority-start-cycle-with-default t
1833 "Non-nil means, start with default priority when starting to cycle.
1834 When this is nil, the first step in the cycle will be (depending on the
1835 command used) one higher or lower that the default priority."
1836 :group 'org-priorities
1837 :type 'boolean)
1839 (defgroup org-time nil
1840 "Options concerning time stamps and deadlines in Org-mode."
1841 :tag "Org Time"
1842 :group 'org)
1844 (defcustom org-insert-labeled-timestamps-at-point nil
1845 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1846 When nil, these labeled time stamps are forces into the second line of an
1847 entry, just after the headline. When scheduling from the global TODO list,
1848 the time stamp will always be forced into the second line."
1849 :group 'org-time
1850 :type 'boolean)
1852 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1853 "Formats for `format-time-string' which are used for time stamps.
1854 It is not recommended to change this constant.")
1856 (defcustom org-time-stamp-rounding-minutes '(0 5)
1857 "Number of minutes to round time stamps to.
1858 These are two values, the first applies when first creating a time stamp.
1859 The second applies when changing it with the commands `S-up' and `S-down'.
1860 When changing the time stamp, this means that it will change in steps
1861 of N minutes, as given by the second value.
1863 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1864 numbers should be factors of 60, so for example 5, 10, 15.
1866 When this is larger than 1, you can still force an exact time-stamp by using
1867 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1868 and by using a prefix arg to `S-up/down' to specify the exact number
1869 of minutes to shift."
1870 :group 'org-time
1871 :get '(lambda (var) ; Make sure all entries have 5 elements
1872 (if (integerp (default-value var))
1873 (list (default-value var) 5)
1874 (default-value var)))
1875 :type '(list
1876 (integer :tag "when inserting times")
1877 (integer :tag "when modifying times")))
1879 ;; Normalize old customizations of this variable.
1880 (when (integerp org-time-stamp-rounding-minutes)
1881 (setq org-time-stamp-rounding-minutes
1882 (list org-time-stamp-rounding-minutes
1883 org-time-stamp-rounding-minutes)))
1885 (defcustom org-display-custom-times nil
1886 "Non-nil means, overlay custom formats over all time stamps.
1887 The formats are defined through the variable `org-time-stamp-custom-formats'.
1888 To turn this on on a per-file basis, insert anywhere in the file:
1889 #+STARTUP: customtime"
1890 :group 'org-time
1891 :set 'set-default
1892 :type 'sexp)
1893 (make-variable-buffer-local 'org-display-custom-times)
1895 (defcustom org-time-stamp-custom-formats
1896 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1897 "Custom formats for time stamps. See `format-time-string' for the syntax.
1898 These are overlayed over the default ISO format if the variable
1899 `org-display-custom-times' is set. Time like %H:%M should be at the
1900 end of the second format."
1901 :group 'org-time
1902 :type 'sexp)
1904 (defun org-time-stamp-format (&optional long inactive)
1905 "Get the right format for a time string."
1906 (let ((f (if long (cdr org-time-stamp-formats)
1907 (car org-time-stamp-formats))))
1908 (if inactive
1909 (concat "[" (substring f 1 -1) "]")
1910 f)))
1912 (defcustom org-time-clocksum-format "%d:%02d"
1913 "The format string used when creating CLOCKSUM lines, or when
1914 org-mode generates a time duration."
1915 :group 'org-time
1916 :type 'string)
1918 (defcustom org-deadline-warning-days 14
1919 "No. of days before expiration during which a deadline becomes active.
1920 This variable governs the display in sparse trees and in the agenda.
1921 When 0 or negative, it means use this number (the absolute value of it)
1922 even if a deadline has a different individual lead time specified."
1923 :group 'org-time
1924 :group 'org-agenda-daily/weekly
1925 :type 'number)
1927 (defcustom org-read-date-prefer-future t
1928 "Non-nil means, assume future for incomplete date input from user.
1929 This affects the following situations:
1930 1. The user gives a day, but no month.
1931 For example, if today is the 15th, and you enter \"3\", Org-mode will
1932 read this as the third of *next* month. However, if you enter \"17\",
1933 it will be considered as *this* month.
1934 2. The user gives a month but not a year.
1935 For example, if it is april and you enter \"feb 2\", this will be read
1936 as feb 2, *next* year. \"May 5\", however, will be this year.
1938 Currently this does not work for ISO week specifications.
1940 When this option is nil, the current month and year will always be used
1941 as defaults."
1942 :group 'org-time
1943 :type 'boolean)
1945 (defcustom org-read-date-display-live t
1946 "Non-nil means, display current interpretation of date prompt live.
1947 This display will be in an overlay, in the minibuffer."
1948 :group 'org-time
1949 :type 'boolean)
1951 (defcustom org-read-date-popup-calendar t
1952 "Non-nil means, pop up a calendar when prompting for a date.
1953 In the calendar, the date can be selected with mouse-1. However, the
1954 minibuffer will also be active, and you can simply enter the date as well.
1955 When nil, only the minibuffer will be available."
1956 :group 'org-time
1957 :type 'boolean)
1958 (if (fboundp 'defvaralias)
1959 (defvaralias 'org-popup-calendar-for-date-prompt
1960 'org-read-date-popup-calendar))
1962 (defcustom org-extend-today-until 0
1963 "The hour when your day really ends. Must be an integer.
1964 This has influence for the following applications:
1965 - When switching the agenda to \"today\". It it is still earlier than
1966 the time given here, the day recognized as TODAY is actually yesterday.
1967 - When a date is read from the user and it is still before the time given
1968 here, the current date and time will be assumed to be yesterday, 23:59.
1969 Also, timestamps inserted in remember templates follow this rule.
1971 IMPORTANT: This is a feature whose implementation is and likely will
1972 remain incomplete. Really, it is only here because past midnight seems to
1973 be the favorite working time of John Wiegley :-)"
1974 :group 'org-time
1975 :type 'number)
1977 (defcustom org-edit-timestamp-down-means-later nil
1978 "Non-nil means, S-down will increase the time in a time stamp.
1979 When nil, S-up will increase."
1980 :group 'org-time
1981 :type 'boolean)
1983 (defcustom org-calendar-follow-timestamp-change t
1984 "Non-nil means, make the calendar window follow timestamp changes.
1985 When a timestamp is modified and the calendar window is visible, it will be
1986 moved to the new date."
1987 :group 'org-time
1988 :type 'boolean)
1990 (defgroup org-tags nil
1991 "Options concerning tags in Org-mode."
1992 :tag "Org Tags"
1993 :group 'org)
1995 (defcustom org-tag-alist nil
1996 "List of tags allowed in Org-mode files.
1997 When this list is nil, Org-mode will base TAG input on what is already in the
1998 buffer.
1999 The value of this variable is an alist, the car of each entry must be a
2000 keyword as a string, the cdr may be a character that is used to select
2001 that tag through the fast-tag-selection interface.
2002 See the manual for details."
2003 :group 'org-tags
2004 :type '(repeat
2005 (choice
2006 (cons (string :tag "Tag name")
2007 (character :tag "Access char"))
2008 (const :tag "Start radio group" (:startgroup))
2009 (const :tag "End radio group" (:endgroup)))))
2011 (defvar org-file-tags nil
2012 "List of tags that can be inherited by all entries in the file.
2013 The tags will be inherited if the variable `org-use-tag-inheritance'
2014 says they should be.
2015 This variable is populated from #+TAG lines.")
2017 (defcustom org-use-fast-tag-selection 'auto
2018 "Non-nil means, use fast tag selection scheme.
2019 This is a special interface to select and deselect tags with single keys.
2020 When nil, fast selection is never used.
2021 When the symbol `auto', fast selection is used if and only if selection
2022 characters for tags have been configured, either through the variable
2023 `org-tag-alist' or through a #+TAGS line in the buffer.
2024 When t, fast selection is always used and selection keys are assigned
2025 automatically if necessary."
2026 :group 'org-tags
2027 :type '(choice
2028 (const :tag "Always" t)
2029 (const :tag "Never" nil)
2030 (const :tag "When selection characters are configured" 'auto)))
2032 (defcustom org-fast-tag-selection-single-key nil
2033 "Non-nil means, fast tag selection exits after first change.
2034 When nil, you have to press RET to exit it.
2035 During fast tag selection, you can toggle this flag with `C-c'.
2036 This variable can also have the value `expert'. In this case, the window
2037 displaying the tags menu is not even shown, until you press C-c again."
2038 :group 'org-tags
2039 :type '(choice
2040 (const :tag "No" nil)
2041 (const :tag "Yes" t)
2042 (const :tag "Expert" expert)))
2044 (defvar org-fast-tag-selection-include-todo nil
2045 "Non-nil means, fast tags selection interface will also offer TODO states.
2046 This is an undocumented feature, you should not rely on it.")
2048 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2049 "The column to which tags should be indented in a headline.
2050 If this number is positive, it specifies the column. If it is negative,
2051 it means that the tags should be flushright to that column. For example,
2052 -80 works well for a normal 80 character screen."
2053 :group 'org-tags
2054 :type 'integer)
2056 (defcustom org-auto-align-tags t
2057 "Non-nil means, realign tags after pro/demotion of TODO state change.
2058 These operations change the length of a headline and therefore shift
2059 the tags around. With this options turned on, after each such operation
2060 the tags are again aligned to `org-tags-column'."
2061 :group 'org-tags
2062 :type 'boolean)
2064 (defcustom org-use-tag-inheritance t
2065 "Non-nil means, tags in levels apply also for sublevels.
2066 When nil, only the tags directly given in a specific line apply there.
2067 This may also be a list of tags that should be inherited, or a regexp that
2068 matches tags that should be inherited. Additional control is possible
2069 with the variable `org-tags-exclude-from-inheritance' which gives an
2070 explicit list of tags to be excluded from inheritance., even if the value of
2071 `org-use-tag-inheritance' would select it for inheritance.
2073 If this option is t, a match early-on in a tree can lead to a large
2074 number of matches in the subtree when constructing the agenda or creating
2075 a sparse tree. If you only want to see the first match in a tree during
2076 a search, check out the variable `org-tags-match-list-sublevels'."
2077 :group 'org-tags
2078 :type '(choice
2079 (const :tag "Not" nil)
2080 (const :tag "Always" t)
2081 (repeat :tag "Specific tags" (string :tag "Tag"))
2082 (regexp :tag "Tags matched by regexp")))
2084 (defcustom org-tags-exclude-from-inheritance nil
2085 "List of tags that should never be inherited.
2086 This is a way to exclude a few tags from inheritance. For way to do
2087 the opposite, to actively allow inheritance for selected tags,
2088 see the variable `org-use-tag-inheritance'."
2089 :group 'org-tags
2090 :type '(repeat (string :tag "Tag")))
2092 (defun org-tag-inherit-p (tag)
2093 "Check if TAG is one that should be inherited."
2094 (cond
2095 ((member tag org-tags-exclude-from-inheritance) nil)
2096 ((eq org-use-tag-inheritance t) t)
2097 ((not org-use-tag-inheritance) nil)
2098 ((stringp org-use-tag-inheritance)
2099 (string-match org-use-tag-inheritance tag))
2100 ((listp org-use-tag-inheritance)
2101 (member tag org-use-tag-inheritance))
2102 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2104 (defcustom org-tags-match-list-sublevels t
2105 "Non-nil means list also sublevels of headlines matching tag search.
2106 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2107 the sublevels of a headline matching a tag search often also match
2108 the same search. Listing all of them can create very long lists.
2109 Setting this variable to nil causes subtrees of a match to be skipped.
2110 This option is off by default, because inheritance in on. If you turn
2111 inheritance off, you very likely want to turn this option on.
2113 As a special case, if the tag search is restricted to TODO items, the
2114 value of this variable is ignored and sublevels are always checked, to
2115 make sure all corresponding TODO items find their way into the list.
2117 This variable is semi-obsolete and probably should always be true. It
2118 is better to limit inheritance to certain tags using the variables
2119 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2120 :group 'org-tags
2121 :type 'boolean)
2123 (defvar org-tags-history nil
2124 "History of minibuffer reads for tags.")
2125 (defvar org-last-tags-completion-table nil
2126 "The last used completion table for tags.")
2127 (defvar org-after-tags-change-hook nil
2128 "Hook that is run after the tags in a line have changed.")
2130 (defgroup org-properties nil
2131 "Options concerning properties in Org-mode."
2132 :tag "Org Properties"
2133 :group 'org)
2135 (defcustom org-property-format "%-10s %s"
2136 "How property key/value pairs should be formatted by `indent-line'.
2137 When `indent-line' hits a property definition, it will format the line
2138 according to this format, mainly to make sure that the values are
2139 lined-up with respect to each other."
2140 :group 'org-properties
2141 :type 'string)
2143 (defcustom org-use-property-inheritance nil
2144 "Non-nil means, properties apply also for sublevels.
2146 This setting is chiefly used during property searches. Turning it on can
2147 cause significant overhead when doing a search, which is why it is not
2148 on by default.
2150 When nil, only the properties directly given in the current entry count.
2151 When t, every property is inherited. The value may also be a list of
2152 properties that should have inheritance, or a regular expression matching
2153 properties that should be inherited.
2155 However, note that some special properties use inheritance under special
2156 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2157 and the properties ending in \"_ALL\" when they are used as descriptor
2158 for valid values of a property.
2160 Note for programmers:
2161 When querying an entry with `org-entry-get', you can control if inheritance
2162 should be used. By default, `org-entry-get' looks only at the local
2163 properties. You can request inheritance by setting the inherit argument
2164 to t (to force inheritance) or to `selective' (to respect the setting
2165 in this variable)."
2166 :group 'org-properties
2167 :type '(choice
2168 (const :tag "Not" nil)
2169 (const :tag "Always" t)
2170 (repeat :tag "Specific properties" (string :tag "Property"))
2171 (regexp :tag "Properties matched by regexp")))
2173 (defun org-property-inherit-p (property)
2174 "Check if PROPERTY is one that should be inherited."
2175 (cond
2176 ((eq org-use-property-inheritance t) t)
2177 ((not org-use-property-inheritance) nil)
2178 ((stringp org-use-property-inheritance)
2179 (string-match org-use-property-inheritance property))
2180 ((listp org-use-property-inheritance)
2181 (member property org-use-property-inheritance))
2182 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2184 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2185 "The default column format, if no other format has been defined.
2186 This variable can be set on the per-file basis by inserting a line
2188 #+COLUMNS: %25ITEM ....."
2189 :group 'org-properties
2190 :type 'string)
2192 (defcustom org-columns-ellipses ".."
2193 "The ellipses to be used when a field in column view is truncated.
2194 When this is the empty string, as many characters as possible are shown,
2195 but then there will be no visual indication that the field has been truncated.
2196 When this is a string of length N, the last N characters of a truncated
2197 field are replaced by this string. If the column is narrower than the
2198 ellipses string, only part of the ellipses string will be shown."
2199 :group 'org-properties
2200 :type 'string)
2202 (defcustom org-columns-modify-value-for-display-function nil
2203 "Function that modifies values for display in column view.
2204 For example, it can be used to cut out a certain part from a time stamp.
2205 The function must take 2 arguments:
2207 column-title The title of the column (*not* the property name)
2208 value The value that should be modified.
2210 The function should return the value that should be displayed,
2211 or nil if the normal value should be used."
2212 :group 'org-properties
2213 :type 'function)
2215 (defcustom org-effort-property "Effort"
2216 "The property that is being used to keep track of effort estimates.
2217 Effort estimates given in this property need to have the format H:MM."
2218 :group 'org-properties
2219 :group 'org-progress
2220 :type '(string :tag "Property"))
2222 (defconst org-global-properties-fixed
2223 '(("VISIBILITY_ALL" . "folded children content all"))
2224 "List of property/value pairs that can be inherited by any entry.
2225 These are fixed values, for the preset properties.")
2228 (defcustom org-global-properties nil
2229 "List of property/value pairs that can be inherited by any entry.
2230 You can set buffer-local values for the same purpose in the variable
2231 `org-file-properties' this by adding lines like
2233 #+PROPERTY: NAME VALUE"
2234 :group 'org-properties
2235 :type '(repeat
2236 (cons (string :tag "Property")
2237 (string :tag "Value"))))
2239 (defvar org-file-properties nil
2240 "List of property/value pairs that can be inherited by any entry.
2241 Valid for the current buffer.
2242 This variable is populated from #+PROPERTY lines.")
2243 (make-variable-buffer-local 'org-file-properties)
2245 (defgroup org-agenda nil
2246 "Options concerning agenda views in Org-mode."
2247 :tag "Org Agenda"
2248 :group 'org)
2250 (defvar org-category nil
2251 "Variable used by org files to set a category for agenda display.
2252 Such files should use a file variable to set it, for example
2254 # -*- mode: org; org-category: \"ELisp\"
2256 or contain a special line
2258 #+CATEGORY: ELisp
2260 If the file does not specify a category, then file's base name
2261 is used instead.")
2262 (make-variable-buffer-local 'org-category)
2263 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2265 (defcustom org-agenda-files nil
2266 "The files to be used for agenda display.
2267 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2268 \\[org-remove-file]. You can also use customize to edit the list.
2270 If an entry is a directory, all files in that directory that are matched by
2271 `org-agenda-file-regexp' will be part of the file list.
2273 If the value of the variable is not a list but a single file name, then
2274 the list of agenda files is actually stored and maintained in that file, one
2275 agenda file per line."
2276 :group 'org-agenda
2277 :type '(choice
2278 (repeat :tag "List of files and directories" file)
2279 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2281 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2282 "Regular expression to match files for `org-agenda-files'.
2283 If any element in the list in that variable contains a directory instead
2284 of a normal file, all files in that directory that are matched by this
2285 regular expression will be included."
2286 :group 'org-agenda
2287 :type 'regexp)
2289 (defcustom org-agenda-text-search-extra-files nil
2290 "List of extra files to be searched by text search commands.
2291 These files will be search in addition to the agenda files by the
2292 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2293 Note that these files will only be searched for text search commands,
2294 not for the other agenda views like todo lists, tag searches or the weekly
2295 agenda. This variable is intended to list notes and possibly archive files
2296 that should also be searched by these two commands.
2297 In fact, if the first element in the list is the symbol `agenda-archives',
2298 than all archive files of all agenda files will be added to the search
2299 scope."
2300 :group 'org-agenda
2301 :type '(set :greedy t
2302 (const :tag "Agenda Archives" agenda-archives)
2303 (repeat :inline t (file))))
2305 (if (fboundp 'defvaralias)
2306 (defvaralias 'org-agenda-multi-occur-extra-files
2307 'org-agenda-text-search-extra-files))
2309 (defcustom org-agenda-skip-unavailable-files nil
2310 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2311 A nil value means to remove them, after a query, from the list."
2312 :group 'org-agenda
2313 :type 'boolean)
2315 (defcustom org-calendar-to-agenda-key [?c]
2316 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2317 The command `org-calendar-goto-agenda' will be bound to this key. The
2318 default is the character `c' because then `c' can be used to switch back and
2319 forth between agenda and calendar."
2320 :group 'org-agenda
2321 :type 'sexp)
2323 (defcustom org-calendar-agenda-action-key [?k]
2324 "The key to be installed in `calendar-mode-map' for agenda-action.
2325 The command `org-agenda-action' will be bound to this key. The
2326 default is the character `k' because we use the same key in the agenda."
2327 :group 'org-agenda
2328 :type 'sexp)
2330 (eval-after-load "calendar"
2331 '(progn
2332 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2333 'org-calendar-goto-agenda)
2334 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2335 'org-agenda-action)))
2337 (defgroup org-latex nil
2338 "Options for embedding LaTeX code into Org-mode."
2339 :tag "Org LaTeX"
2340 :group 'org)
2342 (defcustom org-format-latex-options
2343 '(:foreground default :background default :scale 1.0
2344 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2345 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2346 "Options for creating images from LaTeX fragments.
2347 This is a property list with the following properties:
2348 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2349 `default' means use the foreground of the default face.
2350 :background the background color, or \"Transparent\".
2351 `default' means use the background of the default face.
2352 :scale a scaling factor for the size of the images.
2353 :html-foreground, :html-background, :html-scale
2354 the same numbers for HTML export.
2355 :matchers a list indicating which matchers should be used to
2356 find LaTeX fragments. Valid members of this list are:
2357 \"begin\" find environments
2358 \"$1\" find single characters surrounded by $.$
2359 \"$\" find math expressions surrounded by $...$
2360 \"$$\" find math expressions surrounded by $$....$$
2361 \"\\(\" find math expressions surrounded by \\(...\\)
2362 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2363 :group 'org-latex
2364 :type 'plist)
2366 (defcustom org-format-latex-header "\\documentclass{article}
2367 \\usepackage{fullpage} % do not remove
2368 \\usepackage{amssymb}
2369 \\usepackage[usenames]{color}
2370 \\usepackage{amsmath}
2371 \\usepackage{latexsym}
2372 \\usepackage[mathscr]{eucal}
2373 \\pagestyle{empty} % do not remove"
2374 "The document header used for processing LaTeX fragments."
2375 :group 'org-latex
2376 :type 'string)
2379 (defgroup org-font-lock nil
2380 "Font-lock settings for highlighting in Org-mode."
2381 :tag "Org Font Lock"
2382 :group 'org)
2384 (defcustom org-level-color-stars-only nil
2385 "Non-nil means fontify only the stars in each headline.
2386 When nil, the entire headline is fontified.
2387 Changing it requires restart of `font-lock-mode' to become effective
2388 also in regions already fontified."
2389 :group 'org-font-lock
2390 :type 'boolean)
2392 (defcustom org-hide-leading-stars nil
2393 "Non-nil means, hide the first N-1 stars in a headline.
2394 This works by using the face `org-hide' for these stars. This
2395 face is white for a light background, and black for a dark
2396 background. You may have to customize the face `org-hide' to
2397 make this work.
2398 Changing it requires restart of `font-lock-mode' to become effective
2399 also in regions already fontified.
2400 You may also set this on a per-file basis by adding one of the following
2401 lines to the buffer:
2403 #+STARTUP: hidestars
2404 #+STARTUP: showstars"
2405 :group 'org-font-lock
2406 :type 'boolean)
2408 (defcustom org-fontify-done-headline nil
2409 "Non-nil means, change the face of a headline if it is marked DONE.
2410 Normally, only the TODO/DONE keyword indicates the state of a headline.
2411 When this is non-nil, the headline after the keyword is set to the
2412 `org-headline-done' as an additional indication."
2413 :group 'org-font-lock
2414 :type 'boolean)
2416 (defcustom org-fontify-emphasized-text t
2417 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2418 Changing this variable requires a restart of Emacs to take effect."
2419 :group 'org-font-lock
2420 :type 'boolean)
2422 (defcustom org-highlight-latex-fragments-and-specials nil
2423 "Non-nil means, fontify what is treated specially by the exporters."
2424 :group 'org-font-lock
2425 :type 'boolean)
2427 (defcustom org-hide-emphasis-markers nil
2428 "Non-nil mean font-lock should hide the emphasis marker characters."
2429 :group 'org-font-lock
2430 :type 'boolean)
2432 (defvar org-emph-re nil
2433 "Regular expression for matching emphasis.")
2434 (defvar org-verbatim-re nil
2435 "Regular expression for matching verbatim text.")
2436 (defvar org-emphasis-regexp-components) ; defined just below
2437 (defvar org-emphasis-alist) ; defined just below
2438 (defun org-set-emph-re (var val)
2439 "Set variable and compute the emphasis regular expression."
2440 (set var val)
2441 (when (and (boundp 'org-emphasis-alist)
2442 (boundp 'org-emphasis-regexp-components)
2443 org-emphasis-alist org-emphasis-regexp-components)
2444 (let* ((e org-emphasis-regexp-components)
2445 (pre (car e))
2446 (post (nth 1 e))
2447 (border (nth 2 e))
2448 (body (nth 3 e))
2449 (nl (nth 4 e))
2450 (body1 (concat body "*?"))
2451 (markers (mapconcat 'car org-emphasis-alist ""))
2452 (vmarkers (mapconcat
2453 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2454 org-emphasis-alist "")))
2455 ;; make sure special characters appear at the right position in the class
2456 (if (string-match "\\^" markers)
2457 (setq markers (concat (replace-match "" t t markers) "^")))
2458 (if (string-match "-" markers)
2459 (setq markers (concat (replace-match "" t t markers) "-")))
2460 (if (string-match "\\^" vmarkers)
2461 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2462 (if (string-match "-" vmarkers)
2463 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2464 (if (> nl 0)
2465 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2466 (int-to-string nl) "\\}")))
2467 ;; Make the regexp
2468 (setq org-emph-re
2469 (concat "\\([" pre "]\\|^\\)"
2470 "\\("
2471 "\\([" markers "]\\)"
2472 "\\("
2473 "[^" border "]\\|"
2474 "[^" border "]"
2475 body1
2476 "[^" border "]"
2477 "\\)"
2478 "\\3\\)"
2479 "\\([" post "]\\|$\\)"))
2480 (setq org-verbatim-re
2481 (concat "\\([" pre "]\\|^\\)"
2482 "\\("
2483 "\\([" vmarkers "]\\)"
2484 "\\("
2485 "[^" border "]\\|"
2486 "[^" border "]"
2487 body1
2488 "[^" border "]"
2489 "\\)"
2490 "\\3\\)"
2491 "\\([" post "]\\|$\\)")))))
2493 (defcustom org-emphasis-regexp-components
2494 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2495 "Components used to build the regular expression for emphasis.
2496 This is a list with 6 entries. Terminology: In an emphasis string
2497 like \" *strong word* \", we call the initial space PREMATCH, the final
2498 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2499 and \"trong wor\" is the body. The different components in this variable
2500 specify what is allowed/forbidden in each part:
2502 pre Chars allowed as prematch. Beginning of line will be allowed too.
2503 post Chars allowed as postmatch. End of line will be allowed too.
2504 border The chars *forbidden* as border characters.
2505 body-regexp A regexp like \".\" to match a body character. Don't use
2506 non-shy groups here, and don't allow newline here.
2507 newline The maximum number of newlines allowed in an emphasis exp.
2509 Use customize to modify this, or restart Emacs after changing it."
2510 :group 'org-font-lock
2511 :set 'org-set-emph-re
2512 :type '(list
2513 (sexp :tag "Allowed chars in pre ")
2514 (sexp :tag "Allowed chars in post ")
2515 (sexp :tag "Forbidden chars in border ")
2516 (sexp :tag "Regexp for body ")
2517 (integer :tag "number of newlines allowed")
2518 (option (boolean :tag "Please ignore this button"))))
2520 (defcustom org-emphasis-alist
2521 `(("*" bold "<b>" "</b>")
2522 ("/" italic "<i>" "</i>")
2523 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2524 ("=" org-code "<code>" "</code>" verbatim)
2525 ("~" org-verbatim "<code>" "</code>" verbatim)
2526 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2527 "<del>" "</del>")
2529 "Special syntax for emphasized text.
2530 Text starting and ending with a special character will be emphasized, for
2531 example *bold*, _underlined_ and /italic/. This variable sets the marker
2532 characters, the face to be used by font-lock for highlighting in Org-mode
2533 Emacs buffers, and the HTML tags to be used for this.
2534 Use customize to modify this, or restart Emacs after changing it."
2535 :group 'org-font-lock
2536 :set 'org-set-emph-re
2537 :type '(repeat
2538 (list
2539 (string :tag "Marker character")
2540 (choice
2541 (face :tag "Font-lock-face")
2542 (plist :tag "Face property list"))
2543 (string :tag "HTML start tag")
2544 (string :tag "HTML end tag")
2545 (option (const verbatim)))))
2547 ;;; Miscellaneous options
2549 (defgroup org-completion nil
2550 "Completion in Org-mode."
2551 :tag "Org Completion"
2552 :group 'org)
2554 (defcustom org-completion-use-ido nil
2555 "Non-nil means, use ido completion wherever possible.
2556 Note that `ido-mode' must be active for this variable to be relevant.
2557 If you decide to turn this variable on, you might well want to turn off
2558 `org-outline-path-complete-in-steps'."
2559 :group 'org-completion
2560 :type 'boolean)
2562 (defcustom org-completion-fallback-command 'hippie-expand
2563 "The expansion command called by \\[org-complete] in normal context.
2564 Normal means, no org-mode-specific context."
2565 :group 'org-completion
2566 :type 'function)
2568 ;;; Functions and variables from ther packages
2569 ;; Declared here to avoid compiler warnings
2571 ;; XEmacs only
2572 (defvar outline-mode-menu-heading)
2573 (defvar outline-mode-menu-show)
2574 (defvar outline-mode-menu-hide)
2575 (defvar zmacs-regions) ; XEmacs regions
2577 ;; Emacs only
2578 (defvar mark-active)
2580 ;; Various packages
2581 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2582 (declare-function calendar-forward-day "cal-move" (arg))
2583 (declare-function calendar-goto-date "cal-move" (date))
2584 (declare-function calendar-goto-today "cal-move" ())
2585 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2586 (defvar calc-embedded-close-formula)
2587 (defvar calc-embedded-open-formula)
2588 (declare-function cdlatex-tab "ext:cdlatex" ())
2589 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2590 (defvar font-lock-unfontify-region-function)
2591 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2592 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2593 (defvar iswitchb-temp-buflist)
2594 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2595 (defvar org-agenda-tags-todo-honor-ignore-options)
2596 (declare-function org-agenda-skip "org-agenda" ())
2597 (declare-function org-format-agenda-item "org-agenda"
2598 (extra txt &optional category tags dotime noprefix remove-re))
2599 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2600 (declare-function org-agenda-change-all-lines "org-agenda"
2601 (newhead hdmarker &optional fixface just-this))
2602 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2603 (declare-function org-agenda-maybe-redo "org-agenda" ())
2604 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2605 (beg end))
2606 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2607 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2608 "org-agenda" (&optional end))
2610 (declare-function parse-time-string "parse-time" (string))
2611 (declare-function remember "remember" (&optional initial))
2612 (declare-function remember-buffer-desc "remember" ())
2613 (declare-function remember-finalize "remember" ())
2614 (defvar remember-save-after-remembering)
2615 (defvar remember-data-file)
2616 (defvar remember-register)
2617 (defvar remember-buffer)
2618 (defvar remember-handler-functions)
2619 (defvar remember-annotation-functions)
2620 (defvar texmathp-why)
2621 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2622 (declare-function table--at-cell-p "table" (position &optional object at-column))
2624 (defvar w3m-current-url)
2625 (defvar w3m-current-title)
2627 (defvar org-latex-regexps)
2629 ;;; Autoload and prepare some org modules
2631 ;; Some table stuff that needs to be defined here, because it is used
2632 ;; by the functions setting up org-mode or checking for table context.
2634 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2635 "Detects an org-type or table-type table.")
2636 (defconst org-table-line-regexp "^[ \t]*|"
2637 "Detects an org-type table line.")
2638 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2639 "Detects an org-type table line.")
2640 (defconst org-table-hline-regexp "^[ \t]*|-"
2641 "Detects an org-type table hline.")
2642 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2643 "Detects a table-type table hline.")
2644 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2645 "Searching from within a table (any type) this finds the first line
2646 outside the table.")
2648 ;; Autoload the functions in org-table.el that are needed by functions here.
2650 (eval-and-compile
2651 (org-autoload "org-table"
2652 '(org-table-align org-table-begin org-table-blank-field
2653 org-table-convert org-table-convert-region org-table-copy-down
2654 org-table-copy-region org-table-create
2655 org-table-create-or-convert-from-region
2656 org-table-create-with-table.el org-table-current-dline
2657 org-table-cut-region org-table-delete-column org-table-edit-field
2658 org-table-edit-formulas org-table-end org-table-eval-formula
2659 org-table-export org-table-field-info
2660 org-table-get-stored-formulas org-table-goto-column
2661 org-table-hline-and-move org-table-import org-table-insert-column
2662 org-table-insert-hline org-table-insert-row org-table-iterate
2663 org-table-justify-field-maybe org-table-kill-row
2664 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2665 org-table-move-column org-table-move-column-left
2666 org-table-move-column-right org-table-move-row
2667 org-table-move-row-down org-table-move-row-up
2668 org-table-next-field org-table-next-row org-table-paste-rectangle
2669 org-table-previous-field org-table-recalculate
2670 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2671 org-table-toggle-coordinate-overlays
2672 org-table-toggle-formula-debugger org-table-wrap-region
2673 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2675 (defun org-at-table-p (&optional table-type)
2676 "Return t if the cursor is inside an org-type table.
2677 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2678 (if org-enable-table-editor
2679 (save-excursion
2680 (beginning-of-line 1)
2681 (looking-at (if table-type org-table-any-line-regexp
2682 org-table-line-regexp)))
2683 nil))
2684 (defsubst org-table-p () (org-at-table-p))
2686 (defun org-at-table.el-p ()
2687 "Return t if and only if we are at a table.el table."
2688 (and (org-at-table-p 'any)
2689 (save-excursion
2690 (goto-char (org-table-begin 'any))
2691 (looking-at org-table1-hline-regexp))))
2692 (defun org-table-recognize-table.el ()
2693 "If there is a table.el table nearby, recognize it and move into it."
2694 (if org-table-tab-recognizes-table.el
2695 (if (org-at-table.el-p)
2696 (progn
2697 (beginning-of-line 1)
2698 (if (looking-at org-table-dataline-regexp)
2700 (if (looking-at org-table1-hline-regexp)
2701 (progn
2702 (beginning-of-line 2)
2703 (if (looking-at org-table-any-border-regexp)
2704 (beginning-of-line -1)))))
2705 (if (re-search-forward "|" (org-table-end t) t)
2706 (progn
2707 (require 'table)
2708 (if (table--at-cell-p (point))
2710 (message "recognizing table.el table...")
2711 (table-recognize-table)
2712 (message "recognizing table.el table...done")))
2713 (error "This should not happen..."))
2715 nil)
2716 nil))
2718 (defun org-at-table-hline-p ()
2719 "Return t if the cursor is inside a hline in a table."
2720 (if org-enable-table-editor
2721 (save-excursion
2722 (beginning-of-line 1)
2723 (looking-at org-table-hline-regexp))
2724 nil))
2726 (defvar org-table-clean-did-remove-column nil)
2728 (defun org-table-map-tables (function)
2729 "Apply FUNCTION to the start of all tables in the buffer."
2730 (save-excursion
2731 (save-restriction
2732 (widen)
2733 (goto-char (point-min))
2734 (while (re-search-forward org-table-any-line-regexp nil t)
2735 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2736 (beginning-of-line 1)
2737 (if (looking-at org-table-line-regexp)
2738 (save-excursion (funcall function)))
2739 (re-search-forward org-table-any-border-regexp nil 1))))
2740 (message "Mapping tables: done"))
2742 ;; Declare and autoload functions from org-exp.el
2744 (declare-function org-default-export-plist "org-exp")
2745 (declare-function org-infile-export-plist "org-exp")
2746 (declare-function org-get-current-options "org-exp")
2747 (eval-and-compile
2748 (org-autoload "org-exp"
2749 '(org-export org-export-as-ascii org-export-visible
2750 org-insert-export-options-template org-export-as-html-and-open
2751 org-export-as-html-batch org-export-as-html-to-buffer
2752 org-replace-region-by-html org-export-region-as-html
2753 org-export-as-html org-export-icalendar-this-file
2754 org-export-icalendar-all-agenda-files
2755 org-table-clean-before-export
2756 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2758 ;; Declare and autoload functions from org-agenda.el
2760 (eval-and-compile
2761 (org-autoload "org-agenda"
2762 '(org-agenda org-agenda-list org-search-view
2763 org-todo-list org-tags-view org-agenda-list-stuck-projects
2764 org-diary org-agenda-to-appt
2765 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2767 ;; Autoload org-remember
2769 (eval-and-compile
2770 (org-autoload "org-remember"
2771 '(org-remember-insinuate org-remember-annotation
2772 org-remember-apply-template org-remember org-remember-handler)))
2774 ;; Autoload org-clock.el
2777 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2778 (beg end))
2779 (declare-function org-clock-update-mode-line "org-clock" ())
2780 (defvar org-clock-start-time)
2781 (defvar org-clock-marker (make-marker)
2782 "Marker recording the last clock-in.")
2784 (eval-and-compile
2785 (org-autoload
2786 "org-clock"
2787 '(org-clock-in org-clock-out org-clock-cancel
2788 org-clock-goto org-clock-sum org-clock-display
2789 org-clock-remove-overlays org-clock-report
2790 org-clocktable-shift org-dblock-write:clocktable
2791 org-get-clocktable)))
2793 (defun org-clock-update-time-maybe ()
2794 "If this is a CLOCK line, update it and return t.
2795 Otherwise, return nil."
2796 (interactive)
2797 (save-excursion
2798 (beginning-of-line 1)
2799 (skip-chars-forward " \t")
2800 (when (looking-at org-clock-string)
2801 (let ((re (concat "[ \t]*" org-clock-string
2802 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2803 "\\([ \t]*=>.*\\)?\\)?"))
2804 ts te h m s neg)
2805 (cond
2806 ((not (looking-at re))
2807 nil)
2808 ((not (match-end 2))
2809 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2810 (> org-clock-marker (point))
2811 (<= org-clock-marker (point-at-eol)))
2812 ;; The clock is running here
2813 (setq org-clock-start-time
2814 (apply 'encode-time
2815 (org-parse-time-string (match-string 1))))
2816 (org-clock-update-mode-line)))
2818 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2819 (end-of-line 1)
2820 (setq ts (match-string 1)
2821 te (match-string 3))
2822 (setq s (- (time-to-seconds
2823 (apply 'encode-time (org-parse-time-string te)))
2824 (time-to-seconds
2825 (apply 'encode-time (org-parse-time-string ts))))
2826 neg (< s 0)
2827 s (abs s)
2828 h (floor (/ s 3600))
2829 s (- s (* 3600 h))
2830 m (floor (/ s 60))
2831 s (- s (* 60 s)))
2832 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2833 t))))))
2835 (defun org-check-running-clock ()
2836 "Check if the current buffer contains the running clock.
2837 If yes, offer to stop it and to save the buffer with the changes."
2838 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2839 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2840 (buffer-name))))
2841 (org-clock-out)
2842 (when (y-or-n-p "Save changed buffer?")
2843 (save-buffer))))
2845 (defun org-clocktable-try-shift (dir n)
2846 "Check if this line starts a clock table, if yes, shift the time block."
2847 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2848 (org-clocktable-shift dir n)))
2850 ;; Autoload org-timer.el
2852 ;(declare-function org-timer "org-timer")
2854 (eval-and-compile
2855 (org-autoload
2856 "org-timer"
2857 '(org-timer-start org-timer org-timer-item
2858 org-timer-change-times-in-region)))
2861 ;; Autoload archiving code
2862 ;; The stuff that is needed for cycling and tags has to be defined here.
2864 (defgroup org-archive nil
2865 "Options concerning archiving in Org-mode."
2866 :tag "Org Archive"
2867 :group 'org-structure)
2869 (defcustom org-archive-location "%s_archive::"
2870 "The location where subtrees should be archived.
2872 The value of this variable is a string, consisting of two parts,
2873 separated by a double-colon. The first part is a filename and
2874 the second part is a headline.
2876 When the filename is omitted, archiving happens in the same file.
2877 %s in the filename will be replaced by the current file
2878 name (without the directory part). Archiving to a different file
2879 is useful to keep archived entries from contributing to the
2880 Org-mode Agenda.
2882 The archived entries will be filed as subtrees of the specified
2883 headline. When the headline is omitted, the subtrees are simply
2884 filed away at the end of the file, as top-level entries. Also in
2885 the heading you can use %s to represent the file name, this can be
2886 useful when using the same archive for a number of different files.
2888 Here are a few examples:
2889 \"%s_archive::\"
2890 If the current file is Projects.org, archive in file
2891 Projects.org_archive, as top-level trees. This is the default.
2893 \"::* Archived Tasks\"
2894 Archive in the current file, under the top-level headline
2895 \"* Archived Tasks\".
2897 \"~/org/archive.org::\"
2898 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2900 \"~/org/archive.org::From %s\"
2901 Archive in file ~/org/archive.org (absolute path), und headlines
2902 \"From FILENAME\" where file name is the current file name.
2904 \"basement::** Finished Tasks\"
2905 Archive in file ./basement (relative path), as level 3 trees
2906 below the level 2 heading \"** Finished Tasks\".
2908 You may set this option on a per-file basis by adding to the buffer a
2909 line like
2911 #+ARCHIVE: basement::** Finished Tasks
2913 You may also define it locally for a subtree by setting an ARCHIVE property
2914 in the entry. If such a property is found in an entry, or anywhere up
2915 the hierarchy, it will be used."
2916 :group 'org-archive
2917 :type 'string)
2919 (defcustom org-archive-tag "ARCHIVE"
2920 "The tag that marks a subtree as archived.
2921 An archived subtree does not open during visibility cycling, and does
2922 not contribute to the agenda listings.
2923 After changing this, font-lock must be restarted in the relevant buffers to
2924 get the proper fontification."
2925 :group 'org-archive
2926 :group 'org-keywords
2927 :type 'string)
2929 (defcustom org-agenda-skip-archived-trees t
2930 "Non-nil means, the agenda will skip any items located in archived trees.
2931 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2932 variable is no longer recommended, you should leave it at the value t.
2933 Instead, use the key `v' to cycle the archives-mode in the agenda."
2934 :group 'org-archive
2935 :group 'org-agenda-skip
2936 :type 'boolean)
2938 (defcustom org-cycle-open-archived-trees nil
2939 "Non-nil means, `org-cycle' will open archived trees.
2940 An archived tree is a tree marked with the tag ARCHIVE.
2941 When nil, archived trees will stay folded. You can still open them with
2942 normal outline commands like `show-all', but not with the cycling commands."
2943 :group 'org-archive
2944 :group 'org-cycle
2945 :type 'boolean)
2947 (defcustom org-sparse-tree-open-archived-trees nil
2948 "Non-nil means sparse tree construction shows matches in archived trees.
2949 When nil, matches in these trees are highlighted, but the trees are kept in
2950 collapsed state."
2951 :group 'org-archive
2952 :group 'org-sparse-trees
2953 :type 'boolean)
2955 (defun org-cycle-hide-archived-subtrees (state)
2956 "Re-hide all archived subtrees after a visibility state change."
2957 (when (and (not org-cycle-open-archived-trees)
2958 (not (memq state '(overview folded))))
2959 (save-excursion
2960 (let* ((globalp (memq state '(contents all)))
2961 (beg (if globalp (point-min) (point)))
2962 (end (if globalp (point-max) (org-end-of-subtree t))))
2963 (org-hide-archived-subtrees beg end)
2964 (goto-char beg)
2965 (if (looking-at (concat ".*:" org-archive-tag ":"))
2966 (message "%s" (substitute-command-keys
2967 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2969 (defun org-force-cycle-archived ()
2970 "Cycle subtree even if it is archived."
2971 (interactive)
2972 (setq this-command 'org-cycle)
2973 (let ((org-cycle-open-archived-trees t))
2974 (call-interactively 'org-cycle)))
2976 (defun org-hide-archived-subtrees (beg end)
2977 "Re-hide all archived subtrees after a visibility state change."
2978 (save-excursion
2979 (let* ((re (concat ":" org-archive-tag ":")))
2980 (goto-char beg)
2981 (while (re-search-forward re end t)
2982 (and (org-on-heading-p) (hide-subtree))
2983 (org-end-of-subtree t)))))
2985 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2987 (eval-and-compile
2988 (org-autoload "org-archive"
2989 '(org-add-archive-files org-archive-subtree
2990 org-archive-to-archive-sibling org-toggle-archive-tag)))
2992 ;; Autoload Column View Code
2994 (declare-function org-columns-number-to-string "org-colview")
2995 (declare-function org-columns-get-format-and-top-level "org-colview")
2996 (declare-function org-columns-compute "org-colview")
2998 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2999 '(org-columns-number-to-string org-columns-get-format-and-top-level
3000 org-columns-compute org-agenda-columns org-columns-remove-overlays
3001 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3003 ;; Autoload ID code
3005 (declare-function org-id-store-link "org-id")
3006 (org-autoload "org-id"
3007 '(org-id-get-create org-id-new org-id-copy org-id-get
3008 org-id-get-with-outline-path-completion
3009 org-id-get-with-outline-drilling
3010 org-id-goto org-id-find org-id-store-link))
3012 ;;; Variables for pre-computed regular expressions, all buffer local
3014 (defvar org-drawer-regexp nil
3015 "Matches first line of a hidden block.")
3016 (make-variable-buffer-local 'org-drawer-regexp)
3017 (defvar org-todo-regexp nil
3018 "Matches any of the TODO state keywords.")
3019 (make-variable-buffer-local 'org-todo-regexp)
3020 (defvar org-not-done-regexp nil
3021 "Matches any of the TODO state keywords except the last one.")
3022 (make-variable-buffer-local 'org-not-done-regexp)
3023 (defvar org-todo-line-regexp nil
3024 "Matches a headline and puts TODO state into group 2 if present.")
3025 (make-variable-buffer-local 'org-todo-line-regexp)
3026 (defvar org-complex-heading-regexp nil
3027 "Matches a headline and puts everything into groups:
3028 group 1: the stars
3029 group 2: The todo keyword, maybe
3030 group 3: Priority cookie
3031 group 4: True headline
3032 group 5: Tags")
3033 (make-variable-buffer-local 'org-complex-heading-regexp)
3034 (defvar org-todo-line-tags-regexp nil
3035 "Matches a headline and puts TODO state into group 2 if present.
3036 Also put tags into group 4 if tags are present.")
3037 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3038 (defvar org-nl-done-regexp nil
3039 "Matches newline followed by a headline with the DONE keyword.")
3040 (make-variable-buffer-local 'org-nl-done-regexp)
3041 (defvar org-looking-at-done-regexp nil
3042 "Matches the DONE keyword a point.")
3043 (make-variable-buffer-local 'org-looking-at-done-regexp)
3044 (defvar org-ds-keyword-length 12
3045 "Maximum length of the Deadline and SCHEDULED keywords.")
3046 (make-variable-buffer-local 'org-ds-keyword-length)
3047 (defvar org-deadline-regexp nil
3048 "Matches the DEADLINE keyword.")
3049 (make-variable-buffer-local 'org-deadline-regexp)
3050 (defvar org-deadline-time-regexp nil
3051 "Matches the DEADLINE keyword together with a time stamp.")
3052 (make-variable-buffer-local 'org-deadline-time-regexp)
3053 (defvar org-deadline-line-regexp nil
3054 "Matches the DEADLINE keyword and the rest of the line.")
3055 (make-variable-buffer-local 'org-deadline-line-regexp)
3056 (defvar org-scheduled-regexp nil
3057 "Matches the SCHEDULED keyword.")
3058 (make-variable-buffer-local 'org-scheduled-regexp)
3059 (defvar org-scheduled-time-regexp nil
3060 "Matches the SCHEDULED keyword together with a time stamp.")
3061 (make-variable-buffer-local 'org-scheduled-time-regexp)
3062 (defvar org-closed-time-regexp nil
3063 "Matches the CLOSED keyword together with a time stamp.")
3064 (make-variable-buffer-local 'org-closed-time-regexp)
3066 (defvar org-keyword-time-regexp nil
3067 "Matches any of the 4 keywords, together with the time stamp.")
3068 (make-variable-buffer-local 'org-keyword-time-regexp)
3069 (defvar org-keyword-time-not-clock-regexp nil
3070 "Matches any of the 3 keywords, together with the time stamp.")
3071 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3072 (defvar org-maybe-keyword-time-regexp nil
3073 "Matches a timestamp, possibly preceeded by a keyword.")
3074 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3075 (defvar org-planning-or-clock-line-re nil
3076 "Matches a line with planning or clock info.")
3077 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3079 (defconst org-plain-time-of-day-regexp
3080 (concat
3081 "\\(\\<[012]?[0-9]"
3082 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3083 "\\(--?"
3084 "\\(\\<[012]?[0-9]"
3085 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3086 "\\)?")
3087 "Regular expression to match a plain time or time range.
3088 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3089 groups carry important information:
3090 0 the full match
3091 1 the first time, range or not
3092 8 the second time, if it is a range.")
3094 (defconst org-plain-time-extension-regexp
3095 (concat
3096 "\\(\\<[012]?[0-9]"
3097 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3098 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3099 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3100 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3101 groups carry important information:
3102 0 the full match
3103 7 hours of duration
3104 9 minutes of duration")
3106 (defconst org-stamp-time-of-day-regexp
3107 (concat
3108 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3109 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3110 "\\(--?"
3111 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3112 "Regular expression to match a timestamp time or time range.
3113 After a match, the following groups carry important information:
3114 0 the full match
3115 1 date plus weekday, for backreferencing to make sure both times on same day
3116 2 the first time, range or not
3117 4 the second time, if it is a range.")
3119 (defconst org-startup-options
3120 '(("fold" org-startup-folded t)
3121 ("overview" org-startup-folded t)
3122 ("nofold" org-startup-folded nil)
3123 ("showall" org-startup-folded nil)
3124 ("content" org-startup-folded content)
3125 ("hidestars" org-hide-leading-stars t)
3126 ("showstars" org-hide-leading-stars nil)
3127 ("odd" org-odd-levels-only t)
3128 ("oddeven" org-odd-levels-only nil)
3129 ("align" org-startup-align-all-tables t)
3130 ("noalign" org-startup-align-all-tables nil)
3131 ("customtime" org-display-custom-times t)
3132 ("logdone" org-log-done time)
3133 ("lognotedone" org-log-done note)
3134 ("nologdone" org-log-done nil)
3135 ("lognoteclock-out" org-log-note-clock-out t)
3136 ("nolognoteclock-out" org-log-note-clock-out nil)
3137 ("logrepeat" org-log-repeat state)
3138 ("lognoterepeat" org-log-repeat note)
3139 ("nologrepeat" org-log-repeat nil)
3140 ("fninline" org-footnote-define-inline t)
3141 ("nofninline" org-footnote-define-inline nil)
3142 ("fnlocal" org-footnote-section nil)
3143 ("fnauto" org-footnote-auto-label t)
3144 ("fnprompt" org-footnote-auto-label nil)
3145 ("fnconfirm" org-footnote-auto-label confirm)
3146 ("fnplain" org-footnote-auto-label plain)
3147 ("constcgs" constants-unit-system cgs)
3148 ("constSI" constants-unit-system SI))
3149 "Variable associated with STARTUP options for org-mode.
3150 Each element is a list of three items: The startup options as written
3151 in the #+STARTUP line, the corresponding variable, and the value to
3152 set this variable to if the option is found. An optional forth element PUSH
3153 means to push this value onto the list in the variable.")
3155 (defun org-set-regexps-and-options ()
3156 "Precompute regular expressions for current buffer."
3157 (when (org-mode-p)
3158 (org-set-local 'org-todo-kwd-alist nil)
3159 (org-set-local 'org-todo-key-alist nil)
3160 (org-set-local 'org-todo-key-trigger nil)
3161 (org-set-local 'org-todo-keywords-1 nil)
3162 (org-set-local 'org-done-keywords nil)
3163 (org-set-local 'org-todo-heads nil)
3164 (org-set-local 'org-todo-sets nil)
3165 (org-set-local 'org-todo-log-states nil)
3166 (org-set-local 'org-file-properties nil)
3167 (org-set-local 'org-file-tags nil)
3168 (let ((re (org-make-options-regexp
3169 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3170 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3171 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3172 (splitre "[ \t]+")
3173 kwds kws0 kwsa key log value cat arch tags const links hw dws
3174 tail sep kws1 prio props ftags drawers
3175 ext-setup-or-nil setup-contents (start 0))
3176 (save-excursion
3177 (save-restriction
3178 (widen)
3179 (goto-char (point-min))
3180 (while (or (and ext-setup-or-nil
3181 (string-match re ext-setup-or-nil start)
3182 (setq start (match-end 0)))
3183 (and (setq ext-setup-or-nil nil start 0)
3184 (re-search-forward re nil t)))
3185 (setq key (upcase (match-string 1 ext-setup-or-nil))
3186 value (org-match-string-no-properties 2 ext-setup-or-nil))
3187 (cond
3188 ((equal key "CATEGORY")
3189 (if (string-match "[ \t]+$" value)
3190 (setq value (replace-match "" t t value)))
3191 (setq cat value))
3192 ((member key '("SEQ_TODO" "TODO"))
3193 (push (cons 'sequence (org-split-string value splitre)) kwds))
3194 ((equal key "TYP_TODO")
3195 (push (cons 'type (org-split-string value splitre)) kwds))
3196 ((equal key "TAGS")
3197 (setq tags (append tags (org-split-string value splitre))))
3198 ((equal key "COLUMNS")
3199 (org-set-local 'org-columns-default-format value))
3200 ((equal key "LINK")
3201 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3202 (push (cons (match-string 1 value)
3203 (org-trim (match-string 2 value)))
3204 links)))
3205 ((equal key "PRIORITIES")
3206 (setq prio (org-split-string value " +")))
3207 ((equal key "PROPERTY")
3208 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3209 (push (cons (match-string 1 value) (match-string 2 value))
3210 props)))
3211 ((equal key "FILETAGS")
3212 (when (string-match "\\S-" value)
3213 (setq ftags
3214 (append
3215 ftags
3216 (apply 'append
3217 (mapcar (lambda (x) (org-split-string x ":"))
3218 (org-split-string value)))))))
3219 ((equal key "DRAWERS")
3220 (setq drawers (org-split-string value splitre)))
3221 ((equal key "CONSTANTS")
3222 (setq const (append const (org-split-string value splitre))))
3223 ((equal key "STARTUP")
3224 (let ((opts (org-split-string value splitre))
3225 l var val)
3226 (while (setq l (pop opts))
3227 (when (setq l (assoc l org-startup-options))
3228 (setq var (nth 1 l) val (nth 2 l))
3229 (if (not (nth 3 l))
3230 (set (make-local-variable var) val)
3231 (if (not (listp (symbol-value var)))
3232 (set (make-local-variable var) nil))
3233 (set (make-local-variable var) (symbol-value var))
3234 (add-to-list var val))))))
3235 ((equal key "ARCHIVE")
3236 (string-match " *$" value)
3237 (setq arch (replace-match "" t t value))
3238 (remove-text-properties 0 (length arch)
3239 '(face t fontified t) arch))
3240 ((equal key "SETUPFILE")
3241 (setq setup-contents (org-file-contents
3242 (expand-file-name
3243 (org-remove-double-quotes value))
3244 'noerror))
3245 (if (not ext-setup-or-nil)
3246 (setq ext-setup-or-nil setup-contents start 0)
3247 (setq ext-setup-or-nil
3248 (concat (substring ext-setup-or-nil 0 start)
3249 "\n" setup-contents "\n"
3250 (substring ext-setup-or-nil start)))))
3251 ))))
3252 (when cat
3253 (org-set-local 'org-category (intern cat))
3254 (push (cons "CATEGORY" cat) props))
3255 (when prio
3256 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3257 (setq prio (mapcar 'string-to-char prio))
3258 (org-set-local 'org-highest-priority (nth 0 prio))
3259 (org-set-local 'org-lowest-priority (nth 1 prio))
3260 (org-set-local 'org-default-priority (nth 2 prio)))
3261 (and props (org-set-local 'org-file-properties (nreverse props)))
3262 (and ftags (org-set-local 'org-file-tags ftags))
3263 (and drawers (org-set-local 'org-drawers drawers))
3264 (and arch (org-set-local 'org-archive-location arch))
3265 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3266 ;; Process the TODO keywords
3267 (unless kwds
3268 ;; Use the global values as if they had been given locally.
3269 (setq kwds (default-value 'org-todo-keywords))
3270 (if (stringp (car kwds))
3271 (setq kwds (list (cons org-todo-interpretation
3272 (default-value 'org-todo-keywords)))))
3273 (setq kwds (reverse kwds)))
3274 (setq kwds (nreverse kwds))
3275 (let (inter kws kw)
3276 (while (setq kws (pop kwds))
3277 (setq inter (pop kws) sep (member "|" kws)
3278 kws0 (delete "|" (copy-sequence kws))
3279 kwsa nil
3280 kws1 (mapcar
3281 (lambda (x)
3282 ;; 1 2
3283 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3284 (progn
3285 (setq kw (match-string 1 x)
3286 key (and (match-end 2) (match-string 2 x))
3287 log (org-extract-log-state-settings x))
3288 (push (cons kw (and key (string-to-char key))) kwsa)
3289 (and log (push log org-todo-log-states))
3291 (error "Invalid TODO keyword %s" x)))
3292 kws0)
3293 kwsa (if kwsa (append '((:startgroup))
3294 (nreverse kwsa)
3295 '((:endgroup))))
3296 hw (car kws1)
3297 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3298 tail (list inter hw (car dws) (org-last dws)))
3299 (add-to-list 'org-todo-heads hw 'append)
3300 (push kws1 org-todo-sets)
3301 (setq org-done-keywords (append org-done-keywords dws nil))
3302 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3303 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3304 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3305 (setq org-todo-sets (nreverse org-todo-sets)
3306 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3307 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3308 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3309 ;; Process the constants
3310 (when const
3311 (let (e cst)
3312 (while (setq e (pop const))
3313 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3314 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3315 (setq org-table-formula-constants-local cst)))
3317 ;; Process the tags.
3318 (when tags
3319 (let (e tgs)
3320 (while (setq e (pop tags))
3321 (cond
3322 ((equal e "{") (push '(:startgroup) tgs))
3323 ((equal e "}") (push '(:endgroup) tgs))
3324 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3325 (push (cons (match-string 1 e)
3326 (string-to-char (match-string 2 e)))
3327 tgs))
3328 (t (push (list e) tgs))))
3329 (org-set-local 'org-tag-alist nil)
3330 (while (setq e (pop tgs))
3331 (or (and (stringp (car e))
3332 (assoc (car e) org-tag-alist))
3333 (push e org-tag-alist)))))
3335 ;; Compute the regular expressions and other local variables
3336 (if (not org-done-keywords)
3337 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3338 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3339 (length org-scheduled-string)
3340 (length org-clock-string)
3341 (length org-closed-string)))
3342 org-drawer-regexp
3343 (concat "^[ \t]*:\\("
3344 (mapconcat 'regexp-quote org-drawers "\\|")
3345 "\\):[ \t]*$")
3346 org-not-done-keywords
3347 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3348 org-todo-regexp
3349 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3350 "\\|") "\\)\\>")
3351 org-not-done-regexp
3352 (concat "\\<\\("
3353 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3354 "\\)\\>")
3355 org-todo-line-regexp
3356 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3357 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3358 "\\)\\>\\)?[ \t]*\\(.*\\)")
3359 org-complex-heading-regexp
3360 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3361 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3362 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3363 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3364 org-nl-done-regexp
3365 (concat "\n\\*+[ \t]+"
3366 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3367 "\\)" "\\>")
3368 org-todo-line-tags-regexp
3369 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3370 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3371 (org-re
3372 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3373 org-looking-at-done-regexp
3374 (concat "^" "\\(?:"
3375 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3376 "\\>")
3377 org-deadline-regexp (concat "\\<" org-deadline-string)
3378 org-deadline-time-regexp
3379 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3380 org-deadline-line-regexp
3381 (concat "\\<\\(" org-deadline-string "\\).*")
3382 org-scheduled-regexp
3383 (concat "\\<" org-scheduled-string)
3384 org-scheduled-time-regexp
3385 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3386 org-closed-time-regexp
3387 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3388 org-keyword-time-regexp
3389 (concat "\\<\\(" org-scheduled-string
3390 "\\|" org-deadline-string
3391 "\\|" org-closed-string
3392 "\\|" org-clock-string "\\)"
3393 " *[[<]\\([^]>]+\\)[]>]")
3394 org-keyword-time-not-clock-regexp
3395 (concat "\\<\\(" org-scheduled-string
3396 "\\|" org-deadline-string
3397 "\\|" org-closed-string
3398 "\\)"
3399 " *[[<]\\([^]>]+\\)[]>]")
3400 org-maybe-keyword-time-regexp
3401 (concat "\\(\\<\\(" org-scheduled-string
3402 "\\|" org-deadline-string
3403 "\\|" org-closed-string
3404 "\\|" org-clock-string "\\)\\)?"
3405 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3406 org-planning-or-clock-line-re
3407 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3408 "\\|" org-deadline-string
3409 "\\|" org-closed-string "\\|" org-clock-string
3410 "\\)\\>\\)")
3412 (org-compute-latex-and-specials-regexp)
3413 (org-set-font-lock-defaults))))
3415 (defun org-file-contents (file &optional noerror)
3416 "Return the contents of FILE, as a string."
3417 (if (or (not file)
3418 (not (file-readable-p file)))
3419 (if noerror
3420 (progn
3421 (message "Cannot read file %s" file)
3422 (ding) (sit-for 2)
3424 (error "Cannot read file %s" file))
3425 (with-temp-buffer
3426 (insert-file-contents file)
3427 (buffer-string))))
3429 (defun org-extract-log-state-settings (x)
3430 "Extract the log state setting from a TODO keyword string.
3431 This will extract info from a string like \"WAIT(w@/!)\"."
3432 (let (kw key log1 log2)
3433 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3434 (setq kw (match-string 1 x)
3435 key (and (match-end 2) (match-string 2 x))
3436 log1 (and (match-end 3) (match-string 3 x))
3437 log2 (and (match-end 4) (match-string 4 x)))
3438 (and (or log1 log2)
3439 (list kw
3440 (and log1 (if (equal log1 "!") 'time 'note))
3441 (and log2 (if (equal log2 "!") 'time 'note)))))))
3443 (defun org-remove-keyword-keys (list)
3444 "Remove a pair of parenthesis at the end of each string in LIST."
3445 (mapcar (lambda (x)
3446 (if (string-match "(.*)$" x)
3447 (substring x 0 (match-beginning 0))
3449 list))
3451 ;; FIXME: this could be done much better, using second characters etc.
3452 (defun org-assign-fast-keys (alist)
3453 "Assign fast keys to a keyword-key alist.
3454 Respect keys that are already there."
3455 (let (new e k c c1 c2 (char ?a))
3456 (while (setq e (pop alist))
3457 (cond
3458 ((equal e '(:startgroup)) (push e new))
3459 ((equal e '(:endgroup)) (push e new))
3461 (setq k (car e) c2 nil)
3462 (if (cdr e)
3463 (setq c (cdr e))
3464 ;; automatically assign a character.
3465 (setq c1 (string-to-char
3466 (downcase (substring
3467 k (if (= (string-to-char k) ?@) 1 0)))))
3468 (if (or (rassoc c1 new) (rassoc c1 alist))
3469 (while (or (rassoc char new) (rassoc char alist))
3470 (setq char (1+ char)))
3471 (setq c2 c1))
3472 (setq c (or c2 char)))
3473 (push (cons k c) new))))
3474 (nreverse new)))
3476 ;;; Some variables used in various places
3478 (defvar org-window-configuration nil
3479 "Used in various places to store a window configuration.")
3480 (defvar org-finish-function nil
3481 "Function to be called when `C-c C-c' is used.
3482 This is for getting out of special buffers like remember.")
3485 ;; FIXME: Occasionally check by commenting these, to make sure
3486 ;; no other functions uses these, forgetting to let-bind them.
3487 (defvar entry)
3488 (defvar state)
3489 (defvar last-state)
3490 (defvar date)
3491 (defvar description)
3493 ;; Defined somewhere in this file, but used before definition.
3494 (defvar org-html-entities)
3495 (defvar org-struct-menu)
3496 (defvar org-org-menu)
3497 (defvar org-tbl-menu)
3498 (defvar org-agenda-keymap)
3500 ;;;; Define the Org-mode
3502 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3503 (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."))
3506 ;; We use a before-change function to check if a table might need
3507 ;; an update.
3508 (defvar org-table-may-need-update t
3509 "Indicates that a table might need an update.
3510 This variable is set by `org-before-change-function'.
3511 `org-table-align' sets it back to nil.")
3512 (defun org-before-change-function (beg end)
3513 "Every change indicates that a table might need an update."
3514 (setq org-table-may-need-update t))
3515 (defvar org-mode-map)
3516 (defvar org-mode-hook nil
3517 "Mode hook for Org-mode, run after the mode was turned on.")
3518 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3519 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3520 (defvar org-table-buffer-is-an nil)
3521 (defconst org-outline-regexp "\\*+ ")
3523 ;;;###autoload
3524 (define-derived-mode org-mode outline-mode "Org"
3525 "Outline-based notes management and organizer, alias
3526 \"Carsten's outline-mode for keeping track of everything.\"
3528 Org-mode develops organizational tasks around a NOTES file which
3529 contains information about projects as plain text. Org-mode is
3530 implemented on top of outline-mode, which is ideal to keep the content
3531 of large files well structured. It supports ToDo items, deadlines and
3532 time stamps, which magically appear in the diary listing of the Emacs
3533 calendar. Tables are easily created with a built-in table editor.
3534 Plain text URL-like links connect to websites, emails (VM), Usenet
3535 messages (Gnus), BBDB entries, and any files related to the project.
3536 For printing and sharing of notes, an Org-mode file (or a part of it)
3537 can be exported as a structured ASCII or HTML file.
3539 The following commands are available:
3541 \\{org-mode-map}"
3543 ;; Get rid of Outline menus, they are not needed
3544 ;; Need to do this here because define-derived-mode sets up
3545 ;; the keymap so late. Still, it is a waste to call this each time
3546 ;; we switch another buffer into org-mode.
3547 (if (featurep 'xemacs)
3548 (when (boundp 'outline-mode-menu-heading)
3549 ;; Assume this is Greg's port, it used easymenu
3550 (easy-menu-remove outline-mode-menu-heading)
3551 (easy-menu-remove outline-mode-menu-show)
3552 (easy-menu-remove outline-mode-menu-hide))
3553 (define-key org-mode-map [menu-bar headings] 'undefined)
3554 (define-key org-mode-map [menu-bar hide] 'undefined)
3555 (define-key org-mode-map [menu-bar show] 'undefined))
3557 (org-load-modules-maybe)
3558 (easy-menu-add org-org-menu)
3559 (easy-menu-add org-tbl-menu)
3560 (org-install-agenda-files-menu)
3561 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3562 (org-add-to-invisibility-spec '(org-cwidth))
3563 (when (featurep 'xemacs)
3564 (org-set-local 'line-move-ignore-invisible t))
3565 (org-set-local 'outline-regexp org-outline-regexp)
3566 (org-set-local 'outline-level 'org-outline-level)
3567 (when (and org-ellipsis
3568 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3569 (fboundp 'make-glyph-code))
3570 (unless org-display-table
3571 (setq org-display-table (make-display-table)))
3572 (set-display-table-slot
3573 org-display-table 4
3574 (vconcat (mapcar
3575 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3576 org-ellipsis)))
3577 (if (stringp org-ellipsis) org-ellipsis "..."))))
3578 (setq buffer-display-table org-display-table))
3579 (org-set-regexps-and-options)
3580 (when (and org-tag-faces (not org-tags-special-faces-re))
3581 ;; tag faces set outside customize.... force initialization.
3582 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3583 ;; Calc embedded
3584 (org-set-local 'calc-embedded-open-mode "# ")
3585 (modify-syntax-entry ?# "<")
3586 (modify-syntax-entry ?@ "w")
3587 (if org-startup-truncated (setq truncate-lines t))
3588 (org-set-local 'font-lock-unfontify-region-function
3589 'org-unfontify-region)
3590 ;; Activate before-change-function
3591 (org-set-local 'org-table-may-need-update t)
3592 (org-add-hook 'before-change-functions 'org-before-change-function nil
3593 'local)
3594 ;; Check for running clock before killing a buffer
3595 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3596 ;; Paragraphs and auto-filling
3597 (org-set-autofill-regexps)
3598 (setq indent-line-function 'org-indent-line-function)
3599 (org-update-radio-target-regexp)
3600 ;; Make sure dependence stuff works reliably, even for users who set it
3601 ;; too late :-(
3602 (if org-enforce-todo-dependencies
3603 (add-hook 'org-blocker-hook
3604 'org-block-todo-from-children-or-siblings)
3605 (remove-hook 'org-blocker-hook
3606 'org-block-todo-from-children-or-siblings))
3607 (if org-enforce-todo-checkbox-dependencies
3608 (add-hook 'org-blocker-hook
3609 'org-block-todo-from-checkboxes)
3610 (remove-hook 'org-blocker-hook
3611 'org-block-todo-from-checkboxes))
3613 ;; Comment characters
3614 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3615 (org-set-local 'comment-padding " ")
3617 ;; Align options lines
3618 (org-set-local
3619 'align-mode-rules-list
3620 '((org-in-buffer-settings
3621 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3622 (modes . '(org-mode)))))
3624 ;; Imenu
3625 (org-set-local 'imenu-create-index-function
3626 'org-imenu-get-tree)
3628 ;; Make isearch reveal context
3629 (if (or (featurep 'xemacs)
3630 (not (boundp 'outline-isearch-open-invisible-function)))
3631 ;; Emacs 21 and XEmacs make use of the hook
3632 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3633 ;; Emacs 22 deals with this through a special variable
3634 (org-set-local 'outline-isearch-open-invisible-function
3635 (lambda (&rest ignore) (org-show-context 'isearch))))
3637 ;; If empty file that did not turn on org-mode automatically, make it to.
3638 (if (and org-insert-mode-line-in-empty-file
3639 (interactive-p)
3640 (= (point-min) (point-max)))
3641 (insert "# -*- mode: org -*-\n\n"))
3643 (unless org-inhibit-startup
3644 (when org-startup-align-all-tables
3645 (let ((bmp (buffer-modified-p)))
3646 (org-table-map-tables 'org-table-align)
3647 (set-buffer-modified-p bmp)))
3648 (org-set-startup-visibility)))
3650 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3652 (defun org-current-time ()
3653 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3654 (if (> (car org-time-stamp-rounding-minutes) 1)
3655 (let ((r (car org-time-stamp-rounding-minutes))
3656 (time (decode-time)))
3657 (apply 'encode-time
3658 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3659 (nthcdr 2 time))))
3660 (current-time)))
3662 ;;;; Font-Lock stuff, including the activators
3664 (defvar org-mouse-map (make-sparse-keymap))
3665 (org-defkey org-mouse-map
3666 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3667 (org-defkey org-mouse-map
3668 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3669 (when org-mouse-1-follows-link
3670 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3671 (when org-tab-follows-link
3672 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3673 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3674 (when org-return-follows-link
3675 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3676 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3678 (require 'font-lock)
3680 (defconst org-non-link-chars "]\t\n\r<>")
3681 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3682 "shell" "elisp"))
3683 (defvar org-link-types-re nil
3684 "Matches a link that has a url-like prefix like \"http:\"")
3685 (defvar org-link-re-with-space nil
3686 "Matches a link with spaces, optional angular brackets around it.")
3687 (defvar org-link-re-with-space2 nil
3688 "Matches a link with spaces, optional angular brackets around it.")
3689 (defvar org-link-re-with-space3 nil
3690 "Matches a link with spaces, only for internal part in bracket links.")
3691 (defvar org-angle-link-re nil
3692 "Matches link with angular brackets, spaces are allowed.")
3693 (defvar org-plain-link-re nil
3694 "Matches plain link, without spaces.")
3695 (defvar org-bracket-link-regexp nil
3696 "Matches a link in double brackets.")
3697 (defvar org-bracket-link-analytic-regexp nil
3698 "Regular expression used to analyze links.
3699 Here is what the match groups contain after a match:
3700 1: http:
3701 2: http
3702 3: path
3703 4: [desc]
3704 5: desc")
3705 (defvar org-bracket-link-analytic-regexp++ nil
3706 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3707 (defvar org-any-link-re nil
3708 "Regular expression matching any link.")
3710 (defun org-make-link-regexps ()
3711 "Update the link regular expressions.
3712 This should be called after the variable `org-link-types' has changed."
3713 (setq org-link-types-re
3714 (concat
3715 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3716 org-link-re-with-space
3717 (concat
3718 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3719 "\\([^" org-non-link-chars " ]"
3720 "[^" org-non-link-chars "]*"
3721 "[^" org-non-link-chars " ]\\)>?")
3722 org-link-re-with-space2
3723 (concat
3724 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3725 "\\([^" org-non-link-chars " ]"
3726 "[^\t\n\r]*"
3727 "[^" org-non-link-chars " ]\\)>?")
3728 org-link-re-with-space3
3729 (concat
3730 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3731 "\\([^" org-non-link-chars " ]"
3732 "[^\t\n\r]*\\)")
3733 org-angle-link-re
3734 (concat
3735 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3736 "\\([^" org-non-link-chars " ]"
3737 "[^" org-non-link-chars "]*"
3738 "\\)>")
3739 org-plain-link-re
3740 (concat
3741 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3742 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3743 org-bracket-link-regexp
3744 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3745 org-bracket-link-analytic-regexp
3746 (concat
3747 "\\[\\["
3748 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3749 "\\([^]]+\\)"
3750 "\\]"
3751 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3752 "\\]")
3753 org-bracket-link-analytic-regexp++
3754 (concat
3755 "\\[\\["
3756 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3757 "\\([^]]+\\)"
3758 "\\]"
3759 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3760 "\\]")
3761 org-any-link-re
3762 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3763 org-angle-link-re "\\)\\|\\("
3764 org-plain-link-re "\\)")))
3766 (org-make-link-regexps)
3768 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3769 "Regular expression for fast time stamp matching.")
3770 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3771 "Regular expression for fast time stamp matching.")
3772 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3773 "Regular expression matching time strings for analysis.
3774 This one does not require the space after the date, so it can be used
3775 on a string that terminates immediately after the date.")
3776 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3777 "Regular expression matching time strings for analysis.")
3778 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3779 "Regular expression matching time stamps, with groups.")
3780 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3781 "Regular expression matching time stamps (also [..]), with groups.")
3782 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3783 "Regular expression matching a time stamp range.")
3784 (defconst org-tr-regexp-both
3785 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3786 "Regular expression matching a time stamp range.")
3787 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3788 org-ts-regexp "\\)?")
3789 "Regular expression matching a time stamp or time stamp range.")
3790 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3791 org-ts-regexp-both "\\)?")
3792 "Regular expression matching a time stamp or time stamp range.
3793 The time stamps may be either active or inactive.")
3795 (defvar org-emph-face nil)
3797 (defun org-do-emphasis-faces (limit)
3798 "Run through the buffer and add overlays to links."
3799 (let (rtn)
3800 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3801 (if (not (= (char-after (match-beginning 3))
3802 (char-after (match-beginning 4))))
3803 (progn
3804 (setq rtn t)
3805 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3806 'face
3807 (nth 1 (assoc (match-string 3)
3808 org-emphasis-alist)))
3809 (add-text-properties (match-beginning 2) (match-end 2)
3810 '(font-lock-multiline t))
3811 (when org-hide-emphasis-markers
3812 (add-text-properties (match-end 4) (match-beginning 5)
3813 '(invisible org-link))
3814 (add-text-properties (match-beginning 3) (match-end 3)
3815 '(invisible org-link)))))
3816 (backward-char 1))
3817 rtn))
3819 (defun org-emphasize (&optional char)
3820 "Insert or change an emphasis, i.e. a font like bold or italic.
3821 If there is an active region, change that region to a new emphasis.
3822 If there is no region, just insert the marker characters and position
3823 the cursor between them.
3824 CHAR should be either the marker character, or the first character of the
3825 HTML tag associated with that emphasis. If CHAR is a space, the means
3826 to remove the emphasis of the selected region.
3827 If char is not given (for example in an interactive call) it
3828 will be prompted for."
3829 (interactive)
3830 (let ((eal org-emphasis-alist) e det
3831 (erc org-emphasis-regexp-components)
3832 (prompt "")
3833 (string "") beg end move tag c s)
3834 (if (org-region-active-p)
3835 (setq beg (region-beginning) end (region-end)
3836 string (buffer-substring beg end))
3837 (setq move t))
3839 (while (setq e (pop eal))
3840 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3841 c (aref tag 0))
3842 (push (cons c (string-to-char (car e))) det)
3843 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3844 (substring tag 1)))))
3845 (setq det (nreverse det))
3846 (unless char
3847 (message "%s" (concat "Emphasis marker or tag:" prompt))
3848 (setq char (read-char-exclusive)))
3849 (setq char (or (cdr (assoc char det)) char))
3850 (if (equal char ?\ )
3851 (setq s "" move nil)
3852 (unless (assoc (char-to-string char) org-emphasis-alist)
3853 (error "No such emphasis marker: \"%c\"" char))
3854 (setq s (char-to-string char)))
3855 (while (and (> (length string) 1)
3856 (equal (substring string 0 1) (substring string -1))
3857 (assoc (substring string 0 1) org-emphasis-alist))
3858 (setq string (substring string 1 -1)))
3859 (setq string (concat s string s))
3860 (if beg (delete-region beg end))
3861 (unless (or (bolp)
3862 (string-match (concat "[" (nth 0 erc) "\n]")
3863 (char-to-string (char-before (point)))))
3864 (insert " "))
3865 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3866 (char-to-string (char-after (point))))
3867 (insert " ") (backward-char 1))
3868 (insert string)
3869 (and move (backward-char 1))))
3871 (defconst org-nonsticky-props
3872 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3875 (defun org-activate-plain-links (limit)
3876 "Run through the buffer and add overlays to links."
3877 (catch 'exit
3878 (let (f)
3879 (while (re-search-forward org-plain-link-re limit t)
3880 (setq f (get-text-property (match-beginning 0) 'face))
3881 (if (or (eq f 'org-tag)
3882 (and (listp f) (memq 'org-tag f)))
3884 (add-text-properties (match-beginning 0) (match-end 0)
3885 (list 'mouse-face 'highlight
3886 'rear-nonsticky org-nonsticky-props
3887 'keymap org-mouse-map
3889 (throw 'exit t))))))
3891 (defun org-activate-code (limit)
3892 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3893 (progn
3894 (remove-text-properties (match-beginning 0) (match-end 0)
3895 '(display t invisible t intangible t))
3896 t)))
3898 (defun org-activate-angle-links (limit)
3899 "Run through the buffer and add overlays to links."
3900 (if (re-search-forward org-angle-link-re limit t)
3901 (progn
3902 (add-text-properties (match-beginning 0) (match-end 0)
3903 (list 'mouse-face 'highlight
3904 'rear-nonsticky org-nonsticky-props
3905 'keymap org-mouse-map
3907 t)))
3909 (defun org-activate-footnote-links (limit)
3910 "Run through the buffer and add overlays to links."
3911 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3912 limit t)
3913 (progn
3914 (add-text-properties (match-beginning 2) (match-end 2)
3915 (list 'mouse-face 'highlight
3916 'rear-nonsticky org-nonsticky-props
3917 'keymap org-mouse-map
3918 'help-echo
3919 (if (= (point-at-bol) (match-beginning 2))
3920 "Footnote definition"
3921 "Footnote reference")
3923 t)))
3925 (defun org-activate-bracket-links (limit)
3926 "Run through the buffer and add overlays to bracketed links."
3927 (if (re-search-forward org-bracket-link-regexp limit t)
3928 (let* ((help (concat "LINK: "
3929 (org-match-string-no-properties 1)))
3930 ;; FIXME: above we should remove the escapes.
3931 ;; but that requires another match, protecting match data,
3932 ;; a lot of overhead for font-lock.
3933 (ip (org-maybe-intangible
3934 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3935 'keymap org-mouse-map 'mouse-face 'highlight
3936 'font-lock-multiline t 'help-echo help)))
3937 (vp (list 'rear-nonsticky org-nonsticky-props
3938 'keymap org-mouse-map 'mouse-face 'highlight
3939 ' font-lock-multiline t 'help-echo help)))
3940 ;; We need to remove the invisible property here. Table narrowing
3941 ;; may have made some of this invisible.
3942 (remove-text-properties (match-beginning 0) (match-end 0)
3943 '(invisible nil))
3944 (if (match-end 3)
3945 (progn
3946 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3947 (add-text-properties (match-beginning 3) (match-end 3) vp)
3948 (add-text-properties (match-end 3) (match-end 0) ip))
3949 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3950 (add-text-properties (match-beginning 1) (match-end 1) vp)
3951 (add-text-properties (match-end 1) (match-end 0) ip))
3952 t)))
3954 (defun org-activate-dates (limit)
3955 "Run through the buffer and add overlays to dates."
3956 (if (re-search-forward org-tsr-regexp-both limit t)
3957 (progn
3958 (add-text-properties (match-beginning 0) (match-end 0)
3959 (list 'mouse-face 'highlight
3960 'rear-nonsticky org-nonsticky-props
3961 'keymap org-mouse-map))
3962 (when org-display-custom-times
3963 (if (match-end 3)
3964 (org-display-custom-time (match-beginning 3) (match-end 3)))
3965 (org-display-custom-time (match-beginning 1) (match-end 1)))
3966 t)))
3968 (defvar org-target-link-regexp nil
3969 "Regular expression matching radio targets in plain text.")
3970 (make-variable-buffer-local 'org-target-link-regexp)
3971 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3972 "Regular expression matching a link target.")
3973 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3974 "Regular expression matching a radio target.")
3975 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3976 "Regular expression matching any target.")
3978 (defun org-activate-target-links (limit)
3979 "Run through the buffer and add overlays to target matches."
3980 (when org-target-link-regexp
3981 (let ((case-fold-search t))
3982 (if (re-search-forward org-target-link-regexp limit t)
3983 (progn
3984 (add-text-properties (match-beginning 0) (match-end 0)
3985 (list 'mouse-face 'highlight
3986 'rear-nonsticky org-nonsticky-props
3987 'keymap org-mouse-map
3988 'help-echo "Radio target link"
3989 'org-linked-text t))
3990 t)))))
3992 (defun org-update-radio-target-regexp ()
3993 "Find all radio targets in this file and update the regular expression."
3994 (interactive)
3995 (when (memq 'radio org-activate-links)
3996 (setq org-target-link-regexp
3997 (org-make-target-link-regexp (org-all-targets 'radio)))
3998 (org-restart-font-lock)))
4000 (defun org-hide-wide-columns (limit)
4001 (let (s e)
4002 (setq s (text-property-any (point) (or limit (point-max))
4003 'org-cwidth t))
4004 (when s
4005 (setq e (next-single-property-change s 'org-cwidth))
4006 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4007 (goto-char e)
4008 t)))
4010 (defvar org-latex-and-specials-regexp nil
4011 "Regular expression for highlighting export special stuff.")
4012 (defvar org-match-substring-regexp)
4013 (defvar org-match-substring-with-braces-regexp)
4014 (defvar org-export-html-special-string-regexps)
4016 (defun org-compute-latex-and-specials-regexp ()
4017 "Compute regular expression for stuff treated specially by exporters."
4018 (if (not org-highlight-latex-fragments-and-specials)
4019 (org-set-local 'org-latex-and-specials-regexp nil)
4020 (require 'org-exp)
4021 (let*
4022 ((matchers (plist-get org-format-latex-options :matchers))
4023 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4024 org-latex-regexps)))
4025 (options (org-combine-plists (org-default-export-plist)
4026 (org-infile-export-plist)))
4027 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4028 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4029 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4030 (org-export-html-expand (plist-get options :expand-quoted-html))
4031 (org-export-with-special-strings (plist-get options :special-strings))
4032 (re-sub
4033 (cond
4034 ((equal org-export-with-sub-superscripts '{})
4035 (list org-match-substring-with-braces-regexp))
4036 (org-export-with-sub-superscripts
4037 (list org-match-substring-regexp))
4038 (t nil)))
4039 (re-latex
4040 (if org-export-with-LaTeX-fragments
4041 (mapcar (lambda (x) (nth 1 x)) latexs)))
4042 (re-macros
4043 (if org-export-with-TeX-macros
4044 (list (concat "\\\\"
4045 (regexp-opt
4046 (append (mapcar 'car org-html-entities)
4047 (if (boundp 'org-latex-entities)
4048 org-latex-entities nil))
4049 'words))) ; FIXME
4051 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4052 (re-special (if org-export-with-special-strings
4053 (mapcar (lambda (x) (car x))
4054 org-export-html-special-string-regexps)))
4055 (re-rest
4056 (delq nil
4057 (list
4058 (if org-export-html-expand "@<[^>\n]+>")
4059 ))))
4060 (org-set-local
4061 'org-latex-and-specials-regexp
4062 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4063 re-rest) "\\|")))))
4065 (defun org-do-latex-and-special-faces (limit)
4066 "Run through the buffer and add overlays to links."
4067 (when org-latex-and-specials-regexp
4068 (let (rtn d)
4069 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4070 limit t))
4071 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4072 'face))
4073 '(org-code org-verbatim underline)))
4074 (progn
4075 (setq rtn t
4076 d (cond ((member (char-after (1+ (match-beginning 0)))
4077 '(?_ ?^)) 1)
4078 (t 0)))
4079 (font-lock-prepend-text-property
4080 (+ d (match-beginning 0)) (match-end 0)
4081 'face 'org-latex-and-export-specials)
4082 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4083 '(font-lock-multiline t)))))
4084 rtn)))
4086 (defun org-restart-font-lock ()
4087 "Restart font-lock-mode, to force refontification."
4088 (when (and (boundp 'font-lock-mode) font-lock-mode)
4089 (font-lock-mode -1)
4090 (font-lock-mode 1)))
4092 (defun org-all-targets (&optional radio)
4093 "Return a list of all targets in this file.
4094 With optional argument RADIO, only find radio targets."
4095 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4096 rtn)
4097 (save-excursion
4098 (goto-char (point-min))
4099 (while (re-search-forward re nil t)
4100 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4101 rtn)))
4103 (defun org-make-target-link-regexp (targets)
4104 "Make regular expression matching all strings in TARGETS.
4105 The regular expression finds the targets also if there is a line break
4106 between words."
4107 (and targets
4108 (concat
4109 "\\<\\("
4110 (mapconcat
4111 (lambda (x)
4112 (while (string-match " +" x)
4113 (setq x (replace-match "\\s-+" t t x)))
4115 targets
4116 "\\|")
4117 "\\)\\>")))
4119 (defun org-activate-tags (limit)
4120 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4121 (progn
4122 (add-text-properties (match-beginning 1) (match-end 1)
4123 (list 'mouse-face 'highlight
4124 'rear-nonsticky org-nonsticky-props
4125 'keymap org-mouse-map))
4126 t)))
4128 (defun org-outline-level ()
4129 (save-excursion
4130 (looking-at outline-regexp)
4131 (if (match-beginning 1)
4132 (+ (org-get-string-indentation (match-string 1)) 1000)
4133 (1- (- (match-end 0) (match-beginning 0))))))
4135 (defvar org-font-lock-keywords nil)
4137 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4138 "Regular expression matching a property line.")
4140 (defvar org-font-lock-hook nil
4141 "Functions to be called for special font lock stuff.")
4143 (defun org-font-lock-hook (limit)
4144 (run-hook-with-args 'org-font-lock-hook limit))
4146 (defun org-set-font-lock-defaults ()
4147 (let* ((em org-fontify-emphasized-text)
4148 (lk org-activate-links)
4149 (org-font-lock-extra-keywords
4150 (list
4151 ;; Call the hook
4152 '(org-font-lock-hook)
4153 ;; Headlines
4154 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4155 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4156 ;; Table lines
4157 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4158 (1 'org-table t))
4159 ;; Table internals
4160 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4161 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4162 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4163 ;; Drawers
4164 (list org-drawer-regexp '(0 'org-special-keyword t))
4165 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4166 ;; Properties
4167 (list org-property-re
4168 '(1 'org-special-keyword t)
4169 '(3 'org-property-value t))
4170 (if org-format-transports-properties-p
4171 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4172 ;; Links
4173 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4174 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4175 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4176 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4177 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4178 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4179 (if (memq 'footnote lk) '(org-activate-footnote-links
4180 (2 'org-footnote t)))
4181 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4182 '(org-hide-wide-columns (0 nil append))
4183 ;; TODO lines
4184 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4185 '(1 (org-get-todo-face 1) t))
4186 ;; DONE
4187 (if org-fontify-done-headline
4188 (list (concat "^[*]+ +\\<\\("
4189 (mapconcat 'regexp-quote org-done-keywords "\\|")
4190 "\\)\\(.*\\)")
4191 '(2 'org-headline-done t))
4192 nil)
4193 ;; Priorities
4194 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4195 ;; Tags
4196 '(org-font-lock-add-tag-faces)
4197 ;; Special keywords
4198 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4199 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4200 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4201 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4202 ;; Emphasis
4203 (if em
4204 (if (featurep 'xemacs)
4205 '(org-do-emphasis-faces (0 nil append))
4206 '(org-do-emphasis-faces)))
4207 ;; Checkboxes
4208 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4209 2 'bold prepend)
4210 (if org-provide-checkbox-statistics
4211 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4212 (0 (org-get-checkbox-statistics-face) t)))
4213 ;; Description list items
4214 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4215 2 'bold prepend)
4216 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4217 '(1 'org-archived prepend))
4218 ;; Specials
4219 '(org-do-latex-and-special-faces)
4220 ;; Code
4221 '(org-activate-code (1 'org-code t))
4222 ;; COMMENT
4223 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4224 "\\|" org-quote-string "\\)\\>")
4225 '(1 'org-special-keyword t))
4226 '("^#.*" (0 'font-lock-comment-face t))
4228 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4229 ;; Now set the full font-lock-keywords
4230 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4231 (org-set-local 'font-lock-defaults
4232 '(org-font-lock-keywords t nil nil backward-paragraph))
4233 (kill-local-variable 'font-lock-keywords) nil))
4235 (defvar org-m nil)
4236 (defvar org-l nil)
4237 (defvar org-f nil)
4238 (defun org-get-level-face (n)
4239 "Get the right face for match N in font-lock matching of headlines."
4240 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4241 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4242 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4243 (cond
4244 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4245 ((eq n 2) org-f)
4246 (t (if org-level-color-stars-only nil org-f))))
4248 (defun org-get-todo-face (kwd)
4249 "Get the right face for a TODO keyword KWD.
4250 If KWD is a number, get the corresponding match group."
4251 (if (numberp kwd) (setq kwd (match-string kwd)))
4252 (or (cdr (assoc kwd org-todo-keyword-faces))
4253 (and (member kwd org-done-keywords) 'org-done)
4254 'org-todo))
4256 (defun org-font-lock-add-tag-faces (limit)
4257 "Add the special tag faces."
4258 (when (and org-tag-faces org-tags-special-faces-re)
4259 (while (re-search-forward org-tags-special-faces-re limit t)
4260 (add-text-properties (match-beginning 1) (match-end 1)
4261 (list 'face (org-get-tag-face 1)
4262 'font-lock-fontified t))
4263 (backward-char 1))))
4265 (defun org-get-tag-face (kwd)
4266 "Get the right face for a TODO keyword KWD.
4267 If KWD is a number, get the corresponding match group."
4268 (if (numberp kwd) (setq kwd (match-string kwd)))
4269 (or (cdr (assoc kwd org-tag-faces))
4270 'org-tag))
4272 (defun org-unfontify-region (beg end &optional maybe_loudly)
4273 "Remove fontification and activation overlays from links."
4274 (font-lock-default-unfontify-region beg end)
4275 (let* ((buffer-undo-list t)
4276 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4277 (inhibit-modification-hooks t)
4278 deactivate-mark buffer-file-name buffer-file-truename)
4279 (remove-text-properties beg end
4280 '(mouse-face t keymap t org-linked-text t
4281 invisible t intangible t))))
4283 ;;;; Visibility cycling, including org-goto and indirect buffer
4285 ;;; Cycling
4287 (defvar org-cycle-global-status nil)
4288 (make-variable-buffer-local 'org-cycle-global-status)
4289 (defvar org-cycle-subtree-status nil)
4290 (make-variable-buffer-local 'org-cycle-subtree-status)
4292 ;;;###autoload
4293 (defun org-cycle (&optional arg)
4294 "Visibility cycling for Org-mode.
4296 - When this function is called with a prefix argument, rotate the entire
4297 buffer through 3 states (global cycling)
4298 1. OVERVIEW: Show only top-level headlines.
4299 2. CONTENTS: Show all headlines of all levels, but no body text.
4300 3. SHOW ALL: Show everything.
4301 When called with two C-u C-u prefixes, switch to the startup visibility,
4302 determined by the variable `org-startup-folded', and by any VISIBILITY
4303 properties in the buffer.
4304 When called with three C-u C-u C-u prefixed, show the entire buffer,
4305 including drawers.
4307 - When point is at the beginning of a headline, rotate the subtree started
4308 by this line through 3 different states (local cycling)
4309 1. FOLDED: Only the main headline is shown.
4310 2. CHILDREN: The main headline and the direct children are shown.
4311 From this state, you can move to one of the children
4312 and zoom in further.
4313 3. SUBTREE: Show the entire subtree, including body text.
4315 - When there is a numeric prefix, go up to a heading with level ARG, do
4316 a `show-subtree' and return to the previous cursor position. If ARG
4317 is negative, go up that many levels.
4319 - When point is not at the beginning of a headline, execute the global
4320 binding for TAB, which is re-indenting the line. See the option
4321 `org-cycle-emulate-tab' for details.
4323 - Special case: if point is at the beginning of the buffer and there is
4324 no headline in line 1, this function will act as if called with prefix arg.
4325 But only if also the variable `org-cycle-global-at-bob' is t."
4326 (interactive "P")
4327 (org-load-modules-maybe)
4328 (let* ((outline-regexp
4329 (if (and (org-mode-p) org-cycle-include-plain-lists)
4330 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4331 outline-regexp))
4332 (bob-special (and org-cycle-global-at-bob (bobp)
4333 (not (looking-at outline-regexp))))
4334 (org-cycle-hook
4335 (if bob-special
4336 (delq 'org-optimize-window-after-visibility-change
4337 (copy-sequence org-cycle-hook))
4338 org-cycle-hook))
4339 (pos (point)))
4341 (if (or bob-special (equal arg '(4)))
4342 ;; special case: use global cycling
4343 (setq arg t))
4345 (cond
4347 ((equal arg '(16))
4348 (org-set-startup-visibility)
4349 (message "Startup visibility, plus VISIBILITY properties"))
4351 ((equal arg '(64))
4352 (show-all)
4353 (message "Entire buffer visible, including drawers"))
4355 ((org-at-table-p 'any)
4356 ;; Enter the table or move to the next field in the table
4357 (or (org-table-recognize-table.el)
4358 (progn
4359 (if arg (org-table-edit-field t)
4360 (org-table-justify-field-maybe)
4361 (call-interactively 'org-table-next-field)))))
4363 ((eq arg t) ;; Global cycling
4365 (cond
4366 ((and (eq last-command this-command)
4367 (eq org-cycle-global-status 'overview))
4368 ;; We just created the overview - now do table of contents
4369 ;; This can be slow in very large buffers, so indicate action
4370 (message "CONTENTS...")
4371 (org-content)
4372 (message "CONTENTS...done")
4373 (setq org-cycle-global-status 'contents)
4374 (run-hook-with-args 'org-cycle-hook 'contents))
4376 ((and (eq last-command this-command)
4377 (eq org-cycle-global-status 'contents))
4378 ;; We just showed the table of contents - now show everything
4379 (show-all)
4380 (message "SHOW ALL")
4381 (setq org-cycle-global-status 'all)
4382 (run-hook-with-args 'org-cycle-hook 'all))
4385 ;; Default action: go to overview
4386 (org-overview)
4387 (message "OVERVIEW")
4388 (setq org-cycle-global-status 'overview)
4389 (run-hook-with-args 'org-cycle-hook 'overview))))
4391 ((and org-drawers org-drawer-regexp
4392 (save-excursion
4393 (beginning-of-line 1)
4394 (looking-at org-drawer-regexp)))
4395 ;; Toggle block visibility
4396 (org-flag-drawer
4397 (not (get-char-property (match-end 0) 'invisible))))
4399 ((integerp arg)
4400 ;; Show-subtree, ARG levels up from here.
4401 (save-excursion
4402 (org-back-to-heading)
4403 (outline-up-heading (if (< arg 0) (- arg)
4404 (- (funcall outline-level) arg)))
4405 (org-show-subtree)))
4407 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4408 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4409 ;; At a heading: rotate between three different views
4410 (org-back-to-heading)
4411 (let ((goal-column 0) eoh eol eos)
4412 ;; First, some boundaries
4413 (save-excursion
4414 (org-back-to-heading)
4415 (save-excursion
4416 (beginning-of-line 2)
4417 (while (and (not (eobp)) ;; this is like `next-line'
4418 (get-char-property (1- (point)) 'invisible))
4419 (beginning-of-line 2)) (setq eol (point)))
4420 (outline-end-of-heading) (setq eoh (point))
4421 (org-end-of-subtree t)
4422 (unless (eobp)
4423 (skip-chars-forward " \t\n")
4424 (beginning-of-line 1) ; in case this is an item
4426 (setq eos (1- (point))))
4427 ;; Find out what to do next and set `this-command'
4428 (cond
4429 ((= eos eoh)
4430 ;; Nothing is hidden behind this heading
4431 (message "EMPTY ENTRY")
4432 (setq org-cycle-subtree-status nil)
4433 (save-excursion
4434 (goto-char eos)
4435 (outline-next-heading)
4436 (if (org-invisible-p) (org-flag-heading nil))))
4437 ((or (>= eol eos)
4438 (not (string-match "\\S-" (buffer-substring eol eos))))
4439 ;; Entire subtree is hidden in one line: open it
4440 (org-show-entry)
4441 (show-children)
4442 (message "CHILDREN")
4443 (save-excursion
4444 (goto-char eos)
4445 (outline-next-heading)
4446 (if (org-invisible-p) (org-flag-heading nil)))
4447 (setq org-cycle-subtree-status 'children)
4448 (run-hook-with-args 'org-cycle-hook 'children))
4449 ((and (eq last-command this-command)
4450 (eq org-cycle-subtree-status 'children))
4451 ;; We just showed the children, now show everything.
4452 (org-show-subtree)
4453 (message "SUBTREE")
4454 (setq org-cycle-subtree-status 'subtree)
4455 (run-hook-with-args 'org-cycle-hook 'subtree))
4457 ;; Default action: hide the subtree.
4458 (hide-subtree)
4459 (message "FOLDED")
4460 (setq org-cycle-subtree-status 'folded)
4461 (run-hook-with-args 'org-cycle-hook 'folded)))))
4463 ;; TAB emulation and template completion
4464 (buffer-read-only (org-back-to-heading))
4466 ((org-try-structure-completion))
4468 ((org-try-cdlatex-tab))
4470 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4471 (or (not (bolp))
4472 (not (looking-at outline-regexp))))
4473 (call-interactively (global-key-binding "\t")))
4475 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4476 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4477 (or (and (eq org-cycle-emulate-tab 'white)
4478 (= (match-end 0) (point-at-eol)))
4479 (and (eq org-cycle-emulate-tab 'whitestart)
4480 (>= (match-end 0) pos))))
4482 (eq org-cycle-emulate-tab t))
4483 (call-interactively (global-key-binding "\t")))
4485 (t (save-excursion
4486 (org-back-to-heading)
4487 (org-cycle))))))
4489 ;;;###autoload
4490 (defun org-global-cycle (&optional arg)
4491 "Cycle the global visibility. For details see `org-cycle'.
4492 With C-u prefix arg, switch to startup visibility.
4493 With a numeric prefix, show all headlines up to that level."
4494 (interactive "P")
4495 (let ((org-cycle-include-plain-lists
4496 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4497 (cond
4498 ((integerp arg)
4499 (show-all)
4500 (hide-sublevels arg)
4501 (setq org-cycle-global-status 'contents))
4502 ((equal arg '(4))
4503 (org-set-startup-visibility)
4504 (message "Startup visibility, plus VISIBILITY properties."))
4506 (org-cycle '(4))))))
4508 (defun org-set-startup-visibility ()
4509 "Set the visibility required by startup options and properties."
4510 (cond
4511 ((eq org-startup-folded t)
4512 (org-cycle '(4)))
4513 ((eq org-startup-folded 'content)
4514 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4515 (org-cycle '(4)) (org-cycle '(4)))))
4516 (org-set-visibility-according-to-property 'no-cleanup)
4517 (org-cycle-hide-archived-subtrees 'all)
4518 (org-cycle-hide-drawers 'all)
4519 (org-cycle-show-empty-lines 'all))
4521 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4522 "Switch subtree visibilities according to :VISIBILITY: property."
4523 (interactive)
4524 (let (org-show-entry-below state)
4525 (save-excursion
4526 (goto-char (point-min))
4527 (while (re-search-forward
4528 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4529 nil t)
4530 (setq state (match-string 1))
4531 (save-excursion
4532 (org-back-to-heading t)
4533 (hide-subtree)
4534 (org-reveal)
4535 (cond
4536 ((equal state '("fold" "folded"))
4537 (hide-subtree))
4538 ((equal state "children")
4539 (org-show-hidden-entry)
4540 (show-children))
4541 ((equal state "content")
4542 (save-excursion
4543 (save-restriction
4544 (org-narrow-to-subtree)
4545 (org-content))))
4546 ((member state '("all" "showall"))
4547 (show-subtree)))))
4548 (unless no-cleanup
4549 (org-cycle-hide-archived-subtrees 'all)
4550 (org-cycle-hide-drawers 'all)
4551 (org-cycle-show-empty-lines 'all)))))
4553 (defun org-overview ()
4554 "Switch to overview mode, showing only top-level headlines.
4555 Really, this shows all headlines with level equal or greater than the level
4556 of the first headline in the buffer. This is important, because if the
4557 first headline is not level one, then (hide-sublevels 1) gives confusing
4558 results."
4559 (interactive)
4560 (let ((level (save-excursion
4561 (goto-char (point-min))
4562 (if (re-search-forward (concat "^" outline-regexp) nil t)
4563 (progn
4564 (goto-char (match-beginning 0))
4565 (funcall outline-level))))))
4566 (and level (hide-sublevels level))))
4568 (defun org-content (&optional arg)
4569 "Show all headlines in the buffer, like a table of contents.
4570 With numerical argument N, show content up to level N."
4571 (interactive "P")
4572 (save-excursion
4573 ;; Visit all headings and show their offspring
4574 (and (integerp arg) (org-overview))
4575 (goto-char (point-max))
4576 (catch 'exit
4577 (while (and (progn (condition-case nil
4578 (outline-previous-visible-heading 1)
4579 (error (goto-char (point-min))))
4581 (looking-at outline-regexp))
4582 (if (integerp arg)
4583 (show-children (1- arg))
4584 (show-branches))
4585 (if (bobp) (throw 'exit nil))))))
4588 (defun org-optimize-window-after-visibility-change (state)
4589 "Adjust the window after a change in outline visibility.
4590 This function is the default value of the hook `org-cycle-hook'."
4591 (when (get-buffer-window (current-buffer))
4592 (cond
4593 ; ((eq state 'overview) (org-first-headline-recenter 1))
4594 ; ((eq state 'overview) (org-beginning-of-line))
4595 ((eq state 'content) nil)
4596 ((eq state 'all) nil)
4597 ((eq state 'folded) nil)
4598 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4599 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4601 (defun org-compact-display-after-subtree-move ()
4602 "Show a compacter version of the tree of the entry's parent."
4603 (save-excursion
4604 (if (org-up-heading-safe)
4605 (progn
4606 (hide-subtree)
4607 (show-entry)
4608 (show-children)
4609 (org-cycle-show-empty-lines 'children)
4610 (org-cycle-hide-drawers 'children))
4611 (org-overview))))
4613 (defun org-cycle-show-empty-lines (state)
4614 "Show empty lines above all visible headlines.
4615 The region to be covered depends on STATE when called through
4616 `org-cycle-hook'. Lisp program can use t for STATE to get the
4617 entire buffer covered. Note that an empty line is only shown if there
4618 are at least `org-cycle-separator-lines' empty lines before the headline."
4619 (when (> org-cycle-separator-lines 0)
4620 (save-excursion
4621 (let* ((n org-cycle-separator-lines)
4622 (re (cond
4623 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4624 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4625 (t (let ((ns (number-to-string (- n 2))))
4626 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4627 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4628 beg end)
4629 (cond
4630 ((memq state '(overview contents t))
4631 (setq beg (point-min) end (point-max)))
4632 ((memq state '(children folded))
4633 (setq beg (point) end (progn (org-end-of-subtree t t)
4634 (beginning-of-line 2)
4635 (point)))))
4636 (when beg
4637 (goto-char beg)
4638 (while (re-search-forward re end t)
4639 (if (not (get-char-property (match-end 1) 'invisible))
4640 (outline-flag-region
4641 (match-beginning 1) (match-end 1) nil)))))))
4642 ;; Never hide empty lines at the end of the file.
4643 (save-excursion
4644 (goto-char (point-max))
4645 (outline-previous-heading)
4646 (outline-end-of-heading)
4647 (if (and (looking-at "[ \t\n]+")
4648 (= (match-end 0) (point-max)))
4649 (outline-flag-region (point) (match-end 0) nil))))
4651 (defun org-show-empty-lines-in-parent ()
4652 "Move to the parent and re-show empty lines before visible headlines."
4653 (save-excursion
4654 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4655 (org-cycle-show-empty-lines context))))
4657 (defun org-cycle-hide-drawers (state)
4658 "Re-hide all drawers after a visibility state change."
4659 (when (and (org-mode-p)
4660 (not (memq state '(overview folded))))
4661 (save-excursion
4662 (let* ((globalp (memq state '(contents all)))
4663 (beg (if globalp (point-min) (point)))
4664 (end (if globalp (point-max) (org-end-of-subtree t))))
4665 (goto-char beg)
4666 (while (re-search-forward org-drawer-regexp end t)
4667 (org-flag-drawer t))))))
4669 (defun org-flag-drawer (flag)
4670 (save-excursion
4671 (beginning-of-line 1)
4672 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4673 (let ((b (match-end 0))
4674 (outline-regexp org-outline-regexp))
4675 (if (re-search-forward
4676 "^[ \t]*:END:"
4677 (save-excursion (outline-next-heading) (point)) t)
4678 (outline-flag-region b (point-at-eol) flag)
4679 (error ":END: line missing"))))))
4681 (defun org-subtree-end-visible-p ()
4682 "Is the end of the current subtree visible?"
4683 (pos-visible-in-window-p
4684 (save-excursion (org-end-of-subtree t) (point))))
4686 (defun org-first-headline-recenter (&optional N)
4687 "Move cursor to the first headline and recenter the headline.
4688 Optional argument N means, put the headline into the Nth line of the window."
4689 (goto-char (point-min))
4690 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4691 (beginning-of-line)
4692 (recenter (prefix-numeric-value N))))
4694 ;;; Org-goto
4696 (defvar org-goto-window-configuration nil)
4697 (defvar org-goto-marker nil)
4698 (defvar org-goto-map
4699 (let ((map (make-sparse-keymap)))
4700 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4701 (while (setq cmd (pop cmds))
4702 (substitute-key-definition cmd cmd map global-map)))
4703 (suppress-keymap map)
4704 (org-defkey map "\C-m" 'org-goto-ret)
4705 (org-defkey map [(return)] 'org-goto-ret)
4706 (org-defkey map [(left)] 'org-goto-left)
4707 (org-defkey map [(right)] 'org-goto-right)
4708 (org-defkey map [(control ?g)] 'org-goto-quit)
4709 (org-defkey map "\C-i" 'org-cycle)
4710 (org-defkey map [(tab)] 'org-cycle)
4711 (org-defkey map [(down)] 'outline-next-visible-heading)
4712 (org-defkey map [(up)] 'outline-previous-visible-heading)
4713 (if org-goto-auto-isearch
4714 (if (fboundp 'define-key-after)
4715 (define-key-after map [t] 'org-goto-local-auto-isearch)
4716 nil)
4717 (org-defkey map "q" 'org-goto-quit)
4718 (org-defkey map "n" 'outline-next-visible-heading)
4719 (org-defkey map "p" 'outline-previous-visible-heading)
4720 (org-defkey map "f" 'outline-forward-same-level)
4721 (org-defkey map "b" 'outline-backward-same-level)
4722 (org-defkey map "u" 'outline-up-heading))
4723 (org-defkey map "/" 'org-occur)
4724 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4725 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4726 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4727 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4728 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4729 map))
4731 (defconst org-goto-help
4732 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4733 RET=jump to location [Q]uit and return to previous location
4734 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4736 (defvar org-goto-start-pos) ; dynamically scoped parameter
4738 ;; FIXME: Docstring doe not mention both interfaces
4739 (defun org-goto (&optional alternative-interface)
4740 "Look up a different location in the current file, keeping current visibility.
4742 When you want look-up or go to a different location in a document, the
4743 fastest way is often to fold the entire buffer and then dive into the tree.
4744 This method has the disadvantage, that the previous location will be folded,
4745 which may not be what you want.
4747 This command works around this by showing a copy of the current buffer
4748 in an indirect buffer, in overview mode. You can dive into the tree in
4749 that copy, use org-occur and incremental search to find a location.
4750 When pressing RET or `Q', the command returns to the original buffer in
4751 which the visibility is still unchanged. After RET is will also jump to
4752 the location selected in the indirect buffer and expose the
4753 the headline hierarchy above."
4754 (interactive "P")
4755 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4756 (org-refile-use-outline-path t)
4757 (interface
4758 (if (not alternative-interface)
4759 org-goto-interface
4760 (if (eq org-goto-interface 'outline)
4761 'outline-path-completion
4762 'outline)))
4763 (org-goto-start-pos (point))
4764 (selected-point
4765 (if (eq interface 'outline)
4766 (car (org-get-location (current-buffer) org-goto-help))
4767 (nth 3 (org-refile-get-location "Goto: ")))))
4768 (if selected-point
4769 (progn
4770 (org-mark-ring-push org-goto-start-pos)
4771 (goto-char selected-point)
4772 (if (or (org-invisible-p) (org-invisible-p2))
4773 (org-show-context 'org-goto)))
4774 (message "Quit"))))
4776 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4777 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4778 (defvar org-goto-local-auto-isearch-map) ; defined below
4780 (defun org-get-location (buf help)
4781 "Let the user select a location in the Org-mode buffer BUF.
4782 This function uses a recursive edit. It returns the selected position
4783 or nil."
4784 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4785 (isearch-hide-immediately nil)
4786 (isearch-search-fun-function
4787 (lambda () 'org-goto-local-search-headings))
4788 (org-goto-selected-point org-goto-exit-command))
4789 (save-excursion
4790 (save-window-excursion
4791 (delete-other-windows)
4792 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4793 (switch-to-buffer
4794 (condition-case nil
4795 (make-indirect-buffer (current-buffer) "*org-goto*")
4796 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4797 (with-output-to-temp-buffer "*Help*"
4798 (princ help))
4799 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4800 (setq buffer-read-only nil)
4801 (let ((org-startup-truncated t)
4802 (org-startup-folded nil)
4803 (org-startup-align-all-tables nil))
4804 (org-mode)
4805 (org-overview))
4806 (setq buffer-read-only t)
4807 (if (and (boundp 'org-goto-start-pos)
4808 (integer-or-marker-p org-goto-start-pos))
4809 (let ((org-show-hierarchy-above t)
4810 (org-show-siblings t)
4811 (org-show-following-heading t))
4812 (goto-char org-goto-start-pos)
4813 (and (org-invisible-p) (org-show-context)))
4814 (goto-char (point-min)))
4815 (org-beginning-of-line)
4816 (message "Select location and press RET")
4817 (use-local-map org-goto-map)
4818 (recursive-edit)
4820 (kill-buffer "*org-goto*")
4821 (cons org-goto-selected-point org-goto-exit-command)))
4823 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4824 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4825 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4826 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4828 (defun org-goto-local-search-headings (string bound noerror)
4829 "Search and make sure that any matches are in headlines."
4830 (catch 'return
4831 (while (if isearch-forward
4832 (search-forward string bound noerror)
4833 (search-backward string bound noerror))
4834 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4835 (and (member :headline context)
4836 (not (member :tags context))))
4837 (throw 'return (point))))))
4839 (defun org-goto-local-auto-isearch ()
4840 "Start isearch."
4841 (interactive)
4842 (goto-char (point-min))
4843 (let ((keys (this-command-keys)))
4844 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4845 (isearch-mode t)
4846 (isearch-process-search-char (string-to-char keys)))))
4848 (defun org-goto-ret (&optional arg)
4849 "Finish `org-goto' by going to the new location."
4850 (interactive "P")
4851 (setq org-goto-selected-point (point)
4852 org-goto-exit-command 'return)
4853 (throw 'exit nil))
4855 (defun org-goto-left ()
4856 "Finish `org-goto' by going to the new location."
4857 (interactive)
4858 (if (org-on-heading-p)
4859 (progn
4860 (beginning-of-line 1)
4861 (setq org-goto-selected-point (point)
4862 org-goto-exit-command 'left)
4863 (throw 'exit nil))
4864 (error "Not on a heading")))
4866 (defun org-goto-right ()
4867 "Finish `org-goto' by going to the new location."
4868 (interactive)
4869 (if (org-on-heading-p)
4870 (progn
4871 (setq org-goto-selected-point (point)
4872 org-goto-exit-command 'right)
4873 (throw 'exit nil))
4874 (error "Not on a heading")))
4876 (defun org-goto-quit ()
4877 "Finish `org-goto' without cursor motion."
4878 (interactive)
4879 (setq org-goto-selected-point nil)
4880 (setq org-goto-exit-command 'quit)
4881 (throw 'exit nil))
4883 ;;; Indirect buffer display of subtrees
4885 (defvar org-indirect-dedicated-frame nil
4886 "This is the frame being used for indirect tree display.")
4887 (defvar org-last-indirect-buffer nil)
4889 (defun org-tree-to-indirect-buffer (&optional arg)
4890 "Create indirect buffer and narrow it to current subtree.
4891 With numerical prefix ARG, go up to this level and then take that tree.
4892 If ARG is negative, go up that many levels.
4893 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4894 indirect buffer previously made with this command, to avoid proliferation of
4895 indirect buffers. However, when you call the command with a `C-u' prefix, or
4896 when `org-indirect-buffer-display' is `new-frame', the last buffer
4897 is kept so that you can work with several indirect buffers at the same time.
4898 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4899 requests that a new frame be made for the new buffer, so that the dedicated
4900 frame is not changed."
4901 (interactive "P")
4902 (let ((cbuf (current-buffer))
4903 (cwin (selected-window))
4904 (pos (point))
4905 beg end level heading ibuf)
4906 (save-excursion
4907 (org-back-to-heading t)
4908 (when (numberp arg)
4909 (setq level (org-outline-level))
4910 (if (< arg 0) (setq arg (+ level arg)))
4911 (while (> (setq level (org-outline-level)) arg)
4912 (outline-up-heading 1 t)))
4913 (setq beg (point)
4914 heading (org-get-heading))
4915 (org-end-of-subtree t) (setq end (point)))
4916 (if (and (buffer-live-p org-last-indirect-buffer)
4917 (not (eq org-indirect-buffer-display 'new-frame))
4918 (not arg))
4919 (kill-buffer org-last-indirect-buffer))
4920 (setq ibuf (org-get-indirect-buffer cbuf)
4921 org-last-indirect-buffer ibuf)
4922 (cond
4923 ((or (eq org-indirect-buffer-display 'new-frame)
4924 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4925 (select-frame (make-frame))
4926 (delete-other-windows)
4927 (switch-to-buffer ibuf)
4928 (org-set-frame-title heading))
4929 ((eq org-indirect-buffer-display 'dedicated-frame)
4930 (raise-frame
4931 (select-frame (or (and org-indirect-dedicated-frame
4932 (frame-live-p org-indirect-dedicated-frame)
4933 org-indirect-dedicated-frame)
4934 (setq org-indirect-dedicated-frame (make-frame)))))
4935 (delete-other-windows)
4936 (switch-to-buffer ibuf)
4937 (org-set-frame-title (concat "Indirect: " heading)))
4938 ((eq org-indirect-buffer-display 'current-window)
4939 (switch-to-buffer ibuf))
4940 ((eq org-indirect-buffer-display 'other-window)
4941 (pop-to-buffer ibuf))
4942 (t (error "Invalid value.")))
4943 (if (featurep 'xemacs)
4944 (save-excursion (org-mode) (turn-on-font-lock)))
4945 (narrow-to-region beg end)
4946 (show-all)
4947 (goto-char pos)
4948 (and (window-live-p cwin) (select-window cwin))))
4950 (defun org-get-indirect-buffer (&optional buffer)
4951 (setq buffer (or buffer (current-buffer)))
4952 (let ((n 1) (base (buffer-name buffer)) bname)
4953 (while (buffer-live-p
4954 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4955 (setq n (1+ n)))
4956 (condition-case nil
4957 (make-indirect-buffer buffer bname 'clone)
4958 (error (make-indirect-buffer buffer bname)))))
4960 (defun org-set-frame-title (title)
4961 "Set the title of the current frame to the string TITLE."
4962 ;; FIXME: how to name a single frame in XEmacs???
4963 (unless (featurep 'xemacs)
4964 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4966 ;;;; Structure editing
4968 ;;; Inserting headlines
4970 (defun org-previous-line-empty-p ()
4971 (save-excursion
4972 (and (not (bobp))
4973 (or (beginning-of-line 0) t)
4974 (save-match-data
4975 (looking-at "[ \t]*$")))))
4977 (defun org-insert-heading (&optional force-heading)
4978 "Insert a new heading or item with same depth at point.
4979 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4980 If point is at the beginning of a headline, insert a sibling before the
4981 current headline. If point is not at the beginning, do not split the line,
4982 but create the new headline after the current line."
4983 (interactive "P")
4984 (if (= (buffer-size) 0)
4985 (insert "\n* ")
4986 (when (or force-heading (not (org-insert-item)))
4987 (let* ((empty-line-p nil)
4988 (head (save-excursion
4989 (condition-case nil
4990 (progn
4991 (org-back-to-heading)
4992 (setq empty-line-p (org-previous-line-empty-p))
4993 (match-string 0))
4994 (error "*"))))
4995 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4996 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4997 pos hide-previous previous-pos)
4998 (cond
4999 ((and (org-on-heading-p) (bolp)
5000 (or (bobp)
5001 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5002 ;; insert before the current line
5003 (open-line (if blank 2 1)))
5004 ((and (bolp)
5005 (or (bobp)
5006 (save-excursion
5007 (backward-char 1) (not (org-invisible-p)))))
5008 ;; insert right here
5009 nil)
5011 ;; somewhere in the line
5012 (save-excursion
5013 (setq previous-pos (point-at-bol))
5014 (end-of-line)
5015 (setq hide-previous (org-invisible-p)))
5016 (and org-insert-heading-respect-content (org-show-subtree))
5017 (let ((split
5018 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5019 (save-excursion
5020 (let ((p (point)))
5021 (goto-char (point-at-bol))
5022 (and (looking-at org-complex-heading-regexp)
5023 (> p (match-beginning 4)))))))
5024 tags pos)
5025 (cond
5026 (org-insert-heading-respect-content
5027 (org-end-of-subtree nil t)
5028 (or (bolp) (newline))
5029 (or (org-previous-line-empty-p)
5030 (and blank (newline)))
5031 (open-line 1))
5032 ((org-on-heading-p)
5033 (when hide-previous
5034 (show-children)
5035 (org-show-entry))
5036 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5037 (setq tags (and (match-end 2) (match-string 2)))
5038 (and (match-end 1)
5039 (delete-region (match-beginning 1) (match-end 1)))
5040 (setq pos (point-at-bol))
5041 (or split (end-of-line 1))
5042 (delete-horizontal-space)
5043 (newline (if blank 2 1))
5044 (when tags
5045 (save-excursion
5046 (goto-char pos)
5047 (end-of-line 1)
5048 (insert " " tags)
5049 (org-set-tags nil 'align))))
5051 (or split (end-of-line 1))
5052 (newline (if blank 2 1)))))))
5053 (insert head) (just-one-space)
5054 (setq pos (point))
5055 (end-of-line 1)
5056 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5057 (when (and org-insert-heading-respect-content hide-previous)
5058 (save-excursion
5059 (goto-char previous-pos)
5060 (hide-subtree)))
5061 (run-hooks 'org-insert-heading-hook)))))
5063 (defun org-get-heading (&optional no-tags)
5064 "Return the heading of the current entry, without the stars."
5065 (save-excursion
5066 (org-back-to-heading t)
5067 (if (looking-at
5068 (if no-tags
5069 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5070 "\\*+[ \t]+\\([^\r\n]*\\)"))
5071 (match-string 1) "")))
5073 (defun org-heading-components ()
5074 "Return the components of the current heading.
5075 This is a list with the following elements:
5076 - the level as an integer
5077 - the reduced level, different if `org-odd-levels-only' is set.
5078 - the TODO keyword, or nil
5079 - the priority character, like ?A, or nil if no priority is given
5080 - the headline text itself, or the tags string if no headline text
5081 - the tags string, or nil."
5082 (save-excursion
5083 (org-back-to-heading t)
5084 (if (looking-at org-complex-heading-regexp)
5085 (list (length (match-string 1))
5086 (org-reduced-level (length (match-string 1)))
5087 (org-match-string-no-properties 2)
5088 (and (match-end 3) (aref (match-string 3) 2))
5089 (org-match-string-no-properties 4)
5090 (org-match-string-no-properties 5)))))
5092 (defun org-insert-heading-after-current ()
5093 "Insert a new heading with same level as current, after current subtree."
5094 (interactive)
5095 (org-back-to-heading)
5096 (org-insert-heading)
5097 (org-move-subtree-down)
5098 (end-of-line 1))
5100 (defun org-insert-heading-respect-content ()
5101 (interactive)
5102 (let ((org-insert-heading-respect-content t))
5103 (org-insert-heading t)))
5105 (defun org-insert-todo-heading-respect-content (&optional force-state)
5106 (interactive "P")
5107 (let ((org-insert-heading-respect-content t))
5108 (org-insert-todo-heading force-state t)))
5110 (defun org-insert-todo-heading (arg &optional force-heading)
5111 "Insert a new heading with the same level and TODO state as current heading.
5112 If the heading has no TODO state, or if the state is DONE, use the first
5113 state (TODO by default). Also with prefix arg, force first state."
5114 (interactive "P")
5115 (when (or force-heading (not (org-insert-item 'checkbox)))
5116 (org-insert-heading force-heading)
5117 (save-excursion
5118 (org-back-to-heading)
5119 (outline-previous-heading)
5120 (looking-at org-todo-line-regexp))
5121 (if (or arg
5122 (not (match-beginning 2))
5123 (member (match-string 2) org-done-keywords))
5124 (insert (car org-todo-keywords-1) " ")
5125 (insert (match-string 2) " "))
5126 (when org-provide-todo-statistics
5127 (org-update-parent-todo-statistics))))
5129 (defun org-insert-subheading (arg)
5130 "Insert a new subheading and demote it.
5131 Works for outline headings and for plain lists alike."
5132 (interactive "P")
5133 (org-insert-heading arg)
5134 (cond
5135 ((org-on-heading-p) (org-do-demote))
5136 ((org-at-item-p) (org-indent-item 1))))
5138 (defun org-insert-todo-subheading (arg)
5139 "Insert a new subheading with TODO keyword or checkbox and demote it.
5140 Works for outline headings and for plain lists alike."
5141 (interactive "P")
5142 (org-insert-todo-heading arg)
5143 (cond
5144 ((org-on-heading-p) (org-do-demote))
5145 ((org-at-item-p) (org-indent-item 1))))
5147 ;;; Promotion and Demotion
5149 (defun org-promote-subtree ()
5150 "Promote the entire subtree.
5151 See also `org-promote'."
5152 (interactive)
5153 (save-excursion
5154 (org-map-tree 'org-promote))
5155 (org-fix-position-after-promote))
5157 (defun org-demote-subtree ()
5158 "Demote the entire subtree. See `org-demote'.
5159 See also `org-promote'."
5160 (interactive)
5161 (save-excursion
5162 (org-map-tree 'org-demote))
5163 (org-fix-position-after-promote))
5166 (defun org-do-promote ()
5167 "Promote the current heading higher up the tree.
5168 If the region is active in `transient-mark-mode', promote all headings
5169 in the region."
5170 (interactive)
5171 (save-excursion
5172 (if (org-region-active-p)
5173 (org-map-region 'org-promote (region-beginning) (region-end))
5174 (org-promote)))
5175 (org-fix-position-after-promote))
5177 (defun org-do-demote ()
5178 "Demote the current heading lower down the tree.
5179 If the region is active in `transient-mark-mode', demote all headings
5180 in the region."
5181 (interactive)
5182 (save-excursion
5183 (if (org-region-active-p)
5184 (org-map-region 'org-demote (region-beginning) (region-end))
5185 (org-demote)))
5186 (org-fix-position-after-promote))
5188 (defun org-fix-position-after-promote ()
5189 "Make sure that after pro/demotion cursor position is right."
5190 (let ((pos (point)))
5191 (when (save-excursion
5192 (beginning-of-line 1)
5193 (looking-at org-todo-line-regexp)
5194 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5195 (cond ((eobp) (insert " "))
5196 ((eolp) (insert " "))
5197 ((equal (char-after) ?\ ) (forward-char 1))))))
5199 (defun org-reduced-level (l)
5200 "Compute the effective level of a heading.
5201 This takes into account the setting of `org-odd-levels-only'."
5202 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5204 (defun org-get-valid-level (level &optional change)
5205 "Rectify a level change under the influence of `org-odd-levels-only'
5206 LEVEL is a current level, CHANGE is by how much the level should be
5207 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5208 even level numbers will become the next higher odd number."
5209 (if org-odd-levels-only
5210 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5211 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5212 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5213 (max 1 (+ level change))))
5215 (if (boundp 'define-obsolete-function-alias)
5216 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5217 (define-obsolete-function-alias 'org-get-legal-level
5218 'org-get-valid-level)
5219 (define-obsolete-function-alias 'org-get-legal-level
5220 'org-get-valid-level "23.1")))
5222 (defun org-promote ()
5223 "Promote the current heading higher up the tree.
5224 If the region is active in `transient-mark-mode', promote all headings
5225 in the region."
5226 (org-back-to-heading t)
5227 (let* ((level (save-match-data (funcall outline-level)))
5228 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5229 (diff (abs (- level (length up-head) -1))))
5230 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5231 (replace-match up-head nil t)
5232 ;; Fixup tag positioning
5233 (and org-auto-align-tags (org-set-tags nil t))
5234 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5236 (defun org-demote ()
5237 "Demote the current heading lower down the tree.
5238 If the region is active in `transient-mark-mode', demote all headings
5239 in the region."
5240 (org-back-to-heading t)
5241 (let* ((level (save-match-data (funcall outline-level)))
5242 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5243 (diff (abs (- level (length down-head) -1))))
5244 (replace-match down-head nil t)
5245 ;; Fixup tag positioning
5246 (and org-auto-align-tags (org-set-tags nil t))
5247 (if org-adapt-indentation (org-fixup-indentation diff))))
5249 (defun org-map-tree (fun)
5250 "Call FUN for every heading underneath the current one."
5251 (org-back-to-heading)
5252 (let ((level (funcall outline-level)))
5253 (save-excursion
5254 (funcall fun)
5255 (while (and (progn
5256 (outline-next-heading)
5257 (> (funcall outline-level) level))
5258 (not (eobp)))
5259 (funcall fun)))))
5261 (defun org-map-region (fun beg end)
5262 "Call FUN for every heading between BEG and END."
5263 (let ((org-ignore-region t))
5264 (save-excursion
5265 (setq end (copy-marker end))
5266 (goto-char beg)
5267 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5268 (< (point) end))
5269 (funcall fun))
5270 (while (and (progn
5271 (outline-next-heading)
5272 (< (point) end))
5273 (not (eobp)))
5274 (funcall fun)))))
5276 (defun org-fixup-indentation (diff)
5277 "Change the indentation in the current entry by DIFF
5278 However, if any line in the current entry has no indentation, or if it
5279 would end up with no indentation after the change, nothing at all is done."
5280 (save-excursion
5281 (let ((end (save-excursion (outline-next-heading)
5282 (point-marker)))
5283 (prohibit (if (> diff 0)
5284 "^\\S-"
5285 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5286 col)
5287 (unless (save-excursion (end-of-line 1)
5288 (re-search-forward prohibit end t))
5289 (while (and (< (point) end)
5290 (re-search-forward "^[ \t]+" end t))
5291 (goto-char (match-end 0))
5292 (setq col (current-column))
5293 (if (< diff 0) (replace-match ""))
5294 (org-indent-to-column (+ diff col))))
5295 (move-marker end nil))))
5297 (defun org-convert-to-odd-levels ()
5298 "Convert an org-mode file with all levels allowed to one with odd levels.
5299 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5300 level 5 etc."
5301 (interactive)
5302 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5303 (let ((org-odd-levels-only nil) n)
5304 (save-excursion
5305 (goto-char (point-min))
5306 (while (re-search-forward "^\\*\\*+ " nil t)
5307 (setq n (- (length (match-string 0)) 2))
5308 (while (>= (setq n (1- n)) 0)
5309 (org-demote))
5310 (end-of-line 1))))))
5313 (defun org-convert-to-oddeven-levels ()
5314 "Convert an org-mode file with only odd levels to one with odd and even levels.
5315 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5316 section with an even level, conversion would destroy the structure of the file. An error
5317 is signaled in this case."
5318 (interactive)
5319 (goto-char (point-min))
5320 ;; First check if there are no even levels
5321 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5322 (org-show-context t)
5323 (error "Not all levels are odd in this file. Conversion not possible."))
5324 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5325 (let ((org-odd-levels-only nil) n)
5326 (save-excursion
5327 (goto-char (point-min))
5328 (while (re-search-forward "^\\*\\*+ " nil t)
5329 (setq n (/ (1- (length (match-string 0))) 2))
5330 (while (>= (setq n (1- n)) 0)
5331 (org-promote))
5332 (end-of-line 1))))))
5334 (defun org-tr-level (n)
5335 "Make N odd if required."
5336 (if org-odd-levels-only (1+ (/ n 2)) n))
5338 ;;; Vertical tree motion, cutting and pasting of subtrees
5340 (defun org-move-subtree-up (&optional arg)
5341 "Move the current subtree up past ARG headlines of the same level."
5342 (interactive "p")
5343 (org-move-subtree-down (- (prefix-numeric-value arg))))
5345 (defun org-move-subtree-down (&optional arg)
5346 "Move the current subtree down past ARG headlines of the same level."
5347 (interactive "p")
5348 (setq arg (prefix-numeric-value arg))
5349 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5350 'outline-get-last-sibling))
5351 (ins-point (make-marker))
5352 (cnt (abs arg))
5353 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5354 ;; Select the tree
5355 (org-back-to-heading)
5356 (setq beg0 (point))
5357 (save-excursion
5358 (setq ne-beg (org-back-over-empty-lines))
5359 (setq beg (point)))
5360 (save-match-data
5361 (save-excursion (outline-end-of-heading)
5362 (setq folded (org-invisible-p)))
5363 (outline-end-of-subtree))
5364 (outline-next-heading)
5365 (setq ne-end (org-back-over-empty-lines))
5366 (setq end (point))
5367 (goto-char beg0)
5368 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5369 ;; include less whitespace
5370 (save-excursion
5371 (goto-char beg)
5372 (forward-line (- ne-beg ne-end))
5373 (setq beg (point))))
5374 ;; Find insertion point, with error handling
5375 (while (> cnt 0)
5376 (or (and (funcall movfunc) (looking-at outline-regexp))
5377 (progn (goto-char beg0)
5378 (error "Cannot move past superior level or buffer limit")))
5379 (setq cnt (1- cnt)))
5380 (if (> arg 0)
5381 ;; Moving forward - still need to move over subtree
5382 (progn (org-end-of-subtree t t)
5383 (save-excursion
5384 (org-back-over-empty-lines)
5385 (or (bolp) (newline)))))
5386 (setq ne-ins (org-back-over-empty-lines))
5387 (move-marker ins-point (point))
5388 (setq txt (buffer-substring beg end))
5389 (org-save-markers-in-region beg end)
5390 (delete-region beg end)
5391 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5392 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5393 (let ((bbb (point)))
5394 (insert-before-markers txt)
5395 (org-reinstall-markers-in-region bbb)
5396 (move-marker ins-point bbb))
5397 (or (bolp) (insert "\n"))
5398 (setq ins-end (point))
5399 (goto-char ins-point)
5400 (org-skip-whitespace)
5401 (when (and (< arg 0)
5402 (org-first-sibling-p)
5403 (> ne-ins ne-beg))
5404 ;; Move whitespace back to beginning
5405 (save-excursion
5406 (goto-char ins-end)
5407 (let ((kill-whole-line t))
5408 (kill-line (- ne-ins ne-beg)) (point)))
5409 (insert (make-string (- ne-ins ne-beg) ?\n)))
5410 (move-marker ins-point nil)
5411 (org-compact-display-after-subtree-move)
5412 (org-show-empty-lines-in-parent)
5413 (unless folded
5414 (org-show-entry)
5415 (show-children)
5416 (org-cycle-hide-drawers 'children))))
5418 (defvar org-subtree-clip ""
5419 "Clipboard for cut and paste of subtrees.
5420 This is actually only a copy of the kill, because we use the normal kill
5421 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5423 (defvar org-subtree-clip-folded nil
5424 "Was the last copied subtree folded?
5425 This is used to fold the tree back after pasting.")
5427 (defun org-cut-subtree (&optional n)
5428 "Cut the current subtree into the clipboard.
5429 With prefix arg N, cut this many sequential subtrees.
5430 This is a short-hand for marking the subtree and then cutting it."
5431 (interactive "p")
5432 (org-copy-subtree n 'cut))
5434 (defun org-copy-subtree (&optional n cut force-store-markers)
5435 "Cut the current subtree into the clipboard.
5436 With prefix arg N, cut this many sequential subtrees.
5437 This is a short-hand for marking the subtree and then copying it.
5438 If CUT is non-nil, actually cut the subtree.
5439 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5440 of some markers in the region, even if CUT is non-nil. This is
5441 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5442 (interactive "p")
5443 (let (beg end folded (beg0 (point)))
5444 (if (interactive-p)
5445 (org-back-to-heading nil) ; take what looks like a subtree
5446 (org-back-to-heading t)) ; take what is really there
5447 (org-back-over-empty-lines)
5448 (setq beg (point))
5449 (skip-chars-forward " \t\r\n")
5450 (save-match-data
5451 (save-excursion (outline-end-of-heading)
5452 (setq folded (org-invisible-p)))
5453 (condition-case nil
5454 (outline-forward-same-level (1- n))
5455 (error nil))
5456 (org-end-of-subtree t t))
5457 (org-back-over-empty-lines)
5458 (setq end (point))
5459 (goto-char beg0)
5460 (when (> end beg)
5461 (setq org-subtree-clip-folded folded)
5462 (when (or cut force-store-markers)
5463 (org-save-markers-in-region beg end))
5464 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5465 (setq org-subtree-clip (current-kill 0))
5466 (message "%s: Subtree(s) with %d characters"
5467 (if cut "Cut" "Copied")
5468 (length org-subtree-clip)))))
5470 (defun org-paste-subtree (&optional level tree for-yank)
5471 "Paste the clipboard as a subtree, with modification of headline level.
5472 The entire subtree is promoted or demoted in order to match a new headline
5473 level.
5475 If the cursor is at the beginning of a headline, the same level as
5476 that headline is used to paste the tree
5478 If not, the new level is derived from the *visible* headings
5479 before and after the insertion point, and taken to be the inferior headline
5480 level of the two. So if the previous visible heading is level 3 and the
5481 next is level 4 (or vice versa), level 4 will be used for insertion.
5482 This makes sure that the subtree remains an independent subtree and does
5483 not swallow low level entries.
5485 You can also force a different level, either by using a numeric prefix
5486 argument, or by inserting the heading marker by hand. For example, if the
5487 cursor is after \"*****\", then the tree will be shifted to level 5.
5489 If optional TREE is given, use this text instead of the kill ring.
5491 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5492 move back over whitespace before inserting, and move point to the end of
5493 the inserted text when done."
5494 (interactive "P")
5495 (unless (org-kill-is-subtree-p tree)
5496 (error "%s"
5497 (substitute-command-keys
5498 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5499 (let* ((visp (not (org-invisible-p)))
5500 (txt (or tree (and kill-ring (current-kill 0))))
5501 (^re (concat "^\\(" outline-regexp "\\)"))
5502 (re (concat "\\(" outline-regexp "\\)"))
5503 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5505 (old-level (if (string-match ^re txt)
5506 (- (match-end 0) (match-beginning 0) 1)
5507 -1))
5508 (force-level (cond (level (prefix-numeric-value level))
5509 ((and (looking-at "[ \t]*$")
5510 (string-match
5511 ^re_ (buffer-substring
5512 (point-at-bol) (point))))
5513 (- (match-end 1) (match-beginning 1)))
5514 ((and (bolp)
5515 (looking-at org-outline-regexp))
5516 (- (match-end 0) (point) 1))
5517 (t nil)))
5518 (previous-level (save-excursion
5519 (condition-case nil
5520 (progn
5521 (outline-previous-visible-heading 1)
5522 (if (looking-at re)
5523 (- (match-end 0) (match-beginning 0) 1)
5525 (error 1))))
5526 (next-level (save-excursion
5527 (condition-case nil
5528 (progn
5529 (or (looking-at outline-regexp)
5530 (outline-next-visible-heading 1))
5531 (if (looking-at re)
5532 (- (match-end 0) (match-beginning 0) 1)
5534 (error 1))))
5535 (new-level (or force-level (max previous-level next-level)))
5536 (shift (if (or (= old-level -1)
5537 (= new-level -1)
5538 (= old-level new-level))
5540 (- new-level old-level)))
5541 (delta (if (> shift 0) -1 1))
5542 (func (if (> shift 0) 'org-demote 'org-promote))
5543 (org-odd-levels-only nil)
5544 beg end newend)
5545 ;; Remove the forced level indicator
5546 (if force-level
5547 (delete-region (point-at-bol) (point)))
5548 ;; Paste
5549 (beginning-of-line 1)
5550 (unless for-yank (org-back-over-empty-lines))
5551 (setq beg (point))
5552 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5553 (insert-before-markers txt)
5554 (unless (string-match "\n\\'" txt) (insert "\n"))
5555 (setq newend (point))
5556 (org-reinstall-markers-in-region beg)
5557 (setq end (point))
5558 (goto-char beg)
5559 (skip-chars-forward " \t\n\r")
5560 (setq beg (point))
5561 (if (and (org-invisible-p) visp)
5562 (save-excursion (outline-show-heading)))
5563 ;; Shift if necessary
5564 (unless (= shift 0)
5565 (save-restriction
5566 (narrow-to-region beg end)
5567 (while (not (= shift 0))
5568 (org-map-region func (point-min) (point-max))
5569 (setq shift (+ delta shift)))
5570 (goto-char (point-min))
5571 (setq newend (point-max))))
5572 (when (or (interactive-p) for-yank)
5573 (message "Clipboard pasted as level %d subtree" new-level))
5574 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5575 kill-ring
5576 (eq org-subtree-clip (current-kill 0))
5577 org-subtree-clip-folded)
5578 ;; The tree was folded before it was killed/copied
5579 (hide-subtree))
5580 (and for-yank (goto-char newend))))
5582 (defun org-kill-is-subtree-p (&optional txt)
5583 "Check if the current kill is an outline subtree, or a set of trees.
5584 Returns nil if kill does not start with a headline, or if the first
5585 headline level is not the largest headline level in the tree.
5586 So this will actually accept several entries of equal levels as well,
5587 which is OK for `org-paste-subtree'.
5588 If optional TXT is given, check this string instead of the current kill."
5589 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5590 (start-level (and kill
5591 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5592 org-outline-regexp "\\)")
5593 kill)
5594 (- (match-end 2) (match-beginning 2) 1)))
5595 (re (concat "^" org-outline-regexp))
5596 (start (1+ (or (match-beginning 2) -1))))
5597 (if (not start-level)
5598 (progn
5599 nil) ;; does not even start with a heading
5600 (catch 'exit
5601 (while (setq start (string-match re kill (1+ start)))
5602 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5603 (throw 'exit nil)))
5604 t))))
5606 (defvar org-markers-to-move nil
5607 "Markers that should be moved with a cut-and-paste operation.
5608 Those markers are stored together with their positions relative to
5609 the start of the region.")
5611 (defun org-save-markers-in-region (beg end)
5612 "Check markers in region.
5613 If these markers are between BEG and END, record their position relative
5614 to BEG, so that after moving the block of text, we can put the markers back
5615 into place.
5616 This function gets called just before an entry or tree gets cut from the
5617 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5618 called immediately, to move the markers with the entries."
5619 (setq org-markers-to-move nil)
5620 (when (featurep 'org-clock)
5621 (org-clock-save-markers-for-cut-and-paste beg end))
5622 (when (featurep 'org-agenda)
5623 (org-agenda-save-markers-for-cut-and-paste beg end)))
5625 (defun org-check-and-save-marker (marker beg end)
5626 "Check if MARKER is between BEG and END.
5627 If yes, remember the marker and the distance to BEG."
5628 (when (and (marker-buffer marker)
5629 (equal (marker-buffer marker) (current-buffer)))
5630 (if (and (>= marker beg) (< marker end))
5631 (push (cons marker (- marker beg)) org-markers-to-move))))
5633 (defun org-reinstall-markers-in-region (beg)
5634 "Move all remembered markers to their position relative to BEG."
5635 (mapc (lambda (x)
5636 (move-marker (car x) (+ beg (cdr x))))
5637 org-markers-to-move)
5638 (setq org-markers-to-move nil))
5640 (defun org-narrow-to-subtree ()
5641 "Narrow buffer to the current subtree."
5642 (interactive)
5643 (save-excursion
5644 (save-match-data
5645 (narrow-to-region
5646 (progn (org-back-to-heading) (point))
5647 (progn (org-end-of-subtree t) (point))))))
5650 ;;; Outline Sorting
5652 (defun org-sort (with-case)
5653 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5654 Optional argument WITH-CASE means sort case-sensitively."
5655 (interactive "P")
5656 (if (org-at-table-p)
5657 (org-call-with-arg 'org-table-sort-lines with-case)
5658 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5660 (defun org-sort-remove-invisible (s)
5661 (remove-text-properties 0 (length s) org-rm-props s)
5662 (while (string-match org-bracket-link-regexp s)
5663 (setq s (replace-match (if (match-end 2)
5664 (match-string 3 s)
5665 (match-string 1 s)) t t s)))
5668 (defvar org-priority-regexp) ; defined later in the file
5670 (defun org-sort-entries-or-items
5671 (&optional with-case sorting-type getkey-func compare-func property)
5672 "Sort entries on a certain level of an outline tree.
5673 If there is an active region, the entries in the region are sorted.
5674 Else, if the cursor is before the first entry, sort the top-level items.
5675 Else, the children of the entry at point are sorted.
5677 Sorting can be alphabetically, numerically, and by date/time as given by
5678 the first time stamp in the entry. The command prompts for the sorting
5679 type unless it has been given to the function through the SORTING-TYPE
5680 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5681 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5682 called with point at the beginning of the record. It must return either
5683 a string or a number that should serve as the sorting key for that record.
5685 Comparing entries ignores case by default. However, with an optional argument
5686 WITH-CASE, the sorting considers case as well."
5687 (interactive "P")
5688 (let ((case-func (if with-case 'identity 'downcase))
5689 start beg end stars re re2
5690 txt what tmp plain-list-p)
5691 ;; Find beginning and end of region to sort
5692 (cond
5693 ((org-region-active-p)
5694 ;; we will sort the region
5695 (setq end (region-end)
5696 what "region")
5697 (goto-char (region-beginning))
5698 (if (not (org-on-heading-p)) (outline-next-heading))
5699 (setq start (point)))
5700 ((org-at-item-p)
5701 ;; we will sort this plain list
5702 (org-beginning-of-item-list) (setq start (point))
5703 (org-end-of-item-list) (setq end (point))
5704 (goto-char start)
5705 (setq plain-list-p t
5706 what "plain list"))
5707 ((or (org-on-heading-p)
5708 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5709 ;; we will sort the children of the current headline
5710 (org-back-to-heading)
5711 (setq start (point)
5712 end (progn (org-end-of-subtree t t)
5713 (org-back-over-empty-lines)
5714 (point))
5715 what "children")
5716 (goto-char start)
5717 (show-subtree)
5718 (outline-next-heading))
5720 ;; we will sort the top-level entries in this file
5721 (goto-char (point-min))
5722 (or (org-on-heading-p) (outline-next-heading))
5723 (setq start (point) end (point-max) what "top-level")
5724 (goto-char start)
5725 (show-all)))
5727 (setq beg (point))
5728 (if (>= beg end) (error "Nothing to sort"))
5730 (unless plain-list-p
5731 (looking-at "\\(\\*+\\)")
5732 (setq stars (match-string 1)
5733 re (concat "^" (regexp-quote stars) " +")
5734 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5735 txt (buffer-substring beg end))
5736 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5737 (if (and (not (equal stars "*")) (string-match re2 txt))
5738 (error "Region to sort contains a level above the first entry")))
5740 (unless sorting-type
5741 (message
5742 (if plain-list-p
5743 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5744 "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:")
5745 what)
5746 (setq sorting-type (read-char-exclusive))
5748 (and (= (downcase sorting-type) ?f)
5749 (setq getkey-func
5750 (org-ido-completing-read "Sort using function: "
5751 obarray 'fboundp t nil nil))
5752 (setq getkey-func (intern getkey-func)))
5754 (and (= (downcase sorting-type) ?r)
5755 (setq property
5756 (org-ido-completing-read "Property: "
5757 (mapcar 'list (org-buffer-property-keys t))
5758 nil t))))
5760 (message "Sorting entries...")
5762 (save-restriction
5763 (narrow-to-region start end)
5765 (let ((dcst (downcase sorting-type))
5766 (now (current-time)))
5767 (sort-subr
5768 (/= dcst sorting-type)
5769 ;; This function moves to the beginning character of the "record" to
5770 ;; be sorted.
5771 (if plain-list-p
5772 (lambda nil
5773 (if (org-at-item-p) t (goto-char (point-max))))
5774 (lambda nil
5775 (if (re-search-forward re nil t)
5776 (goto-char (match-beginning 0))
5777 (goto-char (point-max)))))
5778 ;; This function moves to the last character of the "record" being
5779 ;; sorted.
5780 (if plain-list-p
5781 'org-end-of-item
5782 (lambda nil
5783 (save-match-data
5784 (condition-case nil
5785 (outline-forward-same-level 1)
5786 (error
5787 (goto-char (point-max)))))))
5789 ;; This function returns the value that gets sorted against.
5790 (if plain-list-p
5791 (lambda nil
5792 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5793 (cond
5794 ((= dcst ?n)
5795 (string-to-number (buffer-substring (match-end 0)
5796 (point-at-eol))))
5797 ((= dcst ?a)
5798 (buffer-substring (match-end 0) (point-at-eol)))
5799 ((= dcst ?t)
5800 (if (re-search-forward org-ts-regexp
5801 (point-at-eol) t)
5802 (org-time-string-to-time (match-string 0))
5803 now))
5804 ((= dcst ?f)
5805 (if getkey-func
5806 (progn
5807 (setq tmp (funcall getkey-func))
5808 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5809 tmp)
5810 (error "Invalid key function `%s'" getkey-func)))
5811 (t (error "Invalid sorting type `%c'" sorting-type)))))
5812 (lambda nil
5813 (cond
5814 ((= dcst ?n)
5815 (if (looking-at org-complex-heading-regexp)
5816 (string-to-number (match-string 4))
5817 nil))
5818 ((= dcst ?a)
5819 (if (looking-at org-complex-heading-regexp)
5820 (funcall case-func (match-string 4))
5821 nil))
5822 ((= dcst ?t)
5823 (if (re-search-forward org-ts-regexp
5824 (save-excursion
5825 (forward-line 2)
5826 (point)) t)
5827 (org-time-string-to-time (match-string 0))
5828 now))
5829 ((= dcst ?p)
5830 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5831 (string-to-char (match-string 2))
5832 org-default-priority))
5833 ((= dcst ?r)
5834 (or (org-entry-get nil property) ""))
5835 ((= dcst ?o)
5836 (if (looking-at org-complex-heading-regexp)
5837 (- 9999 (length (member (match-string 2)
5838 org-todo-keywords-1)))))
5839 ((= dcst ?f)
5840 (if getkey-func
5841 (progn
5842 (setq tmp (funcall getkey-func))
5843 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5844 tmp)
5845 (error "Invalid key function `%s'" getkey-func)))
5846 (t (error "Invalid sorting type `%c'" sorting-type)))))
5848 (cond
5849 ((= dcst ?a) 'string<)
5850 ((= dcst ?t) 'time-less-p)
5851 ((= dcst ?f) compare-func)
5852 (t nil)))))
5853 (message "Sorting entries...done")))
5855 (defun org-do-sort (table what &optional with-case sorting-type)
5856 "Sort TABLE of WHAT according to SORTING-TYPE.
5857 The user will be prompted for the SORTING-TYPE if the call to this
5858 function does not specify it. WHAT is only for the prompt, to indicate
5859 what is being sorted. The sorting key will be extracted from
5860 the car of the elements of the table.
5861 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5862 (unless sorting-type
5863 (message
5864 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5865 what)
5866 (setq sorting-type (read-char-exclusive)))
5867 (let ((dcst (downcase sorting-type))
5868 extractfun comparefun)
5869 ;; Define the appropriate functions
5870 (cond
5871 ((= dcst ?n)
5872 (setq extractfun 'string-to-number
5873 comparefun (if (= dcst sorting-type) '< '>)))
5874 ((= dcst ?a)
5875 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5876 (lambda(x) (downcase (org-sort-remove-invisible x))))
5877 comparefun (if (= dcst sorting-type)
5878 'string<
5879 (lambda (a b) (and (not (string< a b))
5880 (not (string= a b)))))))
5881 ((= dcst ?t)
5882 (setq extractfun
5883 (lambda (x)
5884 (if (string-match org-ts-regexp x)
5885 (time-to-seconds
5886 (org-time-string-to-time (match-string 0 x)))
5888 comparefun (if (= dcst sorting-type) '< '>)))
5889 (t (error "Invalid sorting type `%c'" sorting-type)))
5891 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5892 table)
5893 (lambda (a b) (funcall comparefun (car a) (car b))))))
5895 ;;; Editing source examples
5897 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5898 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5899 (defvar org-edit-src-force-single-line nil)
5900 (defvar org-edit-src-from-org-mode nil)
5901 (defvar org-edit-src-picture nil)
5903 (define-minor-mode org-exit-edit-mode
5904 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5906 (defun org-edit-src-code ()
5907 "Edit the source code example at point.
5908 An indirect buffer is created, and that buffer is then narrowed to the
5909 example at point and switched to the correct language mode. When done,
5910 exit by killing the buffer with \\[org-edit-src-exit]."
5911 (interactive)
5912 (let ((line (org-current-line))
5913 (case-fold-search t)
5914 (msg (substitute-command-keys
5915 "Edit, then exit with C-c ' (C-c and single quote)"))
5916 (info (org-edit-src-find-region-and-lang))
5917 (org-mode-p (eq major-mode 'org-mode))
5918 beg end lang lang-f single lfmt)
5919 (if (not info)
5921 (setq beg (nth 0 info)
5922 end (nth 1 info)
5923 lang (nth 2 info)
5924 single (nth 3 info)
5925 lfmt (nth 4 info)
5926 lang-f (intern (concat lang "-mode")))
5927 (unless (functionp lang-f)
5928 (error "No such language mode: %s" lang-f))
5929 (goto-line line)
5930 (if (get-buffer "*Org Edit Src Example*")
5931 (kill-buffer "*Org Edit Src Example*"))
5932 (switch-to-buffer (make-indirect-buffer (current-buffer)
5933 "*Org Edit Src Example*"))
5934 (narrow-to-region beg end)
5935 (remove-text-properties beg end '(display nil invisible nil
5936 intangible nil))
5937 (let ((org-inhibit-startup t))
5938 (funcall lang-f))
5939 (set (make-local-variable 'org-edit-src-force-single-line) single)
5940 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5941 (when lfmt
5942 (set (make-local-variable 'org-coderef-label-format) lfmt))
5943 (when org-mode-p
5944 (goto-char (point-min))
5945 (while (re-search-forward "^," nil t)
5946 (replace-match "")))
5947 (goto-line line)
5948 (org-exit-edit-mode)
5949 (org-set-local 'header-line-format msg)
5950 (message "%s" msg)
5951 t)))
5953 (defun org-edit-fixed-width-region ()
5954 "Edit the fixed-width ascii drawing at point.
5955 This must be a region where each line starts with a colon followed by
5956 a space character.
5957 An indirect buffer is created, and that buffer is then narrowed to the
5958 example at point and switched to artist-mode. When done,
5959 exit by killing the buffer with \\[org-edit-src-exit]."
5960 (interactive)
5961 (let ((line (org-current-line))
5962 (case-fold-search t)
5963 (msg (substitute-command-keys
5964 "Edit, then exit with C-c ' (C-c and single quote)"))
5965 (org-mode-p (eq major-mode 'org-mode))
5966 beg end)
5967 (beginning-of-line 1)
5968 (if (looking-at "[ \t]*[^:\n \t]")
5970 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5971 (setq beg (point) end beg)
5972 (save-excursion
5973 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5974 (setq beg (point-at-bol 2))
5975 (setq beg (point))))
5976 (save-excursion
5977 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5978 (setq end (1- (match-beginning 0)))
5979 (setq end (point))))
5980 (goto-line line))
5981 (if (get-buffer "*Org Edit Picture*")
5982 (kill-buffer "*Org Edit Picture*"))
5983 (switch-to-buffer (make-indirect-buffer (current-buffer)
5984 "*Org Edit Picture*"))
5985 (narrow-to-region beg end)
5986 (remove-text-properties beg end '(display nil invisible nil
5987 intangible nil))
5988 (when (fboundp 'font-lock-unfontify-region)
5989 (font-lock-unfontify-region (point-min) (point-max)))
5990 (cond
5991 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5992 (fundamental-mode)
5993 (artist-mode 1))
5994 (t (funcall org-edit-fixed-width-region-mode)))
5995 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5996 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5997 (set (make-local-variable 'org-edit-src-picture) t)
5998 (goto-char (point-min))
5999 (while (re-search-forward "^[ \t]*: ?" nil t)
6000 (replace-match ""))
6001 (goto-line line)
6002 (org-exit-edit-mode)
6003 (org-set-local 'header-line-format msg)
6004 (message "%s" msg)
6005 t)))
6008 (defun org-edit-src-find-region-and-lang ()
6009 "Find the region and language for a local edit.
6010 Return a list with beginning and end of the region, a string representing
6011 the language, a switch telling of the content should be in a single line."
6012 (let ((re-list
6013 (append
6014 org-edit-src-region-extra
6016 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6017 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6018 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6019 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6020 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6021 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6022 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6023 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6024 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6025 ("^#\\+html:" "\n" "html" single-line)
6026 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6027 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6028 ("^#\\+latex:" "\n" "latex" single-line)
6029 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6030 ("^#\\+ascii:" "\n" "ascii" single-line)
6032 (pos (point))
6033 re1 re2 single beg end lang lfmt match-re1)
6034 (catch 'exit
6035 (while (setq entry (pop re-list))
6036 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6037 single (nth 3 entry))
6038 (save-excursion
6039 (if (or (looking-at re1)
6040 (re-search-backward re1 nil t))
6041 (progn
6042 (setq match-re1 (match-string 0))
6043 (setq beg (match-end 0)
6044 lang (org-edit-src-get-lang lang)
6045 lfmt (org-edit-src-get-label-format match-re1))
6046 (if (and (re-search-forward re2 nil t)
6047 (>= (match-end 0) pos))
6048 (throw 'exit (list beg (match-beginning 0)
6049 lang single lfmt))))
6050 (if (or (looking-at re2)
6051 (re-search-forward re2 nil t))
6052 (progn
6053 (setq end (match-beginning 0))
6054 (if (and (re-search-backward re1 nil t)
6055 (<= (match-beginning 0) pos))
6056 (progn
6057 (setq lfmt (org-edit-src-get-label-format
6058 (match-string 0)))
6059 (throw 'exit
6060 (list (match-end 0) end
6061 (org-edit-src-get-lang lang)
6062 single lfmt))))))))))))
6064 (defun org-edit-src-get-lang (lang)
6065 "Extract the src language."
6066 (let ((m (match-string 0)))
6067 (cond
6068 ((stringp lang) lang)
6069 ((integerp lang) (match-string lang))
6070 ((and (eq lang 'lang)
6071 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6072 (match-string 1 m))
6073 ((and (eq lang 'style)
6074 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6075 (match-string 1 m))
6076 (t "fundamental"))))
6078 (defun org-edit-src-get-label-format (s)
6079 "Extract the label format."
6080 (save-match-data
6081 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6082 (match-string 1 s))))
6084 (defun org-edit-src-exit ()
6085 "Exit special edit and protect problematic lines."
6086 (interactive)
6087 (unless (buffer-base-buffer (current-buffer))
6088 (error "This is not an indirect buffer, something is wrong..."))
6089 (unless (> (point-min) 1)
6090 (error "This buffer is not narrowed, something is wrong..."))
6091 (goto-char (point-min))
6092 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6093 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6094 (when (org-bound-and-true-p org-edit-src-force-single-line)
6095 (goto-char (point-min))
6096 (while (re-search-forward "\n" nil t)
6097 (replace-match " "))
6098 (goto-char (point-min))
6099 (if (looking-at "\\s-*") (replace-match " "))
6100 (if (re-search-forward "\\s-+\\'" nil t)
6101 (replace-match "")))
6102 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6103 (goto-char (point-min))
6104 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6105 (replace-match ",\\1"))
6106 (when font-lock-mode
6107 (font-lock-unfontify-region (point-min) (point-max)))
6108 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6109 (when (org-bound-and-true-p org-edit-src-picture)
6110 (untabify (point-min) (point-max))
6111 (goto-char (point-min))
6112 (while (re-search-forward "^" nil t)
6113 (replace-match ": "))
6114 (when font-lock-mode
6115 (font-lock-unfontify-region (point-min) (point-max)))
6116 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6117 (kill-buffer (current-buffer))
6118 (and (org-mode-p) (org-restart-font-lock)))
6121 ;;; The orgstruct minor mode
6123 ;; Define a minor mode which can be used in other modes in order to
6124 ;; integrate the org-mode structure editing commands.
6126 ;; This is really a hack, because the org-mode structure commands use
6127 ;; keys which normally belong to the major mode. Here is how it
6128 ;; works: The minor mode defines all the keys necessary to operate the
6129 ;; structure commands, but wraps the commands into a function which
6130 ;; tests if the cursor is currently at a headline or a plain list
6131 ;; item. If that is the case, the structure command is used,
6132 ;; temporarily setting many Org-mode variables like regular
6133 ;; expressions for filling etc. However, when any of those keys is
6134 ;; used at a different location, function uses `key-binding' to look
6135 ;; up if the key has an associated command in another currently active
6136 ;; keymap (minor modes, major mode, global), and executes that
6137 ;; command. There might be problems if any of the keys is otherwise
6138 ;; used as a prefix key.
6140 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6141 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6142 ;; addresses this by checking explicitly for both bindings.
6144 (defvar orgstruct-mode-map (make-sparse-keymap)
6145 "Keymap for the minor `orgstruct-mode'.")
6147 (defvar org-local-vars nil
6148 "List of local variables, for use by `orgstruct-mode'")
6150 ;;;###autoload
6151 (define-minor-mode orgstruct-mode
6152 "Toggle the minor more `orgstruct-mode'.
6153 This mode is for using Org-mode structure commands in other modes.
6154 The following key behave as if Org-mode was active, if the cursor
6155 is on a headline, or on a plain list item (both in the definition
6156 of Org-mode).
6158 M-up Move entry/item up
6159 M-down Move entry/item down
6160 M-left Promote
6161 M-right Demote
6162 M-S-up Move entry/item up
6163 M-S-down Move entry/item down
6164 M-S-left Promote subtree
6165 M-S-right Demote subtree
6166 M-q Fill paragraph and items like in Org-mode
6167 C-c ^ Sort entries
6168 C-c - Cycle list bullet
6169 TAB Cycle item visibility
6170 M-RET Insert new heading/item
6171 S-M-RET Insert new TODO heading / Checkbox item
6172 C-c C-c Set tags / toggle checkbox"
6173 nil " OrgStruct" nil
6174 (org-load-modules-maybe)
6175 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6177 ;;;###autoload
6178 (defun turn-on-orgstruct ()
6179 "Unconditionally turn on `orgstruct-mode'."
6180 (orgstruct-mode 1))
6182 ;;;###autoload
6183 (defun turn-on-orgstruct++ ()
6184 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6185 In addition to setting orgstruct-mode, this also exports all indentation and
6186 autofilling variables from org-mode into the buffer. Note that turning
6187 off orgstruct-mode will *not* remove these additional settings."
6188 (orgstruct-mode 1)
6189 (let (var val)
6190 (mapc
6191 (lambda (x)
6192 (when (string-match
6193 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6194 (symbol-name (car x)))
6195 (setq var (car x) val (nth 1 x))
6196 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6197 org-local-vars)))
6199 (defun orgstruct-error ()
6200 "Error when there is no default binding for a structure key."
6201 (interactive)
6202 (error "This key has no function outside structure elements"))
6204 (defun orgstruct-setup ()
6205 "Setup orgstruct keymaps."
6206 (let ((nfunc 0)
6207 (bindings
6208 (list
6209 '([(meta up)] org-metaup)
6210 '([(meta down)] org-metadown)
6211 '([(meta left)] org-metaleft)
6212 '([(meta right)] org-metaright)
6213 '([(meta shift up)] org-shiftmetaup)
6214 '([(meta shift down)] org-shiftmetadown)
6215 '([(meta shift left)] org-shiftmetaleft)
6216 '([(meta shift right)] org-shiftmetaright)
6217 '([(shift up)] org-shiftup)
6218 '([(shift down)] org-shiftdown)
6219 '([(shift left)] org-shiftleft)
6220 '([(shift right)] org-shiftright)
6221 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6222 '("\M-q" fill-paragraph)
6223 '("\C-c^" org-sort)
6224 '("\C-c-" org-cycle-list-bullet)))
6225 elt key fun cmd)
6226 (while (setq elt (pop bindings))
6227 (setq nfunc (1+ nfunc))
6228 (setq key (org-key (car elt))
6229 fun (nth 1 elt)
6230 cmd (orgstruct-make-binding fun nfunc key))
6231 (org-defkey orgstruct-mode-map key cmd))
6233 ;; Special treatment needed for TAB and RET
6234 (org-defkey orgstruct-mode-map [(tab)]
6235 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6236 (org-defkey orgstruct-mode-map "\C-i"
6237 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6239 (org-defkey orgstruct-mode-map "\M-\C-m"
6240 (orgstruct-make-binding 'org-insert-heading 105
6241 "\M-\C-m" [(meta return)]))
6242 (org-defkey orgstruct-mode-map [(meta return)]
6243 (orgstruct-make-binding 'org-insert-heading 106
6244 [(meta return)] "\M-\C-m"))
6246 (org-defkey orgstruct-mode-map [(shift meta return)]
6247 (orgstruct-make-binding 'org-insert-todo-heading 107
6248 [(meta return)] "\M-\C-m"))
6250 (unless org-local-vars
6251 (setq org-local-vars (org-get-local-variables)))
6255 (defun orgstruct-make-binding (fun n &rest keys)
6256 "Create a function for binding in the structure minor mode.
6257 FUN is the command to call inside a table. N is used to create a unique
6258 command name. KEYS are keys that should be checked in for a command
6259 to execute outside of tables."
6260 (eval
6261 (list 'defun
6262 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6263 '(arg)
6264 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6265 "Outside of structure, run the binding of `"
6266 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6267 "'.")
6268 '(interactive "p")
6269 (list 'if
6270 '(org-context-p 'headline 'item)
6271 (list 'org-run-like-in-org-mode (list 'quote fun))
6272 (list 'let '(orgstruct-mode)
6273 (list 'call-interactively
6274 (append '(or)
6275 (mapcar (lambda (k)
6276 (list 'key-binding k))
6277 keys)
6278 '('orgstruct-error))))))))
6280 (defun org-context-p (&rest contexts)
6281 "Check if local context is any of CONTEXTS.
6282 Possible values in the list of contexts are `table', `headline', and `item'."
6283 (let ((pos (point)))
6284 (goto-char (point-at-bol))
6285 (prog1 (or (and (memq 'table contexts)
6286 (looking-at "[ \t]*|"))
6287 (and (memq 'headline contexts)
6288 ;;????????? (looking-at "\\*+"))
6289 (looking-at outline-regexp))
6290 (and (memq 'item contexts)
6291 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6292 (goto-char pos))))
6294 (defun org-get-local-variables ()
6295 "Return a list of all local variables in an org-mode buffer."
6296 (let (varlist)
6297 (with-current-buffer (get-buffer-create "*Org tmp*")
6298 (erase-buffer)
6299 (org-mode)
6300 (setq varlist (buffer-local-variables)))
6301 (kill-buffer "*Org tmp*")
6302 (delq nil
6303 (mapcar
6304 (lambda (x)
6305 (setq x
6306 (if (symbolp x)
6307 (list x)
6308 (list (car x) (list 'quote (cdr x)))))
6309 (if (string-match
6310 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6311 (symbol-name (car x)))
6312 x nil))
6313 varlist))))
6315 ;;;###autoload
6316 (defun org-run-like-in-org-mode (cmd)
6317 (org-load-modules-maybe)
6318 (unless org-local-vars
6319 (setq org-local-vars (org-get-local-variables)))
6320 (eval (list 'let org-local-vars
6321 (list 'call-interactively (list 'quote cmd)))))
6323 ;;;; Archiving
6325 (defun org-get-category (&optional pos)
6326 "Get the category applying to position POS."
6327 (get-text-property (or pos (point)) 'org-category))
6329 (defun org-refresh-category-properties ()
6330 "Refresh category text properties in the buffer."
6331 (let ((def-cat (cond
6332 ((null org-category)
6333 (if buffer-file-name
6334 (file-name-sans-extension
6335 (file-name-nondirectory buffer-file-name))
6336 "???"))
6337 ((symbolp org-category) (symbol-name org-category))
6338 (t org-category)))
6339 beg end cat pos optionp)
6340 (org-unmodified
6341 (save-excursion
6342 (save-restriction
6343 (widen)
6344 (goto-char (point-min))
6345 (put-text-property (point) (point-max) 'org-category def-cat)
6346 (while (re-search-forward
6347 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6348 (setq pos (match-end 0)
6349 optionp (equal (char-after (match-beginning 0)) ?#)
6350 cat (org-trim (match-string 2)))
6351 (if optionp
6352 (setq beg (point-at-bol) end (point-max))
6353 (org-back-to-heading t)
6354 (setq beg (point) end (org-end-of-subtree t t)))
6355 (put-text-property beg end 'org-category cat)
6356 (goto-char pos)))))))
6359 ;;;; Link Stuff
6361 ;;; Link abbreviations
6363 (defun org-link-expand-abbrev (link)
6364 "Apply replacements as defined in `org-link-abbrev-alist."
6365 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6366 (let* ((key (match-string 1 link))
6367 (as (or (assoc key org-link-abbrev-alist-local)
6368 (assoc key org-link-abbrev-alist)))
6369 (tag (and (match-end 2) (match-string 3 link)))
6370 rpl)
6371 (if (not as)
6372 link
6373 (setq rpl (cdr as))
6374 (cond
6375 ((symbolp rpl) (funcall rpl tag))
6376 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6377 ((string-match "%h" rpl)
6378 (replace-match (url-hexify-string (or tag "")) t t rpl))
6379 (t (concat rpl tag)))))
6380 link))
6382 ;;; Storing and inserting links
6384 (defvar org-insert-link-history nil
6385 "Minibuffer history for links inserted with `org-insert-link'.")
6387 (defvar org-stored-links nil
6388 "Contains the links stored with `org-store-link'.")
6390 (defvar org-store-link-plist nil
6391 "Plist with info about the most recently link created with `org-store-link'.")
6393 (defvar org-link-protocols nil
6394 "Link protocols added to Org-mode using `org-add-link-type'.")
6396 (defvar org-store-link-functions nil
6397 "List of functions that are called to create and store a link.
6398 Each function will be called in turn until one returns a non-nil
6399 value. Each function should check if it is responsible for creating
6400 this link (for example by looking at the major mode).
6401 If not, it must exit and return nil.
6402 If yes, it should return a non-nil value after a calling
6403 `org-store-link-props' with a list of properties and values.
6404 Special properties are:
6406 :type The link prefix. like \"http\". This must be given.
6407 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6408 This is obligatory as well.
6409 :description Optional default description for the second pair
6410 of brackets in an Org-mode link. The user can still change
6411 this when inserting this link into an Org-mode buffer.
6413 In addition to these, any additional properties can be specified
6414 and then used in remember templates.")
6416 (defun org-add-link-type (type &optional follow export)
6417 "Add TYPE to the list of `org-link-types'.
6418 Re-compute all regular expressions depending on `org-link-types'
6420 FOLLOW and EXPORT are two functions.
6422 FOLLOW should take the link path as the single argument and do whatever
6423 is necessary to follow the link, for example find a file or display
6424 a mail message.
6426 EXPORT should format the link path for export to one of the export formats.
6427 It should be a function accepting three arguments:
6429 path the path of the link, the text after the prefix (like \"http:\")
6430 desc the description of the link, if any, nil if there was no description
6431 format the export format, a symbol like `html' or `latex'.
6433 The function may use the FORMAT information to return different values
6434 depending on the format. The return value will be put literally into
6435 the exported file.
6436 Org-mode has a built-in default for exporting links. If you are happy with
6437 this default, there is no need to define an export function for the link
6438 type. For a simple example of an export function, see `org-bbdb.el'."
6439 (add-to-list 'org-link-types type t)
6440 (org-make-link-regexps)
6441 (if (assoc type org-link-protocols)
6442 (setcdr (assoc type org-link-protocols) (list follow export))
6443 (push (list type follow export) org-link-protocols)))
6445 ;;;###autoload
6446 (defun org-store-link (arg)
6447 "\\<org-mode-map>Store an org-link to the current location.
6448 This link is added to `org-stored-links' and can later be inserted
6449 into an org-buffer with \\[org-insert-link].
6451 For some link types, a prefix arg is interpreted:
6452 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6453 For file links, arg negates `org-context-in-file-links'."
6454 (interactive "P")
6455 (org-load-modules-maybe)
6456 (setq org-store-link-plist nil) ; reset
6457 (let (link cpltxt desc description search txt)
6458 (cond
6460 ((run-hook-with-args-until-success 'org-store-link-functions)
6461 (setq link (plist-get org-store-link-plist :link)
6462 desc (or (plist-get org-store-link-plist :description) link)))
6464 ((equal (buffer-name) "*Org Edit Src Example*")
6465 (let (label gc)
6466 (while (or (not label)
6467 (save-excursion
6468 (save-restriction
6469 (widen)
6470 (goto-char (point-min))
6471 (re-search-forward
6472 (regexp-quote (format org-coderef-label-format label))
6473 nil t))))
6474 (when label (message "Label exists already") (sit-for 2))
6475 (setq label (read-string "Code line label: " label)))
6476 (end-of-line 1)
6477 (setq link (format org-coderef-label-format label))
6478 (setq gc (- 79 (length link)))
6479 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6480 (insert link)
6481 (setq link (concat "(" label ")") desc nil)))
6483 ((eq major-mode 'calendar-mode)
6484 (let ((cd (calendar-cursor-to-date)))
6485 (setq link
6486 (format-time-string
6487 (car org-time-stamp-formats)
6488 (apply 'encode-time
6489 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6490 nil nil nil))))
6491 (org-store-link-props :type "calendar" :date cd)))
6493 ((eq major-mode 'w3-mode)
6494 (setq cpltxt (url-view-url t)
6495 link (org-make-link cpltxt))
6496 (org-store-link-props :type "w3" :url (url-view-url t)))
6498 ((eq major-mode 'w3m-mode)
6499 (setq cpltxt (or w3m-current-title w3m-current-url)
6500 link (org-make-link w3m-current-url))
6501 (org-store-link-props :type "w3m" :url (url-view-url t)))
6503 ((setq search (run-hook-with-args-until-success
6504 'org-create-file-search-functions))
6505 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6506 "::" search))
6507 (setq cpltxt (or description link)))
6509 ((eq major-mode 'image-mode)
6510 (setq cpltxt (concat "file:"
6511 (abbreviate-file-name buffer-file-name))
6512 link (org-make-link cpltxt))
6513 (org-store-link-props :type "image" :file buffer-file-name))
6515 ((eq major-mode 'dired-mode)
6516 ;; link to the file in the current line
6517 (setq cpltxt (concat "file:"
6518 (abbreviate-file-name
6519 (expand-file-name
6520 (dired-get-filename nil t))))
6521 link (org-make-link cpltxt)))
6523 ((and buffer-file-name (org-mode-p))
6524 (cond
6525 ((org-in-regexp "<<\\(.*?\\)>>")
6526 (setq cpltxt
6527 (concat "file:"
6528 (abbreviate-file-name buffer-file-name)
6529 "::" (match-string 1))
6530 link (org-make-link cpltxt)))
6531 ((and (featurep 'org-id)
6532 (or (eq org-link-to-org-use-id t)
6533 (and (eq org-link-to-org-use-id 'create-if-interactive)
6534 (interactive-p))
6535 (and org-link-to-org-use-id
6536 (condition-case nil
6537 (org-entry-get nil "ID")
6538 (error nil)))))
6539 ;; We can make a link using the ID.
6540 (setq link (condition-case nil
6541 (prog1 (org-id-store-link)
6542 (setq desc (plist-get org-store-link-plist
6543 :description)))
6544 (error
6545 ;; probably before first headline, link to file only
6546 (concat "file:"
6547 (abbreviate-file-name buffer-file-name))))))
6549 ;; Just link to current headline
6550 (setq cpltxt (concat "file:"
6551 (abbreviate-file-name buffer-file-name)))
6552 ;; Add a context search string
6553 (when (org-xor org-context-in-file-links arg)
6554 (setq txt (cond
6555 ((org-on-heading-p) nil)
6556 ((org-region-active-p)
6557 (buffer-substring (region-beginning) (region-end)))
6558 (t nil)))
6559 (when (or (null txt) (string-match "\\S-" txt))
6560 (setq cpltxt
6561 (concat cpltxt "::"
6562 (condition-case nil
6563 (org-make-org-heading-search-string txt)
6564 (error "")))
6565 desc "NONE")))
6566 (if (string-match "::\\'" cpltxt)
6567 (setq cpltxt (substring cpltxt 0 -2)))
6568 (setq link (org-make-link cpltxt)))))
6570 ((buffer-file-name (buffer-base-buffer))
6571 ;; Just link to this file here.
6572 (setq cpltxt (concat "file:"
6573 (abbreviate-file-name
6574 (buffer-file-name (buffer-base-buffer)))))
6575 ;; Add a context string
6576 (when (org-xor org-context-in-file-links arg)
6577 (setq txt (if (org-region-active-p)
6578 (buffer-substring (region-beginning) (region-end))
6579 (buffer-substring (point-at-bol) (point-at-eol))))
6580 ;; Only use search option if there is some text.
6581 (when (string-match "\\S-" txt)
6582 (setq cpltxt
6583 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6584 desc "NONE")))
6585 (setq link (org-make-link cpltxt)))
6587 ((interactive-p)
6588 (error "Cannot link to a buffer which is not visiting a file"))
6590 (t (setq link nil)))
6592 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6593 (setq link (or link cpltxt)
6594 desc (or desc cpltxt))
6595 (if (equal desc "NONE") (setq desc nil))
6597 (if (and (interactive-p) link)
6598 (progn
6599 (setq org-stored-links
6600 (cons (list link desc) org-stored-links))
6601 (message "Stored: %s" (or desc link)))
6602 (and link (org-make-link-string link desc)))))
6604 (defun org-store-link-props (&rest plist)
6605 "Store link properties, extract names and addresses."
6606 (let (x adr)
6607 (when (setq x (plist-get plist :from))
6608 (setq adr (mail-extract-address-components x))
6609 (setq plist (plist-put plist :fromname (car adr)))
6610 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6611 (when (setq x (plist-get plist :to))
6612 (setq adr (mail-extract-address-components x))
6613 (setq plist (plist-put plist :toname (car adr)))
6614 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6615 (let ((from (plist-get plist :from))
6616 (to (plist-get plist :to)))
6617 (when (and from to org-from-is-user-regexp)
6618 (setq plist
6619 (plist-put plist :fromto
6620 (if (string-match org-from-is-user-regexp from)
6621 (concat "to %t")
6622 (concat "from %f"))))))
6623 (setq org-store-link-plist plist))
6625 (defun org-add-link-props (&rest plist)
6626 "Add these properties to the link property list."
6627 (let (key value)
6628 (while plist
6629 (setq key (pop plist) value (pop plist))
6630 (setq org-store-link-plist
6631 (plist-put org-store-link-plist key value)))))
6633 (defun org-email-link-description (&optional fmt)
6634 "Return the description part of an email link.
6635 This takes information from `org-store-link-plist' and formats it
6636 according to FMT (default from `org-email-link-description-format')."
6637 (setq fmt (or fmt org-email-link-description-format))
6638 (let* ((p org-store-link-plist)
6639 (to (plist-get p :toaddress))
6640 (from (plist-get p :fromaddress))
6641 (table
6642 (list
6643 (cons "%c" (plist-get p :fromto))
6644 (cons "%F" (plist-get p :from))
6645 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6646 (cons "%T" (plist-get p :to))
6647 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6648 (cons "%s" (plist-get p :subject))
6649 (cons "%m" (plist-get p :message-id)))))
6650 (when (string-match "%c" fmt)
6651 ;; Check if the user wrote this message
6652 (if (and org-from-is-user-regexp from to
6653 (save-match-data (string-match org-from-is-user-regexp from)))
6654 (setq fmt (replace-match "to %t" t t fmt))
6655 (setq fmt (replace-match "from %f" t t fmt))))
6656 (org-replace-escapes fmt table)))
6658 (defun org-make-org-heading-search-string (&optional string heading)
6659 "Make search string for STRING or current headline."
6660 (interactive)
6661 (let ((s (or string (org-get-heading))))
6662 (unless (and string (not heading))
6663 ;; We are using a headline, clean up garbage in there.
6664 (if (string-match org-todo-regexp s)
6665 (setq s (replace-match "" t t s)))
6666 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6667 (setq s (replace-match "" t t s)))
6668 (setq s (org-trim s))
6669 (if (string-match (concat "^\\(" org-quote-string "\\|"
6670 org-comment-string "\\)") s)
6671 (setq s (replace-match "" t t s)))
6672 (while (string-match org-ts-regexp s)
6673 (setq s (replace-match "" t t s))))
6674 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6675 (setq s (replace-match " " t t s)))
6676 (or string (setq s (concat "*" s))) ; Add * for headlines
6677 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6679 (defun org-make-link (&rest strings)
6680 "Concatenate STRINGS."
6681 (apply 'concat strings))
6683 (defun org-make-link-string (link &optional description)
6684 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6685 (unless (string-match "\\S-" link)
6686 (error "Empty link"))
6687 (when (stringp description)
6688 ;; Remove brackets from the description, they are fatal.
6689 (while (string-match "\\[" description)
6690 (setq description (replace-match "{" t t description)))
6691 (while (string-match "\\]" description)
6692 (setq description (replace-match "}" t t description))))
6693 (when (equal (org-link-escape link) description)
6694 ;; No description needed, it is identical
6695 (setq description nil))
6696 (when (and (not description)
6697 (not (equal link (org-link-escape link))))
6698 (setq description (org-extract-attributes link)))
6699 (concat "[[" (org-link-escape link) "]"
6700 (if description (concat "[" description "]") "")
6701 "]"))
6703 (defconst org-link-escape-chars
6704 '((?\ . "%20")
6705 (?\[ . "%5B")
6706 (?\] . "%5D")
6707 (?\340 . "%E0") ; `a
6708 (?\342 . "%E2") ; ^a
6709 (?\347 . "%E7") ; ,c
6710 (?\350 . "%E8") ; `e
6711 (?\351 . "%E9") ; 'e
6712 (?\352 . "%EA") ; ^e
6713 (?\356 . "%EE") ; ^i
6714 (?\364 . "%F4") ; ^o
6715 (?\371 . "%F9") ; `u
6716 (?\373 . "%FB") ; ^u
6717 (?\; . "%3B")
6718 (?? . "%3F")
6719 (?= . "%3D")
6720 (?+ . "%2B")
6722 "Association list of escapes for some characters problematic in links.
6723 This is the list that is used for internal purposes.")
6725 (defconst org-link-escape-chars-browser
6726 '((?\ . "%20")) ; 32 for the SPC char
6727 "Association list of escapes for some characters problematic in links.
6728 This is the list that is used before handing over to the browser.")
6730 (defun org-link-escape (text &optional table)
6731 "Escape characters in TEXT that are problematic for links."
6732 (setq table (or table org-link-escape-chars))
6733 (when text
6734 (let ((re (mapconcat (lambda (x) (regexp-quote
6735 (char-to-string (car x))))
6736 table "\\|")))
6737 (while (string-match re text)
6738 (setq text
6739 (replace-match
6740 (cdr (assoc (string-to-char (match-string 0 text))
6741 table))
6742 t t text)))
6743 text)))
6745 (defun org-link-unescape (text &optional table)
6746 "Reverse the action of `org-link-escape'."
6747 (setq table (or table org-link-escape-chars))
6748 (when text
6749 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6750 table "\\|")))
6751 (while (string-match re text)
6752 (setq text
6753 (replace-match
6754 (char-to-string (car (rassoc (match-string 0 text) table)))
6755 t t text)))
6756 text)))
6758 (defun org-xor (a b)
6759 "Exclusive or."
6760 (if a (not b) b))
6762 (defun org-fixup-message-id-for-http (s)
6763 "Replace special characters in a message id, so it can be used in an http query."
6764 (while (string-match "<" s)
6765 (setq s (replace-match "%3C" t t s)))
6766 (while (string-match ">" s)
6767 (setq s (replace-match "%3E" t t s)))
6768 (while (string-match "@" s)
6769 (setq s (replace-match "%40" t t s)))
6772 ;;;###autoload
6773 (defun org-insert-link-global ()
6774 "Insert a link like Org-mode does.
6775 This command can be called in any mode to insert a link in Org-mode syntax."
6776 (interactive)
6777 (org-load-modules-maybe)
6778 (org-run-like-in-org-mode 'org-insert-link))
6780 (defun org-insert-link (&optional complete-file link-location)
6781 "Insert a link. At the prompt, enter the link.
6783 Completion can be used to insert any of the link protocol prefixes like
6784 http or ftp in use.
6786 The history can be used to select a link previously stored with
6787 `org-store-link'. When the empty string is entered (i.e. if you just
6788 press RET at the prompt), the link defaults to the most recently
6789 stored link. As SPC triggers completion in the minibuffer, you need to
6790 use M-SPC or C-q SPC to force the insertion of a space character.
6792 You will also be prompted for a description, and if one is given, it will
6793 be displayed in the buffer instead of the link.
6795 If there is already a link at point, this command will allow you to edit link
6796 and description parts.
6798 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6799 be selected using completion. The path to the file will be relative to the
6800 current directory if the file is in the current directory or a subdirectory.
6801 Otherwise, the link will be the absolute path as completed in the minibuffer
6802 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6803 option `org-link-file-path-type'.
6805 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6806 the current directory or below.
6808 With three \\[universal-argument] prefixes, negate the meaning of
6809 `org-keep-stored-link-after-insertion'.
6811 If `org-make-link-description-function' is non-nil, this function will be
6812 called with the link target, and the result will be the default
6813 link description.
6815 If the LINK-LOCATION parameter is non-nil, this value will be
6816 used as the link location instead of reading one interactively."
6817 (interactive "P")
6818 (let* ((wcf (current-window-configuration))
6819 (region (if (org-region-active-p)
6820 (buffer-substring (region-beginning) (region-end))))
6821 (remove (and region (list (region-beginning) (region-end))))
6822 (desc region)
6823 tmphist ; byte-compile incorrectly complains about this
6824 (link link-location)
6825 entry file)
6826 (cond
6827 (link-location) ; specified by arg, just use it.
6828 ((org-in-regexp org-bracket-link-regexp 1)
6829 ;; We do have a link at point, and we are going to edit it.
6830 (setq remove (list (match-beginning 0) (match-end 0)))
6831 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6832 (setq link (read-string "Link: "
6833 (org-link-unescape
6834 (org-match-string-no-properties 1)))))
6835 ((or (org-in-regexp org-angle-link-re)
6836 (org-in-regexp org-plain-link-re))
6837 ;; Convert to bracket link
6838 (setq remove (list (match-beginning 0) (match-end 0))
6839 link (read-string "Link: "
6840 (org-remove-angle-brackets (match-string 0)))))
6841 ((member complete-file '((4) (16)))
6842 ;; Completing read for file names.
6843 (setq file (read-file-name "File: "))
6844 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6845 (pwd1 (file-name-as-directory (abbreviate-file-name
6846 (expand-file-name ".")))))
6847 (cond
6848 ((equal complete-file '(16))
6849 (setq link (org-make-link
6850 "file:"
6851 (abbreviate-file-name (expand-file-name file)))))
6852 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6853 (setq link (org-make-link "file:" (match-string 1 file))))
6854 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6855 (expand-file-name file))
6856 (setq link (org-make-link
6857 "file:" (match-string 1 (expand-file-name file)))))
6858 (t (setq link (org-make-link "file:" file))))))
6860 ;; Read link, with completion for stored links.
6861 (with-output-to-temp-buffer "*Org Links*"
6862 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6863 (when org-stored-links
6864 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6865 (princ (mapconcat
6866 (lambda (x)
6867 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6868 (reverse org-stored-links) "\n"))))
6869 (let ((cw (selected-window)))
6870 (select-window (get-buffer-window "*Org Links*"))
6871 (setq truncate-lines t)
6872 (org-fit-window-to-buffer)
6873 (select-window cw))
6874 ;; Fake a link history, containing the stored links.
6875 (setq tmphist (append (mapcar 'car org-stored-links)
6876 org-insert-link-history))
6877 (unwind-protect
6878 (setq link
6879 (let ((org-completion-use-ido nil))
6880 (org-completing-read
6881 "Link: "
6882 (append
6883 (mapcar (lambda (x) (list (concat (car x) ":")))
6884 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6885 (mapcar (lambda (x) (list (concat x ":")))
6886 org-link-types))
6887 nil nil nil
6888 'tmphist
6889 (or (car (car org-stored-links))))))
6890 (set-window-configuration wcf)
6891 (kill-buffer "*Org Links*"))
6892 (setq entry (assoc link org-stored-links))
6893 (or entry (push link org-insert-link-history))
6894 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6895 (not org-keep-stored-link-after-insertion))
6896 (setq org-stored-links (delq (assoc link org-stored-links)
6897 org-stored-links)))
6898 (setq desc (or desc (nth 1 entry)))))
6900 (if (string-match org-plain-link-re link)
6901 ;; URL-like link, normalize the use of angular brackets.
6902 (setq link (org-make-link (org-remove-angle-brackets link))))
6904 ;; Check if we are linking to the current file with a search option
6905 ;; If yes, simplify the link by using only the search option.
6906 (when (and buffer-file-name
6907 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6908 (let* ((path (match-string 1 link))
6909 (case-fold-search nil)
6910 (search (match-string 2 link)))
6911 (save-match-data
6912 (if (equal (file-truename buffer-file-name) (file-truename path))
6913 ;; We are linking to this same file, with a search option
6914 (setq link search)))))
6916 ;; Check if we can/should use a relative path. If yes, simplify the link
6917 (when (string-match "^file:\\(.*\\)" link)
6918 (let* ((path (match-string 1 link))
6919 (origpath path)
6920 (case-fold-search nil))
6921 (cond
6922 ((or (eq org-link-file-path-type 'absolute)
6923 (equal complete-file '(16)))
6924 (setq path (abbreviate-file-name (expand-file-name path))))
6925 ((eq org-link-file-path-type 'noabbrev)
6926 (setq path (expand-file-name path)))
6927 ((eq org-link-file-path-type 'relative)
6928 (setq path (file-relative-name path)))
6930 (save-match-data
6931 (if (string-match (concat "^" (regexp-quote
6932 (file-name-as-directory
6933 (expand-file-name "."))))
6934 (expand-file-name path))
6935 ;; We are linking a file with relative path name.
6936 (setq path (substring (expand-file-name path)
6937 (match-end 0)))
6938 (setq path (abbreviate-file-name (expand-file-name path)))))))
6939 (setq link (concat "file:" path))
6940 (if (equal desc origpath)
6941 (setq desc path))))
6943 (if org-make-link-description-function
6944 (setq desc (funcall org-make-link-description-function link desc)))
6946 (setq desc (read-string "Description: " desc))
6947 (unless (string-match "\\S-" desc) (setq desc nil))
6948 (if remove (apply 'delete-region remove))
6949 (insert (org-make-link-string link desc))))
6951 (defun org-completing-read (&rest args)
6952 "Completing-read with SPACE being a normal character."
6953 (let ((minibuffer-local-completion-map
6954 (copy-keymap minibuffer-local-completion-map)))
6955 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6956 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6957 (apply 'org-ido-completing-read args)))
6959 (defun org-ido-completing-read (&rest args)
6960 "Completing-read using `ido-mode' speedups if available"
6961 (if (and org-completion-use-ido
6962 (fboundp 'ido-completing-read)
6963 (boundp 'ido-mode) ido-mode
6964 (listp (second args)))
6965 (apply 'ido-completing-read (concat (car args)) (cdr args))
6966 (apply 'completing-read args)))
6968 (defun org-extract-attributes (s)
6969 "Extract the attributes cookie from a string and set as text property."
6970 (let (a attr (start 0) key value)
6971 (save-match-data
6972 (when (string-match "{{\\([^}]+\\)}}$" s)
6973 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6974 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6975 (setq key (match-string 1 a) value (match-string 2 a)
6976 start (match-end 0)
6977 attr (plist-put attr (intern key) value))))
6978 (org-add-props s nil 'org-attr attr))
6981 (defun org-attributes-to-string (plist)
6982 "Format a property list into an HTML attribute list."
6983 (let ((s "") key value)
6984 (while plist
6985 (setq key (pop plist) value (pop plist))
6986 (and value
6987 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6990 ;;; Opening/following a link
6992 (defvar org-link-search-failed nil)
6994 (defun org-next-link ()
6995 "Move forward to the next link.
6996 If the link is in hidden text, expose it."
6997 (interactive)
6998 (when (and org-link-search-failed (eq this-command last-command))
6999 (goto-char (point-min))
7000 (message "Link search wrapped back to beginning of buffer"))
7001 (setq org-link-search-failed nil)
7002 (let* ((pos (point))
7003 (ct (org-context))
7004 (a (assoc :link ct)))
7005 (if a (goto-char (nth 2 a)))
7006 (if (re-search-forward org-any-link-re nil t)
7007 (progn
7008 (goto-char (match-beginning 0))
7009 (if (org-invisible-p) (org-show-context)))
7010 (goto-char pos)
7011 (setq org-link-search-failed t)
7012 (error "No further link found"))))
7014 (defun org-previous-link ()
7015 "Move backward to the previous link.
7016 If the link is in hidden text, expose it."
7017 (interactive)
7018 (when (and org-link-search-failed (eq this-command last-command))
7019 (goto-char (point-max))
7020 (message "Link search wrapped back to end of buffer"))
7021 (setq org-link-search-failed nil)
7022 (let* ((pos (point))
7023 (ct (org-context))
7024 (a (assoc :link ct)))
7025 (if a (goto-char (nth 1 a)))
7026 (if (re-search-backward org-any-link-re nil t)
7027 (progn
7028 (goto-char (match-beginning 0))
7029 (if (org-invisible-p) (org-show-context)))
7030 (goto-char pos)
7031 (setq org-link-search-failed t)
7032 (error "No further link found"))))
7034 (defun org-translate-link (s)
7035 "Translate a link string if a translation function has been defined."
7036 (if (and org-link-translation-function
7037 (fboundp org-link-translation-function)
7038 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7039 (progn
7040 (setq s (funcall org-link-translation-function
7041 (match-string 1) (match-string 2)))
7042 (concat (car s) ":" (cdr s)))
7045 (defun org-translate-link-from-planner (type path)
7046 "Translate a link from Emacs Planner syntax so that Org can follow it.
7047 This is still an experimental function, your mileage may vary."
7048 (cond
7049 ((member type '("http" "https" "news" "ftp"))
7050 ;; standard Internet links are the same.
7051 nil)
7052 ((and (equal type "irc") (string-match "^//" path))
7053 ;; Planner has two / at the beginning of an irc link, we have 1.
7054 ;; We should have zero, actually....
7055 (setq path (substring path 1)))
7056 ((and (equal type "lisp") (string-match "^/" path))
7057 ;; Planner has a slash, we do not.
7058 (setq type "elisp" path (substring path 1)))
7059 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7060 ;; A typical message link. Planner has the id after the fina slash,
7061 ;; we separate it with a hash mark
7062 (setq path (concat (match-string 1 path) "#"
7063 (org-remove-angle-brackets (match-string 2 path)))))
7065 (cons type path))
7067 (defun org-find-file-at-mouse (ev)
7068 "Open file link or URL at mouse."
7069 (interactive "e")
7070 (mouse-set-point ev)
7071 (org-open-at-point 'in-emacs))
7073 (defun org-open-at-mouse (ev)
7074 "Open file link or URL at mouse."
7075 (interactive "e")
7076 (mouse-set-point ev)
7077 (if (eq major-mode 'org-agenda-mode)
7078 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7079 (org-open-at-point))
7081 (defvar org-window-config-before-follow-link nil
7082 "The window configuration before following a link.
7083 This is saved in case the need arises to restore it.")
7085 (defvar org-open-link-marker (make-marker)
7086 "Marker pointing to the location where `org-open-at-point; was called.")
7088 ;;;###autoload
7089 (defun org-open-at-point-global ()
7090 "Follow a link like Org-mode does.
7091 This command can be called in any mode to follow a link that has
7092 Org-mode syntax."
7093 (interactive)
7094 (org-run-like-in-org-mode 'org-open-at-point))
7096 ;;;###autoload
7097 (defun org-open-link-from-string (s &optional arg)
7098 "Open a link in the string S, as if it was in Org-mode."
7099 (interactive "sLink: \nP")
7100 (with-temp-buffer
7101 (let ((org-inhibit-startup t))
7102 (org-mode)
7103 (insert s)
7104 (goto-char (point-min))
7105 (org-open-at-point arg))))
7107 (defun org-open-at-point (&optional in-emacs)
7108 "Open link at or after point.
7109 If there is no link at point, this function will search forward up to
7110 the end of the current subtree.
7111 Normally, files will be opened by an appropriate application. If the
7112 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7113 With a double prefix argument, try to open outside of Emacs, in the
7114 application the system uses for this file type."
7115 (interactive "P")
7116 (org-load-modules-maybe)
7117 (move-marker org-open-link-marker (point))
7118 (setq org-window-config-before-follow-link (current-window-configuration))
7119 (org-remove-occur-highlights nil nil t)
7120 (cond
7121 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7122 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7123 (org-footnote-action))
7125 (let (type path link line search (pos (point)))
7126 (catch 'match
7127 (save-excursion
7128 (skip-chars-forward "^]\n\r")
7129 (when (org-in-regexp org-bracket-link-regexp)
7130 (setq link (org-extract-attributes
7131 (org-link-unescape (org-match-string-no-properties 1))))
7132 (while (string-match " *\n *" link)
7133 (setq link (replace-match " " t t link)))
7134 (setq link (org-link-expand-abbrev link))
7135 (cond
7136 ((or (file-name-absolute-p link)
7137 (string-match "^\\.\\.?/" link))
7138 (setq type "file" path link))
7139 ((string-match org-link-re-with-space3 link)
7140 (setq type (match-string 1 link) path (match-string 2 link)))
7141 (t (setq type "thisfile" path link)))
7142 (throw 'match t)))
7144 (when (get-text-property (point) 'org-linked-text)
7145 (setq type "thisfile"
7146 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7147 (1+ (point)) (point))
7148 path (buffer-substring
7149 (previous-single-property-change pos 'org-linked-text)
7150 (next-single-property-change pos 'org-linked-text)))
7151 (throw 'match t))
7153 (save-excursion
7154 (when (or (org-in-regexp org-angle-link-re)
7155 (org-in-regexp org-plain-link-re))
7156 (setq type (match-string 1) path (match-string 2))
7157 (throw 'match t)))
7158 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7159 (setq type "tree-match"
7160 path (match-string 1))
7161 (throw 'match t))
7162 (save-excursion
7163 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7164 (setq type "tags"
7165 path (match-string 1))
7166 (while (string-match ":" path)
7167 (setq path (replace-match "+" t t path)))
7168 (throw 'match t))))
7169 (unless path
7170 (error "No link found"))
7171 ;; Remove any trailing spaces in path
7172 (if (string-match " +\\'" path)
7173 (setq path (replace-match "" t t path)))
7174 (if (and org-link-translation-function
7175 (fboundp org-link-translation-function))
7176 ;; Check if we need to translate the link
7177 (let ((tmp (funcall org-link-translation-function type path)))
7178 (setq type (car tmp) path (cdr tmp))))
7180 (cond
7182 ((assoc type org-link-protocols)
7183 (funcall (nth 1 (assoc type org-link-protocols)) path))
7185 ((equal type "mailto")
7186 (let ((cmd (car org-link-mailto-program))
7187 (args (cdr org-link-mailto-program)) args1
7188 (address path) (subject "") a)
7189 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7190 (setq address (match-string 1 path)
7191 subject (org-link-escape (match-string 2 path))))
7192 (while args
7193 (cond
7194 ((not (stringp (car args))) (push (pop args) args1))
7195 (t (setq a (pop args))
7196 (if (string-match "%a" a)
7197 (setq a (replace-match address t t a)))
7198 (if (string-match "%s" a)
7199 (setq a (replace-match subject t t a)))
7200 (push a args1))))
7201 (apply cmd (nreverse args1))))
7203 ((member type '("http" "https" "ftp" "news"))
7204 (browse-url (concat type ":" (org-link-escape
7205 path org-link-escape-chars-browser))))
7207 ((member type '("message"))
7208 (browse-url (concat type ":" path)))
7210 ((string= type "tags")
7211 (org-tags-view in-emacs path))
7212 ((string= type "thisfile")
7213 (if in-emacs
7214 (switch-to-buffer-other-window
7215 (org-get-buffer-for-internal-link (current-buffer)))
7216 (org-mark-ring-push))
7217 (let ((cmd `(org-link-search
7218 ,path
7219 ,(cond ((equal in-emacs '(4)) 'occur)
7220 ((equal in-emacs '(16)) 'org-occur)
7221 (t nil))
7222 ,pos)))
7223 (condition-case nil (eval cmd)
7224 (error (progn (widen) (eval cmd))))))
7226 ((string= type "tree-match")
7227 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7229 ((string= type "file")
7230 (if (string-match "::\\([0-9]+\\)\\'" path)
7231 (setq line (string-to-number (match-string 1 path))
7232 path (substring path 0 (match-beginning 0)))
7233 (if (string-match "::\\(.+\\)\\'" path)
7234 (setq search (match-string 1 path)
7235 path (substring path 0 (match-beginning 0)))))
7236 (if (string-match "[*?{]" (file-name-nondirectory path))
7237 (dired path)
7238 (org-open-file path in-emacs line search)))
7240 ((string= type "news")
7241 (require 'org-gnus)
7242 (org-gnus-follow-link path))
7244 ((string= type "shell")
7245 (let ((cmd path))
7246 (if (or (not org-confirm-shell-link-function)
7247 (funcall org-confirm-shell-link-function
7248 (format "Execute \"%s\" in shell? "
7249 (org-add-props cmd nil
7250 'face 'org-warning))))
7251 (progn
7252 (message "Executing %s" cmd)
7253 (shell-command cmd))
7254 (error "Abort"))))
7256 ((string= type "elisp")
7257 (let ((cmd path))
7258 (if (or (not org-confirm-elisp-link-function)
7259 (funcall org-confirm-elisp-link-function
7260 (format "Execute \"%s\" as elisp? "
7261 (org-add-props cmd nil
7262 'face 'org-warning))))
7263 (message "%s => %s" cmd
7264 (if (equal (string-to-char cmd) ?\()
7265 (eval (read cmd))
7266 (call-interactively (read cmd))))
7267 (error "Abort"))))
7270 (browse-url-at-point))))))
7271 (move-marker org-open-link-marker nil)
7272 (run-hook-with-args 'org-follow-link-hook))
7274 ;;;; Time estimates
7276 (defun org-get-effort (&optional pom)
7277 "Get the effort estimate for the current entry."
7278 (org-entry-get pom org-effort-property))
7280 ;;; File search
7282 (defvar org-create-file-search-functions nil
7283 "List of functions to construct the right search string for a file link.
7284 These functions are called in turn with point at the location to
7285 which the link should point.
7287 A function in the hook should first test if it would like to
7288 handle this file type, for example by checking the major-mode or
7289 the file extension. If it decides not to handle this file, it
7290 should just return nil to give other functions a chance. If it
7291 does handle the file, it must return the search string to be used
7292 when following the link. The search string will be part of the
7293 file link, given after a double colon, and `org-open-at-point'
7294 will automatically search for it. If special measures must be
7295 taken to make the search successful, another function should be
7296 added to the companion hook `org-execute-file-search-functions',
7297 which see.
7299 A function in this hook may also use `setq' to set the variable
7300 `description' to provide a suggestion for the descriptive text to
7301 be used for this link when it gets inserted into an Org-mode
7302 buffer with \\[org-insert-link].")
7304 (defvar org-execute-file-search-functions nil
7305 "List of functions to execute a file search triggered by a link.
7307 Functions added to this hook must accept a single argument, the
7308 search string that was part of the file link, the part after the
7309 double colon. The function must first check if it would like to
7310 handle this search, for example by checking the major-mode or the
7311 file extension. If it decides not to handle this search, it
7312 should just return nil to give other functions a chance. If it
7313 does handle the search, it must return a non-nil value to keep
7314 other functions from trying.
7316 Each function can access the current prefix argument through the
7317 variable `current-prefix-argument'. Note that a single prefix is
7318 used to force opening a link in Emacs, so it may be good to only
7319 use a numeric or double prefix to guide the search function.
7321 In case this is needed, a function in this hook can also restore
7322 the window configuration before `org-open-at-point' was called using:
7324 (set-window-configuration org-window-config-before-follow-link)")
7326 (defun org-link-search (s &optional type avoid-pos)
7327 "Search for a link search option.
7328 If S is surrounded by forward slashes, it is interpreted as a
7329 regular expression. In org-mode files, this will create an `org-occur'
7330 sparse tree. In ordinary files, `occur' will be used to list matches.
7331 If the current buffer is in `dired-mode', grep will be used to search
7332 in all files. If AVOID-POS is given, ignore matches near that position."
7333 (let ((case-fold-search t)
7334 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7335 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7336 (append '(("") (" ") ("\t") ("\n"))
7337 org-emphasis-alist)
7338 "\\|") "\\)"))
7339 (pos (point))
7340 (pre nil) (post nil)
7341 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7342 (cond
7343 ;; First check if there are any special
7344 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7345 ;; Now try the builtin stuff
7346 ((save-excursion
7347 (goto-char (point-min))
7348 (and
7349 (re-search-forward
7350 (concat "<<" (regexp-quote s0) ">>") nil t)
7351 (setq type 'dedicated
7352 pos (match-beginning 0))))
7353 ;; There is an exact target for this
7354 (goto-char pos))
7355 ((and (string-match "^(\\(.*\\))$" s0)
7356 (save-excursion
7357 (goto-char (point-min))
7358 (and
7359 (re-search-forward
7360 (concat "[^[]" (regexp-quote
7361 (format org-coderef-label-format
7362 (match-string 1 s0))))
7363 nil t)
7364 (setq type 'dedicated
7365 pos (1+ (match-beginning 0))))))
7366 ;; There is a coderef target for this
7367 (goto-char pos))
7368 ((string-match "^/\\(.*\\)/$" s)
7369 ;; A regular expression
7370 (cond
7371 ((org-mode-p)
7372 (org-occur (match-string 1 s)))
7373 ;;((eq major-mode 'dired-mode)
7374 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7375 (t (org-do-occur (match-string 1 s)))))
7377 ;; A normal search strings
7378 (when (equal (string-to-char s) ?*)
7379 ;; Anchor on headlines, post may include tags.
7380 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7381 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7382 s (substring s 1)))
7383 (remove-text-properties
7384 0 (length s)
7385 '(face nil mouse-face nil keymap nil fontified nil) s)
7386 ;; Make a series of regular expressions to find a match
7387 (setq words (org-split-string s "[ \n\r\t]+")
7389 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7390 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7391 "\\)" markers)
7392 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7393 re2a (concat "[ \t\r\n]" re2a_)
7394 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7395 re4 (concat "[^a-zA-Z_]" re4_)
7397 re1 (concat pre re2 post)
7398 re3 (concat pre (if pre re4_ re4) post)
7399 re5 (concat pre ".*" re4)
7400 re2 (concat pre re2)
7401 re2a (concat pre (if pre re2a_ re2a))
7402 re4 (concat pre (if pre re4_ re4))
7403 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7404 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7405 re5 "\\)"
7407 (cond
7408 ((eq type 'org-occur) (org-occur reall))
7409 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7410 (t (goto-char (point-min))
7411 (setq type 'fuzzy)
7412 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7413 (org-search-not-self 1 re1 nil t)
7414 (org-search-not-self 1 re2 nil t)
7415 (org-search-not-self 1 re2a nil t)
7416 (org-search-not-self 1 re3 nil t)
7417 (org-search-not-self 1 re4 nil t)
7418 (org-search-not-self 1 re5 nil t)
7420 (goto-char (match-beginning 1))
7421 (goto-char pos)
7422 (error "No match")))))
7424 ;; Normal string-search
7425 (goto-char (point-min))
7426 (if (search-forward s nil t)
7427 (goto-char (match-beginning 0))
7428 (error "No match"))))
7429 (and (org-mode-p) (org-show-context 'link-search))
7430 type))
7432 (defun org-search-not-self (group &rest args)
7433 "Execute `re-search-forward', but only accept matches that do not
7434 enclose the position of `org-open-link-marker'."
7435 (let ((m org-open-link-marker))
7436 (catch 'exit
7437 (while (apply 're-search-forward args)
7438 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7439 (goto-char (match-end group))
7440 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7441 (> (match-beginning 0) (marker-position m))
7442 (< (match-end 0) (marker-position m)))
7443 (save-match-data
7444 (or (not (org-in-regexp
7445 org-bracket-link-analytic-regexp 1))
7446 (not (match-end 4)) ; no description
7447 (and (<= (match-beginning 4) (point))
7448 (>= (match-end 4) (point))))))
7449 (throw 'exit (point))))))))
7451 (defun org-get-buffer-for-internal-link (buffer)
7452 "Return a buffer to be used for displaying the link target of internal links."
7453 (cond
7454 ((not org-display-internal-link-with-indirect-buffer)
7455 buffer)
7456 ((string-match "(Clone)$" (buffer-name buffer))
7457 (message "Buffer is already a clone, not making another one")
7458 ;; we also do not modify visibility in this case
7459 buffer)
7460 (t ; make a new indirect buffer for displaying the link
7461 (let* ((bn (buffer-name buffer))
7462 (ibn (concat bn "(Clone)"))
7463 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7464 (with-current-buffer ib (org-overview))
7465 ib))))
7467 (defun org-do-occur (regexp &optional cleanup)
7468 "Call the Emacs command `occur'.
7469 If CLEANUP is non-nil, remove the printout of the regular expression
7470 in the *Occur* buffer. This is useful if the regex is long and not useful
7471 to read."
7472 (occur regexp)
7473 (when cleanup
7474 (let ((cwin (selected-window)) win beg end)
7475 (when (setq win (get-buffer-window "*Occur*"))
7476 (select-window win))
7477 (goto-char (point-min))
7478 (when (re-search-forward "match[a-z]+" nil t)
7479 (setq beg (match-end 0))
7480 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7481 (setq end (1- (match-beginning 0)))))
7482 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7483 (goto-char (point-min))
7484 (select-window cwin))))
7486 ;;; The mark ring for links jumps
7488 (defvar org-mark-ring nil
7489 "Mark ring for positions before jumps in Org-mode.")
7490 (defvar org-mark-ring-last-goto nil
7491 "Last position in the mark ring used to go back.")
7492 ;; Fill and close the ring
7493 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7494 (loop for i from 1 to org-mark-ring-length do
7495 (push (make-marker) org-mark-ring))
7496 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7497 org-mark-ring)
7499 (defun org-mark-ring-push (&optional pos buffer)
7500 "Put the current position or POS into the mark ring and rotate it."
7501 (interactive)
7502 (setq pos (or pos (point)))
7503 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7504 (move-marker (car org-mark-ring)
7505 (or pos (point))
7506 (or buffer (current-buffer)))
7507 (message "%s"
7508 (substitute-command-keys
7509 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7511 (defun org-mark-ring-goto (&optional n)
7512 "Jump to the previous position in the mark ring.
7513 With prefix arg N, jump back that many stored positions. When
7514 called several times in succession, walk through the entire ring.
7515 Org-mode commands jumping to a different position in the current file,
7516 or to another Org-mode file, automatically push the old position
7517 onto the ring."
7518 (interactive "p")
7519 (let (p m)
7520 (if (eq last-command this-command)
7521 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7522 (setq p org-mark-ring))
7523 (setq org-mark-ring-last-goto p)
7524 (setq m (car p))
7525 (switch-to-buffer (marker-buffer m))
7526 (goto-char m)
7527 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7529 (defun org-remove-angle-brackets (s)
7530 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7531 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7533 (defun org-add-angle-brackets (s)
7534 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7535 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7537 (defun org-remove-double-quotes (s)
7538 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7539 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7542 ;;; Following specific links
7544 (defun org-follow-timestamp-link ()
7545 (cond
7546 ((org-at-date-range-p t)
7547 (let ((org-agenda-start-on-weekday)
7548 (t1 (match-string 1))
7549 (t2 (match-string 2)))
7550 (setq t1 (time-to-days (org-time-string-to-time t1))
7551 t2 (time-to-days (org-time-string-to-time t2)))
7552 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7553 ((org-at-timestamp-p t)
7554 (org-agenda-list nil (time-to-days (org-time-string-to-time
7555 (substring (match-string 1) 0 10)))
7557 (t (error "This should not happen"))))
7560 ;;; Following file links
7561 (defvar org-wait nil)
7562 (defun org-open-file (path &optional in-emacs line search)
7563 "Open the file at PATH.
7564 First, this expands any special file name abbreviations. Then the
7565 configuration variable `org-file-apps' is checked if it contains an
7566 entry for this file type, and if yes, the corresponding command is launched.
7568 If no application is found, Emacs simply visits the file.
7570 With optional prefix argument IN-EMACS, Emacs will visit the file.
7571 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7572 and o use an external application to visit the file.
7574 Optional LINE specifies a line to go to, optional SEARCH a string to
7575 search for. If LINE or SEARCH is given, the file will always be
7576 opened in Emacs.
7577 If the file does not exist, an error is thrown."
7578 (setq in-emacs (or in-emacs line search))
7579 (let* ((file (if (equal path "")
7580 buffer-file-name
7581 (substitute-in-file-name (expand-file-name path))))
7582 (apps (append org-file-apps (org-default-apps)))
7583 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7584 (dirp (if remp nil (file-directory-p file)))
7585 (file (if (and dirp org-open-directory-means-index-dot-org)
7586 (concat (file-name-as-directory file) "index.org")
7587 file))
7588 (a-m-a-p (assq 'auto-mode apps))
7589 (dfile (downcase file))
7590 (old-buffer (current-buffer))
7591 (old-pos (point))
7592 (old-mode major-mode)
7593 ext cmd)
7594 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7595 (setq ext (match-string 1 dfile))
7596 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7597 (setq ext (match-string 1 dfile))))
7598 (cond
7599 ((equal in-emacs '(16))
7600 (setq cmd (cdr (assoc 'system apps))))
7601 (in-emacs (setq cmd 'emacs))
7603 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7604 (and dirp (cdr (assoc 'directory apps)))
7605 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7606 'string-match)
7607 (cdr (assoc ext apps))
7608 (cdr (assoc t apps))))))
7609 (when (eq cmd 'system)
7610 (setq cmd (cdr (assoc 'system apps))))
7611 (when (eq cmd 'default)
7612 (setq cmd (cdr (assoc t apps))))
7613 (when (eq cmd 'mailcap)
7614 (require 'mailcap)
7615 (mailcap-parse-mailcaps)
7616 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7617 (command (mailcap-mime-info mime-type)))
7618 (if (stringp command)
7619 (setq cmd command)
7620 (setq cmd 'emacs))))
7621 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7622 (not (file-exists-p file))
7623 (not org-open-non-existing-files))
7624 (error "No such file: %s" file))
7625 (cond
7626 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7627 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7628 (while (string-match "['\"]%s['\"]" cmd)
7629 (setq cmd (replace-match "%s" t t cmd)))
7630 (while (string-match "%s" cmd)
7631 (setq cmd (replace-match
7632 (save-match-data
7633 (shell-quote-argument
7634 (convert-standard-filename file)))
7635 t t cmd)))
7636 (save-window-excursion
7637 (start-process-shell-command cmd nil cmd)
7638 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7640 ((or (stringp cmd)
7641 (eq cmd 'emacs))
7642 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7643 (widen)
7644 (if line (goto-line line)
7645 (if search (org-link-search search))))
7646 ((consp cmd)
7647 (let ((file (convert-standard-filename file)))
7648 (eval cmd)))
7649 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7650 (and (org-mode-p) (eq old-mode 'org-mode)
7651 (or (not (equal old-buffer (current-buffer)))
7652 (not (equal old-pos (point))))
7653 (org-mark-ring-push old-pos old-buffer))))
7655 (defun org-default-apps ()
7656 "Return the default applications for this operating system."
7657 (cond
7658 ((eq system-type 'darwin)
7659 org-file-apps-defaults-macosx)
7660 ((eq system-type 'windows-nt)
7661 org-file-apps-defaults-windowsnt)
7662 (t org-file-apps-defaults-gnu)))
7664 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7665 "Convert extensions to regular expressions in the cars of LIST.
7666 Also, weed out any non-string entries, because the return value is used
7667 only for regexp matching.
7668 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7669 point to the symbol `emacs', indicating that the file should
7670 be opened in Emacs."
7671 (append
7672 (delq nil
7673 (mapcar (lambda (x)
7674 (if (not (stringp (car x)))
7676 (if (string-match "\\W" (car x))
7678 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7679 list))
7680 (if add-auto-mode
7681 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7683 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7684 (defun org-file-remote-p (file)
7685 "Test whether FILE specifies a location on a remote system.
7686 Return non-nil if the location is indeed remote.
7688 For example, the filename \"/user@host:/foo\" specifies a location
7689 on the system \"/user@host:\"."
7690 (cond ((fboundp 'file-remote-p)
7691 (file-remote-p file))
7692 ((fboundp 'tramp-handle-file-remote-p)
7693 (tramp-handle-file-remote-p file))
7694 ((and (boundp 'ange-ftp-name-format)
7695 (string-match (car ange-ftp-name-format) file))
7697 (t nil)))
7700 ;;;; Refiling
7702 (defun org-get-org-file ()
7703 "Read a filename, with default directory `org-directory'."
7704 (let ((default (or org-default-notes-file remember-data-file)))
7705 (read-file-name (format "File name [%s]: " default)
7706 (file-name-as-directory org-directory)
7707 default)))
7709 (defun org-notes-order-reversed-p ()
7710 "Check if the current file should receive notes in reversed order."
7711 (cond
7712 ((not org-reverse-note-order) nil)
7713 ((eq t org-reverse-note-order) t)
7714 ((not (listp org-reverse-note-order)) nil)
7715 (t (catch 'exit
7716 (let ((all org-reverse-note-order)
7717 entry)
7718 (while (setq entry (pop all))
7719 (if (string-match (car entry) buffer-file-name)
7720 (throw 'exit (cdr entry))))
7721 nil)))))
7723 (defvar org-refile-target-table nil
7724 "The list of refile targets, created by `org-refile'.")
7726 (defvar org-agenda-new-buffers nil
7727 "Buffers created to visit agenda files.")
7729 (defun org-get-refile-targets (&optional default-buffer)
7730 "Produce a table with refile targets."
7731 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7732 targets txt re files f desc descre fast-path-p level)
7733 (message "Getting targets...")
7734 (with-current-buffer (or default-buffer (current-buffer))
7735 (while (setq entry (pop entries))
7736 (setq files (car entry) desc (cdr entry))
7737 (setq fast-path-p nil)
7738 (cond
7739 ((null files) (setq files (list (current-buffer))))
7740 ((eq files 'org-agenda-files)
7741 (setq files (org-agenda-files 'unrestricted)))
7742 ((and (symbolp files) (fboundp files))
7743 (setq files (funcall files)))
7744 ((and (symbolp files) (boundp files))
7745 (setq files (symbol-value files))))
7746 (if (stringp files) (setq files (list files)))
7747 (cond
7748 ((eq (car desc) :tag)
7749 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7750 ((eq (car desc) :todo)
7751 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7752 ((eq (car desc) :regexp)
7753 (setq descre (cdr desc)))
7754 ((eq (car desc) :level)
7755 (setq descre (concat "^\\*\\{" (number-to-string
7756 (if org-odd-levels-only
7757 (1- (* 2 (cdr desc)))
7758 (cdr desc)))
7759 "\\}[ \t]")))
7760 ((eq (car desc) :maxlevel)
7761 (setq fast-path-p t)
7762 (setq descre (concat "^\\*\\{1," (number-to-string
7763 (if org-odd-levels-only
7764 (1- (* 2 (cdr desc)))
7765 (cdr desc)))
7766 "\\}[ \t]")))
7767 (t (error "Bad refiling target description %s" desc)))
7768 (while (setq f (pop files))
7769 (save-excursion
7770 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7771 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7772 (setq f (expand-file-name f))
7773 (save-excursion
7774 (save-restriction
7775 (widen)
7776 (goto-char (point-min))
7777 (while (re-search-forward descre nil t)
7778 (goto-char (point-at-bol))
7779 (when (looking-at org-complex-heading-regexp)
7780 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7781 txt (org-link-display-format (match-string 4))
7782 re (concat "^" (regexp-quote
7783 (buffer-substring (match-beginning 1)
7784 (match-end 4)))))
7785 (if (match-end 5) (setq re (concat re "[ \t]+"
7786 (regexp-quote
7787 (match-string 5)))))
7788 (setq re (concat re "[ \t]*$"))
7789 (when org-refile-use-outline-path
7790 (setq txt (mapconcat 'org-protect-slash
7791 (append
7792 (if (eq org-refile-use-outline-path 'file)
7793 (list (file-name-nondirectory
7794 (buffer-file-name (buffer-base-buffer))))
7795 (if (eq org-refile-use-outline-path 'full-file-path)
7796 (list (buffer-file-name (buffer-base-buffer)))))
7797 (org-get-outline-path fast-path-p level txt)
7798 (list txt))
7799 "/")))
7800 (push (list txt f re (point)) targets))
7801 (goto-char (point-at-eol))))))))
7802 (message "Getting targets...done")
7803 (nreverse targets))))
7805 (defun org-protect-slash (s)
7806 (while (string-match "/" s)
7807 (setq s (replace-match "\\" t t s)))
7810 (defvar org-olpa (make-vector 20 nil))
7812 (defun org-get-outline-path (&optional fastp level heading)
7813 "Return the outline path to the current entry, as a list."
7814 (if fastp
7815 (progn
7816 (if (> level 19)
7817 (error "Outline path failure, more than 19 levels."))
7818 (loop for i from level upto 19 do
7819 (aset org-olpa i nil))
7820 (prog1
7821 (delq nil (append org-olpa nil))
7822 (aset org-olpa level heading)))
7823 (let (rtn)
7824 (save-excursion
7825 (while (org-up-heading-safe)
7826 (when (looking-at org-complex-heading-regexp)
7827 (push (org-match-string-no-properties 4) rtn)))
7828 rtn))))
7830 (defvar org-refile-history nil
7831 "History for refiling operations.")
7833 (defun org-refile (&optional goto default-buffer)
7834 "Move the entry at point to another heading.
7835 The list of target headings is compiled using the information in
7836 `org-refile-targets', which see. This list is created before each use
7837 and will therefore always be up-to-date.
7839 At the target location, the entry is filed as a subitem of the target heading.
7840 Depending on `org-reverse-note-order', the new subitem will either be the
7841 first or the last subitem.
7843 If there is an active region, all entries in that region will be moved.
7844 However, the region must fulfil the requirement that the first heading
7845 is the first one sets the top-level of the moved text - at most siblings
7846 below it are allowed.
7848 With prefix arg GOTO, the command will only visit the target location,
7849 not actually move anything.
7850 With a double prefix `C-u C-u', go to the location where the last refiling
7851 operation has put the subtree."
7852 (interactive "P")
7853 (let* ((cbuf (current-buffer))
7854 (regionp (org-region-active-p))
7855 (region-start (and regionp (region-beginning)))
7856 (region-end (and regionp (region-end)))
7857 (region-length (and regionp (- region-end region-start)))
7858 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7859 pos it nbuf file re level reversed)
7860 (when regionp (goto-char region-start)
7861 (unless (org-kill-is-subtree-p
7862 (buffer-substring region-start region-end))
7863 (error "The region is not a (sequence of) subtree(s)")))
7864 (if (equal goto '(16))
7865 (org-refile-goto-last-stored)
7866 (when (setq it (org-refile-get-location
7867 (if goto "Goto: " "Refile to: ") default-buffer))
7868 (setq file (nth 1 it)
7869 re (nth 2 it)
7870 pos (nth 3 it))
7871 (if (and (equal (buffer-file-name) file)
7872 (if regionp
7873 (and (>= pos region-start)
7874 (<= pos region-end))
7875 (and (>= pos (point))
7876 (< pos (save-excursion
7877 (org-end-of-subtree t t))))))
7878 (error "Cannot refile to position inside the tree or region"))
7880 (setq nbuf (or (find-buffer-visiting file)
7881 (find-file-noselect file)))
7882 (if goto
7883 (progn
7884 (switch-to-buffer nbuf)
7885 (goto-char pos)
7886 (org-show-context 'org-goto))
7887 (if regionp
7888 (progn
7889 (kill-new (buffer-substring region-start region-end))
7890 (org-save-markers-in-region region-start region-end))
7891 (org-copy-subtree 1 nil t))
7892 (save-excursion
7893 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7894 (find-file-noselect file))))
7895 (setq reversed (org-notes-order-reversed-p))
7896 (save-excursion
7897 (save-restriction
7898 (widen)
7899 (goto-char pos)
7900 (looking-at outline-regexp)
7901 (setq level (org-get-valid-level (funcall outline-level) 1))
7902 (goto-char
7903 (if reversed
7904 (or (outline-next-heading) (point-max))
7905 (or (save-excursion (outline-get-next-sibling))
7906 (org-end-of-subtree t t)
7907 (point-max))))
7908 (if (not (bolp)) (newline))
7909 (bookmark-set "org-refile-last-stored")
7910 (org-paste-subtree level))))
7911 (if regionp
7912 (delete-region (point) (+ (point) region-length))
7913 (org-cut-subtree))
7914 (setq org-markers-to-move nil)
7915 (message "Refiled to \"%s\"" (car it)))))))
7917 (defun org-refile-goto-last-stored ()
7918 "Go to the location where the last refile was stored."
7919 (interactive)
7920 (bookmark-jump "org-refile-last-stored")
7921 (message "This is the location of the last refile"))
7923 (defun org-refile-get-location (&optional prompt default-buffer)
7924 "Prompt the user for a refile location, using PROMPT."
7925 (let ((org-refile-targets org-refile-targets)
7926 (org-refile-use-outline-path org-refile-use-outline-path))
7927 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7928 (unless org-refile-target-table
7929 (error "No refile targets"))
7930 (let* ((cbuf (current-buffer))
7931 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7932 (cfunc (if (and org-refile-use-outline-path
7933 org-outline-path-complete-in-steps)
7934 'org-olpath-completing-read
7935 'org-ido-completing-read))
7936 (extra (if org-refile-use-outline-path "/" ""))
7937 (filename (and cfn (expand-file-name cfn)))
7938 (tbl (mapcar
7939 (lambda (x)
7940 (if (not (equal filename (nth 1 x)))
7941 (cons (concat (car x) extra " ("
7942 (file-name-nondirectory (nth 1 x)) ")")
7943 (cdr x))
7944 (cons (concat (car x) extra) (cdr x))))
7945 org-refile-target-table))
7946 (completion-ignore-case t))
7947 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7948 tbl)))
7950 (defun org-olpath-completing-read (prompt collection &rest args)
7951 "Read an outline path like a file name."
7952 (let ((thetable collection))
7953 (apply
7954 'org-ido-completing-read prompt
7955 (lambda (string predicate &optional flag)
7956 (let (rtn r f (l (length string)))
7957 (cond
7958 ((eq flag nil)
7959 ;; try completion
7960 (try-completion string thetable))
7961 ((eq flag t)
7962 ;; all-completions
7963 (setq rtn (all-completions string thetable predicate))
7964 (mapcar
7965 (lambda (x)
7966 (setq r (substring x l))
7967 (if (string-match " ([^)]*)$" x)
7968 (setq f (match-string 0 x))
7969 (setq f ""))
7970 (if (string-match "/" r)
7971 (concat string (substring r 0 (match-end 0)) f)
7973 rtn))
7974 ((eq flag 'lambda)
7975 ;; exact match?
7976 (assoc string thetable)))
7978 args)))
7980 ;;;; Dynamic blocks
7982 (defun org-find-dblock (name)
7983 "Find the first dynamic block with name NAME in the buffer.
7984 If not found, stay at current position and return nil."
7985 (let (pos)
7986 (save-excursion
7987 (goto-char (point-min))
7988 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7989 nil t)
7990 (match-beginning 0))))
7991 (if pos (goto-char pos))
7992 pos))
7994 (defconst org-dblock-start-re
7995 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7996 "Matches the startline of a dynamic block, with parameters.")
7998 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7999 "Matches the end of a dynamic block.")
8001 (defun org-create-dblock (plist)
8002 "Create a dynamic block section, with parameters taken from PLIST.
8003 PLIST must contain a :name entry which is used as name of the block."
8004 (unless (bolp) (newline))
8005 (let ((name (plist-get plist :name)))
8006 (insert "#+BEGIN: " name)
8007 (while plist
8008 (if (eq (car plist) :name)
8009 (setq plist (cddr plist))
8010 (insert " " (prin1-to-string (pop plist)))))
8011 (insert "\n\n#+END:\n")
8012 (beginning-of-line -2)))
8014 (defun org-prepare-dblock ()
8015 "Prepare dynamic block for refresh.
8016 This empties the block, puts the cursor at the insert position and returns
8017 the property list including an extra property :name with the block name."
8018 (unless (looking-at org-dblock-start-re)
8019 (error "Not at a dynamic block"))
8020 (let* ((begdel (1+ (match-end 0)))
8021 (name (org-no-properties (match-string 1)))
8022 (params (append (list :name name)
8023 (read (concat "(" (match-string 3) ")")))))
8024 (unless (re-search-forward org-dblock-end-re nil t)
8025 (error "Dynamic block not terminated"))
8026 (setq params
8027 (append params
8028 (list :content (buffer-substring
8029 begdel (match-beginning 0)))))
8030 (delete-region begdel (match-beginning 0))
8031 (goto-char begdel)
8032 (open-line 1)
8033 params))
8035 (defun org-map-dblocks (&optional command)
8036 "Apply COMMAND to all dynamic blocks in the current buffer.
8037 If COMMAND is not given, use `org-update-dblock'."
8038 (let ((cmd (or command 'org-update-dblock))
8039 pos)
8040 (save-excursion
8041 (goto-char (point-min))
8042 (while (re-search-forward org-dblock-start-re nil t)
8043 (goto-char (setq pos (match-beginning 0)))
8044 (condition-case nil
8045 (funcall cmd)
8046 (error (message "Error during update of dynamic block")))
8047 (goto-char pos)
8048 (unless (re-search-forward org-dblock-end-re nil t)
8049 (error "Dynamic block not terminated"))))))
8051 (defun org-dblock-update (&optional arg)
8052 "User command for updating dynamic blocks.
8053 Update the dynamic block at point. With prefix ARG, update all dynamic
8054 blocks in the buffer."
8055 (interactive "P")
8056 (if arg
8057 (org-update-all-dblocks)
8058 (or (looking-at org-dblock-start-re)
8059 (org-beginning-of-dblock))
8060 (org-update-dblock)))
8062 (defun org-update-dblock ()
8063 "Update the dynamic block at point
8064 This means to empty the block, parse for parameters and then call
8065 the correct writing function."
8066 (save-window-excursion
8067 (let* ((pos (point))
8068 (line (org-current-line))
8069 (params (org-prepare-dblock))
8070 (name (plist-get params :name))
8071 (cmd (intern (concat "org-dblock-write:" name))))
8072 (message "Updating dynamic block `%s' at line %d..." name line)
8073 (funcall cmd params)
8074 (message "Updating dynamic block `%s' at line %d...done" name line)
8075 (goto-char pos))))
8077 (defun org-beginning-of-dblock ()
8078 "Find the beginning of the dynamic block at point.
8079 Error if there is no such block at point."
8080 (let ((pos (point))
8081 beg)
8082 (end-of-line 1)
8083 (if (and (re-search-backward org-dblock-start-re nil t)
8084 (setq beg (match-beginning 0))
8085 (re-search-forward org-dblock-end-re nil t)
8086 (> (match-end 0) pos))
8087 (goto-char beg)
8088 (goto-char pos)
8089 (error "Not in a dynamic block"))))
8091 (defun org-update-all-dblocks ()
8092 "Update all dynamic blocks in the buffer.
8093 This function can be used in a hook."
8094 (when (org-mode-p)
8095 (org-map-dblocks 'org-update-dblock)))
8098 ;;;; Completion
8100 (defconst org-additional-option-like-keywords
8101 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8102 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8103 "BEGIN_EXAMPLE" "END_EXAMPLE"
8104 "BEGIN_QUOTE" "END_QUOTE"
8105 "BEGIN_VERSE" "END_VERSE"
8106 "BEGIN_SRC" "END_SRC"
8107 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8109 (defcustom org-structure-template-alist
8111 ("s" "#+begin_src ?\n\n#+end_src"
8112 "<src lang=\"?\">\n\n</src>")
8113 ("e" "#+begin_example\n?\n#+end_example"
8114 "<example>\n?\n</example>")
8115 ("q" "#+begin_quote\n?\n#+end_quote"
8116 "<quote>\n?\n</quote>")
8117 ("v" "#+begin_verse\n?\n#+end_verse"
8118 "<verse>\n?\n/verse>")
8119 ("l" "#+begin_latex\n?\n#+end_latex"
8120 "<literal style=\"latex\">\n?\n</literal>")
8121 ("L" "#+latex: "
8122 "<literal style=\"latex\">?</literal>")
8123 ("h" "#+begin_html\n?\n#+end_html"
8124 "<literal style=\"html\">\n?\n</literal>")
8125 ("H" "#+html: "
8126 "<literal style=\"html\">?</literal>")
8127 ("a" "#+begin_ascii\n?\n#+end_ascii")
8128 ("A" "#+ascii: ")
8129 ("i" "#+include %file ?"
8130 "<include file=%file markup=\"?\">")
8132 "Structure completion elements.
8133 This is a list of abbreviation keys and values. The value gets inserted
8134 it you type @samp{.} followed by the key and then the completion key,
8135 usually `M-TAB'. %file will be replaced by a file name after prompting
8136 for the file using completion.
8137 There are two templates for each key, the first uses the original Org syntax,
8138 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8139 the default when the /org-mtags.el/ module has been loaded. See also the
8140 variable `org-mtags-prefer-muse-templates'.
8141 This is an experimental feature, it is undecided if it is going to stay in."
8142 :group 'org-completion
8143 :type '(repeat
8144 (string :tag "Key")
8145 (string :tag "Template")
8146 (string :tag "Muse Template")))
8148 (defun org-try-structure-completion ()
8149 "Try to complete a structure template before point.
8150 This looks for strings like \"<e\" on an otherwise empty line and
8151 expands them."
8152 (let ((l (buffer-substring (point-at-bol) (point)))
8154 (when (and (looking-at "[ \t]*$")
8155 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8156 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8157 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8158 (match-beginning 1)) a)
8159 t)))
8161 (defun org-complete-expand-structure-template (start cell)
8162 "Expand a structure template."
8163 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8164 (rpl (nth (if musep 2 1) cell)))
8165 (delete-region start (point))
8166 (when (string-match "\\`#\\+" rpl)
8167 (cond
8168 ((bolp))
8169 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8170 (delete-region (point-at-bol) (point)))
8171 (t (newline))))
8172 (setq start (point))
8173 (if (string-match "%file" rpl)
8174 (setq rpl (replace-match
8175 (concat
8176 "\""
8177 (save-match-data
8178 (abbreviate-file-name (read-file-name "Include file: ")))
8179 "\"")
8180 t t rpl)))
8181 (insert rpl)
8182 (if (re-search-backward "\\?" start t) (delete-char 1))))
8185 (defun org-complete (&optional arg)
8186 "Perform completion on word at point.
8187 At the beginning of a headline, this completes TODO keywords as given in
8188 `org-todo-keywords'.
8189 If the current word is preceded by a backslash, completes the TeX symbols
8190 that are supported for HTML support.
8191 If the current word is preceded by \"#+\", completes special words for
8192 setting file options.
8193 In the line after \"#+STARTUP:, complete valid keywords.\"
8194 At all other locations, this simply calls the value of
8195 `org-completion-fallback-command'."
8196 (interactive "P")
8197 (org-without-partial-completion
8198 (catch 'exit
8199 (let* ((a nil)
8200 (end (point))
8201 (beg1 (save-excursion
8202 (skip-chars-backward (org-re "[:alnum:]_@"))
8203 (point)))
8204 (beg (save-excursion
8205 (skip-chars-backward "a-zA-Z0-9_:$")
8206 (point)))
8207 (confirm (lambda (x) (stringp (car x))))
8208 (searchhead (equal (char-before beg) ?*))
8209 (struct
8210 (when (and (member (char-before beg1) '(?. ?<))
8211 (setq a (assoc (buffer-substring beg1 (point))
8212 org-structure-template-alist)))
8213 (org-complete-expand-structure-template (1- beg1) a)
8214 (throw 'exit t)))
8215 (tag (and (equal (char-before beg1) ?:)
8216 (equal (char-after (point-at-bol)) ?*)))
8217 (prop (and (equal (char-before beg1) ?:)
8218 (not (equal (char-after (point-at-bol)) ?*))))
8219 (texp (equal (char-before beg) ?\\))
8220 (link (equal (char-before beg) ?\[))
8221 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8222 beg)
8223 "#+"))
8224 (startup (string-match "^#\\+STARTUP:.*"
8225 (buffer-substring (point-at-bol) (point))))
8226 (completion-ignore-case opt)
8227 (type nil)
8228 (tbl nil)
8229 (table (cond
8230 (opt
8231 (setq type :opt)
8232 (require 'org-exp)
8233 (append
8234 (mapcar
8235 (lambda (x)
8236 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8237 (cons (match-string 2 x) (match-string 1 x)))
8238 (org-split-string (org-get-current-options) "\n"))
8239 (mapcar 'list org-additional-option-like-keywords)))
8240 (startup
8241 (setq type :startup)
8242 org-startup-options)
8243 (link (append org-link-abbrev-alist-local
8244 org-link-abbrev-alist))
8245 (texp
8246 (setq type :tex)
8247 org-html-entities)
8248 ((string-match "\\`\\*+[ \t]+\\'"
8249 (buffer-substring (point-at-bol) beg))
8250 (setq type :todo)
8251 (mapcar 'list org-todo-keywords-1))
8252 (searchhead
8253 (setq type :searchhead)
8254 (save-excursion
8255 (goto-char (point-min))
8256 (while (re-search-forward org-todo-line-regexp nil t)
8257 (push (list
8258 (org-make-org-heading-search-string
8259 (match-string 3) t))
8260 tbl)))
8261 tbl)
8262 (tag (setq type :tag beg beg1)
8263 (or org-tag-alist (org-get-buffer-tags)))
8264 (prop (setq type :prop beg beg1)
8265 (mapcar 'list (org-buffer-property-keys nil t t)))
8266 (t (progn
8267 (call-interactively org-completion-fallback-command)
8268 (throw 'exit nil)))))
8269 (pattern (buffer-substring-no-properties beg end))
8270 (completion (try-completion pattern table confirm)))
8271 (cond ((eq completion t)
8272 (if (not (assoc (upcase pattern) table))
8273 (message "Already complete")
8274 (if (and (equal type :opt)
8275 (not (member (car (assoc (upcase pattern) table))
8276 org-additional-option-like-keywords)))
8277 (insert (substring (cdr (assoc (upcase pattern) table))
8278 (length pattern)))
8279 (if (memq type '(:tag :prop)) (insert ":")))))
8280 ((null completion)
8281 (message "Can't find completion for \"%s\"" pattern)
8282 (ding))
8283 ((not (string= pattern completion))
8284 (delete-region beg end)
8285 (if (string-match " +$" completion)
8286 (setq completion (replace-match "" t t completion)))
8287 (insert completion)
8288 (if (get-buffer-window "*Completions*")
8289 (delete-window (get-buffer-window "*Completions*")))
8290 (if (assoc completion table)
8291 (if (eq type :todo) (insert " ")
8292 (if (memq type '(:tag :prop)) (insert ":"))))
8293 (if (and (equal type :opt) (assoc completion table))
8294 (message "%s" (substitute-command-keys
8295 "Press \\[org-complete] again to insert example settings"))))
8297 (message "Making completion list...")
8298 (let ((list (sort (all-completions pattern table confirm)
8299 'string<)))
8300 (with-output-to-temp-buffer "*Completions*"
8301 (condition-case nil
8302 ;; Protection needed for XEmacs and emacs 21
8303 (display-completion-list list pattern)
8304 (error (display-completion-list list)))))
8305 (message "Making completion list...%s" "done")))))))
8307 ;;;; TODO, DEADLINE, Comments
8309 (defun org-toggle-comment ()
8310 "Change the COMMENT state of an entry."
8311 (interactive)
8312 (save-excursion
8313 (org-back-to-heading)
8314 (let (case-fold-search)
8315 (if (looking-at (concat outline-regexp
8316 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8317 (replace-match "" t t nil 1)
8318 (if (looking-at outline-regexp)
8319 (progn
8320 (goto-char (match-end 0))
8321 (insert org-comment-string " ")))))))
8323 (defvar org-last-todo-state-is-todo nil
8324 "This is non-nil when the last TODO state change led to a TODO state.
8325 If the last change removed the TODO tag or switched to DONE, then
8326 this is nil.")
8328 (defvar org-setting-tags nil) ; dynamically skipped
8330 (defun org-parse-local-options (string var)
8331 "Parse STRING for startup setting relevant for variable VAR."
8332 (let ((rtn (symbol-value var))
8333 e opts)
8334 (save-match-data
8335 (if (or (not string) (not (string-match "\\S-" string)))
8337 (setq opts (delq nil (mapcar (lambda (x)
8338 (setq e (assoc x org-startup-options))
8339 (if (eq (nth 1 e) var) e nil))
8340 (org-split-string string "[ \t]+"))))
8341 (if (not opts)
8343 (setq rtn nil)
8344 (while (setq e (pop opts))
8345 (if (not (nth 3 e))
8346 (setq rtn (nth 2 e))
8347 (if (not (listp rtn)) (setq rtn nil))
8348 (push (nth 2 e) rtn)))
8349 rtn)))))
8351 (defvar org-agenda-headline-snapshot-before-repeat)
8352 (defun org-todo (&optional arg)
8353 "Change the TODO state of an item.
8354 The state of an item is given by a keyword at the start of the heading,
8355 like
8356 *** TODO Write paper
8357 *** DONE Call mom
8359 The different keywords are specified in the variable `org-todo-keywords'.
8360 By default the available states are \"TODO\" and \"DONE\".
8361 So for this example: when the item starts with TODO, it is changed to DONE.
8362 When it starts with DONE, the DONE is removed. And when neither TODO nor
8363 DONE are present, add TODO at the beginning of the heading.
8365 With C-u prefix arg, use completion to determine the new state.
8366 With numeric prefix arg, switch to that state.
8367 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8368 With a tripple C-u prefix, circumvent any state blocking.
8370 For calling through lisp, arg is also interpreted in the following way:
8371 'none -> empty state
8372 \"\"(empty string) -> switch to empty state
8373 'done -> switch to DONE
8374 'nextset -> switch to the next set of keywords
8375 'previousset -> switch to the previous set of keywords
8376 \"WAITING\" -> switch to the specified keyword, but only if it
8377 really is a member of `org-todo-keywords'."
8378 (interactive "P")
8379 (if (equal arg '(16)) (setq arg 'nextset))
8380 (let ((org-blocker-hook org-blocker-hook))
8381 (when (equal arg '(64))
8382 (setq arg nil org-blocker-hook nil))
8383 (save-excursion
8384 (catch 'exit
8385 (org-back-to-heading)
8386 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8387 (or (looking-at (concat " +" org-todo-regexp " *"))
8388 (looking-at " *"))
8389 (let* ((match-data (match-data))
8390 (startpos (point-at-bol))
8391 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8392 (org-log-done org-log-done)
8393 (org-log-repeat org-log-repeat)
8394 (org-todo-log-states org-todo-log-states)
8395 (this (match-string 1))
8396 (hl-pos (match-beginning 0))
8397 (head (org-get-todo-sequence-head this))
8398 (ass (assoc head org-todo-kwd-alist))
8399 (interpret (nth 1 ass))
8400 (done-word (nth 3 ass))
8401 (final-done-word (nth 4 ass))
8402 (last-state (or this ""))
8403 (completion-ignore-case t)
8404 (member (member this org-todo-keywords-1))
8405 (tail (cdr member))
8406 (state (cond
8407 ((and org-todo-key-trigger
8408 (or (and (equal arg '(4))
8409 (eq org-use-fast-todo-selection 'prefix))
8410 (and (not arg) org-use-fast-todo-selection
8411 (not (eq org-use-fast-todo-selection
8412 'prefix)))))
8413 ;; Use fast selection
8414 (org-fast-todo-selection))
8415 ((and (equal arg '(4))
8416 (or (not org-use-fast-todo-selection)
8417 (not org-todo-key-trigger)))
8418 ;; Read a state with completion
8419 (org-ido-completing-read
8420 "State: " (mapcar (lambda(x) (list x))
8421 org-todo-keywords-1)
8422 nil t))
8423 ((eq arg 'right)
8424 (if this
8425 (if tail (car tail) nil)
8426 (car org-todo-keywords-1)))
8427 ((eq arg 'left)
8428 (if (equal member org-todo-keywords-1)
8430 (if this
8431 (nth (- (length org-todo-keywords-1)
8432 (length tail) 2)
8433 org-todo-keywords-1)
8434 (org-last org-todo-keywords-1))))
8435 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8436 (setq arg nil))) ; hack to fall back to cycling
8437 (arg
8438 ;; user or caller requests a specific state
8439 (cond
8440 ((equal arg "") nil)
8441 ((eq arg 'none) nil)
8442 ((eq arg 'done) (or done-word (car org-done-keywords)))
8443 ((eq arg 'nextset)
8444 (or (car (cdr (member head org-todo-heads)))
8445 (car org-todo-heads)))
8446 ((eq arg 'previousset)
8447 (let ((org-todo-heads (reverse org-todo-heads)))
8448 (or (car (cdr (member head org-todo-heads)))
8449 (car org-todo-heads))))
8450 ((car (member arg org-todo-keywords-1)))
8451 ((nth (1- (prefix-numeric-value arg))
8452 org-todo-keywords-1))))
8453 ((null member) (or head (car org-todo-keywords-1)))
8454 ((equal this final-done-word) nil) ;; -> make empty
8455 ((null tail) nil) ;; -> first entry
8456 ((eq interpret 'sequence)
8457 (car tail))
8458 ((memq interpret '(type priority))
8459 (if (eq this-command last-command)
8460 (car tail)
8461 (if (> (length tail) 0)
8462 (or done-word (car org-done-keywords))
8463 nil)))
8464 (t nil)))
8465 (next (if state (concat " " state " ") " "))
8466 (change-plist (list :type 'todo-state-change :from this :to state
8467 :position startpos))
8468 dolog now-done-p)
8469 (when org-blocker-hook
8470 (setq org-last-todo-state-is-todo
8471 (not (member this org-done-keywords)))
8472 (unless (save-excursion
8473 (save-match-data
8474 (run-hook-with-args-until-failure
8475 'org-blocker-hook change-plist)))
8476 (if (interactive-p)
8477 (error "TODO state change from %s to %s blocked" this state)
8478 ;; fail silently
8479 (message "TODO state change from %s to %s blocked" this state)
8480 (throw 'exit nil))))
8481 (store-match-data match-data)
8482 (replace-match next t t)
8483 (unless (pos-visible-in-window-p hl-pos)
8484 (message "TODO state changed to %s" (org-trim next)))
8485 (unless head
8486 (setq head (org-get-todo-sequence-head state)
8487 ass (assoc head org-todo-kwd-alist)
8488 interpret (nth 1 ass)
8489 done-word (nth 3 ass)
8490 final-done-word (nth 4 ass)))
8491 (when (memq arg '(nextset previousset))
8492 (message "Keyword-Set %d/%d: %s"
8493 (- (length org-todo-sets) -1
8494 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8495 (length org-todo-sets)
8496 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8497 (setq org-last-todo-state-is-todo
8498 (not (member state org-done-keywords)))
8499 (setq now-done-p (and (member state org-done-keywords)
8500 (not (member this org-done-keywords))))
8501 (and logging (org-local-logging logging))
8502 (when (and (or org-todo-log-states org-log-done)
8503 (not (memq arg '(nextset previousset))))
8504 ;; we need to look at recording a time and note
8505 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8506 (nth 2 (assoc this org-todo-log-states))))
8507 (when (and state
8508 (member state org-not-done-keywords)
8509 (not (member this org-not-done-keywords)))
8510 ;; This is now a todo state and was not one before
8511 ;; If there was a CLOSED time stamp, get rid of it.
8512 (org-add-planning-info nil nil 'closed))
8513 (when (and now-done-p org-log-done)
8514 ;; It is now done, and it was not done before
8515 (org-add-planning-info 'closed (org-current-time))
8516 (if (and (not dolog) (eq 'note org-log-done))
8517 (org-add-log-setup 'done state 'findpos 'note)))
8518 (when (and state dolog)
8519 ;; This is a non-nil state, and we need to log it
8520 (org-add-log-setup 'state state 'findpos dolog)))
8521 ;; Fixup tag positioning
8522 (org-todo-trigger-tag-changes state)
8523 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8524 (when org-provide-todo-statistics
8525 (org-update-parent-todo-statistics))
8526 (run-hooks 'org-after-todo-state-change-hook)
8527 (if (and arg (not (member state org-done-keywords)))
8528 (setq head (org-get-todo-sequence-head state)))
8529 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8530 ;; Do we need to trigger a repeat?
8531 (when now-done-p
8532 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8533 ;; This is for the agenda, take a snapshot of the headline.
8534 (save-match-data
8535 (setq org-agenda-headline-snapshot-before-repeat
8536 (org-get-heading))))
8537 (org-auto-repeat-maybe state))
8538 ;; Fixup cursor location if close to the keyword
8539 (if (and (outline-on-heading-p)
8540 (not (bolp))
8541 (save-excursion (beginning-of-line 1)
8542 (looking-at org-todo-line-regexp))
8543 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8544 (progn
8545 (goto-char (or (match-end 2) (match-end 1)))
8546 (just-one-space)))
8547 (when org-trigger-hook
8548 (save-excursion
8549 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8551 (defun org-block-todo-from-children-or-siblings (change-plist)
8552 "Block turning an entry into a TODO, using the hierarchy.
8553 This checks whether the current task should be blocked from state
8554 changes. Such blocking occurs when:
8556 1. The task has children which are not all in a completed state.
8558 2. A task has a parent with the property :ORDERED:, and there
8559 are siblings prior to the current task with incomplete
8560 status."
8561 (catch 'dont-block
8562 ;; If this is not a todo state change, or if this entry is already DONE,
8563 ;; do not block
8564 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8565 (member (plist-get change-plist :from)
8566 (cons 'done org-done-keywords))
8567 (member (plist-get change-plist :to)
8568 (cons 'todo org-not-done-keywords)))
8569 (throw 'dont-block t))
8570 ;; If this task has children, and any are undone, it's blocked
8571 (save-excursion
8572 (org-back-to-heading t)
8573 (let ((this-level (funcall outline-level)))
8574 (outline-next-heading)
8575 (let ((child-level (funcall outline-level)))
8576 (while (and (not (eobp))
8577 (> child-level this-level))
8578 ;; this todo has children, check whether they are all
8579 ;; completed
8580 (if (and (not (org-entry-is-done-p))
8581 (org-entry-is-todo-p))
8582 (throw 'dont-block nil))
8583 (outline-next-heading)
8584 (setq child-level (funcall outline-level))))))
8585 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8586 ;; any previous siblings are undone, it's blocked
8587 (save-excursion
8588 (org-back-to-heading t)
8589 (when (save-excursion
8590 (ignore-errors
8591 (outline-up-heading 1)
8592 (org-entry-get (point) "ORDERED")))
8593 (let* ((this-level (funcall outline-level))
8594 (current-level this-level))
8595 (while (and (not (bobp))
8596 (= current-level this-level))
8597 (outline-previous-heading)
8598 (setq current-level (funcall outline-level))
8599 (if (= current-level this-level)
8600 ;; this todo has children, check whether they are all
8601 ;; completed
8602 (if (and (not (org-entry-is-done-p))
8603 (org-entry-is-todo-p))
8604 (throw 'dont-block nil)))))))
8605 t)) ; don't block
8607 (defun org-toggle-ordered-property ()
8608 "Toggle the ORDERED property of the current entry."
8609 (interactive)
8610 (save-excursion
8611 (org-back-to-heading)
8612 (if (org-entry-get nil "ORDERED")
8613 (progn
8614 (org-delete-property "ORDERED")
8615 (message "Subtasks can be completed in arbitrary order or parallel"))
8616 (org-entry-put nil "ORDERED" "t")
8617 (message "Subtasks must be completed in sequence"))))
8619 (defun org-block-todo-from-checkboxes (change-plist)
8620 "Block turning an entry into a TODO, using checkboxes.
8621 This checks whether the current task should be blocked from state
8622 changes because there are uncheckd boxes in this entry."
8623 (catch 'dont-block
8624 ;; If this is not a todo state change, or if this entry is already DONE,
8625 ;; do not block
8626 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8627 (member (plist-get change-plist :from)
8628 (cons 'done org-done-keywords))
8629 (member (plist-get change-plist :to)
8630 (cons 'todo org-not-done-keywords)))
8631 (throw 'dont-block t))
8632 ;; If this task has checkboxes that are not checked, it's blocked
8633 (save-excursion
8634 (org-back-to-heading t)
8635 (let ((beg (point)) end)
8636 (outline-next-heading)
8637 (setq end (point))
8638 (goto-char beg)
8639 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8640 end t)
8641 (throw 'dont-block nil))))
8642 t)) ; do not block
8644 (defun org-update-parent-todo-statistics ()
8645 "Update any statistics cookie in the parent of the current headline."
8646 (interactive)
8647 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8648 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8649 (catch 'exit
8650 (save-excursion
8651 (setq level (org-up-heading-safe))
8652 (unless level
8653 (throw 'exit nil))
8654 (while (re-search-forward box-re (point-at-eol) t)
8655 (setq is-percent (match-end 2))
8656 (save-match-data
8657 (unless (outline-next-heading) (throw 'exit nil))
8658 (while (looking-at org-todo-line-regexp)
8659 (setq kwd (match-string 2))
8660 (and kwd (setq cnt-all (1+ cnt-all)))
8661 (and (member kwd org-done-keywords)
8662 (setq cnt-done (1+ cnt-done)))
8663 (condition-case nil
8664 (org-forward-same-level 1)
8665 (error (end-of-line 1)))))
8666 (replace-match
8667 (if is-percent
8668 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8669 (format "[%d/%d]" cnt-done cnt-all))))
8670 (run-hook-with-args 'org-after-todo-statistics-hook
8671 cnt-done (- cnt-all cnt-done))))))
8673 (defvar org-after-todo-statistics-hook nil
8674 "Hook that is called after a TODO statistics cookie has been updated.
8675 Each function is called with two arguments: the number of not-done entries
8676 and the number of done entries.
8678 For example, the following function, when added to this hook, will switch
8679 an entry to DONE when all children are done, and back to TODO when new
8680 entries are set to a TODO status. Note that this hook is only called
8681 when there is a statistics cookie in the headline!
8683 (defun org-summary-todo (n-done n-not-done)
8684 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8685 (let (org-log-done org-log-states) ; turn off logging
8686 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8689 (defun org-todo-trigger-tag-changes (state)
8690 "Apply the changes defined in `org-todo-state-tags-triggers'."
8691 (let ((l org-todo-state-tags-triggers)
8692 changes)
8693 (when (or (not state) (equal state ""))
8694 (setq changes (append changes (cdr (assoc "" l)))))
8695 (when (and (stringp state) (> (length state) 0))
8696 (setq changes (append changes (cdr (assoc state l)))))
8697 (when (member state org-not-done-keywords)
8698 (setq changes (append changes (cdr (assoc 'todo l)))))
8699 (when (member state org-done-keywords)
8700 (setq changes (append changes (cdr (assoc 'done l)))))
8701 (dolist (c changes)
8702 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8704 (defun org-local-logging (value)
8705 "Get logging settings from a property VALUE."
8706 (let* (words w a)
8707 ;; directly set the variables, they are already local.
8708 (setq org-log-done nil
8709 org-log-repeat nil
8710 org-todo-log-states nil)
8711 (setq words (org-split-string value))
8712 (while (setq w (pop words))
8713 (cond
8714 ((setq a (assoc w org-startup-options))
8715 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8716 (set (nth 1 a) (nth 2 a))))
8717 ((setq a (org-extract-log-state-settings w))
8718 (and (member (car a) org-todo-keywords-1)
8719 (push a org-todo-log-states)))))))
8721 (defun org-get-todo-sequence-head (kwd)
8722 "Return the head of the TODO sequence to which KWD belongs.
8723 If KWD is not set, check if there is a text property remembering the
8724 right sequence."
8725 (let (p)
8726 (cond
8727 ((not kwd)
8728 (or (get-text-property (point-at-bol) 'org-todo-head)
8729 (progn
8730 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8731 nil (point-at-eol)))
8732 (get-text-property p 'org-todo-head))))
8733 ((not (member kwd org-todo-keywords-1))
8734 (car org-todo-keywords-1))
8735 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8737 (defun org-fast-todo-selection ()
8738 "Fast TODO keyword selection with single keys.
8739 Returns the new TODO keyword, or nil if no state change should occur."
8740 (let* ((fulltable org-todo-key-alist)
8741 (done-keywords org-done-keywords) ;; needed for the faces.
8742 (maxlen (apply 'max (mapcar
8743 (lambda (x)
8744 (if (stringp (car x)) (string-width (car x)) 0))
8745 fulltable)))
8746 (expert nil)
8747 (fwidth (+ maxlen 3 1 3))
8748 (ncol (/ (- (window-width) 4) fwidth))
8749 tg cnt e c tbl
8750 groups ingroup)
8751 (save-excursion
8752 (save-window-excursion
8753 (if expert
8754 (set-buffer (get-buffer-create " *Org todo*"))
8755 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8756 (erase-buffer)
8757 (org-set-local 'org-done-keywords done-keywords)
8758 (setq tbl fulltable cnt 0)
8759 (while (setq e (pop tbl))
8760 (cond
8761 ((equal e '(:startgroup))
8762 (push '() groups) (setq ingroup t)
8763 (when (not (= cnt 0))
8764 (setq cnt 0)
8765 (insert "\n"))
8766 (insert "{ "))
8767 ((equal e '(:endgroup))
8768 (setq ingroup nil cnt 0)
8769 (insert "}\n"))
8771 (setq tg (car e) c (cdr e))
8772 (if ingroup (push tg (car groups)))
8773 (setq tg (org-add-props tg nil 'face
8774 (org-get-todo-face tg)))
8775 (if (and (= cnt 0) (not ingroup)) (insert " "))
8776 (insert "[" c "] " tg (make-string
8777 (- fwidth 4 (length tg)) ?\ ))
8778 (when (= (setq cnt (1+ cnt)) ncol)
8779 (insert "\n")
8780 (if ingroup (insert " "))
8781 (setq cnt 0)))))
8782 (insert "\n")
8783 (goto-char (point-min))
8784 (if (not expert) (org-fit-window-to-buffer))
8785 (message "[a-z..]:Set [SPC]:clear")
8786 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8787 (cond
8788 ((or (= c ?\C-g)
8789 (and (= c ?q) (not (rassoc c fulltable))))
8790 (setq quit-flag t))
8791 ((= c ?\ ) nil)
8792 ((setq e (rassoc c fulltable) tg (car e))
8794 (t (setq quit-flag t)))))))
8796 (defun org-entry-is-todo-p ()
8797 (member (org-get-todo-state) org-not-done-keywords))
8799 (defun org-entry-is-done-p ()
8800 (member (org-get-todo-state) org-done-keywords))
8802 (defun org-get-todo-state ()
8803 (save-excursion
8804 (org-back-to-heading t)
8805 (and (looking-at org-todo-line-regexp)
8806 (match-end 2)
8807 (match-string 2))))
8809 (defun org-at-date-range-p (&optional inactive-ok)
8810 "Is the cursor inside a date range?"
8811 (interactive)
8812 (save-excursion
8813 (catch 'exit
8814 (let ((pos (point)))
8815 (skip-chars-backward "^[<\r\n")
8816 (skip-chars-backward "<[")
8817 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8818 (>= (match-end 0) pos)
8819 (throw 'exit t))
8820 (skip-chars-backward "^<[\r\n")
8821 (skip-chars-backward "<[")
8822 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8823 (>= (match-end 0) pos)
8824 (throw 'exit t)))
8825 nil)))
8827 (defun org-get-repeat ()
8828 "Check if there is a deadline/schedule with repeater in this entry."
8829 (save-match-data
8830 (save-excursion
8831 (org-back-to-heading t)
8832 (if (re-search-forward
8833 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8834 (match-string 1)))))
8836 (defvar org-last-changed-timestamp)
8837 (defvar org-last-inserted-timestamp)
8838 (defvar org-log-post-message)
8839 (defvar org-log-note-purpose)
8840 (defvar org-log-note-how)
8841 (defvar org-log-note-extra)
8842 (defun org-auto-repeat-maybe (done-word)
8843 "Check if the current headline contains a repeated deadline/schedule.
8844 If yes, set TODO state back to what it was and change the base date
8845 of repeating deadline/scheduled time stamps to new date.
8846 This function is run automatically after each state change to a DONE state."
8847 ;; last-state is dynamically scoped into this function
8848 (let* ((repeat (org-get-repeat))
8849 (aa (assoc last-state org-todo-kwd-alist))
8850 (interpret (nth 1 aa))
8851 (head (nth 2 aa))
8852 (whata '(("d" . day) ("m" . month) ("y" . year)))
8853 (msg "Entry repeats: ")
8854 (org-log-done nil)
8855 (org-todo-log-states nil)
8856 (nshiftmax 10) (nshift 0)
8857 re type n what ts time)
8858 (when repeat
8859 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8860 (org-todo (if (eq interpret 'type) last-state head))
8861 (when org-log-repeat
8862 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8863 (memq 'org-add-log-note post-command-hook))
8864 ;; OK, we are already setup for some record
8865 (if (eq org-log-repeat 'note)
8866 ;; make sure we take a note, not only a time stamp
8867 (setq org-log-note-how 'note))
8868 ;; Set up for taking a record
8869 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8870 'findpos org-log-repeat)))
8871 (org-back-to-heading t)
8872 (org-add-planning-info nil nil 'closed)
8873 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8874 org-deadline-time-regexp "\\)\\|\\("
8875 org-ts-regexp "\\)"))
8876 (while (re-search-forward
8877 re (save-excursion (outline-next-heading) (point)) t)
8878 (setq type (if (match-end 1) org-scheduled-string
8879 (if (match-end 3) org-deadline-string "Plain:"))
8880 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8881 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8882 (setq n (string-to-number (match-string 2 ts))
8883 what (match-string 3 ts))
8884 (if (equal what "w") (setq n (* n 7) what "d"))
8885 ;; Preparation, see if we need to modify the start date for the change
8886 (when (match-end 1)
8887 (setq time (save-match-data (org-time-string-to-time ts)))
8888 (cond
8889 ((equal (match-string 1 ts) ".")
8890 ;; Shift starting date to today
8891 (org-timestamp-change
8892 (- (time-to-days (current-time)) (time-to-days time))
8893 'day))
8894 ((equal (match-string 1 ts) "+")
8895 (while (or (= nshift 0)
8896 (<= (time-to-days time) (time-to-days (current-time))))
8897 (when (= (incf nshift) nshiftmax)
8898 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8899 (error "Abort")))
8900 (org-timestamp-change n (cdr (assoc what whata)))
8901 (org-at-timestamp-p t)
8902 (setq ts (match-string 1))
8903 (setq time (save-match-data (org-time-string-to-time ts))))
8904 (org-timestamp-change (- n) (cdr (assoc what whata)))
8905 ;; rematch, so that we have everything in place for the real shift
8906 (org-at-timestamp-p t)
8907 (setq ts (match-string 1))
8908 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8909 (org-timestamp-change n (cdr (assoc what whata)))
8910 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8911 (setq org-log-post-message msg)
8912 (message "%s" msg))))
8914 (defun org-show-todo-tree (arg)
8915 "Make a compact tree which shows all headlines marked with TODO.
8916 The tree will show the lines where the regexp matches, and all higher
8917 headlines above the match.
8918 With a \\[universal-argument] prefix, also show the DONE entries.
8919 With a numeric prefix N, construct a sparse tree for the Nth element
8920 of `org-todo-keywords-1'."
8921 (interactive "P")
8922 (let ((case-fold-search nil)
8923 (kwd-re
8924 (cond ((null arg) org-not-done-regexp)
8925 ((equal arg '(4))
8926 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8927 (mapcar 'list org-todo-keywords-1))))
8928 (concat "\\("
8929 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8930 "\\)\\>")))
8931 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8932 (regexp-quote (nth (1- (prefix-numeric-value arg))
8933 org-todo-keywords-1)))
8934 (t (error "Invalid prefix argument: %s" arg)))))
8935 (message "%d TODO entries found"
8936 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8938 (defun org-deadline (&optional remove time)
8939 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8940 With argument REMOVE, remove any deadline from the item.
8941 When TIME is set, it should be an internal time specification, and the
8942 scheduling will use the corresponding date."
8943 (interactive "P")
8944 (if remove
8945 (progn
8946 (org-remove-timestamp-with-keyword org-deadline-string)
8947 (message "Item no longer has a deadline."))
8948 (if (org-get-repeat)
8949 (error "Cannot change deadline on task with repeater, please do that by hand")
8950 (org-add-planning-info 'deadline time 'closed)
8951 (message "Deadline on %s" org-last-inserted-timestamp))))
8953 (defun org-schedule (&optional remove time)
8954 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8955 With argument REMOVE, remove any scheduling date from the item.
8956 When TIME is set, it should be an internal time specification, and the
8957 scheduling will use the corresponding date."
8958 (interactive "P")
8959 (if remove
8960 (progn
8961 (org-remove-timestamp-with-keyword org-scheduled-string)
8962 (message "Item is no longer scheduled."))
8963 (if (org-get-repeat)
8964 (error "Cannot reschedule task with repeater, please do that by hand")
8965 (org-add-planning-info 'scheduled time 'closed)
8966 (message "Scheduled to %s" org-last-inserted-timestamp))))
8968 (defun org-remove-timestamp-with-keyword (keyword)
8969 "Remove all time stamps with KEYWORD in the current entry."
8970 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8971 beg)
8972 (save-excursion
8973 (org-back-to-heading t)
8974 (setq beg (point))
8975 (org-end-of-subtree t t)
8976 (while (re-search-backward re beg t)
8977 (replace-match "")
8978 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8979 (equal (char-before) ?\ ))
8980 (backward-delete-char 1)
8981 (if (string-match "^[ \t]*$" (buffer-substring
8982 (point-at-bol) (point-at-eol)))
8983 (delete-region (point-at-bol)
8984 (min (point-max) (1+ (point-at-eol))))))))))
8986 (defun org-add-planning-info (what &optional time &rest remove)
8987 "Insert new timestamp with keyword in the line directly after the headline.
8988 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8989 If non is given, the user is prompted for a date.
8990 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8991 be removed."
8992 (interactive)
8993 (let (org-time-was-given org-end-time-was-given ts
8994 end default-time default-input)
8996 (when (and (not time) (memq what '(scheduled deadline)))
8997 ;; Try to get a default date/time from existing timestamp
8998 (save-excursion
8999 (org-back-to-heading t)
9000 (setq end (save-excursion (outline-next-heading) (point)))
9001 (when (re-search-forward (if (eq what 'scheduled)
9002 org-scheduled-time-regexp
9003 org-deadline-time-regexp)
9004 end t)
9005 (setq ts (match-string 1)
9006 default-time
9007 (apply 'encode-time (org-parse-time-string ts))
9008 default-input (and ts (org-get-compact-tod ts))))))
9009 (when what
9010 ;; If necessary, get the time from the user
9011 (setq time (or time (org-read-date nil 'to-time nil nil
9012 default-time default-input))))
9014 (when (and org-insert-labeled-timestamps-at-point
9015 (member what '(scheduled deadline)))
9016 (insert
9017 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9018 (org-insert-time-stamp time org-time-was-given
9019 nil nil nil (list org-end-time-was-given))
9020 (setq what nil))
9021 (save-excursion
9022 (save-restriction
9023 (let (col list elt ts buffer-invisibility-spec)
9024 (org-back-to-heading t)
9025 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9026 (goto-char (match-end 1))
9027 (setq col (current-column))
9028 (goto-char (match-end 0))
9029 (if (eobp) (insert "\n") (forward-char 1))
9030 (if (and (not (looking-at outline-regexp))
9031 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9032 "[^\r\n]*"))
9033 (not (equal (match-string 1) org-clock-string)))
9034 (narrow-to-region (match-beginning 0) (match-end 0))
9035 (insert-before-markers "\n")
9036 (backward-char 1)
9037 (narrow-to-region (point) (point))
9038 (and org-adapt-indentation (org-indent-to-column col)))
9039 ;; Check if we have to remove something.
9040 (setq list (cons what remove))
9041 (while list
9042 (setq elt (pop list))
9043 (goto-char (point-min))
9044 (when (or (and (eq elt 'scheduled)
9045 (re-search-forward org-scheduled-time-regexp nil t))
9046 (and (eq elt 'deadline)
9047 (re-search-forward org-deadline-time-regexp nil t))
9048 (and (eq elt 'closed)
9049 (re-search-forward org-closed-time-regexp nil t)))
9050 (replace-match "")
9051 (if (looking-at "--+<[^>]+>") (replace-match ""))
9052 (if (looking-at " +") (replace-match ""))))
9053 (goto-char (point-max))
9054 (when what
9055 (insert
9056 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9057 (cond ((eq what 'scheduled) org-scheduled-string)
9058 ((eq what 'deadline) org-deadline-string)
9059 ((eq what 'closed) org-closed-string))
9060 " ")
9061 (setq ts (org-insert-time-stamp
9062 time
9063 (or org-time-was-given
9064 (and (eq what 'closed) org-log-done-with-time))
9065 (eq what 'closed)
9066 nil nil (list org-end-time-was-given)))
9067 (end-of-line 1))
9068 (goto-char (point-min))
9069 (widen)
9070 (if (and (looking-at "[ \t]+\n")
9071 (equal (char-before) ?\n))
9072 (delete-region (1- (point)) (point-at-eol)))
9073 ts)))))
9075 (defvar org-log-note-marker (make-marker))
9076 (defvar org-log-note-purpose nil)
9077 (defvar org-log-note-state nil)
9078 (defvar org-log-note-how nil)
9079 (defvar org-log-note-extra nil)
9080 (defvar org-log-note-window-configuration nil)
9081 (defvar org-log-note-return-to (make-marker))
9082 (defvar org-log-post-message nil
9083 "Message to be displayed after a log note has been stored.
9084 The auto-repeater uses this.")
9086 (defun org-add-note ()
9087 "Add a note to the current entry.
9088 This is done in the same way as adding a state change note."
9089 (interactive)
9090 (org-add-log-setup 'note nil 'findpos nil))
9092 (defvar org-property-end-re)
9093 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
9094 "Set up the post command hook to take a note.
9095 If this is about to TODO state change, the new state is expected in STATE.
9096 When FINDPOS is non-nil, find the correct position for the note in
9097 the current entry. If not, assume that it can be inserted at point.
9098 HOW is an indicator what kind of note should be created.
9099 EXTRA is additional text that will be inserted into the notes buffer."
9100 (save-restriction
9101 (save-excursion
9102 (when findpos
9103 (org-back-to-heading t)
9104 (narrow-to-region (point) (save-excursion
9105 (outline-next-heading) (point)))
9106 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9107 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9108 "[^\r\n]*\\)?"))
9109 (goto-char (match-end 0))
9110 (when (and org-log-state-notes-insert-after-drawers
9111 (save-excursion
9112 (forward-line) (looking-at org-drawer-regexp)))
9113 (progn (forward-line)
9114 (while (looking-at org-drawer-regexp)
9115 (goto-char (match-end 0))
9116 (re-search-forward org-property-end-re (point-max) t)
9117 (forward-line))
9118 (forward-line -1)))
9119 (unless org-log-states-order-reversed
9120 (and (= (char-after) ?\n) (forward-char 1))
9121 (org-skip-over-state-notes)
9122 (skip-chars-backward " \t\n\r")))
9123 (move-marker org-log-note-marker (point))
9124 (setq org-log-note-purpose purpose
9125 org-log-note-state state
9126 org-log-note-how how
9127 org-log-note-extra extra)
9128 (add-hook 'post-command-hook 'org-add-log-note 'append))))
9130 (defun org-skip-over-state-notes ()
9131 "Skip past the list of State notes in an entry."
9132 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9133 (while (looking-at "[ \t]*- State")
9134 (condition-case nil
9135 (org-next-item)
9136 (error (org-end-of-item)))))
9138 (defun org-add-log-note (&optional purpose)
9139 "Pop up a window for taking a note, and add this note later at point."
9140 (remove-hook 'post-command-hook 'org-add-log-note)
9141 (setq org-log-note-window-configuration (current-window-configuration))
9142 (delete-other-windows)
9143 (move-marker org-log-note-return-to (point))
9144 (switch-to-buffer (marker-buffer org-log-note-marker))
9145 (goto-char org-log-note-marker)
9146 (org-switch-to-buffer-other-window "*Org Note*")
9147 (erase-buffer)
9148 (if (memq org-log-note-how '(time state))
9149 (let (current-prefix-arg) (org-store-log-note))
9150 (let ((org-inhibit-startup t)) (org-mode))
9151 (insert (format "# Insert note for %s.
9152 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9153 (cond
9154 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9155 ((eq org-log-note-purpose 'done) "closed todo item")
9156 ((eq org-log-note-purpose 'state)
9157 (format "state change to \"%s\"" org-log-note-state))
9158 ((eq org-log-note-purpose 'note)
9159 "this entry")
9160 (t (error "This should not happen")))))
9161 (if org-log-note-extra (insert org-log-note-extra))
9162 (org-set-local 'org-finish-function 'org-store-log-note)))
9164 (defvar org-note-abort nil) ; dynamically scoped
9165 (defun org-store-log-note ()
9166 "Finish taking a log note, and insert it to where it belongs."
9167 (let ((txt (buffer-string))
9168 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9169 lines ind)
9170 (kill-buffer (current-buffer))
9171 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9172 (setq txt (replace-match "" t t txt)))
9173 (if (string-match "\\s-+\\'" txt)
9174 (setq txt (replace-match "" t t txt)))
9175 (setq lines (org-split-string txt "\n"))
9176 (when (and note (string-match "\\S-" note))
9177 (setq note
9178 (org-replace-escapes
9179 note
9180 (list (cons "%u" (user-login-name))
9181 (cons "%U" user-full-name)
9182 (cons "%t" (format-time-string
9183 (org-time-stamp-format 'long 'inactive)
9184 (current-time)))
9185 (cons "%s" (if org-log-note-state
9186 (concat "\"" org-log-note-state "\"")
9187 "")))))
9188 (if lines (setq note (concat note " \\\\")))
9189 (push note lines))
9190 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9191 (when lines
9192 (save-excursion
9193 (set-buffer (marker-buffer org-log-note-marker))
9194 (save-excursion
9195 (goto-char org-log-note-marker)
9196 (move-marker org-log-note-marker nil)
9197 (end-of-line 1)
9198 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9199 (indent-relative nil)
9200 (insert "- " (pop lines))
9201 (org-indent-line-function)
9202 (beginning-of-line 1)
9203 (looking-at "[ \t]*")
9204 (setq ind (concat (match-string 0) " "))
9205 (end-of-line 1)
9206 (while lines (insert "\n" ind (pop lines)))))))
9207 (set-window-configuration org-log-note-window-configuration)
9208 (with-current-buffer (marker-buffer org-log-note-return-to)
9209 (goto-char org-log-note-return-to))
9210 (move-marker org-log-note-return-to nil)
9211 (and org-log-post-message (message "%s" org-log-post-message)))
9213 (defun org-sparse-tree (&optional arg)
9214 "Create a sparse tree, prompt for the details.
9215 This command can create sparse trees. You first need to select the type
9216 of match used to create the tree:
9218 t Show entries with a specific TODO keyword.
9219 T Show entries selected by a tags match.
9220 p Enter a property name and its value (both with completion on existing
9221 names/values) and show entries with that property.
9222 r Show entries matching a regular expression
9223 d Show deadlines due within `org-deadline-warning-days'."
9224 (interactive "P")
9225 (let (ans kwd value)
9226 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9227 (setq ans (read-char-exclusive))
9228 (cond
9229 ((equal ans ?d)
9230 (call-interactively 'org-check-deadlines))
9231 ((equal ans ?b)
9232 (call-interactively 'org-check-before-date))
9233 ((equal ans ?t)
9234 (org-show-todo-tree '(4)))
9235 ((equal ans ?T)
9236 (call-interactively 'org-tags-sparse-tree))
9237 ((member ans '(?p ?P))
9238 (setq kwd (org-ido-completing-read "Property: "
9239 (mapcar 'list (org-buffer-property-keys))))
9240 (setq value (org-ido-completing-read "Value: "
9241 (mapcar 'list (org-property-values kwd))))
9242 (unless (string-match "\\`{.*}\\'" value)
9243 (setq value (concat "\"" value "\"")))
9244 (org-tags-sparse-tree arg (concat kwd "=" value)))
9245 ((member ans '(?r ?R ?/))
9246 (call-interactively 'org-occur))
9247 (t (error "No such sparse tree command \"%c\"" ans)))))
9249 (defvar org-occur-highlights nil
9250 "List of overlays used for occur matches.")
9251 (make-variable-buffer-local 'org-occur-highlights)
9252 (defvar org-occur-parameters nil
9253 "Parameters of the active org-occur calls.
9254 This is a list, each call to org-occur pushes as cons cell,
9255 containing the regular expression and the callback, onto the list.
9256 The list can contain several entries if `org-occur' has been called
9257 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9258 will only contain one set of parameters. When the highlights are
9259 removed (for example with `C-c C-c', or with the next edit (depending
9260 on `org-remove-highlights-with-change'), this variable is emptied
9261 as well.")
9262 (make-variable-buffer-local 'org-occur-parameters)
9264 (defun org-occur (regexp &optional keep-previous callback)
9265 "Make a compact tree which shows all matches of REGEXP.
9266 The tree will show the lines where the regexp matches, and all higher
9267 headlines above the match. It will also show the heading after the match,
9268 to make sure editing the matching entry is easy.
9269 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9270 call to `org-occur' will be kept, to allow stacking of calls to this
9271 command.
9272 If CALLBACK is non-nil, it is a function which is called to confirm
9273 that the match should indeed be shown."
9274 (interactive "sRegexp: \nP")
9275 (unless keep-previous
9276 (org-remove-occur-highlights nil nil t))
9277 (push (cons regexp callback) org-occur-parameters)
9278 (let ((cnt 0))
9279 (save-excursion
9280 (goto-char (point-min))
9281 (if (or (not keep-previous) ; do not want to keep
9282 (not org-occur-highlights)) ; no previous matches
9283 ;; hide everything
9284 (org-overview))
9285 (while (re-search-forward regexp nil t)
9286 (when (or (not callback)
9287 (save-match-data (funcall callback)))
9288 (setq cnt (1+ cnt))
9289 (when org-highlight-sparse-tree-matches
9290 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9291 (org-show-context 'occur-tree))))
9292 (when org-remove-highlights-with-change
9293 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9294 nil 'local))
9295 (unless org-sparse-tree-open-archived-trees
9296 (org-hide-archived-subtrees (point-min) (point-max)))
9297 (run-hooks 'org-occur-hook)
9298 (if (interactive-p)
9299 (message "%d match(es) for regexp %s" cnt regexp))
9300 cnt))
9302 (defun org-show-context (&optional key)
9303 "Make sure point and context and visible.
9304 How much context is shown depends upon the variables
9305 `org-show-hierarchy-above', `org-show-following-heading'. and
9306 `org-show-siblings'."
9307 (let ((heading-p (org-on-heading-p t))
9308 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9309 (following-p (org-get-alist-option org-show-following-heading key))
9310 (entry-p (org-get-alist-option org-show-entry-below key))
9311 (siblings-p (org-get-alist-option org-show-siblings key)))
9312 (catch 'exit
9313 ;; Show heading or entry text
9314 (if (and heading-p (not entry-p))
9315 (org-flag-heading nil) ; only show the heading
9316 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9317 (org-show-hidden-entry))) ; show entire entry
9318 (when following-p
9319 ;; Show next sibling, or heading below text
9320 (save-excursion
9321 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9322 (org-flag-heading nil))))
9323 (when siblings-p (org-show-siblings))
9324 (when hierarchy-p
9325 ;; show all higher headings, possibly with siblings
9326 (save-excursion
9327 (while (and (condition-case nil
9328 (progn (org-up-heading-all 1) t)
9329 (error nil))
9330 (not (bobp)))
9331 (org-flag-heading nil)
9332 (when siblings-p (org-show-siblings))))))))
9334 (defun org-reveal (&optional siblings)
9335 "Show current entry, hierarchy above it, and the following headline.
9336 This can be used to show a consistent set of context around locations
9337 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9338 not t for the search context.
9340 With optional argument SIBLINGS, on each level of the hierarchy all
9341 siblings are shown. This repairs the tree structure to what it would
9342 look like when opened with hierarchical calls to `org-cycle'."
9343 (interactive "P")
9344 (let ((org-show-hierarchy-above t)
9345 (org-show-following-heading t)
9346 (org-show-siblings (if siblings t org-show-siblings)))
9347 (org-show-context nil)))
9349 (defun org-highlight-new-match (beg end)
9350 "Highlight from BEG to END and mark the highlight is an occur headline."
9351 (let ((ov (org-make-overlay beg end)))
9352 (org-overlay-put ov 'face 'secondary-selection)
9353 (push ov org-occur-highlights)))
9355 (defun org-remove-occur-highlights (&optional beg end noremove)
9356 "Remove the occur highlights from the buffer.
9357 BEG and END are ignored. If NOREMOVE is nil, remove this function
9358 from the `before-change-functions' in the current buffer."
9359 (interactive)
9360 (unless org-inhibit-highlight-removal
9361 (mapc 'org-delete-overlay org-occur-highlights)
9362 (setq org-occur-highlights nil)
9363 (setq org-occur-parameters nil)
9364 (unless noremove
9365 (remove-hook 'before-change-functions
9366 'org-remove-occur-highlights 'local))))
9368 ;;;; Priorities
9370 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9371 "Regular expression matching the priority indicator.")
9373 (defvar org-remove-priority-next-time nil)
9375 (defun org-priority-up ()
9376 "Increase the priority of the current item."
9377 (interactive)
9378 (org-priority 'up))
9380 (defun org-priority-down ()
9381 "Decrease the priority of the current item."
9382 (interactive)
9383 (org-priority 'down))
9385 (defun org-priority (&optional action)
9386 "Change the priority of an item by ARG.
9387 ACTION can be `set', `up', `down', or a character."
9388 (interactive)
9389 (setq action (or action 'set))
9390 (let (current new news have remove)
9391 (save-excursion
9392 (org-back-to-heading)
9393 (if (looking-at org-priority-regexp)
9394 (setq current (string-to-char (match-string 2))
9395 have t)
9396 (setq current org-default-priority))
9397 (cond
9398 ((or (eq action 'set)
9399 (if (featurep 'xemacs) (characterp action) (integerp action)))
9400 (if (not (eq action 'set))
9401 (setq new action)
9402 (message "Priority %c-%c, SPC to remove: "
9403 org-highest-priority org-lowest-priority)
9404 (setq new (read-char-exclusive)))
9405 (if (and (= (upcase org-highest-priority) org-highest-priority)
9406 (= (upcase org-lowest-priority) org-lowest-priority))
9407 (setq new (upcase new)))
9408 (cond ((equal new ?\ ) (setq remove t))
9409 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9410 (error "Priority must be between `%c' and `%c'"
9411 org-highest-priority org-lowest-priority))))
9412 ((eq action 'up)
9413 (if (and (not have) (eq last-command this-command))
9414 (setq new org-lowest-priority)
9415 (setq new (if (and org-priority-start-cycle-with-default (not have))
9416 org-default-priority (1- current)))))
9417 ((eq action 'down)
9418 (if (and (not have) (eq last-command this-command))
9419 (setq new org-highest-priority)
9420 (setq new (if (and org-priority-start-cycle-with-default (not have))
9421 org-default-priority (1+ current)))))
9422 (t (error "Invalid action")))
9423 (if (or (< (upcase new) org-highest-priority)
9424 (> (upcase new) org-lowest-priority))
9425 (setq remove t))
9426 (setq news (format "%c" new))
9427 (if have
9428 (if remove
9429 (replace-match "" t t nil 1)
9430 (replace-match news t t nil 2))
9431 (if remove
9432 (error "No priority cookie found in line")
9433 (looking-at org-todo-line-regexp)
9434 (if (match-end 2)
9435 (progn
9436 (goto-char (match-end 2))
9437 (insert " [#" news "]"))
9438 (goto-char (match-beginning 3))
9439 (insert "[#" news "] ")))))
9440 (org-preserve-lc (org-set-tags nil 'align))
9441 (if remove
9442 (message "Priority removed")
9443 (message "Priority of current item set to %s" news))))
9446 (defun org-get-priority (s)
9447 "Find priority cookie and return priority."
9448 (save-match-data
9449 (if (not (string-match org-priority-regexp s))
9450 (* 1000 (- org-lowest-priority org-default-priority))
9451 (* 1000 (- org-lowest-priority
9452 (string-to-char (match-string 2 s)))))))
9454 ;;;; Tags
9456 (defvar org-agenda-archives-mode)
9457 (defun org-scan-tags (action matcher &optional todo-only)
9458 "Scan headline tags with inheritance and produce output ACTION.
9460 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9461 or `agenda' to produce an entry list for an agenda view. It can also be
9462 a Lisp form or a function that should be called at each matched headline, in
9463 this case the return value is a list of all return values from these calls.
9465 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9466 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9467 only lines with a TODO keyword are included in the output."
9468 (require 'org-agenda)
9469 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9470 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9471 (org-re
9472 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9473 (props (list 'face 'default
9474 'done-face 'org-done
9475 'undone-face 'default
9476 'mouse-face 'highlight
9477 'org-not-done-regexp org-not-done-regexp
9478 'org-todo-regexp org-todo-regexp
9479 'keymap org-agenda-keymap
9480 'help-echo
9481 (format "mouse-2 or RET jump to org file %s"
9482 (abbreviate-file-name
9483 (or (buffer-file-name (buffer-base-buffer))
9484 (buffer-name (buffer-base-buffer)))))))
9485 (case-fold-search nil)
9486 lspos tags tags-list
9487 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9488 (llast 0) rtn rtn1 level category i txt
9489 todo marker entry priority)
9490 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9491 (setq action (list 'lambda nil action)))
9492 (save-excursion
9493 (goto-char (point-min))
9494 (when (eq action 'sparse-tree)
9495 (org-overview)
9496 (org-remove-occur-highlights))
9497 (while (re-search-forward re nil t)
9498 (catch :skip
9499 (setq todo (if (match-end 1) (match-string 2))
9500 tags (if (match-end 4) (match-string 4)))
9501 (goto-char (setq lspos (1+ (match-beginning 0))))
9502 (setq level (org-reduced-level (funcall outline-level))
9503 category (org-get-category))
9504 (setq i llast llast level)
9505 ;; remove tag lists from same and sublevels
9506 (while (>= i level)
9507 (when (setq entry (assoc i tags-alist))
9508 (setq tags-alist (delete entry tags-alist)))
9509 (setq i (1- i)))
9510 ;; add the next tags
9511 (when tags
9512 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9513 tags-alist
9514 (cons (cons level tags) tags-alist)))
9515 ;; compile tags for current headline
9516 (setq tags-list
9517 (if org-use-tag-inheritance
9518 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9519 tags))
9520 (when org-use-tag-inheritance
9521 (setcdr (car tags-alist)
9522 (mapcar (lambda (x)
9523 (setq x (copy-sequence x))
9524 (org-add-prop-inherited x))
9525 (cdar tags-alist))))
9526 (when (and tags org-use-tag-inheritance
9527 (not (eq t org-use-tag-inheritance)))
9528 ;; selective inheritance, remove uninherited ones
9529 (setcdr (car tags-alist)
9530 (org-remove-uniherited-tags (cdar tags-alist))))
9531 (when (and (or (not todo-only)
9532 (and (member todo org-not-done-keywords)
9533 (or (not org-agenda-tags-todo-honor-ignore-options)
9534 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9535 (let ((case-fold-search t)) (eval matcher))
9537 (not (member org-archive-tag tags-list))
9538 ;; we have an archive tag, should we use this anyway?
9539 (or (not org-agenda-skip-archived-trees)
9540 (and (eq action 'agenda) org-agenda-archives-mode))))
9541 (unless (eq action 'sparse-tree) (org-agenda-skip))
9543 ;; select this headline
9545 (cond
9546 ((eq action 'sparse-tree)
9547 (and org-highlight-sparse-tree-matches
9548 (org-get-heading) (match-end 0)
9549 (org-highlight-new-match
9550 (match-beginning 0) (match-beginning 1)))
9551 (org-show-context 'tags-tree))
9552 ((eq action 'agenda)
9553 (setq txt (org-format-agenda-item
9555 (concat
9556 (if org-tags-match-list-sublevels
9557 (make-string (1- level) ?.) "")
9558 (org-get-heading))
9559 category (org-get-tags-at))
9560 priority (org-get-priority txt))
9561 (goto-char lspos)
9562 (setq marker (org-agenda-new-marker))
9563 (org-add-props txt props
9564 'org-marker marker 'org-hd-marker marker 'org-category category
9565 'priority priority 'type "tagsmatch")
9566 (push txt rtn))
9567 ((functionp action)
9568 (save-excursion
9569 (setq rtn1 (funcall action))
9570 (push rtn1 rtn))
9571 (goto-char (point-at-eol)))
9572 (t (error "Invalid action")))
9574 ;; if we are to skip sublevels, jump to end of subtree
9575 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9576 (when (and (eq action 'sparse-tree)
9577 (not org-sparse-tree-open-archived-trees))
9578 (org-hide-archived-subtrees (point-min) (point-max)))
9579 (nreverse rtn)))
9581 (defun org-remove-uniherited-tags (tags)
9582 "Remove all tags that are not inherited from the list TAGS."
9583 (cond
9584 ((eq org-use-tag-inheritance t)
9585 (if org-tags-exclude-from-inheritance
9586 (org-delete-all org-tags-exclude-from-inheritance tags)
9587 tags))
9588 ((not org-use-tag-inheritance) nil)
9589 ((stringp org-use-tag-inheritance)
9590 (delq nil (mapcar
9591 (lambda (x)
9592 (if (and (string-match org-use-tag-inheritance x)
9593 (not (member x org-tags-exclude-from-inheritance)))
9594 x nil))
9595 tags)))
9596 ((listp org-use-tag-inheritance)
9597 (delq nil (mapcar
9598 (lambda (x)
9599 (if (member x org-use-tag-inheritance) x nil))
9600 tags)))))
9602 (defvar todo-only) ;; dynamically scoped
9604 (defun org-tags-sparse-tree (&optional todo-only match)
9605 "Create a sparse tree according to tags string MATCH.
9606 MATCH can contain positive and negative selection of tags, like
9607 \"+WORK+URGENT-WITHBOSS\".
9608 If optional argument TODO-ONLY is non-nil, only select lines that are
9609 also TODO lines."
9610 (interactive "P")
9611 (org-prepare-agenda-buffers (list (current-buffer)))
9612 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9614 (defvar org-cached-props nil)
9615 (defun org-cached-entry-get (pom property)
9616 (if (or (eq t org-use-property-inheritance)
9617 (and (stringp org-use-property-inheritance)
9618 (string-match org-use-property-inheritance property))
9619 (and (listp org-use-property-inheritance)
9620 (member property org-use-property-inheritance)))
9621 ;; Caching is not possible, check it directly
9622 (org-entry-get pom property 'inherit)
9623 ;; Get all properties, so that we can do complicated checks easily
9624 (cdr (assoc property (or org-cached-props
9625 (setq org-cached-props
9626 (org-entry-properties pom)))))))
9628 (defun org-global-tags-completion-table (&optional files)
9629 "Return the list of all tags in all agenda buffer/files."
9630 (save-excursion
9631 (org-uniquify
9632 (delq nil
9633 (apply 'append
9634 (mapcar
9635 (lambda (file)
9636 (set-buffer (find-file-noselect file))
9637 (append (org-get-buffer-tags)
9638 (mapcar (lambda (x) (if (stringp (car-safe x))
9639 (list (car-safe x)) nil))
9640 org-tag-alist)))
9641 (if (and files (car files))
9642 files
9643 (org-agenda-files))))))))
9645 (defun org-make-tags-matcher (match)
9646 "Create the TAGS//TODO matcher form for the selection string MATCH."
9647 ;; todo-only is scoped dynamically into this function, and the function
9648 ;; may change it if the matcher asks for it.
9649 (unless match
9650 ;; Get a new match request, with completion
9651 (let ((org-last-tags-completion-table
9652 (org-global-tags-completion-table)))
9653 (setq match (org-completing-read
9654 "Match: " 'org-tags-completion-function nil nil nil
9655 'org-tags-history))))
9657 ;; Parse the string and create a lisp form
9658 (let ((match0 match)
9659 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9660 minus tag mm
9661 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9662 orterms term orlist re-p str-p level-p level-op time-p
9663 prop-p pn pv po cat-p gv rest)
9664 (if (string-match "/+" match)
9665 ;; match contains also a todo-matching request
9666 (progn
9667 (setq tagsmatch (substring match 0 (match-beginning 0))
9668 todomatch (substring match (match-end 0)))
9669 (if (string-match "^!" todomatch)
9670 (setq todo-only t todomatch (substring todomatch 1)))
9671 (if (string-match "^\\s-*$" todomatch)
9672 (setq todomatch nil)))
9673 ;; only matching tags
9674 (setq tagsmatch match todomatch nil))
9676 ;; Make the tags matcher
9677 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9678 (setq tagsmatcher t)
9679 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9680 (while (setq term (pop orterms))
9681 (while (and (equal (substring term -1) "\\") orterms)
9682 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9683 (while (string-match re term)
9684 (setq rest (substring term (match-end 0))
9685 minus (and (match-end 1)
9686 (equal (match-string 1 term) "-"))
9687 tag (match-string 2 term)
9688 re-p (equal (string-to-char tag) ?{)
9689 level-p (match-end 4)
9690 prop-p (match-end 5)
9691 mm (cond
9692 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9693 (level-p
9694 (setq level-op (org-op-to-function (match-string 3 term)))
9695 `(,level-op level ,(string-to-number
9696 (match-string 4 term))))
9697 (prop-p
9698 (setq pn (match-string 5 term)
9699 po (match-string 6 term)
9700 pv (match-string 7 term)
9701 cat-p (equal pn "CATEGORY")
9702 re-p (equal (string-to-char pv) ?{)
9703 str-p (equal (string-to-char pv) ?\")
9704 time-p (save-match-data
9705 (string-match "^\"[[<].*[]>]\"$" pv))
9706 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9707 (if time-p (setq pv (org-matcher-time pv)))
9708 (setq po (org-op-to-function po (if time-p 'time str-p)))
9709 (cond
9710 ((equal pn "CATEGORY")
9711 (setq gv '(get-text-property (point) 'org-category)))
9712 ((equal pn "TODO")
9713 (setq gv 'todo))
9715 (setq gv `(org-cached-entry-get nil ,pn))))
9716 (if re-p
9717 (if (eq po 'org<>)
9718 `(not (string-match ,pv (or ,gv "")))
9719 `(string-match ,pv (or ,gv "")))
9720 (if str-p
9721 `(,po (or ,gv "") ,pv)
9722 `(,po (string-to-number (or ,gv ""))
9723 ,(string-to-number pv) ))))
9724 (t `(member ,(downcase tag) tags-list)))
9725 mm (if minus (list 'not mm) mm)
9726 term rest)
9727 (push mm tagsmatcher))
9728 (push (if (> (length tagsmatcher) 1)
9729 (cons 'and tagsmatcher)
9730 (car tagsmatcher))
9731 orlist)
9732 (setq tagsmatcher nil))
9733 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9734 (setq tagsmatcher
9735 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9736 ;; Make the todo matcher
9737 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9738 (setq todomatcher t)
9739 (setq orterms (org-split-string todomatch "|") orlist nil)
9740 (while (setq term (pop orterms))
9741 (while (string-match re term)
9742 (setq minus (and (match-end 1)
9743 (equal (match-string 1 term) "-"))
9744 kwd (match-string 2 term)
9745 re-p (equal (string-to-char kwd) ?{)
9746 term (substring term (match-end 0))
9747 mm (if re-p
9748 `(string-match ,(substring kwd 1 -1) todo)
9749 (list 'equal 'todo kwd))
9750 mm (if minus (list 'not mm) mm))
9751 (push mm todomatcher))
9752 (push (if (> (length todomatcher) 1)
9753 (cons 'and todomatcher)
9754 (car todomatcher))
9755 orlist)
9756 (setq todomatcher nil))
9757 (setq todomatcher (if (> (length orlist) 1)
9758 (cons 'or orlist) (car orlist))))
9760 ;; Return the string and lisp forms of the matcher
9761 (setq matcher (if todomatcher
9762 (list 'and tagsmatcher todomatcher)
9763 tagsmatcher))
9764 (cons match0 matcher)))
9766 (defun org-op-to-function (op &optional stringp)
9767 "Turn an operator into the appropriate function."
9768 (setq op
9769 (cond
9770 ((equal op "<" ) '(< string< org-time<))
9771 ((equal op ">" ) '(> org-string> org-time>))
9772 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9773 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9774 ((member op '("=" "==")) '(= string= org-time=))
9775 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9776 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9778 (defun org<> (a b) (not (= a b)))
9779 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9780 (defun org-string>= (a b) (not (string< a b)))
9781 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9782 (defun org-string<> (a b) (not (string= a b)))
9783 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9784 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9785 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9786 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9787 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9788 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9789 (defun org-2ft (s)
9790 "Convert S to a floating point time.
9791 If S is already a number, just return it. If it is a string, parse
9792 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9793 (cond
9794 ((numberp s) s)
9795 ((stringp s)
9796 (condition-case nil
9797 (float-time (apply 'encode-time (org-parse-time-string s)))
9798 (error 0.)))
9799 (t 0.)))
9801 (defun org-time-today ()
9802 "Time in seconds today at 0:00.
9803 Returns the float number of seconds since the beginning of the
9804 epoch to the beginning of today (00:00)."
9805 (float-time (apply 'encode-time
9806 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9808 (defun org-matcher-time (s)
9809 "Interpret a time comparison value."
9810 (save-match-data
9811 (cond
9812 ((string= s "<now>") (float-time))
9813 ((string= s "<today>") (org-time-today))
9814 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9815 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9816 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9817 (+ (org-time-today)
9818 (* (string-to-number (match-string 1 s))
9819 (cdr (assoc (match-string 2 s)
9820 '(("d" . 86400.0) ("w" . 604800.0)
9821 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9822 (t (org-2ft s)))))
9824 (defun org-match-any-p (re list)
9825 "Does re match any element of list?"
9826 (setq list (mapcar (lambda (x) (string-match re x)) list))
9827 (delq nil list))
9829 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9830 (defvar org-tags-overlay (org-make-overlay 1 1))
9831 (org-detach-overlay org-tags-overlay)
9833 (defun org-get-local-tags-at (&optional pos)
9834 "Get a list of tags defined in the current headline."
9835 (org-get-tags-at pos 'local))
9837 (defun org-get-local-tags ()
9838 "Get a list of tags defined in the current headline."
9839 (org-get-tags-at nil 'local))
9841 (defun org-get-tags-at (&optional pos local)
9842 "Get a list of all headline tags applicable at POS.
9843 POS defaults to point. If tags are inherited, the list contains
9844 the targets in the same sequence as the headlines appear, i.e.
9845 the tags of the current headline come last.
9846 When LOCAL is non-nil, only return tags from the current headline,
9847 ignore inherited ones."
9848 (interactive)
9849 (let (tags ltags lastpos parent)
9850 (save-excursion
9851 (save-restriction
9852 (widen)
9853 (goto-char (or pos (point)))
9854 (save-match-data
9855 (catch 'done
9856 (condition-case nil
9857 (progn
9858 (org-back-to-heading t)
9859 (while (not (equal lastpos (point)))
9860 (setq lastpos (point))
9861 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9862 (setq ltags (org-split-string
9863 (org-match-string-no-properties 1) ":"))
9864 (when parent
9865 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9866 (setq tags (append
9867 (if parent
9868 (org-remove-uniherited-tags ltags)
9869 ltags)
9870 tags)))
9871 (or org-use-tag-inheritance (throw 'done t))
9872 (if local (throw 'done t))
9873 (org-up-heading-all 1)
9874 (setq parent t)))
9875 (error nil)))))
9876 (append (org-remove-uniherited-tags org-file-tags) tags))))
9878 (defun org-add-prop-inherited (s)
9879 (add-text-properties 0 (length s) '(inherited t) s)
9882 (defun org-toggle-tag (tag &optional onoff)
9883 "Toggle the tag TAG for the current line.
9884 If ONOFF is `on' or `off', don't toggle but set to this state."
9885 (let (res current)
9886 (save-excursion
9887 (org-back-to-heading t)
9888 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9889 (point-at-eol) t)
9890 (progn
9891 (setq current (match-string 1))
9892 (replace-match ""))
9893 (setq current ""))
9894 (setq current (nreverse (org-split-string current ":")))
9895 (cond
9896 ((eq onoff 'on)
9897 (setq res t)
9898 (or (member tag current) (push tag current)))
9899 ((eq onoff 'off)
9900 (or (not (member tag current)) (setq current (delete tag current))))
9901 (t (if (member tag current)
9902 (setq current (delete tag current))
9903 (setq res t)
9904 (push tag current))))
9905 (end-of-line 1)
9906 (if current
9907 (progn
9908 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9909 (org-set-tags nil t))
9910 (delete-horizontal-space))
9911 (run-hooks 'org-after-tags-change-hook))
9912 res))
9914 (defun org-align-tags-here (to-col)
9915 ;; Assumes that this is a headline
9916 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9917 (beginning-of-line 1)
9918 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9919 (< pos (match-beginning 2)))
9920 (progn
9921 (setq tags-l (- (match-end 2) (match-beginning 2)))
9922 (goto-char (match-beginning 1))
9923 (insert " ")
9924 (delete-region (point) (1+ (match-beginning 2)))
9925 (setq ncol (max (1+ (current-column))
9926 (1+ col)
9927 (if (> to-col 0)
9928 to-col
9929 (- (abs to-col) tags-l))))
9930 (setq p (point))
9931 (insert (make-string (- ncol (current-column)) ?\ ))
9932 (setq ncol (current-column))
9933 (when indent-tabs-mode (tabify p (point-at-eol)))
9934 (org-move-to-column (min ncol col) t))
9935 (goto-char pos))))
9937 (defun org-set-tags-command (&optional arg just-align)
9938 "Call the set-tags command for the current entry."
9939 (interactive "P")
9940 (if (org-on-heading-p)
9941 (org-set-tags arg just-align)
9942 (save-excursion
9943 (org-back-to-heading t)
9944 (org-set-tags arg just-align))))
9946 (defun org-set-tags (&optional arg just-align)
9947 "Set the tags for the current headline.
9948 With prefix ARG, realign all tags in headings in the current buffer."
9949 (interactive "P")
9950 (let* ((re (concat "^" outline-regexp))
9951 (current (org-get-tags-string))
9952 (col (current-column))
9953 (org-setting-tags t)
9954 table current-tags inherited-tags ; computed below when needed
9955 tags p0 c0 c1 rpl)
9956 (if arg
9957 (save-excursion
9958 (goto-char (point-min))
9959 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9960 (while (re-search-forward re nil t)
9961 (org-set-tags nil t)
9962 (end-of-line 1)))
9963 (message "All tags realigned to column %d" org-tags-column))
9964 (if just-align
9965 (setq tags current)
9966 ;; Get a new set of tags from the user
9967 (save-excursion
9968 (setq table (or org-tag-alist (org-get-buffer-tags))
9969 org-last-tags-completion-table table
9970 current-tags (org-split-string current ":")
9971 inherited-tags (nreverse
9972 (nthcdr (length current-tags)
9973 (nreverse (org-get-tags-at))))
9974 tags
9975 (if (or (eq t org-use-fast-tag-selection)
9976 (and org-use-fast-tag-selection
9977 (delq nil (mapcar 'cdr table))))
9978 (org-fast-tag-selection
9979 current-tags inherited-tags table
9980 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9981 (let ((org-add-colon-after-tag-completion t))
9982 (org-trim
9983 (org-without-partial-completion
9984 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9985 nil nil current 'org-tags-history)))))))
9986 (while (string-match "[-+&]+" tags)
9987 ;; No boolean logic, just a list
9988 (setq tags (replace-match ":" t t tags))))
9990 (if (string-match "\\`[\t ]*\\'" tags)
9991 (setq tags "")
9992 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9993 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9995 ;; Insert new tags at the correct column
9996 (beginning-of-line 1)
9997 (cond
9998 ((and (equal current "") (equal tags "")))
9999 ((re-search-forward
10000 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10001 (point-at-eol) t)
10002 (if (equal tags "")
10003 (setq rpl "")
10004 (goto-char (match-beginning 0))
10005 (setq c0 (current-column) p0 (point)
10006 c1 (max (1+ c0) (if (> org-tags-column 0)
10007 org-tags-column
10008 (- (- org-tags-column) (length tags))))
10009 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10010 (replace-match rpl t t)
10011 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10012 tags)
10013 (t (error "Tags alignment failed")))
10014 (org-move-to-column col)
10015 (unless just-align
10016 (run-hooks 'org-after-tags-change-hook)))))
10018 (defun org-change-tag-in-region (beg end tag off)
10019 "Add or remove TAG for each entry in the region.
10020 This works in the agenda, and also in an org-mode buffer."
10021 (interactive
10022 (list (region-beginning) (region-end)
10023 (let ((org-last-tags-completion-table
10024 (if (org-mode-p)
10025 (org-get-buffer-tags)
10026 (org-global-tags-completion-table))))
10027 (org-ido-completing-read
10028 "Tag: " 'org-tags-completion-function nil nil nil
10029 'org-tags-history))
10030 (progn
10031 (message "[s]et or [r]emove? ")
10032 (equal (read-char-exclusive) ?r))))
10033 (if (fboundp 'deactivate-mark) (deactivate-mark))
10034 (let ((agendap (equal major-mode 'org-agenda-mode))
10035 l1 l2 m buf pos newhead (cnt 0))
10036 (goto-char end)
10037 (setq l2 (1- (org-current-line)))
10038 (goto-char beg)
10039 (setq l1 (org-current-line))
10040 (loop for l from l1 to l2 do
10041 (goto-line l)
10042 (setq m (get-text-property (point) 'org-hd-marker))
10043 (when (or (and (org-mode-p) (org-on-heading-p))
10044 (and agendap m))
10045 (setq buf (if agendap (marker-buffer m) (current-buffer))
10046 pos (if agendap m (point)))
10047 (with-current-buffer buf
10048 (save-excursion
10049 (save-restriction
10050 (goto-char pos)
10051 (setq cnt (1+ cnt))
10052 (org-toggle-tag tag (if off 'off 'on))
10053 (setq newhead (org-get-heading)))))
10054 (and agendap (org-agenda-change-all-lines newhead m))))
10055 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10057 (defun org-tags-completion-function (string predicate &optional flag)
10058 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10059 (confirm (lambda (x) (stringp (car x)))))
10060 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10061 (setq s1 (match-string 1 string)
10062 s2 (match-string 2 string))
10063 (setq s1 "" s2 string))
10064 (cond
10065 ((eq flag nil)
10066 ;; try completion
10067 (setq rtn (try-completion s2 ctable confirm))
10068 (if (stringp rtn)
10069 (setq rtn
10070 (concat s1 s2 (substring rtn (length s2))
10071 (if (and org-add-colon-after-tag-completion
10072 (assoc rtn ctable))
10073 ":" ""))))
10074 rtn)
10075 ((eq flag t)
10076 ;; all-completions
10077 (all-completions s2 ctable confirm)
10079 ((eq flag 'lambda)
10080 ;; exact match?
10081 (assoc s2 ctable)))
10084 (defun org-fast-tag-insert (kwd tags face &optional end)
10085 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10086 (insert (format "%-12s" (concat kwd ":"))
10087 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10088 (or end "")))
10090 (defun org-fast-tag-show-exit (flag)
10091 (save-excursion
10092 (goto-line 3)
10093 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10094 (replace-match ""))
10095 (when flag
10096 (end-of-line 1)
10097 (org-move-to-column (- (window-width) 19) t)
10098 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10100 (defun org-set-current-tags-overlay (current prefix)
10101 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10102 (if (featurep 'xemacs)
10103 (org-overlay-display org-tags-overlay (concat prefix s)
10104 'secondary-selection)
10105 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10106 (org-overlay-display org-tags-overlay (concat prefix s)))))
10108 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10109 "Fast tag selection with single keys.
10110 CURRENT is the current list of tags in the headline, INHERITED is the
10111 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10112 possibly with grouping information. TODO-TABLE is a similar table with
10113 TODO keywords, should these have keys assigned to them.
10114 If the keys are nil, a-z are automatically assigned.
10115 Returns the new tags string, or nil to not change the current settings."
10116 (let* ((fulltable (append table todo-table))
10117 (maxlen (apply 'max (mapcar
10118 (lambda (x)
10119 (if (stringp (car x)) (string-width (car x)) 0))
10120 fulltable)))
10121 (buf (current-buffer))
10122 (expert (eq org-fast-tag-selection-single-key 'expert))
10123 (buffer-tags nil)
10124 (fwidth (+ maxlen 3 1 3))
10125 (ncol (/ (- (window-width) 4) fwidth))
10126 (i-face 'org-done)
10127 (c-face 'org-todo)
10128 tg cnt e c char c1 c2 ntable tbl rtn
10129 ov-start ov-end ov-prefix
10130 (exit-after-next org-fast-tag-selection-single-key)
10131 (done-keywords org-done-keywords)
10132 groups ingroup)
10133 (save-excursion
10134 (beginning-of-line 1)
10135 (if (looking-at
10136 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10137 (setq ov-start (match-beginning 1)
10138 ov-end (match-end 1)
10139 ov-prefix "")
10140 (setq ov-start (1- (point-at-eol))
10141 ov-end (1+ ov-start))
10142 (skip-chars-forward "^\n\r")
10143 (setq ov-prefix
10144 (concat
10145 (buffer-substring (1- (point)) (point))
10146 (if (> (current-column) org-tags-column)
10148 (make-string (- org-tags-column (current-column)) ?\ ))))))
10149 (org-move-overlay org-tags-overlay ov-start ov-end)
10150 (save-window-excursion
10151 (if expert
10152 (set-buffer (get-buffer-create " *Org tags*"))
10153 (delete-other-windows)
10154 (split-window-vertically)
10155 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10156 (erase-buffer)
10157 (org-set-local 'org-done-keywords done-keywords)
10158 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10159 (org-fast-tag-insert "Current" current c-face "\n\n")
10160 (org-fast-tag-show-exit exit-after-next)
10161 (org-set-current-tags-overlay current ov-prefix)
10162 (setq tbl fulltable char ?a cnt 0)
10163 (while (setq e (pop tbl))
10164 (cond
10165 ((equal e '(:startgroup))
10166 (push '() groups) (setq ingroup t)
10167 (when (not (= cnt 0))
10168 (setq cnt 0)
10169 (insert "\n"))
10170 (insert "{ "))
10171 ((equal e '(:endgroup))
10172 (setq ingroup nil cnt 0)
10173 (insert "}\n"))
10175 (setq tg (car e) c2 nil)
10176 (if (cdr e)
10177 (setq c (cdr e))
10178 ;; automatically assign a character.
10179 (setq c1 (string-to-char
10180 (downcase (substring
10181 tg (if (= (string-to-char tg) ?@) 1 0)))))
10182 (if (or (rassoc c1 ntable) (rassoc c1 table))
10183 (while (or (rassoc char ntable) (rassoc char table))
10184 (setq char (1+ char)))
10185 (setq c2 c1))
10186 (setq c (or c2 char)))
10187 (if ingroup (push tg (car groups)))
10188 (setq tg (org-add-props tg nil 'face
10189 (cond
10190 ((not (assoc tg table))
10191 (org-get-todo-face tg))
10192 ((member tg current) c-face)
10193 ((member tg inherited) i-face)
10194 (t nil))))
10195 (if (and (= cnt 0) (not ingroup)) (insert " "))
10196 (insert "[" c "] " tg (make-string
10197 (- fwidth 4 (length tg)) ?\ ))
10198 (push (cons tg c) ntable)
10199 (when (= (setq cnt (1+ cnt)) ncol)
10200 (insert "\n")
10201 (if ingroup (insert " "))
10202 (setq cnt 0)))))
10203 (setq ntable (nreverse ntable))
10204 (insert "\n")
10205 (goto-char (point-min))
10206 (if (not expert) (org-fit-window-to-buffer))
10207 (setq rtn
10208 (catch 'exit
10209 (while t
10210 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10211 (if groups " [!] no groups" " [!]groups")
10212 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10213 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10214 (cond
10215 ((= c ?\r) (throw 'exit t))
10216 ((= c ?!)
10217 (setq groups (not groups))
10218 (goto-char (point-min))
10219 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10220 ((= c ?\C-c)
10221 (if (not expert)
10222 (org-fast-tag-show-exit
10223 (setq exit-after-next (not exit-after-next)))
10224 (setq expert nil)
10225 (delete-other-windows)
10226 (split-window-vertically)
10227 (org-switch-to-buffer-other-window " *Org tags*")
10228 (org-fit-window-to-buffer)))
10229 ((or (= c ?\C-g)
10230 (and (= c ?q) (not (rassoc c ntable))))
10231 (org-detach-overlay org-tags-overlay)
10232 (setq quit-flag t))
10233 ((= c ?\ )
10234 (setq current nil)
10235 (if exit-after-next (setq exit-after-next 'now)))
10236 ((= c ?\t)
10237 (condition-case nil
10238 (setq tg (org-ido-completing-read
10239 "Tag: "
10240 (or buffer-tags
10241 (with-current-buffer buf
10242 (org-get-buffer-tags)))))
10243 (quit (setq tg "")))
10244 (when (string-match "\\S-" tg)
10245 (add-to-list 'buffer-tags (list tg))
10246 (if (member tg current)
10247 (setq current (delete tg current))
10248 (push tg current)))
10249 (if exit-after-next (setq exit-after-next 'now)))
10250 ((setq e (rassoc c todo-table) tg (car e))
10251 (with-current-buffer buf
10252 (save-excursion (org-todo tg)))
10253 (if exit-after-next (setq exit-after-next 'now)))
10254 ((setq e (rassoc c ntable) tg (car e))
10255 (if (member tg current)
10256 (setq current (delete tg current))
10257 (loop for g in groups do
10258 (if (member tg g)
10259 (mapc (lambda (x)
10260 (setq current (delete x current)))
10261 g)))
10262 (push tg current))
10263 (if exit-after-next (setq exit-after-next 'now))))
10265 ;; Create a sorted list
10266 (setq current
10267 (sort current
10268 (lambda (a b)
10269 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10270 (if (eq exit-after-next 'now) (throw 'exit t))
10271 (goto-char (point-min))
10272 (beginning-of-line 2)
10273 (delete-region (point) (point-at-eol))
10274 (org-fast-tag-insert "Current" current c-face)
10275 (org-set-current-tags-overlay current ov-prefix)
10276 (while (re-search-forward
10277 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10278 (setq tg (match-string 1))
10279 (add-text-properties
10280 (match-beginning 1) (match-end 1)
10281 (list 'face
10282 (cond
10283 ((member tg current) c-face)
10284 ((member tg inherited) i-face)
10285 (t (get-text-property (match-beginning 1) 'face))))))
10286 (goto-char (point-min)))))
10287 (org-detach-overlay org-tags-overlay)
10288 (if rtn
10289 (mapconcat 'identity current ":")
10290 nil))))
10292 (defun org-get-tags-string ()
10293 "Get the TAGS string in the current headline."
10294 (unless (org-on-heading-p t)
10295 (error "Not on a heading"))
10296 (save-excursion
10297 (beginning-of-line 1)
10298 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10299 (org-match-string-no-properties 1)
10300 "")))
10302 (defun org-get-tags ()
10303 "Get the list of tags specified in the current headline."
10304 (org-split-string (org-get-tags-string) ":"))
10306 (defun org-get-buffer-tags ()
10307 "Get a table of all tags used in the buffer, for completion."
10308 (let (tags)
10309 (save-excursion
10310 (goto-char (point-min))
10311 (while (re-search-forward
10312 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10313 (when (equal (char-after (point-at-bol 0)) ?*)
10314 (mapc (lambda (x) (add-to-list 'tags x))
10315 (org-split-string (org-match-string-no-properties 1) ":")))))
10316 (mapcar 'list tags)))
10318 ;;;; The mapping API
10320 ;;;###autoload
10321 (defun org-map-entries (func &optional match scope &rest skip)
10322 "Call FUNC at each headline selected by MATCH in SCOPE.
10324 FUNC is a function or a lisp form. The function will be called without
10325 arguments, with the cursor positioned at the beginning of the headline.
10326 The return values of all calls to the function will be collected and
10327 returned as a list.
10329 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10330 Only headlines that are matched by this query will be considered during
10331 the iteration. When MATCH is nil or t, all headlines will be
10332 visited by the iteration.
10334 SCOPE determines the scope of this command. It can be any of:
10336 nil The current buffer, respecting the restriction if any
10337 tree The subtree started with the entry at point
10338 file The current buffer, without restriction
10339 file-with-archives
10340 The current buffer, and any archives associated with it
10341 agenda All agenda files
10342 agenda-with-archives
10343 All agenda files with any archive files associated with them
10344 \(file1 file2 ...)
10345 If this is a list, all files in the list will be scanned
10347 The remaining args are treated as settings for the skipping facilities of
10348 the scanner. The following items can be given here:
10350 archive skip trees with the archive tag.
10351 comment skip trees with the COMMENT keyword
10352 function or Emacs Lisp form:
10353 will be used as value for `org-agenda-skip-function', so whenever
10354 the the function returns t, FUNC will not be called for that
10355 entry and search will continue from the point where the
10356 function leaves it."
10357 (let* ((org-agenda-archives-mode nil) ; just to make sure
10358 (org-agenda-skip-archived-trees (memq 'archive skip))
10359 (org-agenda-skip-comment-trees (memq 'comment skip))
10360 (org-agenda-skip-function
10361 (car (org-delete-all '(comment archive) skip)))
10362 (org-tags-match-list-sublevels t)
10363 matcher file res
10364 org-todo-keywords-for-agenda
10365 org-done-keywords-for-agenda
10366 org-todo-keyword-alist-for-agenda
10367 org-tag-alist-for-agenda)
10369 (cond
10370 ((eq match t) (setq matcher t))
10371 ((eq match nil) (setq matcher t))
10372 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10374 (save-excursion
10375 (save-restriction
10376 (when (eq scope 'tree)
10377 (org-back-to-heading t)
10378 (org-narrow-to-subtree)
10379 (setq scope nil))
10381 (if (not scope)
10382 (progn
10383 (org-prepare-agenda-buffers
10384 (list (buffer-file-name (current-buffer))))
10385 (setq res (org-scan-tags func matcher)))
10386 ;; Get the right scope
10387 (cond
10388 ((and scope (listp scope) (symbolp (car scope)))
10389 (setq scope (eval scope)))
10390 ((eq scope 'agenda)
10391 (setq scope (org-agenda-files t)))
10392 ((eq scope 'agenda-with-archives)
10393 (setq scope (org-agenda-files t))
10394 (setq scope (org-add-archive-files scope)))
10395 ((eq scope 'file)
10396 (setq scope (list (buffer-file-name))))
10397 ((eq scope 'file-with-archives)
10398 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10399 (org-prepare-agenda-buffers scope)
10400 (while (setq file (pop scope))
10401 (with-current-buffer (org-find-base-buffer-visiting file)
10402 (save-excursion
10403 (save-restriction
10404 (widen)
10405 (goto-char (point-min))
10406 (setq res (append res (org-scan-tags func matcher))))))))))
10407 res))
10409 ;;;; Properties
10411 ;;; Setting and retrieving properties
10413 (defconst org-special-properties
10414 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10415 "TIMESTAMP" "TIMESTAMP_IA")
10416 "The special properties valid in Org-mode.
10418 These are properties that are not defined in the property drawer,
10419 but in some other way.")
10421 (defconst org-default-properties
10422 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10423 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10424 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10425 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10426 "Some properties that are used by Org-mode for various purposes.
10427 Being in this list makes sure that they are offered for completion.")
10429 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10430 "Regular expression matching the first line of a property drawer.")
10432 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10433 "Regular expression matching the first line of a property drawer.")
10435 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10436 "Regular expression matching the first line of a property drawer.")
10438 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10439 "Regular expression matching the first line of a property drawer.")
10441 (defconst org-property-drawer-re
10442 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10443 org-property-end-re "\\)\n?")
10444 "Matches an entire property drawer.")
10446 (defconst org-clock-drawer-re
10447 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10448 org-property-end-re "\\)\n?")
10449 "Matches an entire clock drawer.")
10451 (defun org-property-action ()
10452 "Do an action on properties."
10453 (interactive)
10454 (let (c)
10455 (org-at-property-p)
10456 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10457 (setq c (read-char-exclusive))
10458 (cond
10459 ((equal c ?s)
10460 (call-interactively 'org-set-property))
10461 ((equal c ?d)
10462 (call-interactively 'org-delete-property))
10463 ((equal c ?D)
10464 (call-interactively 'org-delete-property-globally))
10465 ((equal c ?c)
10466 (call-interactively 'org-compute-property-at-point))
10467 (t (error "No such property action %c" c)))))
10469 (defun org-at-property-p ()
10470 "Is the cursor in a property line?"
10471 ;; FIXME: Does not check if we are actually in the drawer.
10472 ;; FIXME: also returns true on any drawers.....
10473 ;; This is used by C-c C-c for property action.
10474 (save-excursion
10475 (beginning-of-line 1)
10476 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10478 (defun org-get-property-block (&optional beg end force)
10479 "Return the (beg . end) range of the body of the property drawer.
10480 BEG and END can be beginning and end of subtree, if not given
10481 they will be found.
10482 If the drawer does not exist and FORCE is non-nil, create the drawer."
10483 (catch 'exit
10484 (save-excursion
10485 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10486 (end (or end (progn (outline-next-heading) (point)))))
10487 (goto-char beg)
10488 (if (re-search-forward org-property-start-re end t)
10489 (setq beg (1+ (match-end 0)))
10490 (if force
10491 (save-excursion
10492 (org-insert-property-drawer)
10493 (setq end (progn (outline-next-heading) (point))))
10494 (throw 'exit nil))
10495 (goto-char beg)
10496 (if (re-search-forward org-property-start-re end t)
10497 (setq beg (1+ (match-end 0)))))
10498 (if (re-search-forward org-property-end-re end t)
10499 (setq end (match-beginning 0))
10500 (or force (throw 'exit nil))
10501 (goto-char beg)
10502 (setq end beg)
10503 (org-indent-line-function)
10504 (insert ":END:\n"))
10505 (cons beg end)))))
10507 (defun org-entry-properties (&optional pom which)
10508 "Get all properties of the entry at point-or-marker POM.
10509 This includes the TODO keyword, the tags, time strings for deadline,
10510 scheduled, and clocking, and any additional properties defined in the
10511 entry. The return value is an alist, keys may occur multiple times
10512 if the property key was used several times.
10513 POM may also be nil, in which case the current entry is used.
10514 If WHICH is nil or `all', get all properties. If WHICH is
10515 `special' or `standard', only get that subclass."
10516 (setq which (or which 'all))
10517 (org-with-point-at pom
10518 (let ((clockstr (substring org-clock-string 0 -1))
10519 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10520 beg end range props sum-props key value string clocksum)
10521 (save-excursion
10522 (when (condition-case nil
10523 (and (org-mode-p) (org-back-to-heading t))
10524 (error nil))
10525 (setq beg (point))
10526 (setq sum-props (get-text-property (point) 'org-summaries))
10527 (setq clocksum (get-text-property (point) :org-clock-minutes))
10528 (outline-next-heading)
10529 (setq end (point))
10530 (when (memq which '(all special))
10531 ;; Get the special properties, like TODO and tags
10532 (goto-char beg)
10533 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10534 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10535 (when (looking-at org-priority-regexp)
10536 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10537 (when (and (setq value (org-get-tags-string))
10538 (string-match "\\S-" value))
10539 (push (cons "TAGS" value) props))
10540 (when (setq value (org-get-tags-at))
10541 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10542 props))
10543 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10544 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10545 string (if (equal key clockstr)
10546 (org-no-properties
10547 (org-trim
10548 (buffer-substring
10549 (match-beginning 3) (goto-char (point-at-eol)))))
10550 (substring (org-match-string-no-properties 3) 1 -1)))
10551 (unless key
10552 (if (= (char-after (match-beginning 3)) ?\[)
10553 (setq key "TIMESTAMP_IA")
10554 (setq key "TIMESTAMP")))
10555 (when (or (equal key clockstr) (not (assoc key props)))
10556 (push (cons key string) props)))
10560 (when (memq which '(all standard))
10561 ;; Get the standard properties, like :PORP: ...
10562 (setq range (org-get-property-block beg end))
10563 (when range
10564 (goto-char (car range))
10565 (while (re-search-forward
10566 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10567 (cdr range) t)
10568 (setq key (org-match-string-no-properties 1)
10569 value (org-trim (or (org-match-string-no-properties 2) "")))
10570 (unless (member key excluded)
10571 (push (cons key (or value "")) props)))))
10572 (if clocksum
10573 (push (cons "CLOCKSUM"
10574 (org-columns-number-to-string (/ (float clocksum) 60.)
10575 'add_times))
10576 props))
10577 (unless (assoc "CATEGORY" props)
10578 (setq value (or (org-get-category)
10579 (progn (org-refresh-category-properties)
10580 (org-get-category))))
10581 (push (cons "CATEGORY" value) props))
10582 (append sum-props (nreverse props)))))))
10584 (defun org-entry-get (pom property &optional inherit)
10585 "Get value of PROPERTY for entry at point-or-marker POM.
10586 If INHERIT is non-nil and the entry does not have the property,
10587 then also check higher levels of the hierarchy.
10588 If INHERIT is the symbol `selective', use inheritance only if the setting
10589 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10590 If the property is present but empty, the return value is the empty string.
10591 If the property is not present at all, nil is returned."
10592 (org-with-point-at pom
10593 (if (and inherit (if (eq inherit 'selective)
10594 (org-property-inherit-p property)
10596 (org-entry-get-with-inheritance property)
10597 (if (member property org-special-properties)
10598 ;; We need a special property. Use brute force, get all properties.
10599 (cdr (assoc property (org-entry-properties nil 'special)))
10600 (let ((range (org-get-property-block)))
10601 (if (and range
10602 (goto-char (car range))
10603 (re-search-forward
10604 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10605 (cdr range) t))
10606 ;; Found the property, return it.
10607 (if (match-end 1)
10608 (org-match-string-no-properties 1)
10609 "")))))))
10611 (defun org-property-or-variable-value (var &optional inherit)
10612 "Check if there is a property fixing the value of VAR.
10613 If yes, return this value. If not, return the current value of the variable."
10614 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10615 (if (and prop (stringp prop) (string-match "\\S-" prop))
10616 (read prop)
10617 (symbol-value var))))
10619 (defun org-entry-delete (pom property)
10620 "Delete the property PROPERTY from entry at point-or-marker POM."
10621 (org-with-point-at pom
10622 (if (member property org-special-properties)
10623 nil ; cannot delete these properties.
10624 (let ((range (org-get-property-block)))
10625 (if (and range
10626 (goto-char (car range))
10627 (re-search-forward
10628 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10629 (cdr range) t))
10630 (progn
10631 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10633 nil)))))
10635 ;; Multi-values properties are properties that contain multiple values
10636 ;; These values are assumed to be single words, separated by whitespace.
10637 (defun org-entry-add-to-multivalued-property (pom property value)
10638 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10639 (let* ((old (org-entry-get pom property))
10640 (values (and old (org-split-string old "[ \t]"))))
10641 (setq value (org-entry-protect-space value))
10642 (unless (member value values)
10643 (setq values (cons value values))
10644 (org-entry-put pom property
10645 (mapconcat 'identity values " ")))))
10647 (defun org-entry-remove-from-multivalued-property (pom property value)
10648 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10649 (let* ((old (org-entry-get pom property))
10650 (values (and old (org-split-string old "[ \t]"))))
10651 (setq value (org-entry-protect-space value))
10652 (when (member value values)
10653 (setq values (delete value values))
10654 (org-entry-put pom property
10655 (mapconcat 'identity values " ")))))
10657 (defun org-entry-member-in-multivalued-property (pom property value)
10658 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10659 (let* ((old (org-entry-get pom property))
10660 (values (and old (org-split-string old "[ \t]"))))
10661 (setq value (org-entry-protect-space value))
10662 (member value values)))
10664 (defun org-entry-get-multivalued-property (pom property)
10665 "Return a list of values in a multivalued property."
10666 (let* ((value (org-entry-get pom property))
10667 (values (and value (org-split-string value "[ \t]"))))
10668 (mapcar 'org-entry-restore-space values)))
10670 (defun org-entry-put-multivalued-property (pom property &rest values)
10671 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10672 VALUES should be a list of strings. Spaces will be protected."
10673 (org-entry-put pom property
10674 (mapconcat 'org-entry-protect-space values " "))
10675 (let* ((value (org-entry-get pom property))
10676 (values (and value (org-split-string value "[ \t]"))))
10677 (mapcar 'org-entry-restore-space values)))
10679 (defun org-entry-protect-space (s)
10680 "Protect spaces and newline in string S."
10681 (while (string-match " " s)
10682 (setq s (replace-match "%20" t t s)))
10683 (while (string-match "\n" s)
10684 (setq s (replace-match "%0A" t t s)))
10687 (defun org-entry-restore-space (s)
10688 "Restore spaces and newline in string S."
10689 (while (string-match "%20" s)
10690 (setq s (replace-match " " t t s)))
10691 (while (string-match "%0A" s)
10692 (setq s (replace-match "\n" t t s)))
10695 (defvar org-entry-property-inherited-from (make-marker)
10696 "Marker pointing to the entry from where a property was inherited.
10697 Each call to `org-entry-get-with-inheritance' will set this marker to the
10698 location of the entry where the inheritance search matched. If there was
10699 no match, the marker will point nowhere.
10700 Note that also `org-entry-get' calls this function, if the INHERIT flag
10701 is set.")
10703 (defun org-entry-get-with-inheritance (property)
10704 "Get entry property, and search higher levels if not present."
10705 (move-marker org-entry-property-inherited-from nil)
10706 (let (tmp)
10707 (save-excursion
10708 (save-restriction
10709 (widen)
10710 (catch 'ex
10711 (while t
10712 (when (setq tmp (org-entry-get nil property))
10713 (org-back-to-heading t)
10714 (move-marker org-entry-property-inherited-from (point))
10715 (throw 'ex tmp))
10716 (or (org-up-heading-safe) (throw 'ex nil)))))
10717 (or tmp
10718 (cdr (assoc property org-file-properties))
10719 (cdr (assoc property org-global-properties))
10720 (cdr (assoc property org-global-properties-fixed))))))
10722 (defun org-entry-put (pom property value)
10723 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10724 (org-with-point-at pom
10725 (org-back-to-heading t)
10726 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10727 range)
10728 (cond
10729 ((equal property "TODO")
10730 (when (and (stringp value) (string-match "\\S-" value)
10731 (not (member value org-todo-keywords-1)))
10732 (error "\"%s\" is not a valid TODO state" value))
10733 (if (or (not value)
10734 (not (string-match "\\S-" value)))
10735 (setq value 'none))
10736 (org-todo value)
10737 (org-set-tags nil 'align))
10738 ((equal property "PRIORITY")
10739 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10740 (string-to-char value) ?\ ))
10741 (org-set-tags nil 'align))
10742 ((equal property "SCHEDULED")
10743 (if (re-search-forward org-scheduled-time-regexp end t)
10744 (cond
10745 ((eq value 'earlier) (org-timestamp-change -1 'day))
10746 ((eq value 'later) (org-timestamp-change 1 'day))
10747 (t (call-interactively 'org-schedule)))
10748 (call-interactively 'org-schedule)))
10749 ((equal property "DEADLINE")
10750 (if (re-search-forward org-deadline-time-regexp end t)
10751 (cond
10752 ((eq value 'earlier) (org-timestamp-change -1 'day))
10753 ((eq value 'later) (org-timestamp-change 1 'day))
10754 (t (call-interactively 'org-deadline)))
10755 (call-interactively 'org-deadline)))
10756 ((member property org-special-properties)
10757 (error "The %s property can not yet be set with `org-entry-put'"
10758 property))
10759 (t ; a non-special property
10760 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10761 (setq range (org-get-property-block beg end 'force))
10762 (goto-char (car range))
10763 (if (re-search-forward
10764 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10765 (progn
10766 (delete-region (match-beginning 1) (match-end 1))
10767 (goto-char (match-beginning 1)))
10768 (goto-char (cdr range))
10769 (insert "\n")
10770 (backward-char 1)
10771 (org-indent-line-function)
10772 (insert ":" property ":"))
10773 (and value (insert " " value))
10774 (org-indent-line-function)))))))
10776 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10777 "Get all property keys in the current buffer.
10778 With INCLUDE-SPECIALS, also list the special properties that reflect things
10779 like tags and TODO state.
10780 With INCLUDE-DEFAULTS, also include properties that has special meaning
10781 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10782 With INCLUDE-COLUMNS, also include property names given in COLUMN
10783 formats in the current buffer."
10784 (let (rtn range cfmt s p)
10785 (save-excursion
10786 (save-restriction
10787 (widen)
10788 (goto-char (point-min))
10789 (while (re-search-forward org-property-start-re nil t)
10790 (setq range (org-get-property-block))
10791 (goto-char (car range))
10792 (while (re-search-forward
10793 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10794 (cdr range) t)
10795 (add-to-list 'rtn (org-match-string-no-properties 1)))
10796 (outline-next-heading))))
10798 (when include-specials
10799 (setq rtn (append org-special-properties rtn)))
10801 (when include-defaults
10802 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10804 (when include-columns
10805 (save-excursion
10806 (save-restriction
10807 (widen)
10808 (goto-char (point-min))
10809 (while (re-search-forward
10810 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10811 nil t)
10812 (setq cfmt (match-string 2) s 0)
10813 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10814 cfmt s)
10815 (setq s (match-end 0)
10816 p (match-string 1 cfmt))
10817 (unless (or (equal p "ITEM")
10818 (member p org-special-properties))
10819 (add-to-list 'rtn (match-string 1 cfmt))))))))
10821 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10823 (defun org-property-values (key)
10824 "Return a list of all values of property KEY."
10825 (save-excursion
10826 (save-restriction
10827 (widen)
10828 (goto-char (point-min))
10829 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10830 values)
10831 (while (re-search-forward re nil t)
10832 (add-to-list 'values (org-trim (match-string 1))))
10833 (delete "" values)))))
10835 (defun org-insert-property-drawer ()
10836 "Insert a property drawer into the current entry."
10837 (interactive)
10838 (org-back-to-heading t)
10839 (looking-at outline-regexp)
10840 (let ((indent (- (match-end 0)(match-beginning 0)))
10841 (beg (point))
10842 (re (concat "^[ \t]*" org-keyword-time-regexp))
10843 end hiddenp)
10844 (outline-next-heading)
10845 (setq end (point))
10846 (goto-char beg)
10847 (while (re-search-forward re end t))
10848 (setq hiddenp (org-invisible-p))
10849 (end-of-line 1)
10850 (and (equal (char-after) ?\n) (forward-char 1))
10851 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10852 (beginning-of-line 2))
10853 (org-skip-over-state-notes)
10854 (skip-chars-backward " \t\n\r")
10855 (if (eq (char-before) ?*) (forward-char 1))
10856 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10857 (beginning-of-line 0)
10858 (org-indent-to-column indent)
10859 (beginning-of-line 2)
10860 (org-indent-to-column indent)
10861 (beginning-of-line 0)
10862 (if hiddenp
10863 (save-excursion
10864 (org-back-to-heading t)
10865 (hide-entry))
10866 (org-flag-drawer t))))
10868 (defun org-set-property (property value)
10869 "In the current entry, set PROPERTY to VALUE.
10870 When called interactively, this will prompt for a property name, offering
10871 completion on existing and default properties. And then it will prompt
10872 for a value, offering completion either on allowed values (via an inherited
10873 xxx_ALL property) or on existing values in other instances of this property
10874 in the current file."
10875 (interactive
10876 (let* ((completion-ignore-case t)
10877 (keys (org-buffer-property-keys nil t t))
10878 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10879 (prop (if (member prop0 keys)
10880 prop0
10881 (or (cdr (assoc (downcase prop0)
10882 (mapcar (lambda (x) (cons (downcase x) x))
10883 keys)))
10884 prop0)))
10885 (cur (org-entry-get nil prop))
10886 (allowed (org-property-get-allowed-values nil prop 'table))
10887 (existing (mapcar 'list (org-property-values prop)))
10888 (val (if allowed
10889 (org-completing-read "Value: " allowed nil 'req-match)
10890 (org-completing-read
10891 (concat "Value" (if (and cur (string-match "\\S-" cur))
10892 (concat "[" cur "]") "")
10893 ": ")
10894 existing nil nil "" nil cur))))
10895 (list prop (if (equal val "") cur val))))
10896 (unless (equal (org-entry-get nil property) value)
10897 (org-entry-put nil property value)))
10899 (defun org-delete-property (property)
10900 "In the current entry, delete PROPERTY."
10901 (interactive
10902 (let* ((completion-ignore-case t)
10903 (prop (org-ido-completing-read
10904 "Property: " (org-entry-properties nil 'standard))))
10905 (list prop)))
10906 (message "Property %s %s" property
10907 (if (org-entry-delete nil property)
10908 "deleted"
10909 "was not present in the entry")))
10911 (defun org-delete-property-globally (property)
10912 "Remove PROPERTY globally, from all entries."
10913 (interactive
10914 (let* ((completion-ignore-case t)
10915 (prop (org-ido-completing-read
10916 "Globally remove property: "
10917 (mapcar 'list (org-buffer-property-keys)))))
10918 (list prop)))
10919 (save-excursion
10920 (save-restriction
10921 (widen)
10922 (goto-char (point-min))
10923 (let ((cnt 0))
10924 (while (re-search-forward
10925 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10926 nil t)
10927 (setq cnt (1+ cnt))
10928 (replace-match ""))
10929 (message "Property \"%s\" removed from %d entries" property cnt)))))
10931 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10933 (defun org-compute-property-at-point ()
10934 "Compute the property at point.
10935 This looks for an enclosing column format, extracts the operator and
10936 then applies it to the property in the column format's scope."
10937 (interactive)
10938 (unless (org-at-property-p)
10939 (error "Not at a property"))
10940 (let ((prop (org-match-string-no-properties 2)))
10941 (org-columns-get-format-and-top-level)
10942 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10943 (error "No operator defined for property %s" prop))
10944 (org-columns-compute prop)))
10946 (defun org-property-get-allowed-values (pom property &optional table)
10947 "Get allowed values for the property PROPERTY.
10948 When TABLE is non-nil, return an alist that can directly be used for
10949 completion."
10950 (let (vals)
10951 (cond
10952 ((equal property "TODO")
10953 (setq vals (org-with-point-at pom
10954 (append org-todo-keywords-1 '("")))))
10955 ((equal property "PRIORITY")
10956 (let ((n org-lowest-priority))
10957 (while (>= n org-highest-priority)
10958 (push (char-to-string n) vals)
10959 (setq n (1- n)))))
10960 ((member property org-special-properties))
10962 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10964 (when (and vals (string-match "\\S-" vals))
10965 (setq vals (car (read-from-string (concat "(" vals ")"))))
10966 (setq vals (mapcar (lambda (x)
10967 (cond ((stringp x) x)
10968 ((numberp x) (number-to-string x))
10969 ((symbolp x) (symbol-name x))
10970 (t "???")))
10971 vals)))))
10972 (if table (mapcar 'list vals) vals)))
10974 (defun org-property-previous-allowed-value (&optional previous)
10975 "Switch to the next allowed value for this property."
10976 (interactive)
10977 (org-property-next-allowed-value t))
10979 (defun org-property-next-allowed-value (&optional previous)
10980 "Switch to the next allowed value for this property."
10981 (interactive)
10982 (unless (org-at-property-p)
10983 (error "Not at a property"))
10984 (let* ((key (match-string 2))
10985 (value (match-string 3))
10986 (allowed (or (org-property-get-allowed-values (point) key)
10987 (and (member value '("[ ]" "[-]" "[X]"))
10988 '("[ ]" "[X]"))))
10989 nval)
10990 (unless allowed
10991 (error "Allowed values for this property have not been defined"))
10992 (if previous (setq allowed (reverse allowed)))
10993 (if (member value allowed)
10994 (setq nval (car (cdr (member value allowed)))))
10995 (setq nval (or nval (car allowed)))
10996 (if (equal nval value)
10997 (error "Only one allowed value for this property"))
10998 (org-at-property-p)
10999 (replace-match (concat " :" key ": " nval) t t)
11000 (org-indent-line-function)
11001 (beginning-of-line 1)
11002 (skip-chars-forward " \t")))
11004 (defun org-find-entry-with-id (ident)
11005 "Locate the entry that contains the ID property with exact value IDENT.
11006 IDENT can be a string, a symbol or a number, this function will search for
11007 the string representation of it.
11008 Return the position where this entry starts, or nil if there is no such entry."
11009 (interactive "sID: ")
11010 (let ((id (cond
11011 ((stringp ident) ident)
11012 ((symbol-name ident) (symbol-name ident))
11013 ((numberp ident) (number-to-string ident))
11014 (t (error "IDENT %s must be a string, symbol or number" ident))))
11015 (case-fold-search nil))
11016 (save-excursion
11017 (save-restriction
11018 (widen)
11019 (goto-char (point-min))
11020 (when (re-search-forward
11021 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11022 nil t)
11023 (org-back-to-heading)
11024 (point))))))
11026 ;;;; Timestamps
11028 (defvar org-last-changed-timestamp nil)
11029 (defvar org-last-inserted-timestamp nil
11030 "The last time stamp inserted with `org-insert-time-stamp'.")
11031 (defvar org-time-was-given) ; dynamically scoped parameter
11032 (defvar org-end-time-was-given) ; dynamically scoped parameter
11033 (defvar org-ts-what) ; dynamically scoped parameter
11035 (defun org-time-stamp (arg &optional inactive)
11036 "Prompt for a date/time and insert a time stamp.
11037 If the user specifies a time like HH:MM, or if this command is called
11038 with a prefix argument, the time stamp will contain date and time.
11039 Otherwise, only the date will be included. All parts of a date not
11040 specified by the user will be filled in from the current date/time.
11041 So if you press just return without typing anything, the time stamp
11042 will represent the current date/time. If there is already a timestamp
11043 at the cursor, it will be modified."
11044 (interactive "P")
11045 (let* ((ts nil)
11046 (default-time
11047 ;; Default time is either today, or, when entering a range,
11048 ;; the range start.
11049 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11050 (save-excursion
11051 (re-search-backward
11052 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11053 (- (point) 20) t)))
11054 (apply 'encode-time (org-parse-time-string (match-string 1)))
11055 (current-time)))
11056 (default-input (and ts (org-get-compact-tod ts)))
11057 org-time-was-given org-end-time-was-given time)
11058 (cond
11059 ((and (org-at-timestamp-p t)
11060 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11061 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11062 (insert "--")
11063 (setq time (let ((this-command this-command))
11064 (org-read-date arg 'totime nil nil
11065 default-time default-input)))
11066 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11067 ((org-at-timestamp-p t)
11068 (setq time (let ((this-command this-command))
11069 (org-read-date arg 'totime nil nil default-time default-input)))
11070 (when (org-at-timestamp-p t) ; just to get the match data
11071 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11072 (replace-match "")
11073 (setq org-last-changed-timestamp
11074 (org-insert-time-stamp
11075 time (or org-time-was-given arg)
11076 inactive nil nil (list org-end-time-was-given))))
11077 (message "Timestamp updated"))
11079 (setq time (let ((this-command this-command))
11080 (org-read-date arg 'totime nil nil default-time default-input)))
11081 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11082 nil nil (list org-end-time-was-given))))))
11084 ;; FIXME: can we use this for something else, like computing time differences?
11085 (defun org-get-compact-tod (s)
11086 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11087 (let* ((t1 (match-string 1 s))
11088 (h1 (string-to-number (match-string 2 s)))
11089 (m1 (string-to-number (match-string 3 s)))
11090 (t2 (and (match-end 4) (match-string 5 s)))
11091 (h2 (and t2 (string-to-number (match-string 6 s))))
11092 (m2 (and t2 (string-to-number (match-string 7 s))))
11093 dh dm)
11094 (if (not t2)
11096 (setq dh (- h2 h1) dm (- m2 m1))
11097 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11098 (concat t1 "+" (number-to-string dh)
11099 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11101 (defun org-time-stamp-inactive (&optional arg)
11102 "Insert an inactive time stamp.
11103 An inactive time stamp is enclosed in square brackets instead of angle
11104 brackets. It is inactive in the sense that it does not trigger agenda entries,
11105 does not link to the calendar and cannot be changed with the S-cursor keys.
11106 So these are more for recording a certain time/date."
11107 (interactive "P")
11108 (org-time-stamp arg 'inactive))
11110 (defvar org-date-ovl (org-make-overlay 1 1))
11111 (org-overlay-put org-date-ovl 'face 'org-warning)
11112 (org-detach-overlay org-date-ovl)
11114 (defvar org-ans1) ; dynamically scoped parameter
11115 (defvar org-ans2) ; dynamically scoped parameter
11117 (defvar org-plain-time-of-day-regexp) ; defined below
11119 (defvar org-overriding-default-time nil) ; dynamically scoped
11120 (defvar org-read-date-overlay nil)
11121 (defvar org-dcst nil) ; dynamically scoped
11123 (defun org-read-date (&optional with-time to-time from-string prompt
11124 default-time default-input)
11125 "Read a date, possibly a time, and make things smooth for the user.
11126 The prompt will suggest to enter an ISO date, but you can also enter anything
11127 which will at least partially be understood by `parse-time-string'.
11128 Unrecognized parts of the date will default to the current day, month, year,
11129 hour and minute. If this command is called to replace a timestamp at point,
11130 of to enter the second timestamp of a range, the default time is taken from the
11131 existing stamp. For example,
11132 3-2-5 --> 2003-02-05
11133 feb 15 --> currentyear-02-15
11134 sep 12 9 --> 2009-09-12
11135 12:45 --> today 12:45
11136 22 sept 0:34 --> currentyear-09-22 0:34
11137 12 --> currentyear-currentmonth-12
11138 Fri --> nearest Friday (today or later)
11139 etc.
11141 Furthermore you can specify a relative date by giving, as the *first* thing
11142 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11143 change in days weeks, months, years.
11144 With a single plus or minus, the date is relative to today. With a double
11145 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11146 +4d --> four days from today
11147 +4 --> same as above
11148 +2w --> two weeks from today
11149 ++5 --> five days from default date
11151 The function understands only English month and weekday abbreviations,
11152 but this can be configured with the variables `parse-time-months' and
11153 `parse-time-weekdays'.
11155 While prompting, a calendar is popped up - you can also select the
11156 date with the mouse (button 1). The calendar shows a period of three
11157 months. To scroll it to other months, use the keys `>' and `<'.
11158 If you don't like the calendar, turn it off with
11159 \(setq org-read-date-popup-calendar nil)
11161 With optional argument TO-TIME, the date will immediately be converted
11162 to an internal time.
11163 With an optional argument WITH-TIME, the prompt will suggest to also
11164 insert a time. Note that when WITH-TIME is not set, you can still
11165 enter a time, and this function will inform the calling routine about
11166 this change. The calling routine may then choose to change the format
11167 used to insert the time stamp into the buffer to include the time.
11168 With optional argument FROM-STRING, read from this string instead from
11169 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11170 the time/date that is used for everything that is not specified by the
11171 user."
11172 (require 'parse-time)
11173 (let* ((org-time-stamp-rounding-minutes
11174 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11175 (org-dcst org-display-custom-times)
11176 (ct (org-current-time))
11177 (def (or org-overriding-default-time default-time ct))
11178 (defdecode (decode-time def))
11179 (dummy (progn
11180 (when (< (nth 2 defdecode) org-extend-today-until)
11181 (setcar (nthcdr 2 defdecode) -1)
11182 (setcar (nthcdr 1 defdecode) 59)
11183 (setq def (apply 'encode-time defdecode)
11184 defdecode (decode-time def)))))
11185 (calendar-move-hook nil)
11186 (calendar-view-diary-initially-flag nil)
11187 (view-diary-entries-initially nil)
11188 (calendar-view-holidays-initially-flag nil)
11189 (view-calendar-holidays-initially nil)
11190 (timestr (format-time-string
11191 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11192 (prompt (concat (if prompt (concat prompt " ") "")
11193 (format "Date+time [%s]: " timestr)))
11194 ans (org-ans0 "") org-ans1 org-ans2 final)
11196 (cond
11197 (from-string (setq ans from-string))
11198 (org-read-date-popup-calendar
11199 (save-excursion
11200 (save-window-excursion
11201 (calendar)
11202 (calendar-forward-day (- (time-to-days def)
11203 (calendar-absolute-from-gregorian
11204 (calendar-current-date))))
11205 (org-eval-in-calendar nil t)
11206 (let* ((old-map (current-local-map))
11207 (map (copy-keymap calendar-mode-map))
11208 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11209 (org-defkey map (kbd "RET") 'org-calendar-select)
11210 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11211 'org-calendar-select-mouse)
11212 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11213 'org-calendar-select-mouse)
11214 (org-defkey minibuffer-local-map [(meta shift left)]
11215 (lambda () (interactive)
11216 (org-eval-in-calendar '(calendar-backward-month 1))))
11217 (org-defkey minibuffer-local-map [(meta shift right)]
11218 (lambda () (interactive)
11219 (org-eval-in-calendar '(calendar-forward-month 1))))
11220 (org-defkey minibuffer-local-map [(meta shift up)]
11221 (lambda () (interactive)
11222 (org-eval-in-calendar '(calendar-backward-year 1))))
11223 (org-defkey minibuffer-local-map [(meta shift down)]
11224 (lambda () (interactive)
11225 (org-eval-in-calendar '(calendar-forward-year 1))))
11226 (org-defkey minibuffer-local-map [(shift up)]
11227 (lambda () (interactive)
11228 (org-eval-in-calendar '(calendar-backward-week 1))))
11229 (org-defkey minibuffer-local-map [(shift down)]
11230 (lambda () (interactive)
11231 (org-eval-in-calendar '(calendar-forward-week 1))))
11232 (org-defkey minibuffer-local-map [(shift left)]
11233 (lambda () (interactive)
11234 (org-eval-in-calendar '(calendar-backward-day 1))))
11235 (org-defkey minibuffer-local-map [(shift right)]
11236 (lambda () (interactive)
11237 (org-eval-in-calendar '(calendar-forward-day 1))))
11238 (org-defkey minibuffer-local-map ">"
11239 (lambda () (interactive)
11240 (org-eval-in-calendar '(scroll-calendar-left 1))))
11241 (org-defkey minibuffer-local-map "<"
11242 (lambda () (interactive)
11243 (org-eval-in-calendar '(scroll-calendar-right 1))))
11244 (unwind-protect
11245 (progn
11246 (use-local-map map)
11247 (add-hook 'post-command-hook 'org-read-date-display)
11248 (setq org-ans0 (read-string prompt default-input nil nil))
11249 ;; org-ans0: from prompt
11250 ;; org-ans1: from mouse click
11251 ;; org-ans2: from calendar motion
11252 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11253 (remove-hook 'post-command-hook 'org-read-date-display)
11254 (use-local-map old-map)
11255 (when org-read-date-overlay
11256 (org-delete-overlay org-read-date-overlay)
11257 (setq org-read-date-overlay nil)))))))
11259 (t ; Naked prompt only
11260 (unwind-protect
11261 (setq ans (read-string prompt default-input nil timestr))
11262 (when org-read-date-overlay
11263 (org-delete-overlay org-read-date-overlay)
11264 (setq org-read-date-overlay nil)))))
11266 (setq final (org-read-date-analyze ans def defdecode))
11268 (if to-time
11269 (apply 'encode-time final)
11270 (if (and (boundp 'org-time-was-given) org-time-was-given)
11271 (format "%04d-%02d-%02d %02d:%02d"
11272 (nth 5 final) (nth 4 final) (nth 3 final)
11273 (nth 2 final) (nth 1 final))
11274 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11275 (defvar def)
11276 (defvar defdecode)
11277 (defvar with-time)
11278 (defun org-read-date-display ()
11279 "Display the current date prompt interpretation in the minibuffer."
11280 (when org-read-date-display-live
11281 (when org-read-date-overlay
11282 (org-delete-overlay org-read-date-overlay))
11283 (let ((p (point)))
11284 (end-of-line 1)
11285 (while (not (equal (buffer-substring
11286 (max (point-min) (- (point) 4)) (point))
11287 " "))
11288 (insert " "))
11289 (goto-char p))
11290 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11291 " " (or org-ans1 org-ans2)))
11292 (org-end-time-was-given nil)
11293 (f (org-read-date-analyze ans def defdecode))
11294 (fmts (if org-dcst
11295 org-time-stamp-custom-formats
11296 org-time-stamp-formats))
11297 (fmt (if (or with-time
11298 (and (boundp 'org-time-was-given) org-time-was-given))
11299 (cdr fmts)
11300 (car fmts)))
11301 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11302 (when (and org-end-time-was-given
11303 (string-match org-plain-time-of-day-regexp txt))
11304 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11305 org-end-time-was-given
11306 (substring txt (match-end 0)))))
11307 (setq org-read-date-overlay
11308 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11309 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11311 (defun org-read-date-analyze (ans def defdecode)
11312 "Analyse the combined answer of the date prompt."
11313 ;; FIXME: cleanup and comment
11314 (let (delta deltan deltaw deltadef year month day
11315 hour minute second wday pm h2 m2 tl wday1
11316 iso-year iso-weekday iso-week iso-year iso-date)
11318 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11319 (setq ans "+0"))
11321 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11322 (setq ans (replace-match "" t t ans)
11323 deltan (car delta)
11324 deltaw (nth 1 delta)
11325 deltadef (nth 2 delta)))
11327 ;; Check if there is an iso week date in there
11328 ;; If yes, sore the info and postpone interpreting it until the rest
11329 ;; of the parsing is done
11330 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11331 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11332 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11333 iso-week (string-to-number (match-string 2 ans)))
11334 (setq ans (replace-match "" t t ans)))
11336 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11337 (when (string-match
11338 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11339 (setq year (if (match-end 2)
11340 (string-to-number (match-string 2 ans))
11341 (string-to-number (format-time-string "%Y")))
11342 month (string-to-number (match-string 3 ans))
11343 day (string-to-number (match-string 4 ans)))
11344 (if (< year 100) (setq year (+ 2000 year)))
11345 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11346 t nil ans)))
11347 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11348 ;; If there is a time with am/pm, and *no* time without it, we convert
11349 ;; so that matching will be successful.
11350 (loop for i from 1 to 2 do ; twice, for end time as well
11351 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11352 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11353 (setq hour (string-to-number (match-string 1 ans))
11354 minute (if (match-end 3)
11355 (string-to-number (match-string 3 ans))
11357 pm (equal ?p
11358 (string-to-char (downcase (match-string 4 ans)))))
11359 (if (and (= hour 12) (not pm))
11360 (setq hour 0)
11361 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11362 (setq ans (replace-match (format "%02d:%02d" hour minute)
11363 t t ans))))
11365 ;; Check if a time range is given as a duration
11366 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11367 (setq hour (string-to-number (match-string 1 ans))
11368 h2 (+ hour (string-to-number (match-string 3 ans)))
11369 minute (string-to-number (match-string 2 ans))
11370 m2 (+ minute (if (match-end 5) (string-to-number
11371 (match-string 5 ans))0)))
11372 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11373 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11374 t t ans)))
11376 ;; Check if there is a time range
11377 (when (boundp 'org-end-time-was-given)
11378 (setq org-time-was-given nil)
11379 (when (and (string-match org-plain-time-of-day-regexp ans)
11380 (match-end 8))
11381 (setq org-end-time-was-given (match-string 8 ans))
11382 (setq ans (concat (substring ans 0 (match-beginning 7))
11383 (substring ans (match-end 7))))))
11385 (setq tl (parse-time-string ans)
11386 day (or (nth 3 tl) (nth 3 defdecode))
11387 month (or (nth 4 tl)
11388 (if (and org-read-date-prefer-future
11389 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11390 (1+ (nth 4 defdecode))
11391 (nth 4 defdecode)))
11392 year (or (nth 5 tl)
11393 (if (and org-read-date-prefer-future
11394 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11395 (1+ (nth 5 defdecode))
11396 (nth 5 defdecode)))
11397 hour (or (nth 2 tl) (nth 2 defdecode))
11398 minute (or (nth 1 tl) (nth 1 defdecode))
11399 second (or (nth 0 tl) 0)
11400 wday (nth 6 tl))
11402 ;; Special date definitions below
11403 (cond
11404 (iso-week
11405 ;; There was an iso week
11406 (setq year (or iso-year year)
11407 day (or iso-weekday wday 1)
11408 wday nil ; to make sure that the trigger below does not match
11409 iso-date (calendar-gregorian-from-absolute
11410 (calendar-absolute-from-iso
11411 (list iso-week day year))))
11412 ; FIXME: Should we also push ISO weeks into the future?
11413 ; (when (and org-read-date-prefer-future
11414 ; (not iso-year)
11415 ; (< (calendar-absolute-from-gregorian iso-date)
11416 ; (time-to-days (current-time))))
11417 ; (setq year (1+ year)
11418 ; iso-date (calendar-gregorian-from-absolute
11419 ; (calendar-absolute-from-iso
11420 ; (list iso-week day year)))))
11421 (setq month (car iso-date)
11422 year (nth 2 iso-date)
11423 day (nth 1 iso-date)))
11424 (deltan
11425 (unless deltadef
11426 (let ((now (decode-time (current-time))))
11427 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11428 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11429 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11430 ((equal deltaw "m") (setq month (+ month deltan)))
11431 ((equal deltaw "y") (setq year (+ year deltan)))))
11432 ((and wday (not (nth 3 tl)))
11433 ;; Weekday was given, but no day, so pick that day in the week
11434 ;; on or after the derived date.
11435 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11436 (unless (equal wday wday1)
11437 (setq day (+ day (% (- wday wday1 -7) 7))))))
11438 (if (and (boundp 'org-time-was-given)
11439 (nth 2 tl))
11440 (setq org-time-was-given t))
11441 (if (< year 100) (setq year (+ 2000 year)))
11442 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11443 (list second minute hour day month year)))
11445 (defvar parse-time-weekdays)
11447 (defun org-read-date-get-relative (s today default)
11448 "Check string S for special relative date string.
11449 TODAY and DEFAULT are internal times, for today and for a default.
11450 Return shift list (N what def-flag)
11451 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11452 N is the number of WHATs to shift.
11453 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11454 the DEFAULT date rather than TODAY."
11455 (when (and
11456 (string-match
11457 (concat
11458 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11459 "\\([0-9]+\\)?"
11460 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11461 "\\([ \t]\\|$\\)") s)
11462 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11463 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11464 (string-to-char (substring (match-string 1 s) -1))
11465 ?+))
11466 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11467 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11468 (what (if (match-end 3) (match-string 3 s) "d"))
11469 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11470 (date (if rel default today))
11471 (wday (nth 6 (decode-time date)))
11472 delta)
11473 (if wday1
11474 (progn
11475 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11476 (if (= dir ?-) (setq delta (- delta 7)))
11477 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11478 (list delta "d" rel))
11479 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11481 (defun org-eval-in-calendar (form &optional keepdate)
11482 "Eval FORM in the calendar window and return to current window.
11483 Also, store the cursor date in variable org-ans2."
11484 (let ((sw (selected-window)))
11485 (select-window (get-buffer-window "*Calendar*"))
11486 (eval form)
11487 (when (and (not keepdate) (calendar-cursor-to-date))
11488 (let* ((date (calendar-cursor-to-date))
11489 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11490 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11491 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11492 (select-window sw)))
11494 (defun org-calendar-select ()
11495 "Return to `org-read-date' with the date currently selected.
11496 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11497 (interactive)
11498 (when (calendar-cursor-to-date)
11499 (let* ((date (calendar-cursor-to-date))
11500 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11501 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11502 (if (active-minibuffer-window) (exit-minibuffer))))
11504 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11505 "Insert a date stamp for the date given by the internal TIME.
11506 WITH-HM means, use the stamp format that includes the time of the day.
11507 INACTIVE means use square brackets instead of angular ones, so that the
11508 stamp will not contribute to the agenda.
11509 PRE and POST are optional strings to be inserted before and after the
11510 stamp.
11511 The command returns the inserted time stamp."
11512 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11513 stamp)
11514 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11515 (insert-before-markers (or pre ""))
11516 (insert-before-markers (setq stamp (format-time-string fmt time)))
11517 (when (listp extra)
11518 (setq extra (car extra))
11519 (if (and (stringp extra)
11520 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11521 (setq extra (format "-%02d:%02d"
11522 (string-to-number (match-string 1 extra))
11523 (string-to-number (match-string 2 extra))))
11524 (setq extra nil)))
11525 (when extra
11526 (backward-char 1)
11527 (insert-before-markers extra)
11528 (forward-char 1))
11529 (insert-before-markers (or post ""))
11530 (setq org-last-inserted-timestamp stamp)))
11532 (defun org-toggle-time-stamp-overlays ()
11533 "Toggle the use of custom time stamp formats."
11534 (interactive)
11535 (setq org-display-custom-times (not org-display-custom-times))
11536 (unless org-display-custom-times
11537 (let ((p (point-min)) (bmp (buffer-modified-p)))
11538 (while (setq p (next-single-property-change p 'display))
11539 (if (and (get-text-property p 'display)
11540 (eq (get-text-property p 'face) 'org-date))
11541 (remove-text-properties
11542 p (setq p (next-single-property-change p 'display))
11543 '(display t))))
11544 (set-buffer-modified-p bmp)))
11545 (if (featurep 'xemacs)
11546 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11547 (org-restart-font-lock)
11548 (setq org-table-may-need-update t)
11549 (if org-display-custom-times
11550 (message "Time stamps are overlayed with custom format")
11551 (message "Time stamp overlays removed")))
11553 (defun org-display-custom-time (beg end)
11554 "Overlay modified time stamp format over timestamp between BEG and END."
11555 (let* ((ts (buffer-substring beg end))
11556 t1 w1 with-hm tf time str w2 (off 0))
11557 (save-match-data
11558 (setq t1 (org-parse-time-string ts t))
11559 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11560 (setq off (- (match-end 0) (match-beginning 0)))))
11561 (setq end (- end off))
11562 (setq w1 (- end beg)
11563 with-hm (and (nth 1 t1) (nth 2 t1))
11564 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11565 time (org-fix-decoded-time t1)
11566 str (org-add-props
11567 (format-time-string
11568 (substring tf 1 -1) (apply 'encode-time time))
11569 nil 'mouse-face 'highlight)
11570 w2 (length str))
11571 (if (not (= w2 w1))
11572 (add-text-properties (1+ beg) (+ 2 beg)
11573 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11574 (if (featurep 'xemacs)
11575 (progn
11576 (put-text-property beg end 'invisible t)
11577 (put-text-property beg end 'end-glyph (make-glyph str)))
11578 (put-text-property beg end 'display str))))
11580 (defun org-translate-time (string)
11581 "Translate all timestamps in STRING to custom format.
11582 But do this only if the variable `org-display-custom-times' is set."
11583 (when org-display-custom-times
11584 (save-match-data
11585 (let* ((start 0)
11586 (re org-ts-regexp-both)
11587 t1 with-hm inactive tf time str beg end)
11588 (while (setq start (string-match re string start))
11589 (setq beg (match-beginning 0)
11590 end (match-end 0)
11591 t1 (save-match-data
11592 (org-parse-time-string (substring string beg end) t))
11593 with-hm (and (nth 1 t1) (nth 2 t1))
11594 inactive (equal (substring string beg (1+ beg)) "[")
11595 tf (funcall (if with-hm 'cdr 'car)
11596 org-time-stamp-custom-formats)
11597 time (org-fix-decoded-time t1)
11598 str (format-time-string
11599 (concat
11600 (if inactive "[" "<") (substring tf 1 -1)
11601 (if inactive "]" ">"))
11602 (apply 'encode-time time))
11603 string (replace-match str t t string)
11604 start (+ start (length str)))))))
11605 string)
11607 (defun org-fix-decoded-time (time)
11608 "Set 0 instead of nil for the first 6 elements of time.
11609 Don't touch the rest."
11610 (let ((n 0))
11611 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11613 (defun org-days-to-time (timestamp-string)
11614 "Difference between TIMESTAMP-STRING and now in days."
11615 (- (time-to-days (org-time-string-to-time timestamp-string))
11616 (time-to-days (current-time))))
11618 (defun org-deadline-close (timestamp-string &optional ndays)
11619 "Is the time in TIMESTAMP-STRING close to the current date?"
11620 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11621 (and (< (org-days-to-time timestamp-string) ndays)
11622 (not (org-entry-is-done-p))))
11624 (defun org-get-wdays (ts)
11625 "Get the deadline lead time appropriate for timestring TS."
11626 (cond
11627 ((<= org-deadline-warning-days 0)
11628 ;; 0 or negative, enforce this value no matter what
11629 (- org-deadline-warning-days))
11630 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11631 ;; lead time is specified.
11632 (floor (* (string-to-number (match-string 1 ts))
11633 (cdr (assoc (match-string 2 ts)
11634 '(("d" . 1) ("w" . 7)
11635 ("m" . 30.4) ("y" . 365.25)))))))
11636 ;; go for the default.
11637 (t org-deadline-warning-days)))
11639 (defun org-calendar-select-mouse (ev)
11640 "Return to `org-read-date' with the date currently selected.
11641 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11642 (interactive "e")
11643 (mouse-set-point ev)
11644 (when (calendar-cursor-to-date)
11645 (let* ((date (calendar-cursor-to-date))
11646 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11647 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11648 (if (active-minibuffer-window) (exit-minibuffer))))
11650 (defun org-check-deadlines (ndays)
11651 "Check if there are any deadlines due or past due.
11652 A deadline is considered due if it happens within `org-deadline-warning-days'
11653 days from today's date. If the deadline appears in an entry marked DONE,
11654 it is not shown. The prefix arg NDAYS can be used to test that many
11655 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11656 (interactive "P")
11657 (let* ((org-warn-days
11658 (cond
11659 ((equal ndays '(4)) 100000)
11660 (ndays (prefix-numeric-value ndays))
11661 (t (abs org-deadline-warning-days))))
11662 (case-fold-search nil)
11663 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11664 (callback
11665 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11667 (message "%d deadlines past-due or due within %d days"
11668 (org-occur regexp nil callback)
11669 org-warn-days)))
11671 (defun org-check-before-date (date)
11672 "Check if there are deadlines or scheduled entries before DATE."
11673 (interactive (list (org-read-date)))
11674 (let ((case-fold-search nil)
11675 (regexp (concat "\\<\\(" org-deadline-string
11676 "\\|" org-scheduled-string
11677 "\\) *<\\([^>]+\\)>"))
11678 (callback
11679 (lambda () (time-less-p
11680 (org-time-string-to-time (match-string 2))
11681 (org-time-string-to-time date)))))
11682 (message "%d entries before %s"
11683 (org-occur regexp nil callback) date)))
11685 (defun org-evaluate-time-range (&optional to-buffer)
11686 "Evaluate a time range by computing the difference between start and end.
11687 Normally the result is just printed in the echo area, but with prefix arg
11688 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11689 If the time range is actually in a table, the result is inserted into the
11690 next column.
11691 For time difference computation, a year is assumed to be exactly 365
11692 days in order to avoid rounding problems."
11693 (interactive "P")
11695 (org-clock-update-time-maybe)
11696 (save-excursion
11697 (unless (org-at-date-range-p t)
11698 (goto-char (point-at-bol))
11699 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11700 (if (not (org-at-date-range-p t))
11701 (error "Not at a time-stamp range, and none found in current line")))
11702 (let* ((ts1 (match-string 1))
11703 (ts2 (match-string 2))
11704 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11705 (match-end (match-end 0))
11706 (time1 (org-time-string-to-time ts1))
11707 (time2 (org-time-string-to-time ts2))
11708 (t1 (time-to-seconds time1))
11709 (t2 (time-to-seconds time2))
11710 (diff (abs (- t2 t1)))
11711 (negative (< (- t2 t1) 0))
11712 ;; (ys (floor (* 365 24 60 60)))
11713 (ds (* 24 60 60))
11714 (hs (* 60 60))
11715 (fy "%dy %dd %02d:%02d")
11716 (fy1 "%dy %dd")
11717 (fd "%dd %02d:%02d")
11718 (fd1 "%dd")
11719 (fh "%02d:%02d")
11720 y d h m align)
11721 (if havetime
11722 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11724 d (floor (/ diff ds)) diff (mod diff ds)
11725 h (floor (/ diff hs)) diff (mod diff hs)
11726 m (floor (/ diff 60)))
11727 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11729 d (floor (+ (/ diff ds) 0.5))
11730 h 0 m 0))
11731 (if (not to-buffer)
11732 (message "%s" (org-make-tdiff-string y d h m))
11733 (if (org-at-table-p)
11734 (progn
11735 (goto-char match-end)
11736 (setq align t)
11737 (and (looking-at " *|") (goto-char (match-end 0))))
11738 (goto-char match-end))
11739 (if (looking-at
11740 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11741 (replace-match ""))
11742 (if negative (insert " -"))
11743 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11744 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11745 (insert " " (format fh h m))))
11746 (if align (org-table-align))
11747 (message "Time difference inserted")))))
11749 (defun org-make-tdiff-string (y d h m)
11750 (let ((fmt "")
11751 (l nil))
11752 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11753 l (push y l)))
11754 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11755 l (push d l)))
11756 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11757 l (push h l)))
11758 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11759 l (push m l)))
11760 (apply 'format fmt (nreverse l))))
11762 (defun org-time-string-to-time (s)
11763 (apply 'encode-time (org-parse-time-string s)))
11765 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11766 "Convert a time stamp to an absolute day number.
11767 If there is a specifyer for a cyclic time stamp, get the closest date to
11768 DAYNR.
11769 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11770 (cond
11771 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11772 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11773 daynr
11774 (+ daynr 1000)))
11775 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11776 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11777 (time-to-days (current-time))) (match-string 0 s)
11778 prefer show-all))
11779 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11781 (defun org-days-to-iso-week (days)
11782 "Return the iso week number."
11783 (require 'cal-iso)
11784 (car (calendar-iso-from-absolute days)))
11786 (defun org-small-year-to-year (year)
11787 "Convert 2-digit years into 4-digit years.
11788 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11789 The year 2000 cannot be abbreviated. Any year larger than 99
11790 is returned unchanged."
11791 (if (< year 38)
11792 (setq year (+ 2000 year))
11793 (if (< year 100)
11794 (setq year (+ 1900 year))))
11795 year)
11797 (defun org-time-from-absolute (d)
11798 "Return the time corresponding to date D.
11799 D may be an absolute day number, or a calendar-type list (month day year)."
11800 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11801 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11803 (defun org-calendar-holiday ()
11804 "List of holidays, for Diary display in Org-mode."
11805 (require 'holidays)
11806 (let ((hl (funcall
11807 (if (fboundp 'calendar-check-holidays)
11808 'calendar-check-holidays 'check-calendar-holidays) date)))
11809 (if hl (mapconcat 'identity hl "; "))))
11811 (defun org-diary-sexp-entry (sexp entry date)
11812 "Process a SEXP diary ENTRY for DATE."
11813 (require 'diary-lib)
11814 (let ((result (if calendar-debug-sexp
11815 (let ((stack-trace-on-error t))
11816 (eval (car (read-from-string sexp))))
11817 (condition-case nil
11818 (eval (car (read-from-string sexp)))
11819 (error
11820 (beep)
11821 (message "Bad sexp at line %d in %s: %s"
11822 (org-current-line)
11823 (buffer-file-name) sexp)
11824 (sleep-for 2))))))
11825 (cond ((stringp result) result)
11826 ((and (consp result)
11827 (stringp (cdr result))) (cdr result))
11828 (result entry)
11829 (t nil))))
11831 (defun org-diary-to-ical-string (frombuf)
11832 "Get iCalendar entries from diary entries in buffer FROMBUF.
11833 This uses the icalendar.el library."
11834 (let* ((tmpdir (if (featurep 'xemacs)
11835 (temp-directory)
11836 temporary-file-directory))
11837 (tmpfile (make-temp-name
11838 (expand-file-name "orgics" tmpdir)))
11839 buf rtn b e)
11840 (save-excursion
11841 (set-buffer frombuf)
11842 (icalendar-export-region (point-min) (point-max) tmpfile)
11843 (setq buf (find-buffer-visiting tmpfile))
11844 (set-buffer buf)
11845 (goto-char (point-min))
11846 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11847 (setq b (match-beginning 0)))
11848 (goto-char (point-max))
11849 (if (re-search-backward "^END:VEVENT" nil t)
11850 (setq e (match-end 0)))
11851 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11852 (kill-buffer buf)
11853 (delete-file tmpfile)
11854 rtn))
11856 (defun org-closest-date (start current change prefer show-all)
11857 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11858 When PREFER is `past' return a date that is either CURRENT or past.
11859 When PREFER is `future', return a date that is either CURRENT or future.
11860 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11861 ;; Make the proper lists from the dates
11862 (catch 'exit
11863 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11864 dn dw sday cday n1 n2 n0
11865 d m y y1 y2 date1 date2 nmonths nm ny m2)
11867 (setq start (org-date-to-gregorian start)
11868 current (org-date-to-gregorian
11869 (if show-all
11870 current
11871 (time-to-days (current-time))))
11872 sday (calendar-absolute-from-gregorian start)
11873 cday (calendar-absolute-from-gregorian current))
11875 (if (<= cday sday) (throw 'exit sday))
11877 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11878 (setq dn (string-to-number (match-string 1 change))
11879 dw (cdr (assoc (match-string 2 change) a1)))
11880 (error "Invalid change specifyer: %s" change))
11881 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11882 (cond
11883 ((eq dw 'day)
11884 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11885 n2 (+ n1 dn)))
11886 ((eq dw 'year)
11887 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11888 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11889 (setq date1 (list m d y1)
11890 n1 (calendar-absolute-from-gregorian date1)
11891 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11892 n2 (calendar-absolute-from-gregorian date2)))
11893 ((eq dw 'month)
11894 ;; approx number of month between the two dates
11895 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11896 ;; How often does dn fit in there?
11897 (setq d (nth 1 start) m (car start) y (nth 2 start)
11898 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11899 m (+ m nm)
11900 ny (floor (/ m 12))
11901 y (+ y ny)
11902 m (- m (* ny 12)))
11903 (while (> m 12) (setq m (- m 12) y (1+ y)))
11904 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11905 (setq m2 (+ m dn) y2 y)
11906 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11907 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11908 (while (<= n2 cday)
11909 (setq n1 n2 m m2 y y2)
11910 (setq m2 (+ m dn) y2 y)
11911 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11912 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11913 ;; Make sure n1 is the earlier date
11914 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11915 (if show-all
11916 (cond
11917 ((eq prefer 'past) n1)
11918 ((eq prefer 'future) (if (= cday n1) n1 n2))
11919 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11920 (cond
11921 ((eq prefer 'past) n1)
11922 ((eq prefer 'future) (if (= cday n1) n1 n2))
11923 (t (if (= cday n1) n1 n2)))))))
11925 (defun org-date-to-gregorian (date)
11926 "Turn any specification of DATE into a gregorian date for the calendar."
11927 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11928 ((and (listp date) (= (length date) 3)) date)
11929 ((stringp date)
11930 (setq date (org-parse-time-string date))
11931 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11932 ((listp date)
11933 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11935 (defun org-parse-time-string (s &optional nodefault)
11936 "Parse the standard Org-mode time string.
11937 This should be a lot faster than the normal `parse-time-string'.
11938 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11939 hour and minute fields will be nil if not given."
11940 (if (string-match org-ts-regexp0 s)
11941 (list 0
11942 (if (or (match-beginning 8) (not nodefault))
11943 (string-to-number (or (match-string 8 s) "0")))
11944 (if (or (match-beginning 7) (not nodefault))
11945 (string-to-number (or (match-string 7 s) "0")))
11946 (string-to-number (match-string 4 s))
11947 (string-to-number (match-string 3 s))
11948 (string-to-number (match-string 2 s))
11949 nil nil nil)
11950 (make-list 9 0)))
11952 (defun org-timestamp-up (&optional arg)
11953 "Increase the date item at the cursor by one.
11954 If the cursor is on the year, change the year. If it is on the month or
11955 the day, change that.
11956 With prefix ARG, change by that many units."
11957 (interactive "p")
11958 (org-timestamp-change (prefix-numeric-value arg)))
11960 (defun org-timestamp-down (&optional arg)
11961 "Decrease the date item at the cursor by one.
11962 If the cursor is on the year, change the year. If it is on the month or
11963 the day, change that.
11964 With prefix ARG, change by that many units."
11965 (interactive "p")
11966 (org-timestamp-change (- (prefix-numeric-value arg))))
11968 (defun org-timestamp-up-day (&optional arg)
11969 "Increase the date in the time stamp by one day.
11970 With prefix ARG, change that many days."
11971 (interactive "p")
11972 (if (and (not (org-at-timestamp-p t))
11973 (org-on-heading-p))
11974 (org-todo 'up)
11975 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11977 (defun org-timestamp-down-day (&optional arg)
11978 "Decrease the date in the time stamp by one day.
11979 With prefix ARG, change that many days."
11980 (interactive "p")
11981 (if (and (not (org-at-timestamp-p t))
11982 (org-on-heading-p))
11983 (org-todo 'down)
11984 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11986 (defun org-at-timestamp-p (&optional inactive-ok)
11987 "Determine if the cursor is in or at a timestamp."
11988 (interactive)
11989 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11990 (pos (point))
11991 (ans (or (looking-at tsr)
11992 (save-excursion
11993 (skip-chars-backward "^[<\n\r\t")
11994 (if (> (point) (point-min)) (backward-char 1))
11995 (and (looking-at tsr)
11996 (> (- (match-end 0) pos) -1))))))
11997 (and ans
11998 (boundp 'org-ts-what)
11999 (setq org-ts-what
12000 (cond
12001 ((= pos (match-beginning 0)) 'bracket)
12002 ((= pos (1- (match-end 0))) 'bracket)
12003 ((org-pos-in-match-range pos 2) 'year)
12004 ((org-pos-in-match-range pos 3) 'month)
12005 ((org-pos-in-match-range pos 7) 'hour)
12006 ((org-pos-in-match-range pos 8) 'minute)
12007 ((or (org-pos-in-match-range pos 4)
12008 (org-pos-in-match-range pos 5)) 'day)
12009 ((and (> pos (or (match-end 8) (match-end 5)))
12010 (< pos (match-end 0)))
12011 (- pos (or (match-end 8) (match-end 5))))
12012 (t 'day))))
12013 ans))
12015 (defun org-toggle-timestamp-type ()
12016 "Toggle the type (<active> or [inactive]) of a time stamp."
12017 (interactive)
12018 (when (org-at-timestamp-p t)
12019 (let ((beg (match-beginning 0)) (end (match-end 0))
12020 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12021 (save-excursion
12022 (goto-char beg)
12023 (while (re-search-forward "[][<>]" end t)
12024 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12025 t t)))
12026 (message "Timestamp is now %sactive"
12027 (if (equal (char-after beg) ?<) "" "in")))))
12029 (defun org-timestamp-change (n &optional what)
12030 "Change the date in the time stamp at point.
12031 The date will be changed by N times WHAT. WHAT can be `day', `month',
12032 `year', `minute', `second'. If WHAT is not given, the cursor position
12033 in the timestamp determines what will be changed."
12034 (let ((pos (point))
12035 with-hm inactive
12036 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12037 org-ts-what
12038 extra rem
12039 ts time time0)
12040 (if (not (org-at-timestamp-p t))
12041 (error "Not at a timestamp"))
12042 (if (and (not what) (eq org-ts-what 'bracket))
12043 (org-toggle-timestamp-type)
12044 (if (and (not what) (not (eq org-ts-what 'day))
12045 org-display-custom-times
12046 (get-text-property (point) 'display)
12047 (not (get-text-property (1- (point)) 'display)))
12048 (setq org-ts-what 'day))
12049 (setq org-ts-what (or what org-ts-what)
12050 inactive (= (char-after (match-beginning 0)) ?\[)
12051 ts (match-string 0))
12052 (replace-match "")
12053 (if (string-match
12054 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12056 (setq extra (match-string 1 ts)))
12057 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12058 (setq with-hm t))
12059 (setq time0 (org-parse-time-string ts))
12060 (when (and (eq org-ts-what 'minute)
12061 (eq current-prefix-arg nil))
12062 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12063 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12064 (setcar (cdr time0) (+ (nth 1 time0)
12065 (if (> n 0) (- rem) (- dm rem))))))
12066 (setq time
12067 (encode-time (or (car time0) 0)
12068 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12069 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12070 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12071 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12072 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12073 (nthcdr 6 time0)))
12074 (when (integerp org-ts-what)
12075 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12076 (if (eq what 'calendar)
12077 (let ((cal-date (org-get-date-from-calendar)))
12078 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12079 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12080 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12081 (setcar time0 (or (car time0) 0))
12082 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12083 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12084 (setq time (apply 'encode-time time0))))
12085 (setq org-last-changed-timestamp
12086 (org-insert-time-stamp time with-hm inactive nil nil extra))
12087 (org-clock-update-time-maybe)
12088 (goto-char pos)
12089 ;; Try to recenter the calendar window, if any
12090 (if (and org-calendar-follow-timestamp-change
12091 (get-buffer-window "*Calendar*" t)
12092 (memq org-ts-what '(day month year)))
12093 (org-recenter-calendar (time-to-days time))))))
12095 (defun org-modify-ts-extra (s pos n dm)
12096 "Change the different parts of the lead-time and repeat fields in timestamp."
12097 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12098 ng h m new rem)
12099 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12100 (cond
12101 ((or (org-pos-in-match-range pos 2)
12102 (org-pos-in-match-range pos 3))
12103 (setq m (string-to-number (match-string 3 s))
12104 h (string-to-number (match-string 2 s)))
12105 (if (org-pos-in-match-range pos 2)
12106 (setq h (+ h n))
12107 (setq n (* dm (org-no-warnings (signum n))))
12108 (when (not (= 0 (setq rem (% m dm))))
12109 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12110 (setq m (+ m n)))
12111 (if (< m 0) (setq m (+ m 60) h (1- h)))
12112 (if (> m 59) (setq m (- m 60) h (1+ h)))
12113 (setq h (min 24 (max 0 h)))
12114 (setq ng 1 new (format "-%02d:%02d" h m)))
12115 ((org-pos-in-match-range pos 6)
12116 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12117 ((org-pos-in-match-range pos 5)
12118 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12120 ((org-pos-in-match-range pos 9)
12121 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12122 ((org-pos-in-match-range pos 8)
12123 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12125 (when ng
12126 (setq s (concat
12127 (substring s 0 (match-beginning ng))
12129 (substring s (match-end ng))))))
12132 (defun org-recenter-calendar (date)
12133 "If the calendar is visible, recenter it to DATE."
12134 (let* ((win (selected-window))
12135 (cwin (get-buffer-window "*Calendar*" t))
12136 (calendar-move-hook nil))
12137 (when cwin
12138 (select-window cwin)
12139 (calendar-goto-date (if (listp date) date
12140 (calendar-gregorian-from-absolute date)))
12141 (select-window win))))
12143 (defun org-goto-calendar (&optional arg)
12144 "Go to the Emacs calendar at the current date.
12145 If there is a time stamp in the current line, go to that date.
12146 A prefix ARG can be used to force the current date."
12147 (interactive "P")
12148 (let ((tsr org-ts-regexp) diff
12149 (calendar-move-hook nil)
12150 (calendar-view-holidays-initially-flag nil)
12151 (view-calendar-holidays-initially nil)
12152 (calendar-view-diary-initially-flag nil)
12153 (view-diary-entries-initially nil))
12154 (if (or (org-at-timestamp-p)
12155 (save-excursion
12156 (beginning-of-line 1)
12157 (looking-at (concat ".*" tsr))))
12158 (let ((d1 (time-to-days (current-time)))
12159 (d2 (time-to-days
12160 (org-time-string-to-time (match-string 1)))))
12161 (setq diff (- d2 d1))))
12162 (calendar)
12163 (calendar-goto-today)
12164 (if (and diff (not arg)) (calendar-forward-day diff))))
12166 (defun org-get-date-from-calendar ()
12167 "Return a list (month day year) of date at point in calendar."
12168 (with-current-buffer "*Calendar*"
12169 (save-match-data
12170 (calendar-cursor-to-date))))
12172 (defun org-date-from-calendar ()
12173 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12174 If there is already a time stamp at the cursor position, update it."
12175 (interactive)
12176 (if (org-at-timestamp-p t)
12177 (org-timestamp-change 0 'calendar)
12178 (let ((cal-date (org-get-date-from-calendar)))
12179 (org-insert-time-stamp
12180 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12182 (defun org-minutes-to-hh:mm-string (m)
12183 "Compute H:MM from a number of minutes."
12184 (let ((h (/ m 60)))
12185 (setq m (- m (* 60 h)))
12186 (format org-time-clocksum-format h m)))
12188 (defun org-hh:mm-string-to-minutes (s)
12189 "Convert a string H:MM to a number of minutes."
12190 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12191 (+ (* (string-to-number (match-string 1 s)) 60)
12192 (string-to-number (match-string 2 s)))
12195 ;;;; Agenda files
12197 ;;;###autoload
12198 (defun org-iswitchb (&optional arg)
12199 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12200 With a prefix argument, restrict available to files.
12201 With two prefix arguments, restrict available buffers to agenda files.
12203 Due to some yet unresolved reason, the global function
12204 `iswitchb-mode' needs to be active for this function to work."
12205 (interactive "P")
12206 (require 'iswitchb)
12207 (let ((enabled iswitchb-mode) blist)
12208 (or enabled (iswitchb-mode 1))
12209 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12210 ((equal arg '(16)) (org-buffer-list 'agenda))
12211 (t (org-buffer-list))))
12212 (unwind-protect
12213 (let ((iswitchb-make-buflist-hook
12214 (lambda ()
12215 (setq iswitchb-temp-buflist
12216 (mapcar 'buffer-name blist)))))
12217 (switch-to-buffer
12218 (iswitchb-read-buffer
12219 "Switch-to: " nil t))
12220 (or enabled (iswitchb-mode -1))))))
12222 ;;;###autoload
12223 (defun org-ido-switchb (&optional arg)
12224 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12225 With a prefix argument, restrict available to files.
12226 With two prefix arguments, restrict available buffers to agenda files."
12227 (interactive "P")
12228 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12229 ((equal arg '(16)) (org-buffer-list 'agenda))
12230 (t (org-buffer-list)))))
12231 (switch-to-buffer
12232 (org-ido-completing-read "Org buffer: "
12233 (mapcar 'buffer-name blist)
12234 nil t))))
12236 (defun org-buffer-list (&optional predicate exclude-tmp)
12237 "Return a list of Org buffers.
12238 PREDICATE can be `export', `files' or `agenda'.
12240 export restrict the list to Export buffers.
12241 files restrict the list to buffers visiting Org files.
12242 agenda restrict the list to buffers visiting agenda files.
12244 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12245 (let* ((bfn nil)
12246 (agenda-files (and (eq predicate 'agenda)
12247 (mapcar 'file-truename (org-agenda-files t))))
12248 (filter
12249 (cond
12250 ((eq predicate 'files)
12251 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12252 ((eq predicate 'export)
12253 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12254 ((eq predicate 'agenda)
12255 (lambda (b)
12256 (with-current-buffer b
12257 (and (eq major-mode 'org-mode)
12258 (setq bfn (buffer-file-name b))
12259 (member (file-truename bfn) agenda-files)))))
12260 (t (lambda (b) (with-current-buffer b
12261 (or (eq major-mode 'org-mode)
12262 (string-match "\*Org .*Export"
12263 (buffer-name b)))))))))
12264 (delq nil
12265 (mapcar
12266 (lambda(b)
12267 (if (and (funcall filter b)
12268 (or (not exclude-tmp)
12269 (not (string-match "tmp" (buffer-name b)))))
12271 nil))
12272 (buffer-list)))))
12274 (defun org-agenda-files (&optional unrestricted archives)
12275 "Get the list of agenda files.
12276 Optional UNRESTRICTED means return the full list even if a restriction
12277 is currently in place.
12278 When ARCHIVES is t, include all archive files hat are really being
12279 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12280 `org-agenda-archives-mode' is t."
12281 (let ((files
12282 (cond
12283 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12284 ((stringp org-agenda-files) (org-read-agenda-file-list))
12285 ((listp org-agenda-files) org-agenda-files)
12286 (t (error "Invalid value of `org-agenda-files'")))))
12287 (setq files (apply 'append
12288 (mapcar (lambda (f)
12289 (if (file-directory-p f)
12290 (directory-files
12291 f t org-agenda-file-regexp)
12292 (list f)))
12293 files)))
12294 (when org-agenda-skip-unavailable-files
12295 (setq files (delq nil
12296 (mapcar (function
12297 (lambda (file)
12298 (and (file-readable-p file) file)))
12299 files))))
12300 (when (or (eq archives t)
12301 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12302 (setq files (org-add-archive-files files)))
12303 files))
12305 (defun org-edit-agenda-file-list ()
12306 "Edit the list of agenda files.
12307 Depending on setup, this either uses customize to edit the variable
12308 `org-agenda-files', or it visits the file that is holding the list. In the
12309 latter case, the buffer is set up in a way that saving it automatically kills
12310 the buffer and restores the previous window configuration."
12311 (interactive)
12312 (if (stringp org-agenda-files)
12313 (let ((cw (current-window-configuration)))
12314 (find-file org-agenda-files)
12315 (org-set-local 'org-window-configuration cw)
12316 (org-add-hook 'after-save-hook
12317 (lambda ()
12318 (set-window-configuration
12319 (prog1 org-window-configuration
12320 (kill-buffer (current-buffer))))
12321 (org-install-agenda-files-menu)
12322 (message "New agenda file list installed"))
12323 nil 'local)
12324 (message "%s" (substitute-command-keys
12325 "Edit list and finish with \\[save-buffer]")))
12326 (customize-variable 'org-agenda-files)))
12328 (defun org-store-new-agenda-file-list (list)
12329 "Set new value for the agenda file list and save it correctly."
12330 (if (stringp org-agenda-files)
12331 (let ((f org-agenda-files) b)
12332 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12333 (with-temp-file f
12334 (insert (mapconcat 'identity list "\n") "\n")))
12335 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12336 (setq org-agenda-files list)
12337 (customize-save-variable 'org-agenda-files org-agenda-files))))
12339 (defun org-read-agenda-file-list ()
12340 "Read the list of agenda files from a file."
12341 (when (file-directory-p org-agenda-files)
12342 (error "`org-agenda-files' cannot be a single directory"))
12343 (when (stringp org-agenda-files)
12344 (with-temp-buffer
12345 (insert-file-contents org-agenda-files)
12346 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12349 ;;;###autoload
12350 (defun org-cycle-agenda-files ()
12351 "Cycle through the files in `org-agenda-files'.
12352 If the current buffer visits an agenda file, find the next one in the list.
12353 If the current buffer does not, find the first agenda file."
12354 (interactive)
12355 (let* ((fs (org-agenda-files t))
12356 (files (append fs (list (car fs))))
12357 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12358 file)
12359 (unless files (error "No agenda files"))
12360 (catch 'exit
12361 (while (setq file (pop files))
12362 (if (equal (file-truename file) tcf)
12363 (when (car files)
12364 (find-file (car files))
12365 (throw 'exit t))))
12366 (find-file (car fs)))
12367 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12369 (defun org-agenda-file-to-front (&optional to-end)
12370 "Move/add the current file to the top of the agenda file list.
12371 If the file is not present in the list, it is added to the front. If it is
12372 present, it is moved there. With optional argument TO-END, add/move to the
12373 end of the list."
12374 (interactive "P")
12375 (let ((org-agenda-skip-unavailable-files nil)
12376 (file-alist (mapcar (lambda (x)
12377 (cons (file-truename x) x))
12378 (org-agenda-files t)))
12379 (ctf (file-truename buffer-file-name))
12380 x had)
12381 (setq x (assoc ctf file-alist) had x)
12383 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12384 (if to-end
12385 (setq file-alist (append (delq x file-alist) (list x)))
12386 (setq file-alist (cons x (delq x file-alist))))
12387 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12388 (org-install-agenda-files-menu)
12389 (message "File %s to %s of agenda file list"
12390 (if had "moved" "added") (if to-end "end" "front"))))
12392 (defun org-remove-file (&optional file)
12393 "Remove current file from the list of files in variable `org-agenda-files'.
12394 These are the files which are being checked for agenda entries.
12395 Optional argument FILE means, use this file instead of the current."
12396 (interactive)
12397 (let* ((org-agenda-skip-unavailable-files nil)
12398 (file (or file buffer-file-name))
12399 (true-file (file-truename file))
12400 (afile (abbreviate-file-name file))
12401 (files (delq nil (mapcar
12402 (lambda (x)
12403 (if (equal true-file
12404 (file-truename x))
12405 nil x))
12406 (org-agenda-files t)))))
12407 (if (not (= (length files) (length (org-agenda-files t))))
12408 (progn
12409 (org-store-new-agenda-file-list files)
12410 (org-install-agenda-files-menu)
12411 (message "Removed file: %s" afile))
12412 (message "File was not in list: %s (not removed)" afile))))
12414 (defun org-file-menu-entry (file)
12415 (vector file (list 'find-file file) t))
12417 (defun org-check-agenda-file (file)
12418 "Make sure FILE exists. If not, ask user what to do."
12419 (when (not (file-exists-p file))
12420 (message "non-existent file %s. [R]emove from list or [A]bort?"
12421 (abbreviate-file-name file))
12422 (let ((r (downcase (read-char-exclusive))))
12423 (cond
12424 ((equal r ?r)
12425 (org-remove-file file)
12426 (throw 'nextfile t))
12427 (t (error "Abort"))))))
12429 (defun org-get-agenda-file-buffer (file)
12430 "Get a buffer visiting FILE. If the buffer needs to be created, add
12431 it to the list of buffers which might be released later."
12432 (let ((buf (org-find-base-buffer-visiting file)))
12433 (if buf
12434 buf ; just return it
12435 ;; Make a new buffer and remember it
12436 (setq buf (find-file-noselect file))
12437 (if buf (push buf org-agenda-new-buffers))
12438 buf)))
12440 (defun org-release-buffers (blist)
12441 "Release all buffers in list, asking the user for confirmation when needed.
12442 When a buffer is unmodified, it is just killed. When modified, it is saved
12443 \(if the user agrees) and then killed."
12444 (let (buf file)
12445 (while (setq buf (pop blist))
12446 (setq file (buffer-file-name buf))
12447 (when (and (buffer-modified-p buf)
12448 file
12449 (y-or-n-p (format "Save file %s? " file)))
12450 (with-current-buffer buf (save-buffer)))
12451 (kill-buffer buf))))
12453 (defun org-prepare-agenda-buffers (files)
12454 "Create buffers for all agenda files, protect archived trees and comments."
12455 (interactive)
12456 (let ((pa '(:org-archived t))
12457 (pc '(:org-comment t))
12458 (pall '(:org-archived t :org-comment t))
12459 (inhibit-read-only t)
12460 (rea (concat ":" org-archive-tag ":"))
12461 bmp file re)
12462 (save-excursion
12463 (save-restriction
12464 (while (setq file (pop files))
12465 (if (bufferp file)
12466 (set-buffer file)
12467 (org-check-agenda-file file)
12468 (set-buffer (org-get-agenda-file-buffer file)))
12469 (widen)
12470 (setq bmp (buffer-modified-p))
12471 (org-refresh-category-properties)
12472 (setq org-todo-keywords-for-agenda
12473 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12474 (setq org-done-keywords-for-agenda
12475 (append org-done-keywords-for-agenda org-done-keywords))
12476 (setq org-todo-keyword-alist-for-agenda
12477 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12478 (setq org-tag-alist-for-agenda
12479 (append org-tag-alist-for-agenda org-tag-alist))
12481 (save-excursion
12482 (remove-text-properties (point-min) (point-max) pall)
12483 (when org-agenda-skip-archived-trees
12484 (goto-char (point-min))
12485 (while (re-search-forward rea nil t)
12486 (if (org-on-heading-p t)
12487 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12488 (goto-char (point-min))
12489 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12490 (while (re-search-forward re nil t)
12491 (add-text-properties
12492 (match-beginning 0) (org-end-of-subtree t) pc)))
12493 (set-buffer-modified-p bmp))))
12494 (setq org-todo-keyword-alist-for-agenda
12495 (org-uniquify org-todo-keyword-alist-for-agenda)
12496 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12498 ;;;; Embedded LaTeX
12500 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12501 "Keymap for the minor `org-cdlatex-mode'.")
12503 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12504 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12505 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12506 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12507 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12509 (defvar org-cdlatex-texmathp-advice-is-done nil
12510 "Flag remembering if we have applied the advice to texmathp already.")
12512 (define-minor-mode org-cdlatex-mode
12513 "Toggle the minor `org-cdlatex-mode'.
12514 This mode supports entering LaTeX environment and math in LaTeX fragments
12515 in Org-mode.
12516 \\{org-cdlatex-mode-map}"
12517 nil " OCDL" nil
12518 (when org-cdlatex-mode (require 'cdlatex))
12519 (unless org-cdlatex-texmathp-advice-is-done
12520 (setq org-cdlatex-texmathp-advice-is-done t)
12521 (defadvice texmathp (around org-math-always-on activate)
12522 "Always return t in org-mode buffers.
12523 This is because we want to insert math symbols without dollars even outside
12524 the LaTeX math segments. If Orgmode thinks that point is actually inside
12525 an embedded LaTeX fragment, let texmathp do its job.
12526 \\[org-cdlatex-mode-map]"
12527 (interactive)
12528 (let (p)
12529 (cond
12530 ((not (org-mode-p)) ad-do-it)
12531 ((eq this-command 'cdlatex-math-symbol)
12532 (setq ad-return-value t
12533 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12535 (let ((p (org-inside-LaTeX-fragment-p)))
12536 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12537 (setq ad-return-value t
12538 texmathp-why '("Org-mode embedded math" . 0))
12539 (if p ad-do-it)))))))))
12541 (defun turn-on-org-cdlatex ()
12542 "Unconditionally turn on `org-cdlatex-mode'."
12543 (org-cdlatex-mode 1))
12545 (defun org-inside-LaTeX-fragment-p ()
12546 "Test if point is inside a LaTeX fragment.
12547 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12548 sequence appearing also before point.
12549 Even though the matchers for math are configurable, this function assumes
12550 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12551 delimiters are skipped when they have been removed by customization.
12552 The return value is nil, or a cons cell with the delimiter and
12553 and the position of this delimiter.
12555 This function does a reasonably good job, but can locally be fooled by
12556 for example currency specifications. For example it will assume being in
12557 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12558 fragments that are properly closed, but during editing, we have to live
12559 with the uncertainty caused by missing closing delimiters. This function
12560 looks only before point, not after."
12561 (catch 'exit
12562 (let ((pos (point))
12563 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12564 (lim (progn
12565 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12566 (point)))
12567 dd-on str (start 0) m re)
12568 (goto-char pos)
12569 (when dodollar
12570 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12571 re (nth 1 (assoc "$" org-latex-regexps)))
12572 (while (string-match re str start)
12573 (cond
12574 ((= (match-end 0) (length str))
12575 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12576 ((= (match-end 0) (- (length str) 5))
12577 (throw 'exit nil))
12578 (t (setq start (match-end 0))))))
12579 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12580 (goto-char pos)
12581 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12582 (and (match-beginning 2) (throw 'exit nil))
12583 ;; count $$
12584 (while (re-search-backward "\\$\\$" lim t)
12585 (setq dd-on (not dd-on)))
12586 (goto-char pos)
12587 (if dd-on (cons "$$" m))))))
12590 (defun org-try-cdlatex-tab ()
12591 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12592 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12593 - inside a LaTeX fragment, or
12594 - after the first word in a line, where an abbreviation expansion could
12595 insert a LaTeX environment."
12596 (when org-cdlatex-mode
12597 (cond
12598 ((save-excursion
12599 (skip-chars-backward "a-zA-Z0-9*")
12600 (skip-chars-backward " \t")
12601 (bolp))
12602 (cdlatex-tab) t)
12603 ((org-inside-LaTeX-fragment-p)
12604 (cdlatex-tab) t)
12605 (t nil))))
12607 (defun org-cdlatex-underscore-caret (&optional arg)
12608 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12609 Revert to the normal definition outside of these fragments."
12610 (interactive "P")
12611 (if (org-inside-LaTeX-fragment-p)
12612 (call-interactively 'cdlatex-sub-superscript)
12613 (let (org-cdlatex-mode)
12614 (call-interactively (key-binding (vector last-input-event))))))
12616 (defun org-cdlatex-math-modify (&optional arg)
12617 "Execute `cdlatex-math-modify' in LaTeX fragments.
12618 Revert to the normal definition outside of these fragments."
12619 (interactive "P")
12620 (if (org-inside-LaTeX-fragment-p)
12621 (call-interactively 'cdlatex-math-modify)
12622 (let (org-cdlatex-mode)
12623 (call-interactively (key-binding (vector last-input-event))))))
12625 (defvar org-latex-fragment-image-overlays nil
12626 "List of overlays carrying the images of latex fragments.")
12627 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12629 (defun org-remove-latex-fragment-image-overlays ()
12630 "Remove all overlays with LaTeX fragment images in current buffer."
12631 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12632 (setq org-latex-fragment-image-overlays nil))
12634 (defun org-preview-latex-fragment (&optional subtree)
12635 "Preview the LaTeX fragment at point, or all locally or globally.
12636 If the cursor is in a LaTeX fragment, create the image and overlay
12637 it over the source code. If there is no fragment at point, display
12638 all fragments in the current text, from one headline to the next. With
12639 prefix SUBTREE, display all fragments in the current subtree. With a
12640 double prefix `C-u C-u', or when the cursor is before the first headline,
12641 display all fragments in the buffer.
12642 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12643 (interactive "P")
12644 (org-remove-latex-fragment-image-overlays)
12645 (save-excursion
12646 (save-restriction
12647 (let (beg end at msg)
12648 (cond
12649 ((or (equal subtree '(16))
12650 (not (save-excursion
12651 (re-search-backward (concat "^" outline-regexp) nil t))))
12652 (setq beg (point-min) end (point-max)
12653 msg "Creating images for buffer...%s"))
12654 ((equal subtree '(4))
12655 (org-back-to-heading)
12656 (setq beg (point) end (org-end-of-subtree t)
12657 msg "Creating images for subtree...%s"))
12659 (if (setq at (org-inside-LaTeX-fragment-p))
12660 (goto-char (max (point-min) (- (cdr at) 2)))
12661 (org-back-to-heading))
12662 (setq beg (point) end (progn (outline-next-heading) (point))
12663 msg (if at "Creating image...%s"
12664 "Creating images for entry...%s"))))
12665 (message msg "")
12666 (narrow-to-region beg end)
12667 (goto-char beg)
12668 (org-format-latex
12669 (concat "ltxpng/" (file-name-sans-extension
12670 (file-name-nondirectory
12671 buffer-file-name)))
12672 default-directory 'overlays msg at 'forbuffer)
12673 (message msg "done. Use `C-c C-c' to remove images.")))))
12675 (defvar org-latex-regexps
12676 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12677 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12678 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12679 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12680 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12681 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12682 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12683 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12684 "Regular expressions for matching embedded LaTeX.")
12686 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12687 "Replace LaTeX fragments with links to an image, and produce images."
12688 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12689 (let* ((prefixnodir (file-name-nondirectory prefix))
12690 (absprefix (expand-file-name prefix dir))
12691 (todir (file-name-directory absprefix))
12692 (opt org-format-latex-options)
12693 (matchers (plist-get opt :matchers))
12694 (re-list org-latex-regexps)
12695 (cnt 0) txt link beg end re e checkdir
12696 m n block linkfile movefile ov)
12697 ;; Check if there are old images files with this prefix, and remove them
12698 (when (file-directory-p todir)
12699 (mapc 'delete-file
12700 (directory-files
12701 todir 'full
12702 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12703 ;; Check the different regular expressions
12704 (while (setq e (pop re-list))
12705 (setq m (car e) re (nth 1 e) n (nth 2 e)
12706 block (if (nth 3 e) "\n\n" ""))
12707 (when (member m matchers)
12708 (goto-char (point-min))
12709 (while (re-search-forward re nil t)
12710 (when (or (not at) (equal (cdr at) (match-beginning n)))
12711 (setq txt (match-string n)
12712 beg (match-beginning n) end (match-end n)
12713 cnt (1+ cnt)
12714 linkfile (format "%s_%04d.png" prefix cnt)
12715 movefile (format "%s_%04d.png" absprefix cnt)
12716 link (concat block "[[file:" linkfile "]]" block))
12717 (if msg (message msg cnt))
12718 (goto-char beg)
12719 (unless checkdir ; make sure the directory exists
12720 (setq checkdir t)
12721 (or (file-directory-p todir) (make-directory todir)))
12722 (org-create-formula-image
12723 txt movefile opt forbuffer)
12724 (if overlays
12725 (progn
12726 (setq ov (org-make-overlay beg end))
12727 (if (featurep 'xemacs)
12728 (progn
12729 (org-overlay-put ov 'invisible t)
12730 (org-overlay-put
12731 ov 'end-glyph
12732 (make-glyph (vector 'png :file movefile))))
12733 (org-overlay-put
12734 ov 'display
12735 (list 'image :type 'png :file movefile :ascent 'center)))
12736 (push ov org-latex-fragment-image-overlays)
12737 (goto-char end))
12738 (delete-region beg end)
12739 (insert link))))))))
12741 ;; This function borrows from Ganesh Swami's latex2png.el
12742 (defun org-create-formula-image (string tofile options buffer)
12743 (let* ((tmpdir (if (featurep 'xemacs)
12744 (temp-directory)
12745 temporary-file-directory))
12746 (texfilebase (make-temp-name
12747 (expand-file-name "orgtex" tmpdir)))
12748 (texfile (concat texfilebase ".tex"))
12749 (dvifile (concat texfilebase ".dvi"))
12750 (pngfile (concat texfilebase ".png"))
12751 (fnh (if (featurep 'xemacs)
12752 (font-height (get-face-font 'default))
12753 (face-attribute 'default :height nil)))
12754 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12755 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12756 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12757 "Black"))
12758 (bg (or (plist-get options (if buffer :background :html-background))
12759 "Transparent")))
12760 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12761 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12762 (with-temp-file texfile
12763 (insert org-format-latex-header
12764 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12765 (let ((dir default-directory))
12766 (condition-case nil
12767 (progn
12768 (cd tmpdir)
12769 (call-process "latex" nil nil nil texfile))
12770 (error nil))
12771 (cd dir))
12772 (if (not (file-exists-p dvifile))
12773 (progn (message "Failed to create dvi file from %s" texfile) nil)
12774 (condition-case nil
12775 (call-process "dvipng" nil nil nil
12776 "-E" "-fg" fg "-bg" bg
12777 "-D" dpi
12778 ;;"-x" scale "-y" scale
12779 "-T" "tight"
12780 "-o" pngfile
12781 dvifile)
12782 (error nil))
12783 (if (not (file-exists-p pngfile))
12784 (progn (message "Failed to create png file from %s" texfile) nil)
12785 ;; Use the requested file name and clean up
12786 (copy-file pngfile tofile 'replace)
12787 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12788 (delete-file (concat texfilebase e)))
12789 pngfile))))
12791 (defun org-dvipng-color (attr)
12792 "Return an rgb color specification for dvipng."
12793 (apply 'format "rgb %s %s %s"
12794 (mapcar 'org-normalize-color
12795 (color-values (face-attribute 'default attr nil)))))
12797 (defun org-normalize-color (value)
12798 "Return string to be used as color value for an RGB component."
12799 (format "%g" (/ value 65535.0)))
12801 ;;;; Key bindings
12803 ;; Make `C-c C-x' a prefix key
12804 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12806 ;; TAB key with modifiers
12807 (org-defkey org-mode-map "\C-i" 'org-cycle)
12808 (org-defkey org-mode-map [(tab)] 'org-cycle)
12809 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12810 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12811 (org-defkey org-mode-map "\M-\t" 'org-complete)
12812 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12813 ;; The following line is necessary under Suse GNU/Linux
12814 (unless (featurep 'xemacs)
12815 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12816 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12817 (define-key org-mode-map [backtab] 'org-shifttab)
12819 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12820 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12821 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12823 ;; Cursor keys with modifiers
12824 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12825 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12826 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12827 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12829 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12830 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12831 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12832 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12834 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12835 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12836 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12837 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12839 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12840 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12842 ;;; Extra keys for tty access.
12843 ;; We only set them when really needed because otherwise the
12844 ;; menus don't show the simple keys
12846 (when (or org-use-extra-keys
12847 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12848 (not window-system))
12849 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12850 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12851 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12852 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12853 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12854 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12855 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12856 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12857 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12858 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12859 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12860 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12861 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12862 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12863 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12864 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12865 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12866 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12867 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12868 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12869 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12870 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12872 ;; All the other keys
12874 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12875 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12876 (if (boundp 'narrow-map)
12877 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12878 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12879 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12880 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12881 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12882 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12883 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12884 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12885 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12886 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12887 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12888 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12889 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12890 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12891 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12892 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12893 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12894 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12895 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12896 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12897 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12898 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12899 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12900 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12901 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12902 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12903 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12904 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12905 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12906 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12907 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12908 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12909 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12910 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12911 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12912 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12913 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12914 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12915 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12916 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12917 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12918 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12919 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12920 (org-defkey org-mode-map "\C-c^" 'org-sort)
12921 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12922 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12923 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12924 (org-defkey org-mode-map "\C-m" 'org-return)
12925 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12926 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12927 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12928 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12929 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12930 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12931 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12932 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12933 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12934 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12935 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12936 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12937 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12938 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12939 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12940 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12941 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12943 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12944 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12945 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12946 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12948 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12949 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12950 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12951 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12952 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12953 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12954 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12955 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12956 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12957 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12958 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12959 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
12960 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12962 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12963 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12964 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12965 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12967 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12969 (when (featurep 'xemacs)
12970 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12972 (defvar org-table-auto-blank-field) ; defined in org-table.el
12973 (defun org-self-insert-command (N)
12974 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12975 If the cursor is in a table looking at whitespace, the whitespace is
12976 overwritten, and the table is not marked as requiring realignment."
12977 (interactive "p")
12978 (if (and (org-table-p)
12979 (progn
12980 ;; check if we blank the field, and if that triggers align
12981 (and (featurep 'org-table) org-table-auto-blank-field
12982 (member last-command
12983 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12984 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12985 ;; got extra space, this field does not determine column width
12986 (let (org-table-may-need-update) (org-table-blank-field))
12987 ;; no extra space, this field may determine column width
12988 (org-table-blank-field)))
12990 (eq N 1)
12991 (looking-at "[^|\n]* |"))
12992 (let (org-table-may-need-update)
12993 (goto-char (1- (match-end 0)))
12994 (delete-backward-char 1)
12995 (goto-char (match-beginning 0))
12996 (self-insert-command N))
12997 (setq org-table-may-need-update t)
12998 (self-insert-command N)
12999 (org-fix-tags-on-the-fly)))
13001 (defun org-fix-tags-on-the-fly ()
13002 (when (and (equal (char-after (point-at-bol)) ?*)
13003 (org-on-heading-p))
13004 (org-align-tags-here org-tags-column)))
13006 (defun org-delete-backward-char (N)
13007 "Like `delete-backward-char', insert whitespace at field end in tables.
13008 When deleting backwards, in tables this function will insert whitespace in
13009 front of the next \"|\" separator, to keep the table aligned. The table will
13010 still be marked for re-alignment if the field did fill the entire column,
13011 because, in this case the deletion might narrow the column."
13012 (interactive "p")
13013 (if (and (org-table-p)
13014 (eq N 1)
13015 (string-match "|" (buffer-substring (point-at-bol) (point)))
13016 (looking-at ".*?|"))
13017 (let ((pos (point))
13018 (noalign (looking-at "[^|\n\r]* |"))
13019 (c org-table-may-need-update))
13020 (backward-delete-char N)
13021 (skip-chars-forward "^|")
13022 (insert " ")
13023 (goto-char (1- pos))
13024 ;; noalign: if there were two spaces at the end, this field
13025 ;; does not determine the width of the column.
13026 (if noalign (setq org-table-may-need-update c)))
13027 (backward-delete-char N)
13028 (org-fix-tags-on-the-fly)))
13030 (defun org-delete-char (N)
13031 "Like `delete-char', but insert whitespace at field end in tables.
13032 When deleting characters, in tables this function will insert whitespace in
13033 front of the next \"|\" separator, to keep the table aligned. The table will
13034 still be marked for re-alignment if the field did fill the entire column,
13035 because, in this case the deletion might narrow the column."
13036 (interactive "p")
13037 (if (and (org-table-p)
13038 (not (bolp))
13039 (not (= (char-after) ?|))
13040 (eq N 1))
13041 (if (looking-at ".*?|")
13042 (let ((pos (point))
13043 (noalign (looking-at "[^|\n\r]* |"))
13044 (c org-table-may-need-update))
13045 (replace-match (concat
13046 (substring (match-string 0) 1 -1)
13047 " |"))
13048 (goto-char pos)
13049 ;; noalign: if there were two spaces at the end, this field
13050 ;; does not determine the width of the column.
13051 (if noalign (setq org-table-may-need-update c)))
13052 (delete-char N))
13053 (delete-char N)
13054 (org-fix-tags-on-the-fly)))
13056 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13057 (put 'org-self-insert-command 'delete-selection t)
13058 (put 'orgtbl-self-insert-command 'delete-selection t)
13059 (put 'org-delete-char 'delete-selection 'supersede)
13060 (put 'org-delete-backward-char 'delete-selection 'supersede)
13061 (put 'org-yank 'delete-selection 'yank)
13063 ;; Make `flyspell-mode' delay after some commands
13064 (put 'org-self-insert-command 'flyspell-delayed t)
13065 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13066 (put 'org-delete-char 'flyspell-delayed t)
13067 (put 'org-delete-backward-char 'flyspell-delayed t)
13069 ;; Make pabbrev-mode expand after org-mode commands
13070 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13071 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13073 ;; How to do this: Measure non-white length of current string
13074 ;; If equal to column width, we should realign.
13076 (defun org-remap (map &rest commands)
13077 "In MAP, remap the functions given in COMMANDS.
13078 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13079 (let (new old)
13080 (while commands
13081 (setq old (pop commands) new (pop commands))
13082 (if (fboundp 'command-remapping)
13083 (org-defkey map (vector 'remap old) new)
13084 (substitute-key-definition old new map global-map)))))
13086 (when (eq org-enable-table-editor 'optimized)
13087 ;; If the user wants maximum table support, we need to hijack
13088 ;; some standard editing functions
13089 (org-remap org-mode-map
13090 'self-insert-command 'org-self-insert-command
13091 'delete-char 'org-delete-char
13092 'delete-backward-char 'org-delete-backward-char)
13093 (org-defkey org-mode-map "|" 'org-force-self-insert))
13095 (defun org-modifier-cursor-error ()
13096 "Throw an error, a modified cursor command was applied in wrong context."
13097 (error "This command is active in special context like tables, headlines or items"))
13099 (defun org-shiftselect-error ()
13100 "Throw an error because Shift-Cursor command was applied in wrong context."
13101 (if (and (boundp 'shift-select-mode) shift-select-mode)
13102 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13103 (error "This command works only in special context like headlines or timestamps.")))
13105 (defun org-call-for-shift-select (cmd)
13106 (let ((this-command-keys-shift-translated t))
13107 (call-interactively cmd)))
13109 (defun org-shifttab (&optional arg)
13110 "Global visibility cycling or move to previous table field.
13111 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13112 on context.
13113 See the individual commands for more information."
13114 (interactive "P")
13115 (cond
13116 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13117 ((integerp arg)
13118 (message "Content view to level: %d" arg)
13119 (org-content (prefix-numeric-value arg))
13120 (setq org-cycle-global-status 'overview))
13121 (t (call-interactively 'org-global-cycle))))
13123 (defun org-shiftmetaleft ()
13124 "Promote subtree or delete table column.
13125 Calls `org-promote-subtree', `org-outdent-item',
13126 or `org-table-delete-column', depending on context.
13127 See the individual commands for more information."
13128 (interactive)
13129 (cond
13130 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13131 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13132 ((org-at-item-p) (call-interactively 'org-outdent-item))
13133 (t (org-modifier-cursor-error))))
13135 (defun org-shiftmetaright ()
13136 "Demote subtree or insert table column.
13137 Calls `org-demote-subtree', `org-indent-item',
13138 or `org-table-insert-column', depending on context.
13139 See the individual commands for more information."
13140 (interactive)
13141 (cond
13142 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13143 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13144 ((org-at-item-p) (call-interactively 'org-indent-item))
13145 (t (org-modifier-cursor-error))))
13147 (defun org-shiftmetaup (&optional arg)
13148 "Move subtree up or kill table row.
13149 Calls `org-move-subtree-up' or `org-table-kill-row' or
13150 `org-move-item-up' depending on context. See the individual commands
13151 for more information."
13152 (interactive "P")
13153 (cond
13154 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13155 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13156 ((org-at-item-p) (call-interactively 'org-move-item-up))
13157 (t (org-modifier-cursor-error))))
13158 (defun org-shiftmetadown (&optional arg)
13159 "Move subtree down or insert table row.
13160 Calls `org-move-subtree-down' or `org-table-insert-row' or
13161 `org-move-item-down', depending on context. See the individual
13162 commands for more information."
13163 (interactive "P")
13164 (cond
13165 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13166 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13167 ((org-at-item-p) (call-interactively 'org-move-item-down))
13168 (t (org-modifier-cursor-error))))
13170 (defun org-metaleft (&optional arg)
13171 "Promote heading or move table column to left.
13172 Calls `org-do-promote' or `org-table-move-column', depending on context.
13173 With no specific context, calls the Emacs default `backward-word'.
13174 See the individual commands for more information."
13175 (interactive "P")
13176 (cond
13177 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13178 ((or (org-on-heading-p) (org-region-active-p))
13179 (call-interactively 'org-do-promote))
13180 ((org-at-item-p) (call-interactively 'org-outdent-item))
13181 (t (call-interactively 'backward-word))))
13183 (defun org-metaright (&optional arg)
13184 "Demote subtree or move table column to right.
13185 Calls `org-do-demote' or `org-table-move-column', depending on context.
13186 With no specific context, calls the Emacs default `forward-word'.
13187 See the individual commands for more information."
13188 (interactive "P")
13189 (cond
13190 ((org-at-table-p) (call-interactively 'org-table-move-column))
13191 ((or (org-on-heading-p) (org-region-active-p))
13192 (call-interactively 'org-do-demote))
13193 ((org-at-item-p) (call-interactively 'org-indent-item))
13194 (t (call-interactively 'forward-word))))
13196 (defun org-metaup (&optional arg)
13197 "Move subtree up or move table row up.
13198 Calls `org-move-subtree-up' or `org-table-move-row' or
13199 `org-move-item-up', depending on context. See the individual commands
13200 for more information."
13201 (interactive "P")
13202 (cond
13203 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13204 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13205 ((org-at-item-p) (call-interactively 'org-move-item-up))
13206 (t (transpose-lines 1) (beginning-of-line -1))))
13208 (defun org-metadown (&optional arg)
13209 "Move subtree down or move table row down.
13210 Calls `org-move-subtree-down' or `org-table-move-row' or
13211 `org-move-item-down', depending on context. See the individual
13212 commands for more information."
13213 (interactive "P")
13214 (cond
13215 ((org-at-table-p) (call-interactively 'org-table-move-row))
13216 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13217 ((org-at-item-p) (call-interactively 'org-move-item-down))
13218 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13220 (defun org-shiftup (&optional arg)
13221 "Increase item in timestamp or increase priority of current headline.
13222 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13223 depending on context. See the individual commands for more information."
13224 (interactive "P")
13225 (cond
13226 ((and org-support-shift-select (org-region-active-p))
13227 (org-call-for-shift-select 'previous-line))
13228 ((org-at-timestamp-p t)
13229 (call-interactively (if org-edit-timestamp-down-means-later
13230 'org-timestamp-down 'org-timestamp-up)))
13231 ((and (not (eq org-support-shift-select 'always))
13232 (org-on-heading-p))
13233 (call-interactively 'org-priority-up))
13234 ((and (not org-support-shift-select) (org-at-item-p))
13235 (call-interactively 'org-previous-item))
13236 ((org-clocktable-try-shift 'up arg))
13237 (org-support-shift-select
13238 (org-call-for-shift-select 'previous-line))
13239 (t (org-shiftselect-error))))
13241 (defun org-shiftdown (&optional arg)
13242 "Decrease item in timestamp or decrease priority of current headline.
13243 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13244 depending on context. See the individual commands for more information."
13245 (interactive "P")
13246 (cond
13247 ((and org-support-shift-select (org-region-active-p))
13248 (org-call-for-shift-select 'next-line))
13249 ((org-at-timestamp-p t)
13250 (call-interactively (if org-edit-timestamp-down-means-later
13251 'org-timestamp-up 'org-timestamp-down)))
13252 ((and (not (eq org-support-shift-select 'always))
13253 (org-on-heading-p))
13254 (call-interactively 'org-priority-down))
13255 ((and (not org-support-shift-select) (org-at-item-p))
13256 (call-interactively 'org-next-item))
13257 ((org-clocktable-try-shift 'down arg))
13258 (org-support-shift-select
13259 (org-call-for-shift-select 'next-line))
13260 (t (org-shiftselect-error))))
13262 (defun org-shiftright (&optional arg)
13263 "Cycle the thing at point or in the current line, depending on context.
13264 Depending on context, this does one of the following:
13266 - switch a timestamp at point one day into the future
13267 - on a headline, switch to the next TODO keyword.
13268 - on an item, switch entire list to the next bullet type
13269 - on a property line, switch to the next allowed value
13270 - on a clocktable definition line, move time block into the future"
13271 (interactive "P")
13272 (cond
13273 ((and org-support-shift-select (org-region-active-p))
13274 (org-call-for-shift-select 'forward-char))
13275 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13276 ((and (not (eq org-support-shift-select 'always))
13277 (org-on-heading-p))
13278 (org-call-with-arg 'org-todo 'right))
13279 ((or (and org-support-shift-select
13280 (not (eq org-support-shift-select 'always))
13281 (org-at-item-bullet-p))
13282 (and (not org-support-shift-select) (org-at-item-p)))
13283 (org-call-with-arg 'org-cycle-list-bullet nil))
13284 ((and (not (eq org-support-shift-select 'always))
13285 (org-at-property-p))
13286 (call-interactively 'org-property-next-allowed-value))
13287 ((org-clocktable-try-shift 'right arg))
13288 (org-support-shift-select
13289 (org-call-for-shift-select 'forward-char))
13290 (t (org-shiftselect-error))))
13292 (defun org-shiftleft (&optional arg)
13293 "Cycle the thing at point or in the current line, depending on context.
13294 Depending on context, this does one of the following:
13296 - switch a timestamp at point one day into the past
13297 - on a headline, switch to the previous TODO keyword.
13298 - on an item, switch entire list to the previous bullet type
13299 - on a property line, switch to the previous allowed value
13300 - on a clocktable definition line, move time block into the past"
13301 (interactive "P")
13302 (cond
13303 ((and org-support-shift-select (org-region-active-p))
13304 (org-call-for-shift-select 'backward-char))
13305 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13306 ((and (not (eq org-support-shift-select 'always))
13307 (org-on-heading-p))
13308 (org-call-with-arg 'org-todo 'left))
13309 ((or (and org-support-shift-select
13310 (not (eq org-support-shift-select 'always))
13311 (org-at-item-bullet-p))
13312 (and (not org-support-shift-select) (org-at-item-p)))
13313 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13314 ((and (not (eq org-support-shift-select 'always))
13315 (org-at-property-p))
13316 (call-interactively 'org-property-previous-allowed-value))
13317 ((org-clocktable-try-shift 'left arg))
13318 (org-support-shift-select
13319 (org-call-for-shift-select 'backward-char))
13320 (t (org-shiftselect-error))))
13322 (defun org-shiftcontrolright ()
13323 "Switch to next TODO set."
13324 (interactive)
13325 (cond
13326 ((and org-support-shift-select (org-region-active-p))
13327 (org-call-for-shift-select 'forward-word))
13328 ((and (not (eq org-support-shift-select 'always))
13329 (org-on-heading-p))
13330 (org-call-with-arg 'org-todo 'nextset))
13331 (org-support-shift-select
13332 (org-call-for-shift-select 'forward-word))
13333 (t (org-shiftselect-error))))
13335 (defun org-shiftcontrolleft ()
13336 "Switch to previous TODO set."
13337 (interactive)
13338 (cond
13339 ((and org-support-shift-select (org-region-active-p))
13340 (org-call-for-shift-select 'backward-word))
13341 ((and (not (eq org-support-shift-select 'always))
13342 (org-on-heading-p))
13343 (org-call-with-arg 'org-todo 'previousset))
13344 (org-support-shift-select
13345 (org-call-for-shift-select 'backward-word))
13346 (t (org-shiftselect-error))))
13348 (defun org-ctrl-c-ret ()
13349 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13350 (interactive)
13351 (cond
13352 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13353 (t (call-interactively 'org-insert-heading))))
13355 (defun org-copy-special ()
13356 "Copy region in table or copy current subtree.
13357 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13358 See the individual commands for more information."
13359 (interactive)
13360 (call-interactively
13361 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13363 (defun org-cut-special ()
13364 "Cut region in table or cut current subtree.
13365 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13366 See the individual commands for more information."
13367 (interactive)
13368 (call-interactively
13369 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13371 (defun org-paste-special (arg)
13372 "Paste rectangular region into table, or past subtree relative to level.
13373 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13374 See the individual commands for more information."
13375 (interactive "P")
13376 (if (org-at-table-p)
13377 (org-table-paste-rectangle)
13378 (org-paste-subtree arg)))
13380 (defun org-edit-special ()
13381 "Call a special editor for the stuff at point.
13382 When at a table, call the formula editor with `org-table-edit-formulas'.
13383 When at the first line of an src example, call `org-edit-src-code'.
13384 When in an #+include line, visit the include file. Otherwise call
13385 `ffap' to visit the file at point."
13386 (interactive)
13387 (cond
13388 ((org-at-table-p)
13389 (call-interactively 'org-table-edit-formulas))
13390 ((save-excursion
13391 (beginning-of-line 1)
13392 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13393 (find-file (org-trim (match-string 1))))
13394 ((org-edit-src-code))
13395 ((org-edit-fixed-width-region))
13396 (t (call-interactively 'ffap))))
13398 (defun org-ctrl-c-ctrl-c (&optional arg)
13399 "Set tags in headline, or update according to changed information at point.
13401 This command does many different things, depending on context:
13403 - If the cursor is in a headline, prompt for tags and insert them
13404 into the current line, aligned to `org-tags-column'. When called
13405 with prefix arg, realign all tags in the current buffer.
13407 - If the cursor is in one of the special #+KEYWORD lines, this
13408 triggers scanning the buffer for these lines and updating the
13409 information.
13411 - If the cursor is inside a table, realign the table. This command
13412 works even if the automatic table editor has been turned off.
13414 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13415 the entire table.
13417 - If the cursor is at a footnote reference or definition, jump to
13418 the corresponding definition or references, respectively.
13420 - If the cursor is a the beginning of a dynamic block, update it.
13422 - If the cursor is inside a table created by the table.el package,
13423 activate that table.
13425 - If the current buffer is a remember buffer, close note and file
13426 it. A prefix argument of 1 files to the default location
13427 without further interaction. A prefix argument of 2 files to
13428 the currently clocking task.
13430 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13431 links in this buffer.
13433 - If the cursor is on a numbered item in a plain list, renumber the
13434 ordered list.
13436 - If the cursor is on a checkbox, toggle it."
13437 (interactive "P")
13438 (let ((org-enable-table-editor t))
13439 (cond
13440 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13441 org-occur-highlights
13442 org-latex-fragment-image-overlays)
13443 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13444 (org-remove-occur-highlights)
13445 (org-remove-latex-fragment-image-overlays)
13446 (message "Temporary highlights/overlays removed from current buffer"))
13447 ((and (local-variable-p 'org-finish-function (current-buffer))
13448 (fboundp org-finish-function))
13449 (funcall org-finish-function))
13450 ((org-at-property-p)
13451 (call-interactively 'org-property-action))
13452 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13453 ((org-on-heading-p) (call-interactively 'org-set-tags))
13454 ((org-at-table.el-p)
13455 (require 'table)
13456 (beginning-of-line 1)
13457 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13458 (call-interactively 'table-recognize-table))
13459 ((org-at-table-p)
13460 (org-table-maybe-eval-formula)
13461 (if arg
13462 (call-interactively 'org-table-recalculate)
13463 (org-table-maybe-recalculate-line))
13464 (call-interactively 'org-table-align))
13465 ((or (org-footnote-at-reference-p)
13466 (org-footnote-at-definition-p))
13467 (call-interactively 'org-footnote-action))
13468 ((org-at-item-checkbox-p)
13469 (call-interactively 'org-toggle-checkbox))
13470 ((org-at-item-p)
13471 (call-interactively 'org-maybe-renumber-ordered-list))
13472 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13473 ;; Dynamic block
13474 (beginning-of-line 1)
13475 (save-excursion (org-update-dblock)))
13476 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13477 (cond
13478 ((equal (match-string 1) "TBLFM")
13479 ;; Recalculate the table before this line
13480 (save-excursion
13481 (beginning-of-line 1)
13482 (skip-chars-backward " \r\n\t")
13483 (if (org-at-table-p)
13484 (org-call-with-arg 'org-table-recalculate t))))
13486 ; (org-set-regexps-and-options)
13487 ; (org-restart-font-lock)
13488 (let ((org-inhibit-startup t)) (org-mode-restart))
13489 (message "Local setup has been refreshed"))))
13490 (t (error "C-c C-c can do nothing useful at this location.")))))
13492 (defun org-mode-restart ()
13493 "Restart Org-mode, to scan again for special lines.
13494 Also updates the keyword regular expressions."
13495 (interactive)
13496 (org-mode)
13497 (message "Org-mode restarted"))
13499 (defun org-kill-note-or-show-branches ()
13500 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13501 (interactive)
13502 (if (not org-finish-function)
13503 (call-interactively 'show-branches)
13504 (let ((org-note-abort t))
13505 (funcall org-finish-function))))
13507 (defun org-return (&optional indent)
13508 "Goto next table row or insert a newline.
13509 Calls `org-table-next-row' or `newline', depending on context.
13510 See the individual commands for more information."
13511 (interactive)
13512 (cond
13513 ((bobp) (if indent (newline-and-indent) (newline)))
13514 ((and (org-at-heading-p)
13515 (looking-at
13516 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13517 (org-show-entry)
13518 (end-of-line 1)
13519 (newline))
13520 ((org-at-table-p)
13521 (org-table-justify-field-maybe)
13522 (call-interactively 'org-table-next-row))
13523 (t (if indent (newline-and-indent) (newline)))))
13525 (defun org-return-indent ()
13526 "Goto next table row or insert a newline and indent.
13527 Calls `org-table-next-row' or `newline-and-indent', depending on
13528 context. See the individual commands for more information."
13529 (interactive)
13530 (org-return t))
13532 (defun org-ctrl-c-star ()
13533 "Compute table, or change heading status of lines.
13534 Calls `org-table-recalculate' or `org-toggle-heading',
13535 depending on context."
13536 (interactive)
13537 (cond
13538 ((org-at-table-p)
13539 (call-interactively 'org-table-recalculate))
13541 ;; Convert all lines in region to list items
13542 (call-interactively 'org-toggle-heading))))
13544 (defun org-ctrl-c-minus ()
13545 "Insert separator line in table or modify bullet status of line.
13546 Also turns a plain line or a region of lines into list items.
13547 Calls `org-table-insert-hline', `org-toggle-item', or
13548 `org-cycle-list-bullet', depending on context."
13549 (interactive)
13550 (cond
13551 ((org-at-table-p)
13552 (call-interactively 'org-table-insert-hline))
13553 ((org-region-active-p)
13554 (call-interactively 'org-toggle-item))
13555 ((org-in-item-p)
13556 (call-interactively 'org-cycle-list-bullet))
13558 (call-interactively 'org-toggle-item))))
13560 (defun org-toggle-item ()
13561 "Convert headings or normal lines to items, items to normal lines.
13562 If there is no active region, only the current line is considered.
13564 If the first line in the region is a headline, convert all headlines to items.
13566 If the first line in the region is an item, convert all items to normal lines.
13568 If the first line is normal text, add an item bullet to each line."
13569 (interactive)
13570 (let (l2 l beg end)
13571 (if (org-region-active-p)
13572 (setq beg (region-beginning) end (region-end))
13573 (setq beg (point-at-bol)
13574 end (min (1+ (point-at-eol)) (point-max))))
13575 (save-excursion
13576 (goto-char end)
13577 (setq l2 (org-current-line))
13578 (goto-char beg)
13579 (beginning-of-line 1)
13580 (setq l (1- (org-current-line)))
13581 (if (org-at-item-p)
13582 ;; We already have items, de-itemize
13583 (while (< (setq l (1+ l)) l2)
13584 (when (org-at-item-p)
13585 (goto-char (match-beginning 2))
13586 (delete-region (match-beginning 2) (match-end 2))
13587 (and (looking-at "[ \t]+") (replace-match "")))
13588 (beginning-of-line 2))
13589 (if (org-on-heading-p)
13590 ;; Headings, convert to items
13591 (while (< (setq l (1+ l)) l2)
13592 (if (looking-at org-outline-regexp)
13593 (replace-match "- " t t))
13594 (beginning-of-line 2))
13595 ;; normal lines, turn them into items
13596 (while (< (setq l (1+ l)) l2)
13597 (unless (org-at-item-p)
13598 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13599 (replace-match "\\1- \\2")))
13600 (beginning-of-line 2)))))))
13602 (defun org-toggle-heading (&optional nstars)
13603 "Convert headings to normal text, or items or text to headings.
13604 If there is no active region, only the current line is considered.
13606 If the first line is a heading, remove the stars from all headlines
13607 in the region.
13609 If the first line is a plain list item, turn all plain list items into
13610 headings.
13612 If the first line is a normal line, turn each and every line in the region
13613 into a heading.
13615 When converting a line into a heading, the number of stars is chosen
13616 such that the lines become children of the current entry. However, when
13617 a prefix argument is given, its value determines the number of stars to add."
13618 (interactive "P")
13619 (let (l2 l itemp beg end)
13620 (if (org-region-active-p)
13621 (setq beg (region-beginning) end (region-end))
13622 (setq beg (point-at-bol)
13623 end (min (1+ (point-at-eol)) (point-max))))
13624 (save-excursion
13625 (goto-char end)
13626 (setq l2 (org-current-line))
13627 (goto-char beg)
13628 (beginning-of-line 1)
13629 (setq l (1- (org-current-line)))
13630 (if (org-on-heading-p)
13631 ;; We already have headlines, de-star them
13632 (while (< (setq l (1+ l)) l2)
13633 (when (org-on-heading-p t)
13634 (and (looking-at outline-regexp) (replace-match "")))
13635 (beginning-of-line 2))
13636 (setq itemp (org-at-item-p))
13637 (let* ((stars
13638 (if nstars
13639 (make-string (prefix-numeric-value current-prefix-arg)
13641 (save-excursion
13642 (re-search-backward org-complex-heading-regexp nil t)
13643 (or (match-string 1) "*"))))
13644 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13645 (rpl (concat stars add-stars " ")))
13646 (while (< (setq l (1+ l)) l2)
13647 (if itemp
13648 (and (org-at-item-p) (replace-match rpl t t))
13649 (unless (org-on-heading-p)
13650 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13651 (replace-match (concat rpl (match-string 2))))))
13652 (beginning-of-line 2)))))))
13654 (defun org-meta-return (&optional arg)
13655 "Insert a new heading or wrap a region in a table.
13656 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13657 See the individual commands for more information."
13658 (interactive "P")
13659 (cond
13660 ((org-at-table-p)
13661 (call-interactively 'org-table-wrap-region))
13662 (t (call-interactively 'org-insert-heading))))
13664 ;;; Menu entries
13666 ;; Define the Org-mode menus
13667 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13668 '("Tbl"
13669 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13670 ["Next Field" org-cycle (org-at-table-p)]
13671 ["Previous Field" org-shifttab (org-at-table-p)]
13672 ["Next Row" org-return (org-at-table-p)]
13673 "--"
13674 ["Blank Field" org-table-blank-field (org-at-table-p)]
13675 ["Edit Field" org-table-edit-field (org-at-table-p)]
13676 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13677 "--"
13678 ("Column"
13679 ["Move Column Left" org-metaleft (org-at-table-p)]
13680 ["Move Column Right" org-metaright (org-at-table-p)]
13681 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13682 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13683 ("Row"
13684 ["Move Row Up" org-metaup (org-at-table-p)]
13685 ["Move Row Down" org-metadown (org-at-table-p)]
13686 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13687 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13688 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13689 "--"
13690 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13691 ("Rectangle"
13692 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13693 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13694 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13695 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13696 "--"
13697 ("Calculate"
13698 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13699 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13700 ["Edit Formulas" org-edit-special (org-at-table-p)]
13701 "--"
13702 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13703 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13704 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13705 "--"
13706 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13707 "--"
13708 ["Sum Column/Rectangle" org-table-sum
13709 (or (org-at-table-p) (org-region-active-p))]
13710 ["Which Column?" org-table-current-column (org-at-table-p)])
13711 ["Debug Formulas"
13712 org-table-toggle-formula-debugger
13713 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13714 ["Show Col/Row Numbers"
13715 org-table-toggle-coordinate-overlays
13716 :style toggle
13717 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13718 "--"
13719 ["Create" org-table-create (and (not (org-at-table-p))
13720 org-enable-table-editor)]
13721 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13722 ["Import from File" org-table-import (not (org-at-table-p))]
13723 ["Export to File" org-table-export (org-at-table-p)]
13724 "--"
13725 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13727 (easy-menu-define org-org-menu org-mode-map "Org menu"
13728 '("Org"
13729 ("Show/Hide"
13730 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13731 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13732 ["Sparse Tree..." org-sparse-tree t]
13733 ["Reveal Context" org-reveal t]
13734 ["Show All" show-all t]
13735 "--"
13736 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13737 "--"
13738 ["New Heading" org-insert-heading t]
13739 ("Navigate Headings"
13740 ["Up" outline-up-heading t]
13741 ["Next" outline-next-visible-heading t]
13742 ["Previous" outline-previous-visible-heading t]
13743 ["Next Same Level" outline-forward-same-level t]
13744 ["Previous Same Level" outline-backward-same-level t]
13745 "--"
13746 ["Jump" org-goto t])
13747 ("Edit Structure"
13748 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13749 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13750 "--"
13751 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13752 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13753 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13754 "--"
13755 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13756 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13757 ["Demote Heading" org-metaright (not (org-at-table-p))]
13758 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13759 "--"
13760 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13761 "--"
13762 ["Convert to odd levels" org-convert-to-odd-levels t]
13763 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13764 ("Editing"
13765 ["Emphasis..." org-emphasize t]
13766 ["Edit Source Example" org-edit-special t]
13767 "--"
13768 ["Footnote new/jump" org-footnote-action t]
13769 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13770 ("Archive"
13771 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13772 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13773 ; :active t :keys "C-u C-c C-x C-a"]
13774 ["Sparse trees open ARCHIVE trees"
13775 (setq org-sparse-tree-open-archived-trees
13776 (not org-sparse-tree-open-archived-trees))
13777 :style toggle :selected org-sparse-tree-open-archived-trees]
13778 ["Cycling opens ARCHIVE trees"
13779 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13780 :style toggle :selected org-cycle-open-archived-trees]
13781 "--"
13782 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13783 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13784 ; ["Check and Move Children" (org-archive-subtree '(4))
13785 ; :active t :keys "C-u C-c C-x C-s"]
13787 "--"
13788 ("TODO Lists"
13789 ["TODO/DONE/-" org-todo t]
13790 ("Select keyword"
13791 ["Next keyword" org-shiftright (org-on-heading-p)]
13792 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13793 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13794 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13795 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13796 ["Show TODO Tree" org-show-todo-tree t]
13797 ["Global TODO list" org-todo-list t]
13798 "--"
13799 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
13800 :selected org-enforce-todo-dependencies :style toggle :active t]
13801 "Settings for tree at point"
13802 ["Do Children sequentially" org-toggle-ordered-property :style radio
13803 :selected (ignore-errors (org-entry-get nil "ORDERED"))
13804 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13805 ["Do Children parallel" org-toggle-ordered-property :style radio
13806 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
13807 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13808 "--"
13809 ["Set Priority" org-priority t]
13810 ["Priority Up" org-shiftup t]
13811 ["Priority Down" org-shiftdown t])
13812 ("TAGS and Properties"
13813 ["Set Tags" org-set-tags-command t]
13814 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13815 "--"
13816 ["Set property" org-set-property t]
13817 ["Column view of properties" org-columns t]
13818 ["Insert Column View DBlock" org-insert-columns-dblock t])
13819 ("Dates and Scheduling"
13820 ["Timestamp" org-time-stamp t]
13821 ["Timestamp (inactive)" org-time-stamp-inactive t]
13822 ("Change Date"
13823 ["1 Day Later" org-shiftright t]
13824 ["1 Day Earlier" org-shiftleft t]
13825 ["1 ... Later" org-shiftup t]
13826 ["1 ... Earlier" org-shiftdown t])
13827 ["Compute Time Range" org-evaluate-time-range t]
13828 ["Schedule Item" org-schedule t]
13829 ["Deadline" org-deadline t]
13830 "--"
13831 ["Custom time format" org-toggle-time-stamp-overlays
13832 :style radio :selected org-display-custom-times]
13833 "--"
13834 ["Goto Calendar" org-goto-calendar t]
13835 ["Date from Calendar" org-date-from-calendar t]
13836 "--"
13837 ["Start/Restart Timer" org-timer-start t]
13838 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13839 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13840 ["Insert Timer String" org-timer t]
13841 ["Insert Timer Item" org-timer-item t])
13842 ("Logging work"
13843 ["Clock in" org-clock-in t]
13844 ["Clock out" org-clock-out t]
13845 ["Clock cancel" org-clock-cancel t]
13846 ["Goto running clock" org-clock-goto t]
13847 ["Display times" org-clock-display t]
13848 ["Create clock table" org-clock-report t]
13849 "--"
13850 ["Record DONE time"
13851 (progn (setq org-log-done (not org-log-done))
13852 (message "Switching to %s will %s record a timestamp"
13853 (car org-done-keywords)
13854 (if org-log-done "automatically" "not")))
13855 :style toggle :selected org-log-done])
13856 "--"
13857 ["Agenda Command..." org-agenda t]
13858 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13859 ("File List for Agenda")
13860 ("Special views current file"
13861 ["TODO Tree" org-show-todo-tree t]
13862 ["Check Deadlines" org-check-deadlines t]
13863 ["Timeline" org-timeline t]
13864 ["Tags Tree" org-tags-sparse-tree t])
13865 "--"
13866 ("Hyperlinks"
13867 ["Store Link (Global)" org-store-link t]
13868 ["Insert Link" org-insert-link t]
13869 ["Follow Link" org-open-at-point t]
13870 "--"
13871 ["Next link" org-next-link t]
13872 ["Previous link" org-previous-link t]
13873 "--"
13874 ["Descriptive Links"
13875 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13876 :style radio
13877 :selected (member '(org-link) buffer-invisibility-spec)]
13878 ["Literal Links"
13879 (progn
13880 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13881 :style radio
13882 :selected (not (member '(org-link) buffer-invisibility-spec))])
13883 "--"
13884 ["Export/Publish..." org-export t]
13885 ("LaTeX"
13886 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13887 :selected org-cdlatex-mode]
13888 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13889 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13890 ["Modify math symbol" org-cdlatex-math-modify
13891 (org-inside-LaTeX-fragment-p)]
13892 ["Export LaTeX fragments as images"
13893 (if (featurep 'org-exp)
13894 (setq org-export-with-LaTeX-fragments
13895 (not org-export-with-LaTeX-fragments))
13896 (require 'org-exp))
13897 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13898 org-export-with-LaTeX-fragments)])
13899 "--"
13900 ("Documentation"
13901 ["Show Version" org-version t]
13902 ["Info Documentation" org-info t])
13903 ("Customize"
13904 ["Browse Org Group" org-customize t]
13905 "--"
13906 ["Expand This Menu" org-create-customize-menu
13907 (fboundp 'customize-menu-create)])
13908 "--"
13909 ["Refresh setup" org-mode-restart t]
13912 (defun org-info (&optional node)
13913 "Read documentation for Org-mode in the info system.
13914 With optional NODE, go directly to that node."
13915 (interactive)
13916 (info (format "(org)%s" (or node ""))))
13918 (defun org-install-agenda-files-menu ()
13919 (let ((bl (buffer-list)))
13920 (save-excursion
13921 (while bl
13922 (set-buffer (pop bl))
13923 (if (org-mode-p) (setq bl nil)))
13924 (when (org-mode-p)
13925 (easy-menu-change
13926 '("Org") "File List for Agenda"
13927 (append
13928 (list
13929 ["Edit File List" (org-edit-agenda-file-list) t]
13930 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13931 ["Remove Current File from List" org-remove-file t]
13932 ["Cycle through agenda files" org-cycle-agenda-files t]
13933 ["Occur in all agenda files" org-occur-in-agenda-files t]
13934 "--")
13935 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13937 ;;;; Documentation
13939 ;;;###autoload
13940 (defun org-require-autoloaded-modules ()
13941 (interactive)
13942 (mapc 'require
13943 '(org-agenda org-archive org-attach org-clock org-colview
13944 org-exp org-id org-export-latex org-publish
13945 org-remember org-table org-timer)))
13947 ;;;###autoload
13948 (defun org-customize ()
13949 "Call the customize function with org as argument."
13950 (interactive)
13951 (org-load-modules-maybe)
13952 (org-require-autoloaded-modules)
13953 (customize-browse 'org))
13955 (defun org-create-customize-menu ()
13956 "Create a full customization menu for Org-mode, insert it into the menu."
13957 (interactive)
13958 (org-load-modules-maybe)
13959 (org-require-autoloaded-modules)
13960 (if (fboundp 'customize-menu-create)
13961 (progn
13962 (easy-menu-change
13963 '("Org") "Customize"
13964 `(["Browse Org group" org-customize t]
13965 "--"
13966 ,(customize-menu-create 'org)
13967 ["Set" Custom-set t]
13968 ["Save" Custom-save t]
13969 ["Reset to Current" Custom-reset-current t]
13970 ["Reset to Saved" Custom-reset-saved t]
13971 ["Reset to Standard Settings" Custom-reset-standard t]))
13972 (message "\"Org\"-menu now contains full customization menu"))
13973 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13975 ;;;; Miscellaneous stuff
13977 ;;; Generally useful functions
13979 (defun org-find-text-property-in-string (prop s)
13980 "Return the first non-nil value of property PROP in string S."
13981 (or (get-text-property 0 prop s)
13982 (get-text-property (or (next-single-property-change 0 prop s) 0)
13983 prop s)))
13985 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13986 "Display the given MESSAGE as a warning."
13987 (if (fboundp 'display-warning)
13988 (display-warning 'org message
13989 (if (featurep 'xemacs)
13990 'warning
13991 :warning))
13992 (let ((buf (get-buffer-create "*Org warnings*")))
13993 (with-current-buffer buf
13994 (goto-char (point-max))
13995 (insert "Warning (Org): " message)
13996 (unless (bolp)
13997 (newline)))
13998 (display-buffer buf)
13999 (sit-for 0))))
14001 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14002 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14003 (if (and marker (marker-buffer marker)
14004 (buffer-live-p (marker-buffer marker)))
14005 (progn
14006 (switch-to-buffer (marker-buffer marker))
14007 (if (or (> marker (point-max)) (< marker (point-min)))
14008 (widen))
14009 (goto-char marker)
14010 (org-show-context 'org-goto))
14011 (if bookmark
14012 (bookmark-jump bookmark)
14013 (error "Cannot find location"))))
14015 (defun org-quote-csv-field (s)
14016 "Quote field for inclusion in CSV material."
14017 (if (string-match "[\",]" s)
14018 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14021 (defun org-plist-delete (plist property)
14022 "Delete PROPERTY from PLIST.
14023 This is in contrast to merely setting it to 0."
14024 (let (p)
14025 (while plist
14026 (if (not (eq property (car plist)))
14027 (setq p (plist-put p (car plist) (nth 1 plist))))
14028 (setq plist (cddr plist)))
14031 (defun org-force-self-insert (N)
14032 "Needed to enforce self-insert under remapping."
14033 (interactive "p")
14034 (self-insert-command N))
14036 (defun org-string-width (s)
14037 "Compute width of string, ignoring invisible characters.
14038 This ignores character with invisibility property `org-link', and also
14039 characters with property `org-cwidth', because these will become invisible
14040 upon the next fontification round."
14041 (let (b l)
14042 (when (or (eq t buffer-invisibility-spec)
14043 (assq 'org-link buffer-invisibility-spec))
14044 (while (setq b (text-property-any 0 (length s)
14045 'invisible 'org-link s))
14046 (setq s (concat (substring s 0 b)
14047 (substring s (or (next-single-property-change
14048 b 'invisible s) (length s)))))))
14049 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14050 (setq s (concat (substring s 0 b)
14051 (substring s (or (next-single-property-change
14052 b 'org-cwidth s) (length s))))))
14053 (setq l (string-width s) b -1)
14054 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14055 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14058 (defun org-get-indentation (&optional line)
14059 "Get the indentation of the current line, interpreting tabs.
14060 When LINE is given, assume it represents a line and compute its indentation."
14061 (if line
14062 (if (string-match "^ *" (org-remove-tabs line))
14063 (match-end 0))
14064 (save-excursion
14065 (beginning-of-line 1)
14066 (skip-chars-forward " \t")
14067 (current-column))))
14069 (defun org-remove-tabs (s &optional width)
14070 "Replace tabulators in S with spaces.
14071 Assumes that s is a single line, starting in column 0."
14072 (setq width (or width tab-width))
14073 (while (string-match "\t" s)
14074 (setq s (replace-match
14075 (make-string
14076 (- (* width (/ (+ (match-beginning 0) width) width))
14077 (match-beginning 0)) ?\ )
14078 t t s)))
14081 (defun org-fix-indentation (line ind)
14082 "Fix indentation in LINE.
14083 IND is a cons cell with target and minimum indentation.
14084 If the current indentation in LINE is smaller than the minimum,
14085 leave it alone. If it is larger than ind, set it to the target."
14086 (let* ((l (org-remove-tabs line))
14087 (i (org-get-indentation l))
14088 (i1 (car ind)) (i2 (cdr ind)))
14089 (if (>= i i2) (setq l (substring line i2)))
14090 (if (> i1 0)
14091 (concat (make-string i1 ?\ ) l)
14092 l)))
14094 (defun org-base-buffer (buffer)
14095 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14096 (if (not buffer)
14097 buffer
14098 (or (buffer-base-buffer buffer)
14099 buffer)))
14101 (defun org-trim (s)
14102 "Remove whitespace at beginning and end of string."
14103 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14104 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14107 (defun org-wrap (string &optional width lines)
14108 "Wrap string to either a number of lines, or a width in characters.
14109 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14110 that costs. If there is a word longer than WIDTH, the text is actually
14111 wrapped to the length of that word.
14112 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14113 many lines, whatever width that takes.
14114 The return value is a list of lines, without newlines at the end."
14115 (let* ((words (org-split-string string "[ \t\n]+"))
14116 (maxword (apply 'max (mapcar 'org-string-width words)))
14117 w ll)
14118 (cond (width
14119 (org-do-wrap words (max maxword width)))
14120 (lines
14121 (setq w maxword)
14122 (setq ll (org-do-wrap words maxword))
14123 (if (<= (length ll) lines)
14125 (setq ll words)
14126 (while (> (length ll) lines)
14127 (setq w (1+ w))
14128 (setq ll (org-do-wrap words w)))
14129 ll))
14130 (t (error "Cannot wrap this")))))
14132 (defun org-do-wrap (words width)
14133 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14134 (let (lines line)
14135 (while words
14136 (setq line (pop words))
14137 (while (and words (< (+ (length line) (length (car words))) width))
14138 (setq line (concat line " " (pop words))))
14139 (setq lines (push line lines)))
14140 (nreverse lines)))
14142 (defun org-split-string (string &optional separators)
14143 "Splits STRING into substrings at SEPARATORS.
14144 No empty strings are returned if there are matches at the beginning
14145 and end of string."
14146 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14147 (start 0)
14148 notfirst
14149 (list nil))
14150 (while (and (string-match rexp string
14151 (if (and notfirst
14152 (= start (match-beginning 0))
14153 (< start (length string)))
14154 (1+ start) start))
14155 (< (match-beginning 0) (length string)))
14156 (setq notfirst t)
14157 (or (eq (match-beginning 0) 0)
14158 (and (eq (match-beginning 0) (match-end 0))
14159 (eq (match-beginning 0) start))
14160 (setq list
14161 (cons (substring string start (match-beginning 0))
14162 list)))
14163 (setq start (match-end 0)))
14164 (or (eq start (length string))
14165 (setq list
14166 (cons (substring string start)
14167 list)))
14168 (nreverse list)))
14170 (defun org-context ()
14171 "Return a list of contexts of the current cursor position.
14172 If several contexts apply, all are returned.
14173 Each context entry is a list with a symbol naming the context, and
14174 two positions indicating start and end of the context. Possible
14175 contexts are:
14177 :headline anywhere in a headline
14178 :headline-stars on the leading stars in a headline
14179 :todo-keyword on a TODO keyword (including DONE) in a headline
14180 :tags on the TAGS in a headline
14181 :priority on the priority cookie in a headline
14182 :item on the first line of a plain list item
14183 :item-bullet on the bullet/number of a plain list item
14184 :checkbox on the checkbox in a plain list item
14185 :table in an org-mode table
14186 :table-special on a special filed in a table
14187 :table-table in a table.el table
14188 :link on a hyperlink
14189 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14190 :target on a <<target>>
14191 :radio-target on a <<<radio-target>>>
14192 :latex-fragment on a LaTeX fragment
14193 :latex-preview on a LaTeX fragment with overlayed preview image
14195 This function expects the position to be visible because it uses font-lock
14196 faces as a help to recognize the following contexts: :table-special, :link,
14197 and :keyword."
14198 (let* ((f (get-text-property (point) 'face))
14199 (faces (if (listp f) f (list f)))
14200 (p (point)) clist o)
14201 ;; First the large context
14202 (cond
14203 ((org-on-heading-p t)
14204 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14205 (when (progn
14206 (beginning-of-line 1)
14207 (looking-at org-todo-line-tags-regexp))
14208 (push (org-point-in-group p 1 :headline-stars) clist)
14209 (push (org-point-in-group p 2 :todo-keyword) clist)
14210 (push (org-point-in-group p 4 :tags) clist))
14211 (goto-char p)
14212 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14213 (if (looking-at "\\[#[A-Z0-9]\\]")
14214 (push (org-point-in-group p 0 :priority) clist)))
14216 ((org-at-item-p)
14217 (push (org-point-in-group p 2 :item-bullet) clist)
14218 (push (list :item (point-at-bol)
14219 (save-excursion (org-end-of-item) (point)))
14220 clist)
14221 (and (org-at-item-checkbox-p)
14222 (push (org-point-in-group p 0 :checkbox) clist)))
14224 ((org-at-table-p)
14225 (push (list :table (org-table-begin) (org-table-end)) clist)
14226 (if (memq 'org-formula faces)
14227 (push (list :table-special
14228 (previous-single-property-change p 'face)
14229 (next-single-property-change p 'face)) clist)))
14230 ((org-at-table-p 'any)
14231 (push (list :table-table) clist)))
14232 (goto-char p)
14234 ;; Now the small context
14235 (cond
14236 ((org-at-timestamp-p)
14237 (push (org-point-in-group p 0 :timestamp) clist))
14238 ((memq 'org-link faces)
14239 (push (list :link
14240 (previous-single-property-change p 'face)
14241 (next-single-property-change p 'face)) clist))
14242 ((memq 'org-special-keyword faces)
14243 (push (list :keyword
14244 (previous-single-property-change p 'face)
14245 (next-single-property-change p 'face)) clist))
14246 ((org-on-target-p)
14247 (push (org-point-in-group p 0 :target) clist)
14248 (goto-char (1- (match-beginning 0)))
14249 (if (looking-at org-radio-target-regexp)
14250 (push (org-point-in-group p 0 :radio-target) clist))
14251 (goto-char p))
14252 ((setq o (car (delq nil
14253 (mapcar
14254 (lambda (x)
14255 (if (memq x org-latex-fragment-image-overlays) x))
14256 (org-overlays-at (point))))))
14257 (push (list :latex-fragment
14258 (org-overlay-start o) (org-overlay-end o)) clist)
14259 (push (list :latex-preview
14260 (org-overlay-start o) (org-overlay-end o)) clist))
14261 ((org-inside-LaTeX-fragment-p)
14262 ;; FIXME: positions wrong.
14263 (push (list :latex-fragment (point) (point)) clist)))
14265 (setq clist (nreverse (delq nil clist)))
14266 clist))
14268 ;; FIXME: Compare with at-regexp-p Do we need both?
14269 (defun org-in-regexp (re &optional nlines visually)
14270 "Check if point is inside a match of regexp.
14271 Normally only the current line is checked, but you can include NLINES extra
14272 lines both before and after point into the search.
14273 If VISUALLY is set, require that the cursor is not after the match but
14274 really on, so that the block visually is on the match."
14275 (catch 'exit
14276 (let ((pos (point))
14277 (eol (point-at-eol (+ 1 (or nlines 0))))
14278 (inc (if visually 1 0)))
14279 (save-excursion
14280 (beginning-of-line (- 1 (or nlines 0)))
14281 (while (re-search-forward re eol t)
14282 (if (and (<= (match-beginning 0) pos)
14283 (>= (+ inc (match-end 0)) pos))
14284 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14286 (defun org-at-regexp-p (regexp)
14287 "Is point inside a match of REGEXP in the current line?"
14288 (catch 'exit
14289 (save-excursion
14290 (let ((pos (point)) (end (point-at-eol)))
14291 (beginning-of-line 1)
14292 (while (re-search-forward regexp end t)
14293 (if (and (<= (match-beginning 0) pos)
14294 (>= (match-end 0) pos))
14295 (throw 'exit t)))
14296 nil))))
14298 (defun org-occur-in-agenda-files (regexp &optional nlines)
14299 "Call `multi-occur' with buffers for all agenda files."
14300 (interactive "sOrg-files matching: \np")
14301 (let* ((files (org-agenda-files))
14302 (tnames (mapcar 'file-truename files))
14303 (extra org-agenda-text-search-extra-files)
14305 (when (eq (car extra) 'agenda-archives)
14306 (setq extra (cdr extra))
14307 (setq files (org-add-archive-files files)))
14308 (while (setq f (pop extra))
14309 (unless (member (file-truename f) tnames)
14310 (add-to-list 'files f 'append)
14311 (add-to-list 'tnames (file-truename f) 'append)))
14312 (multi-occur
14313 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14314 regexp)))
14316 (if (boundp 'occur-mode-find-occurrence-hook)
14317 ;; Emacs 23
14318 (add-hook 'occur-mode-find-occurrence-hook
14319 (lambda ()
14320 (when (org-mode-p)
14321 (org-reveal))))
14322 ;; Emacs 22
14323 (defadvice occur-mode-goto-occurrence
14324 (after org-occur-reveal activate)
14325 (and (org-mode-p) (org-reveal)))
14326 (defadvice occur-mode-goto-occurrence-other-window
14327 (after org-occur-reveal activate)
14328 (and (org-mode-p) (org-reveal)))
14329 (defadvice occur-mode-display-occurrence
14330 (after org-occur-reveal activate)
14331 (when (org-mode-p)
14332 (let ((pos (occur-mode-find-occurrence)))
14333 (with-current-buffer (marker-buffer pos)
14334 (save-excursion
14335 (goto-char pos)
14336 (org-reveal)))))))
14338 (defun org-uniquify (list)
14339 "Remove duplicate elements from LIST."
14340 (let (res)
14341 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14342 res))
14344 (defun org-delete-all (elts list)
14345 "Remove all elements in ELTS from LIST."
14346 (while elts
14347 (setq list (delete (pop elts) list)))
14348 list)
14350 (defun org-back-over-empty-lines ()
14351 "Move backwards over whitespace, to the beginning of the first empty line.
14352 Returns the number of empty lines passed."
14353 (let ((pos (point)))
14354 (skip-chars-backward " \t\n\r")
14355 (beginning-of-line 2)
14356 (goto-char (min (point) pos))
14357 (count-lines (point) pos)))
14359 (defun org-skip-whitespace ()
14360 (skip-chars-forward " \t\n\r"))
14362 (defun org-point-in-group (point group &optional context)
14363 "Check if POINT is in match-group GROUP.
14364 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14365 match. If the match group does ot exist or point is not inside it,
14366 return nil."
14367 (and (match-beginning group)
14368 (>= point (match-beginning group))
14369 (<= point (match-end group))
14370 (if context
14371 (list context (match-beginning group) (match-end group))
14372 t)))
14374 (defun org-switch-to-buffer-other-window (&rest args)
14375 "Switch to buffer in a second window on the current frame.
14376 In particular, do not allow pop-up frames."
14377 (let (pop-up-frames special-display-buffer-names special-display-regexps
14378 special-display-function)
14379 (apply 'switch-to-buffer-other-window args)))
14381 (defun org-combine-plists (&rest plists)
14382 "Create a single property list from all plists in PLISTS.
14383 The process starts by copying the first list, and then setting properties
14384 from the other lists. Settings in the last list are the most significant
14385 ones and overrule settings in the other lists."
14386 (let ((rtn (copy-sequence (pop plists)))
14387 p v ls)
14388 (while plists
14389 (setq ls (pop plists))
14390 (while ls
14391 (setq p (pop ls) v (pop ls))
14392 (setq rtn (plist-put rtn p v))))
14393 rtn))
14395 (defun org-move-line-down (arg)
14396 "Move the current line down. With prefix argument, move it past ARG lines."
14397 (interactive "p")
14398 (let ((col (current-column))
14399 beg end pos)
14400 (beginning-of-line 1) (setq beg (point))
14401 (beginning-of-line 2) (setq end (point))
14402 (beginning-of-line (+ 1 arg))
14403 (setq pos (move-marker (make-marker) (point)))
14404 (insert (delete-and-extract-region beg end))
14405 (goto-char pos)
14406 (org-move-to-column col)))
14408 (defun org-move-line-up (arg)
14409 "Move the current line up. With prefix argument, move it past ARG lines."
14410 (interactive "p")
14411 (let ((col (current-column))
14412 beg end pos)
14413 (beginning-of-line 1) (setq beg (point))
14414 (beginning-of-line 2) (setq end (point))
14415 (beginning-of-line (- arg))
14416 (setq pos (move-marker (make-marker) (point)))
14417 (insert (delete-and-extract-region beg end))
14418 (goto-char pos)
14419 (org-move-to-column col)))
14421 (defun org-replace-escapes (string table)
14422 "Replace %-escapes in STRING with values in TABLE.
14423 TABLE is an association list with keys like \"%a\" and string values.
14424 The sequences in STRING may contain normal field width and padding information,
14425 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14426 so values can contain further %-escapes if they are define later in TABLE."
14427 (let ((case-fold-search nil)
14428 e re rpl)
14429 (while (setq e (pop table))
14430 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14431 (while (string-match re string)
14432 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14433 (cdr e)))
14434 (setq string (replace-match rpl t t string))))
14435 string))
14438 (defun org-sublist (list start end)
14439 "Return a section of LIST, from START to END.
14440 Counting starts at 1."
14441 (let (rtn (c start))
14442 (setq list (nthcdr (1- start) list))
14443 (while (and list (<= c end))
14444 (push (pop list) rtn)
14445 (setq c (1+ c)))
14446 (nreverse rtn)))
14448 (defun org-find-base-buffer-visiting (file)
14449 "Like `find-buffer-visiting' but alway return the base buffer and
14450 not an indirect buffer."
14451 (let ((buf (find-buffer-visiting file)))
14452 (if buf
14453 (or (buffer-base-buffer buf) buf)
14454 nil)))
14456 (defun org-image-file-name-regexp (&optional extensions)
14457 "Return regexp matching the file names of images.
14458 If EXTENSIONS is given, only match these."
14459 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14460 (image-file-name-regexp)
14461 (let ((image-file-name-extensions
14462 (or extensions
14463 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14464 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14465 (concat "\\."
14466 (regexp-opt (nconc (mapcar 'upcase
14467 image-file-name-extensions)
14468 image-file-name-extensions)
14470 "\\'"))))
14472 (defun org-file-image-p (file &optional extensions)
14473 "Return non-nil if FILE is an image."
14474 (save-match-data
14475 (string-match (org-image-file-name-regexp extensions) file)))
14477 (defun org-get-cursor-date ()
14478 "Return the date at cursor in as a time.
14479 This works in the calendar and in the agenda, anywhere else it just
14480 returns the current time."
14481 (let (date day defd)
14482 (cond
14483 ((eq major-mode 'calendar-mode)
14484 (setq date (calendar-cursor-to-date)
14485 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14486 ((eq major-mode 'org-agenda-mode)
14487 (setq day (get-text-property (point) 'day))
14488 (if day
14489 (setq date (calendar-gregorian-from-absolute day)
14490 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14491 (nth 2 date))))))
14492 (or defd (current-time))))
14494 (defvar org-agenda-action-marker (make-marker)
14495 "Marker pointing to the entry for the next agenda action.")
14497 (defun org-mark-entry-for-agenda-action ()
14498 "Mark the current entry as target of an agenda action.
14499 Agenda actions are actions executed from the agenda with the key `k',
14500 which make use of the date at the cursor."
14501 (interactive)
14502 (move-marker org-agenda-action-marker
14503 (save-excursion (org-back-to-heading t) (point))
14504 (current-buffer))
14505 (message
14506 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14508 ;;; Paragraph filling stuff.
14509 ;; We want this to be just right, so use the full arsenal.
14511 (defun org-indent-line-function ()
14512 "Indent line like previous, but further if previous was headline or item."
14513 (interactive)
14514 (let* ((pos (point))
14515 (itemp (org-at-item-p))
14516 column bpos bcol tpos tcol bullet btype bullet-type)
14517 ;; Find the previous relevant line
14518 (beginning-of-line 1)
14519 (cond
14520 ((looking-at "#") (setq column 0))
14521 ((looking-at "\\*+ ") (setq column 0))
14523 (beginning-of-line 0)
14524 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14525 (beginning-of-line 0))
14526 (cond
14527 ((looking-at "\\*+[ \t]+")
14528 (if (not org-adapt-indentation)
14529 (setq column 0)
14530 (goto-char (match-end 0))
14531 (setq column (current-column))))
14532 ((org-in-item-p)
14533 (org-beginning-of-item)
14534 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14535 (setq bpos (match-beginning 1) tpos (match-end 0)
14536 bcol (progn (goto-char bpos) (current-column))
14537 tcol (progn (goto-char tpos) (current-column))
14538 bullet (match-string 1)
14539 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14540 (if (> tcol (+ bcol org-description-max-indent))
14541 (setq tcol (+ bcol 5)))
14542 (if (not itemp)
14543 (setq column tcol)
14544 (goto-char pos)
14545 (beginning-of-line 1)
14546 (if (looking-at "\\S-")
14547 (progn
14548 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14549 (setq bullet (match-string 1)
14550 btype (if (string-match "[0-9]" bullet) "n" bullet))
14551 (setq column (if (equal btype bullet-type) bcol tcol)))
14552 (setq column (org-get-indentation)))))
14553 (t (setq column (org-get-indentation))))))
14554 (goto-char pos)
14555 (if (<= (current-column) (current-indentation))
14556 (org-indent-line-to column)
14557 (save-excursion (org-indent-line-to column)))
14558 (setq column (current-column))
14559 (beginning-of-line 1)
14560 (if (looking-at
14561 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14562 (replace-match (concat "\\1" (format org-property-format
14563 (match-string 2) (match-string 3)))
14564 t nil))
14565 (org-move-to-column column)))
14567 (defun org-set-autofill-regexps ()
14568 (interactive)
14569 ;; In the paragraph separator we include headlines, because filling
14570 ;; text in a line directly attached to a headline would otherwise
14571 ;; fill the headline as well.
14572 (org-set-local 'comment-start-skip "^#+[ \t]*")
14573 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14574 ;; The paragraph starter includes hand-formatted lists.
14575 (org-set-local 'paragraph-start
14576 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14577 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14578 ;; But only if the user has not turned off tables or fixed-width regions
14579 (org-set-local
14580 'auto-fill-inhibit-regexp
14581 (concat "\\*+ \\|#\\+"
14582 "\\|[ \t]*" org-keyword-time-regexp
14583 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14584 (concat
14585 "\\|[ \t]*["
14586 (if org-enable-table-editor "|" "")
14587 (if org-enable-fixed-width-editor ":" "")
14588 "]"))))
14589 ;; We use our own fill-paragraph function, to make sure that tables
14590 ;; and fixed-width regions are not wrapped. That function will pass
14591 ;; through to `fill-paragraph' when appropriate.
14592 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14593 ; Adaptive filling: To get full control, first make sure that
14594 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14595 (org-set-local 'adaptive-fill-regexp "\000")
14596 (org-set-local 'adaptive-fill-function
14597 'org-adaptive-fill-function)
14598 (org-set-local
14599 'align-mode-rules-list
14600 '((org-in-buffer-settings
14601 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14602 (modes . '(org-mode))))))
14604 (defun org-fill-paragraph (&optional justify)
14605 "Re-align a table, pass through to fill-paragraph if no table."
14606 (let ((table-p (org-at-table-p))
14607 (table.el-p (org-at-table.el-p)))
14608 (cond ((and (equal (char-after (point-at-bol)) ?*)
14609 (save-excursion (goto-char (point-at-bol))
14610 (looking-at outline-regexp)))
14611 t) ; skip headlines
14612 (table.el-p t) ; skip table.el tables
14613 (table-p (org-table-align) t) ; align org-mode tables
14614 (t nil)))) ; call paragraph-fill
14616 ;; For reference, this is the default value of adaptive-fill-regexp
14617 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14619 (defun org-adaptive-fill-function ()
14620 "Return a fill prefix for org-mode files.
14621 In particular, this makes sure hanging paragraphs for hand-formatted lists
14622 work correctly."
14623 (cond ((looking-at "#[ \t]+")
14624 (match-string 0))
14625 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14626 (save-excursion
14627 (if (> (match-end 1) (+ (match-beginning 1)
14628 org-description-max-indent))
14629 (goto-char (+ (match-beginning 1) 5))
14630 (goto-char (match-end 0)))
14631 (make-string (current-column) ?\ )))
14632 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14633 (save-excursion
14634 (goto-char (match-end 0))
14635 (make-string (current-column) ?\ )))
14636 (t nil)))
14638 ;;; Other stuff.
14640 (defun org-toggle-fixed-width-section (arg)
14641 "Toggle the fixed-width export.
14642 If there is no active region, the QUOTE keyword at the current headline is
14643 inserted or removed. When present, it causes the text between this headline
14644 and the next to be exported as fixed-width text, and unmodified.
14645 If there is an active region, this command adds or removes a colon as the
14646 first character of this line. If the first character of a line is a colon,
14647 this line is also exported in fixed-width font."
14648 (interactive "P")
14649 (let* ((cc 0)
14650 (regionp (org-region-active-p))
14651 (beg (if regionp (region-beginning) (point)))
14652 (end (if regionp (region-end)))
14653 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14654 (case-fold-search nil)
14655 (re "[ \t]*\\(:\\)")
14656 off)
14657 (if regionp
14658 (save-excursion
14659 (goto-char beg)
14660 (setq cc (current-column))
14661 (beginning-of-line 1)
14662 (setq off (looking-at re))
14663 (while (> nlines 0)
14664 (setq nlines (1- nlines))
14665 (beginning-of-line 1)
14666 (cond
14667 (arg
14668 (org-move-to-column cc t)
14669 (insert ":\n")
14670 (forward-line -1))
14671 ((and off (looking-at re))
14672 (replace-match "" t t nil 1))
14673 ((not off) (org-move-to-column cc t) (insert ":")))
14674 (forward-line 1)))
14675 (save-excursion
14676 (org-back-to-heading)
14677 (if (looking-at (concat outline-regexp
14678 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14679 (replace-match "" t t nil 1)
14680 (if (looking-at outline-regexp)
14681 (progn
14682 (goto-char (match-end 0))
14683 (insert org-quote-string " "))))))))
14685 ;;;; Functions extending outline functionality
14687 (defun org-beginning-of-line (&optional arg)
14688 "Go to the beginning of the current line. If that is invisible, continue
14689 to a visible line beginning. This makes the function of C-a more intuitive.
14690 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14691 first attempt, and only move to after the tags when the cursor is already
14692 beyond the end of the headline."
14693 (interactive "P")
14694 (let ((pos (point)) refpos)
14695 (beginning-of-line 1)
14696 (if (bobp)
14698 (backward-char 1)
14699 (if (org-invisible-p)
14700 (while (and (not (bobp)) (org-invisible-p))
14701 (backward-char 1)
14702 (beginning-of-line 1))
14703 (forward-char 1)))
14704 (when org-special-ctrl-a/e
14705 (cond
14706 ((and (looking-at org-complex-heading-regexp)
14707 (= (char-after (match-end 1)) ?\ ))
14708 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14709 (point-at-eol)))
14710 (goto-char
14711 (if (eq org-special-ctrl-a/e t)
14712 (cond ((> pos refpos) refpos)
14713 ((= pos (point)) refpos)
14714 (t (point)))
14715 (cond ((> pos (point)) (point))
14716 ((not (eq last-command this-command)) (point))
14717 (t refpos)))))
14718 ((org-at-item-p)
14719 (goto-char
14720 (if (eq org-special-ctrl-a/e t)
14721 (cond ((> pos (match-end 4)) (match-end 4))
14722 ((= pos (point)) (match-end 4))
14723 (t (point)))
14724 (cond ((> pos (point)) (point))
14725 ((not (eq last-command this-command)) (point))
14726 (t (match-end 4))))))))
14727 (org-no-warnings
14728 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14730 (defun org-end-of-line (&optional arg)
14731 "Go to the end of the line.
14732 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14733 first attempt, and only move to after the tags when the cursor is already
14734 beyond the end of the headline."
14735 (interactive "P")
14736 (if (or (not org-special-ctrl-a/e)
14737 (not (org-on-heading-p)))
14738 (end-of-line arg)
14739 (let ((pos (point)))
14740 (beginning-of-line 1)
14741 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14742 (if (eq org-special-ctrl-a/e t)
14743 (if (or (< pos (match-beginning 1))
14744 (= pos (match-end 0)))
14745 (goto-char (match-beginning 1))
14746 (goto-char (match-end 0)))
14747 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14748 (goto-char (match-end 0))
14749 (goto-char (match-beginning 1))))
14750 (end-of-line arg))))
14751 (org-no-warnings
14752 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14755 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14756 (define-key org-mode-map "\C-e" 'org-end-of-line)
14758 (defun org-kill-line (&optional arg)
14759 "Kill line, to tags or end of line."
14760 (interactive "P")
14761 (cond
14762 ((or (not org-special-ctrl-k)
14763 (bolp)
14764 (not (org-on-heading-p)))
14765 (call-interactively 'kill-line))
14766 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14767 (kill-region (point) (match-beginning 1))
14768 (org-set-tags nil t))
14769 (t (kill-region (point) (point-at-eol)))))
14771 (define-key org-mode-map "\C-k" 'org-kill-line)
14773 (defun org-yank (&optional arg)
14774 "Yank. If the kill is a subtree, treat it specially.
14775 This command will look at the current kill and check if is a single
14776 subtree, or a series of subtrees[1]. If it passes the test, and if the
14777 cursor is at the beginning of a line or after the stars of a currently
14778 empty headline, then the yank is handled specially. How exactly depends
14779 on the value of the following variables, both set by default.
14781 org-yank-folded-subtrees
14782 When set, the subtree(s) will be folded after insertion, but only
14783 if doing so would now swallow text after the yanked text.
14785 org-yank-adjusted-subtrees
14786 When set, the subtree will be promoted or demoted in order to
14787 fit into the local outline tree structure, which means that the level
14788 will be adjusted so that it becomes the smaller one of the two
14789 *visible* surrounding headings.
14791 Any prefix to this command will cause `yank' to be called directly with
14792 no special treatment. In particular, a simple `C-u' prefix will just
14793 plainly yank the text as it is.
14795 \[1] Basically, the test checks if the first non-white line is a heading
14796 and if there are no other headings with fewer stars."
14797 (interactive "P")
14798 (setq this-command 'yank)
14799 (if arg
14800 (call-interactively 'yank)
14801 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14802 (and (org-kill-is-subtree-p)
14803 (or (bolp)
14804 (and (looking-at "[ \t]*$")
14805 (string-match
14806 "\\`\\*+\\'"
14807 (buffer-substring (point-at-bol) (point)))))))
14808 swallowp)
14809 (cond
14810 ((and subtreep org-yank-folded-subtrees)
14811 (let ((beg (point))
14812 end)
14813 (if (and subtreep org-yank-adjusted-subtrees)
14814 (org-paste-subtree nil nil 'for-yank)
14815 (call-interactively 'yank))
14816 (setq end (point))
14817 (goto-char beg)
14818 (when (and (bolp) subtreep
14819 (not (setq swallowp
14820 (org-yank-folding-would-swallow-text beg end))))
14821 (or (looking-at outline-regexp)
14822 (re-search-forward (concat "^" outline-regexp) end t))
14823 (while (and (< (point) end) (looking-at outline-regexp))
14824 (hide-subtree)
14825 (org-cycle-show-empty-lines 'folded)
14826 (condition-case nil
14827 (outline-forward-same-level 1)
14828 (error (goto-char end)))))
14829 (when swallowp
14830 (message
14831 "Yanked text not folded because that would swallow text"))
14832 (goto-char end)
14833 (skip-chars-forward " \t\n\r")
14834 (beginning-of-line 1)
14835 (push-mark beg 'nomsg)))
14836 ((and subtreep org-yank-adjusted-subtrees)
14837 (let ((beg (point-at-bol)))
14838 (org-paste-subtree nil nil 'for-yank)
14839 (push-mark beg 'nomsg)))
14841 (call-interactively 'yank))))))
14843 (defun org-yank-folding-would-swallow-text (beg end)
14844 "Would hide-subtree at BEG swallow any text after END?"
14845 (let (level)
14846 (save-excursion
14847 (goto-char beg)
14848 (when (or (looking-at outline-regexp)
14849 (re-search-forward (concat "^" outline-regexp) end t))
14850 (setq level (org-outline-level)))
14851 (goto-char end)
14852 (skip-chars-forward " \t\r\n\v\f")
14853 (if (or (eobp)
14854 (and (bolp) (looking-at org-outline-regexp)
14855 (<= (org-outline-level) level)))
14856 nil ; Nothing would be swallowed
14857 t)))) ; something would swallow
14859 (define-key org-mode-map "\C-y" 'org-yank)
14861 (defun org-invisible-p ()
14862 "Check if point is at a character currently not visible."
14863 ;; Early versions of noutline don't have `outline-invisible-p'.
14864 (if (fboundp 'outline-invisible-p)
14865 (outline-invisible-p)
14866 (get-char-property (point) 'invisible)))
14868 (defun org-invisible-p2 ()
14869 "Check if point is at a character currently not visible."
14870 (save-excursion
14871 (if (and (eolp) (not (bobp))) (backward-char 1))
14872 ;; Early versions of noutline don't have `outline-invisible-p'.
14873 (if (fboundp 'outline-invisible-p)
14874 (outline-invisible-p)
14875 (get-char-property (point) 'invisible))))
14877 (defun org-back-to-heading (&optional invisible-ok)
14878 "Call `outline-back-to-heading', but provide a better error message."
14879 (condition-case nil
14880 (outline-back-to-heading invisible-ok)
14881 (error (error "Before first headline at position %d in buffer %s"
14882 (point) (current-buffer)))))
14884 (defun org-before-first-heading-p ()
14885 "Before first heading?"
14886 (save-excursion
14887 (null (re-search-backward "^\\*+ " nil t))))
14889 (defalias 'org-on-heading-p 'outline-on-heading-p)
14890 (defalias 'org-at-heading-p 'outline-on-heading-p)
14891 (defun org-at-heading-or-item-p ()
14892 (or (org-on-heading-p) (org-at-item-p)))
14894 (defun org-on-target-p ()
14895 (or (org-in-regexp org-radio-target-regexp)
14896 (org-in-regexp org-target-regexp)))
14898 (defun org-up-heading-all (arg)
14899 "Move to the heading line of which the present line is a subheading.
14900 This function considers both visible and invisible heading lines.
14901 With argument, move up ARG levels."
14902 (if (fboundp 'outline-up-heading-all)
14903 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14904 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14906 (defun org-up-heading-safe ()
14907 "Move to the heading line of which the present line is a subheading.
14908 This version will not throw an error. It will return the level of the
14909 headline found, or nil if no higher level is found."
14910 (let (start-level re)
14911 (org-back-to-heading t)
14912 (setq start-level (funcall outline-level))
14913 (if (equal start-level 1)
14915 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14916 (if (re-search-backward re nil t)
14917 (funcall outline-level)))))
14919 (defun org-first-sibling-p ()
14920 "Is this heading the first child of its parents?"
14921 (interactive)
14922 (let ((re (concat "^" outline-regexp))
14923 level l)
14924 (unless (org-at-heading-p t)
14925 (error "Not at a heading"))
14926 (setq level (funcall outline-level))
14927 (save-excursion
14928 (if (not (re-search-backward re nil t))
14930 (setq l (funcall outline-level))
14931 (< l level)))))
14933 (defun org-goto-sibling (&optional previous)
14934 "Goto the next sibling, even if it is invisible.
14935 When PREVIOUS is set, go to the previous sibling instead. Returns t
14936 when a sibling was found. When none is found, return nil and don't
14937 move point."
14938 (let ((fun (if previous 're-search-backward 're-search-forward))
14939 (pos (point))
14940 (re (concat "^" outline-regexp))
14941 level l)
14942 (when (condition-case nil (org-back-to-heading t) (error nil))
14943 (setq level (funcall outline-level))
14944 (catch 'exit
14945 (or previous (forward-char 1))
14946 (while (funcall fun re nil t)
14947 (setq l (funcall outline-level))
14948 (when (< l level) (goto-char pos) (throw 'exit nil))
14949 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14950 (goto-char pos)
14951 nil))))
14953 (defun org-show-siblings ()
14954 "Show all siblings of the current headline."
14955 (save-excursion
14956 (while (org-goto-sibling) (org-flag-heading nil)))
14957 (save-excursion
14958 (while (org-goto-sibling 'previous)
14959 (org-flag-heading nil))))
14961 (defun org-show-hidden-entry ()
14962 "Show an entry where even the heading is hidden."
14963 (save-excursion
14964 (org-show-entry)))
14966 (defun org-flag-heading (flag &optional entry)
14967 "Flag the current heading. FLAG non-nil means make invisible.
14968 When ENTRY is non-nil, show the entire entry."
14969 (save-excursion
14970 (org-back-to-heading t)
14971 ;; Check if we should show the entire entry
14972 (if entry
14973 (progn
14974 (org-show-entry)
14975 (save-excursion
14976 (and (outline-next-heading)
14977 (org-flag-heading nil))))
14978 (outline-flag-region (max (point-min) (1- (point)))
14979 (save-excursion (outline-end-of-heading) (point))
14980 flag))))
14982 (defun org-forward-same-level (arg)
14983 "Move forward to the ARG'th subheading at same level as this one.
14984 Stop at the first and last subheadings of a superior heading.
14985 This is like outline-forward-same-level, but invisible headings are ok."
14986 (interactive "p")
14987 (org-back-to-heading t)
14988 (while (> arg 0)
14989 (let ((point-to-move-to (save-excursion
14990 (org-get-next-sibling))))
14991 (if point-to-move-to
14992 (progn
14993 (goto-char point-to-move-to)
14994 (setq arg (1- arg)))
14995 (progn
14996 (setq arg 0)
14997 (error "No following same-level heading"))))))
14999 (defun org-get-next-sibling ()
15000 "Move to next heading of the same level, and return point.
15001 If there is no such heading, return nil.
15002 This is like outline-next-sibling, but invisible headings are ok."
15003 (let ((level (funcall outline-level)))
15004 (outline-next-heading)
15005 (while (and (not (eobp)) (> (funcall outline-level) level))
15006 (outline-next-heading))
15007 (if (or (eobp) (< (funcall outline-level) level))
15009 (point))))
15011 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15012 ;; This is an exact copy of the original function, but it uses
15013 ;; `org-back-to-heading', to make it work also in invisible
15014 ;; trees. And is uses an invisible-OK argument.
15015 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15016 (org-back-to-heading invisible-OK)
15017 (let ((first t)
15018 (level (funcall outline-level)))
15019 (while (and (not (eobp))
15020 (or first (> (funcall outline-level) level)))
15021 (setq first nil)
15022 (outline-next-heading))
15023 (unless to-heading
15024 (if (memq (preceding-char) '(?\n ?\^M))
15025 (progn
15026 ;; Go to end of line before heading
15027 (forward-char -1)
15028 (if (memq (preceding-char) '(?\n ?\^M))
15029 ;; leave blank line before heading
15030 (forward-char -1))))))
15031 (point))
15033 (defun org-show-subtree ()
15034 "Show everything after this heading at deeper levels."
15035 (outline-flag-region
15036 (point)
15037 (save-excursion
15038 (outline-end-of-subtree) (outline-next-heading) (point))
15039 nil))
15041 (defun org-show-entry ()
15042 "Show the body directly following this heading.
15043 Show the heading too, if it is currently invisible."
15044 (interactive)
15045 (save-excursion
15046 (condition-case nil
15047 (progn
15048 (org-back-to-heading t)
15049 (outline-flag-region
15050 (max (point-min) (1- (point)))
15051 (save-excursion
15052 (re-search-forward
15053 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15054 (or (match-beginning 1) (point-max)))
15055 nil))
15056 (error nil))))
15058 (defun org-make-options-regexp (kwds)
15059 "Make a regular expression for keyword lines."
15060 (concat
15062 "#?[ \t]*\\+\\("
15063 (mapconcat 'regexp-quote kwds "\\|")
15064 "\\):[ \t]*"
15065 "\\(.+\\)"))
15067 ;; Make isearch reveal the necessary context
15068 (defun org-isearch-end ()
15069 "Reveal context after isearch exits."
15070 (when isearch-success ; only if search was successful
15071 (if (featurep 'xemacs)
15072 ;; Under XEmacs, the hook is run in the correct place,
15073 ;; we directly show the context.
15074 (org-show-context 'isearch)
15075 ;; In Emacs the hook runs *before* restoring the overlays.
15076 ;; So we have to use a one-time post-command-hook to do this.
15077 ;; (Emacs 22 has a special variable, see function `org-mode')
15078 (unless (and (boundp 'isearch-mode-end-hook-quit)
15079 isearch-mode-end-hook-quit)
15080 ;; Only when the isearch was not quitted.
15081 (org-add-hook 'post-command-hook 'org-isearch-post-command
15082 'append 'local)))))
15084 (defun org-isearch-post-command ()
15085 "Remove self from hook, and show context."
15086 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15087 (org-show-context 'isearch))
15090 ;;;; Integration with and fixes for other packages
15092 ;;; Imenu support
15094 (defvar org-imenu-markers nil
15095 "All markers currently used by Imenu.")
15096 (make-variable-buffer-local 'org-imenu-markers)
15098 (defun org-imenu-new-marker (&optional pos)
15099 "Return a new marker for use by Imenu, and remember the marker."
15100 (let ((m (make-marker)))
15101 (move-marker m (or pos (point)))
15102 (push m org-imenu-markers)
15105 (defun org-imenu-get-tree ()
15106 "Produce the index for Imenu."
15107 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15108 (setq org-imenu-markers nil)
15109 (let* ((n org-imenu-depth)
15110 (re (concat "^" outline-regexp))
15111 (subs (make-vector (1+ n) nil))
15112 (last-level 0)
15113 m level head)
15114 (save-excursion
15115 (save-restriction
15116 (widen)
15117 (goto-char (point-max))
15118 (while (re-search-backward re nil t)
15119 (setq level (org-reduced-level (funcall outline-level)))
15120 (when (<= level n)
15121 (looking-at org-complex-heading-regexp)
15122 (setq head (org-link-display-format
15123 (org-match-string-no-properties 4))
15124 m (org-imenu-new-marker))
15125 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15126 (if (>= level last-level)
15127 (push (cons head m) (aref subs level))
15128 (push (cons head (aref subs (1+ level))) (aref subs level))
15129 (loop for i from (1+ level) to n do (aset subs i nil)))
15130 (setq last-level level)))))
15131 (aref subs 1)))
15133 (eval-after-load "imenu"
15134 '(progn
15135 (add-hook 'imenu-after-jump-hook
15136 (lambda ()
15137 (if (eq major-mode 'org-mode)
15138 (org-show-context 'org-goto))))))
15140 (defun org-link-display-format (link)
15141 "Replace a link with either the description, or the link target
15142 if no description is present"
15143 (save-match-data
15144 (if (string-match org-bracket-link-analytic-regexp link)
15145 (replace-match (or (match-string 5 link)
15146 (concat (match-string 1 link)
15147 (match-string 3 link)))
15148 nil nil link)
15149 link)))
15151 ;; Speedbar support
15153 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15154 "Overlay marking the agenda restriction line in speedbar.")
15155 (org-overlay-put org-speedbar-restriction-lock-overlay
15156 'face 'org-agenda-restriction-lock)
15157 (org-overlay-put org-speedbar-restriction-lock-overlay
15158 'help-echo "Agendas are currently limited to this item.")
15159 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15161 (defun org-speedbar-set-agenda-restriction ()
15162 "Restrict future agenda commands to the location at point in speedbar.
15163 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15164 (interactive)
15165 (require 'org-agenda)
15166 (let (p m tp np dir txt)
15167 (cond
15168 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15169 'org-imenu t))
15170 (setq m (get-text-property p 'org-imenu-marker))
15171 (save-excursion
15172 (save-restriction
15173 (set-buffer (marker-buffer m))
15174 (goto-char m)
15175 (org-agenda-set-restriction-lock 'subtree))))
15176 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15177 'speedbar-function 'speedbar-find-file))
15178 (setq tp (previous-single-property-change
15179 (1+ p) 'speedbar-function)
15180 np (next-single-property-change
15181 tp 'speedbar-function)
15182 dir (speedbar-line-directory)
15183 txt (buffer-substring-no-properties (or tp (point-min))
15184 (or np (point-max))))
15185 (save-excursion
15186 (save-restriction
15187 (set-buffer (find-file-noselect
15188 (let ((default-directory dir))
15189 (expand-file-name txt))))
15190 (unless (org-mode-p)
15191 (error "Cannot restrict to non-Org-mode file"))
15192 (org-agenda-set-restriction-lock 'file))))
15193 (t (error "Don't know how to restrict Org-mode's agenda")))
15194 (org-move-overlay org-speedbar-restriction-lock-overlay
15195 (point-at-bol) (point-at-eol))
15196 (setq current-prefix-arg nil)
15197 (org-agenda-maybe-redo)))
15199 (eval-after-load "speedbar"
15200 '(progn
15201 (speedbar-add-supported-extension ".org")
15202 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15203 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15204 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15205 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15206 (add-hook 'speedbar-visiting-tag-hook
15207 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15210 ;;; Fixes and Hacks for problems with other packages
15212 ;; Make flyspell not check words in links, to not mess up our keymap
15213 (defun org-mode-flyspell-verify ()
15214 "Don't let flyspell put overlays at active buttons."
15215 (not (get-text-property (point) 'keymap)))
15217 ;; Make `bookmark-jump' show the jump location if it was hidden.
15218 (eval-after-load "bookmark"
15219 '(if (boundp 'bookmark-after-jump-hook)
15220 ;; We can use the hook
15221 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15222 ;; Hook not available, use advice
15223 (defadvice bookmark-jump (after org-make-visible activate)
15224 "Make the position visible."
15225 (org-bookmark-jump-unhide))))
15227 ;; Make sure saveplace show the location if it was hidden
15228 (eval-after-load "saveplace"
15229 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15230 "Make the position visible."
15231 (org-bookmark-jump-unhide)))
15233 (defun org-bookmark-jump-unhide ()
15234 "Unhide the current position, to show the bookmark location."
15235 (and (org-mode-p)
15236 (or (org-invisible-p)
15237 (save-excursion (goto-char (max (point-min) (1- (point))))
15238 (org-invisible-p)))
15239 (org-show-context 'bookmark-jump)))
15241 ;; Make session.el ignore our circular variable
15242 (eval-after-load "session"
15243 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15245 ;;;; Experimental code
15247 (defun org-closed-in-range ()
15248 "Sparse tree of items closed in a certain time range.
15249 Still experimental, may disappear in the future."
15250 (interactive)
15251 ;; Get the time interval from the user.
15252 (let* ((time1 (time-to-seconds
15253 (org-read-date nil 'to-time nil "Starting date: ")))
15254 (time2 (time-to-seconds
15255 (org-read-date nil 'to-time nil "End date:")))
15256 ;; callback function
15257 (callback (lambda ()
15258 (let ((time
15259 (time-to-seconds
15260 (apply 'encode-time
15261 (org-parse-time-string
15262 (match-string 1))))))
15263 ;; check if time in interval
15264 (and (>= time time1) (<= time time2))))))
15265 ;; make tree, check each match with the callback
15266 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15269 ;;;; Finish up
15271 (provide 'org)
15273 (run-hooks 'org-load-hook)
15275 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15277 ;;; org.el ends here