Release 6.21b
[org-mode.git] / lisp / org.el
blobda33628e75a247b72de1312039a4015390ddf647
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.21b
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.21b"
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 cookie-present)
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 cnt-all 0 cnt-done 0 cookie-present t)
8656 (setq is-percent (match-end 2))
8657 (save-match-data
8658 (unless (outline-next-heading) (throw 'exit nil))
8659 (while (looking-at org-todo-line-regexp)
8660 (setq kwd (match-string 2))
8661 (and kwd (setq cnt-all (1+ cnt-all)))
8662 (and (member kwd org-done-keywords)
8663 (setq cnt-done (1+ cnt-done)))
8664 (condition-case nil
8665 (org-forward-same-level 1)
8666 (error (end-of-line 1)))))
8667 (replace-match
8668 (if is-percent
8669 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8670 (format "[%d/%d]" cnt-done cnt-all))))
8671 (when cookie-present
8672 (run-hook-with-args 'org-after-todo-statistics-hook
8673 cnt-done (- cnt-all cnt-done)))))))
8675 (defvar org-after-todo-statistics-hook nil
8676 "Hook that is called after a TODO statistics cookie has been updated.
8677 Each function is called with two arguments: the number of not-done entries
8678 and the number of done entries.
8680 For example, the following function, when added to this hook, will switch
8681 an entry to DONE when all children are done, and back to TODO when new
8682 entries are set to a TODO status. Note that this hook is only called
8683 when there is a statistics cookie in the headline!
8685 (defun org-summary-todo (n-done n-not-done)
8686 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8687 (let (org-log-done org-log-states) ; turn off logging
8688 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8691 (defun org-todo-trigger-tag-changes (state)
8692 "Apply the changes defined in `org-todo-state-tags-triggers'."
8693 (let ((l org-todo-state-tags-triggers)
8694 changes)
8695 (when (or (not state) (equal state ""))
8696 (setq changes (append changes (cdr (assoc "" l)))))
8697 (when (and (stringp state) (> (length state) 0))
8698 (setq changes (append changes (cdr (assoc state l)))))
8699 (when (member state org-not-done-keywords)
8700 (setq changes (append changes (cdr (assoc 'todo l)))))
8701 (when (member state org-done-keywords)
8702 (setq changes (append changes (cdr (assoc 'done l)))))
8703 (dolist (c changes)
8704 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8706 (defun org-local-logging (value)
8707 "Get logging settings from a property VALUE."
8708 (let* (words w a)
8709 ;; directly set the variables, they are already local.
8710 (setq org-log-done nil
8711 org-log-repeat nil
8712 org-todo-log-states nil)
8713 (setq words (org-split-string value))
8714 (while (setq w (pop words))
8715 (cond
8716 ((setq a (assoc w org-startup-options))
8717 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8718 (set (nth 1 a) (nth 2 a))))
8719 ((setq a (org-extract-log-state-settings w))
8720 (and (member (car a) org-todo-keywords-1)
8721 (push a org-todo-log-states)))))))
8723 (defun org-get-todo-sequence-head (kwd)
8724 "Return the head of the TODO sequence to which KWD belongs.
8725 If KWD is not set, check if there is a text property remembering the
8726 right sequence."
8727 (let (p)
8728 (cond
8729 ((not kwd)
8730 (or (get-text-property (point-at-bol) 'org-todo-head)
8731 (progn
8732 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8733 nil (point-at-eol)))
8734 (get-text-property p 'org-todo-head))))
8735 ((not (member kwd org-todo-keywords-1))
8736 (car org-todo-keywords-1))
8737 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8739 (defun org-fast-todo-selection ()
8740 "Fast TODO keyword selection with single keys.
8741 Returns the new TODO keyword, or nil if no state change should occur."
8742 (let* ((fulltable org-todo-key-alist)
8743 (done-keywords org-done-keywords) ;; needed for the faces.
8744 (maxlen (apply 'max (mapcar
8745 (lambda (x)
8746 (if (stringp (car x)) (string-width (car x)) 0))
8747 fulltable)))
8748 (expert nil)
8749 (fwidth (+ maxlen 3 1 3))
8750 (ncol (/ (- (window-width) 4) fwidth))
8751 tg cnt e c tbl
8752 groups ingroup)
8753 (save-excursion
8754 (save-window-excursion
8755 (if expert
8756 (set-buffer (get-buffer-create " *Org todo*"))
8757 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8758 (erase-buffer)
8759 (org-set-local 'org-done-keywords done-keywords)
8760 (setq tbl fulltable cnt 0)
8761 (while (setq e (pop tbl))
8762 (cond
8763 ((equal e '(:startgroup))
8764 (push '() groups) (setq ingroup t)
8765 (when (not (= cnt 0))
8766 (setq cnt 0)
8767 (insert "\n"))
8768 (insert "{ "))
8769 ((equal e '(:endgroup))
8770 (setq ingroup nil cnt 0)
8771 (insert "}\n"))
8773 (setq tg (car e) c (cdr e))
8774 (if ingroup (push tg (car groups)))
8775 (setq tg (org-add-props tg nil 'face
8776 (org-get-todo-face tg)))
8777 (if (and (= cnt 0) (not ingroup)) (insert " "))
8778 (insert "[" c "] " tg (make-string
8779 (- fwidth 4 (length tg)) ?\ ))
8780 (when (= (setq cnt (1+ cnt)) ncol)
8781 (insert "\n")
8782 (if ingroup (insert " "))
8783 (setq cnt 0)))))
8784 (insert "\n")
8785 (goto-char (point-min))
8786 (if (not expert) (org-fit-window-to-buffer))
8787 (message "[a-z..]:Set [SPC]:clear")
8788 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8789 (cond
8790 ((or (= c ?\C-g)
8791 (and (= c ?q) (not (rassoc c fulltable))))
8792 (setq quit-flag t))
8793 ((= c ?\ ) nil)
8794 ((setq e (rassoc c fulltable) tg (car e))
8796 (t (setq quit-flag t)))))))
8798 (defun org-entry-is-todo-p ()
8799 (member (org-get-todo-state) org-not-done-keywords))
8801 (defun org-entry-is-done-p ()
8802 (member (org-get-todo-state) org-done-keywords))
8804 (defun org-get-todo-state ()
8805 (save-excursion
8806 (org-back-to-heading t)
8807 (and (looking-at org-todo-line-regexp)
8808 (match-end 2)
8809 (match-string 2))))
8811 (defun org-at-date-range-p (&optional inactive-ok)
8812 "Is the cursor inside a date range?"
8813 (interactive)
8814 (save-excursion
8815 (catch 'exit
8816 (let ((pos (point)))
8817 (skip-chars-backward "^[<\r\n")
8818 (skip-chars-backward "<[")
8819 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8820 (>= (match-end 0) pos)
8821 (throw 'exit t))
8822 (skip-chars-backward "^<[\r\n")
8823 (skip-chars-backward "<[")
8824 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8825 (>= (match-end 0) pos)
8826 (throw 'exit t)))
8827 nil)))
8829 (defun org-get-repeat ()
8830 "Check if there is a deadline/schedule with repeater in this entry."
8831 (save-match-data
8832 (save-excursion
8833 (org-back-to-heading t)
8834 (if (re-search-forward
8835 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8836 (match-string 1)))))
8838 (defvar org-last-changed-timestamp)
8839 (defvar org-last-inserted-timestamp)
8840 (defvar org-log-post-message)
8841 (defvar org-log-note-purpose)
8842 (defvar org-log-note-how)
8843 (defvar org-log-note-extra)
8844 (defun org-auto-repeat-maybe (done-word)
8845 "Check if the current headline contains a repeated deadline/schedule.
8846 If yes, set TODO state back to what it was and change the base date
8847 of repeating deadline/scheduled time stamps to new date.
8848 This function is run automatically after each state change to a DONE state."
8849 ;; last-state is dynamically scoped into this function
8850 (let* ((repeat (org-get-repeat))
8851 (aa (assoc last-state org-todo-kwd-alist))
8852 (interpret (nth 1 aa))
8853 (head (nth 2 aa))
8854 (whata '(("d" . day) ("m" . month) ("y" . year)))
8855 (msg "Entry repeats: ")
8856 (org-log-done nil)
8857 (org-todo-log-states nil)
8858 (nshiftmax 10) (nshift 0)
8859 re type n what ts time)
8860 (when repeat
8861 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8862 (org-todo (if (eq interpret 'type) last-state head))
8863 (when org-log-repeat
8864 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8865 (memq 'org-add-log-note post-command-hook))
8866 ;; OK, we are already setup for some record
8867 (if (eq org-log-repeat 'note)
8868 ;; make sure we take a note, not only a time stamp
8869 (setq org-log-note-how 'note))
8870 ;; Set up for taking a record
8871 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8872 'findpos org-log-repeat)))
8873 (org-back-to-heading t)
8874 (org-add-planning-info nil nil 'closed)
8875 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8876 org-deadline-time-regexp "\\)\\|\\("
8877 org-ts-regexp "\\)"))
8878 (while (re-search-forward
8879 re (save-excursion (outline-next-heading) (point)) t)
8880 (setq type (if (match-end 1) org-scheduled-string
8881 (if (match-end 3) org-deadline-string "Plain:"))
8882 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8883 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8884 (setq n (string-to-number (match-string 2 ts))
8885 what (match-string 3 ts))
8886 (if (equal what "w") (setq n (* n 7) what "d"))
8887 ;; Preparation, see if we need to modify the start date for the change
8888 (when (match-end 1)
8889 (setq time (save-match-data (org-time-string-to-time ts)))
8890 (cond
8891 ((equal (match-string 1 ts) ".")
8892 ;; Shift starting date to today
8893 (org-timestamp-change
8894 (- (time-to-days (current-time)) (time-to-days time))
8895 'day))
8896 ((equal (match-string 1 ts) "+")
8897 (while (or (= nshift 0)
8898 (<= (time-to-days time) (time-to-days (current-time))))
8899 (when (= (incf nshift) nshiftmax)
8900 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8901 (error "Abort")))
8902 (org-timestamp-change n (cdr (assoc what whata)))
8903 (org-at-timestamp-p t)
8904 (setq ts (match-string 1))
8905 (setq time (save-match-data (org-time-string-to-time ts))))
8906 (org-timestamp-change (- n) (cdr (assoc what whata)))
8907 ;; rematch, so that we have everything in place for the real shift
8908 (org-at-timestamp-p t)
8909 (setq ts (match-string 1))
8910 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8911 (org-timestamp-change n (cdr (assoc what whata)))
8912 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8913 (setq org-log-post-message msg)
8914 (message "%s" msg))))
8916 (defun org-show-todo-tree (arg)
8917 "Make a compact tree which shows all headlines marked with TODO.
8918 The tree will show the lines where the regexp matches, and all higher
8919 headlines above the match.
8920 With a \\[universal-argument] prefix, also show the DONE entries.
8921 With a numeric prefix N, construct a sparse tree for the Nth element
8922 of `org-todo-keywords-1'."
8923 (interactive "P")
8924 (let ((case-fold-search nil)
8925 (kwd-re
8926 (cond ((null arg) org-not-done-regexp)
8927 ((equal arg '(4))
8928 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8929 (mapcar 'list org-todo-keywords-1))))
8930 (concat "\\("
8931 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8932 "\\)\\>")))
8933 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8934 (regexp-quote (nth (1- (prefix-numeric-value arg))
8935 org-todo-keywords-1)))
8936 (t (error "Invalid prefix argument: %s" arg)))))
8937 (message "%d TODO entries found"
8938 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8940 (defun org-deadline (&optional remove time)
8941 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8942 With argument REMOVE, remove any deadline from the item.
8943 When TIME is set, it should be an internal time specification, and the
8944 scheduling will use the corresponding date."
8945 (interactive "P")
8946 (if remove
8947 (progn
8948 (org-remove-timestamp-with-keyword org-deadline-string)
8949 (message "Item no longer has a deadline."))
8950 (if (org-get-repeat)
8951 (error "Cannot change deadline on task with repeater, please do that by hand")
8952 (org-add-planning-info 'deadline time 'closed)
8953 (message "Deadline on %s" org-last-inserted-timestamp))))
8955 (defun org-schedule (&optional remove time)
8956 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8957 With argument REMOVE, remove any scheduling date from the item.
8958 When TIME is set, it should be an internal time specification, and the
8959 scheduling will use the corresponding date."
8960 (interactive "P")
8961 (if remove
8962 (progn
8963 (org-remove-timestamp-with-keyword org-scheduled-string)
8964 (message "Item is no longer scheduled."))
8965 (if (org-get-repeat)
8966 (error "Cannot reschedule task with repeater, please do that by hand")
8967 (org-add-planning-info 'scheduled time 'closed)
8968 (message "Scheduled to %s" org-last-inserted-timestamp))))
8970 (defun org-remove-timestamp-with-keyword (keyword)
8971 "Remove all time stamps with KEYWORD in the current entry."
8972 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8973 beg)
8974 (save-excursion
8975 (org-back-to-heading t)
8976 (setq beg (point))
8977 (org-end-of-subtree t t)
8978 (while (re-search-backward re beg t)
8979 (replace-match "")
8980 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8981 (equal (char-before) ?\ ))
8982 (backward-delete-char 1)
8983 (if (string-match "^[ \t]*$" (buffer-substring
8984 (point-at-bol) (point-at-eol)))
8985 (delete-region (point-at-bol)
8986 (min (point-max) (1+ (point-at-eol))))))))))
8988 (defun org-add-planning-info (what &optional time &rest remove)
8989 "Insert new timestamp with keyword in the line directly after the headline.
8990 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8991 If non is given, the user is prompted for a date.
8992 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8993 be removed."
8994 (interactive)
8995 (let (org-time-was-given org-end-time-was-given ts
8996 end default-time default-input)
8998 (when (and (not time) (memq what '(scheduled deadline)))
8999 ;; Try to get a default date/time from existing timestamp
9000 (save-excursion
9001 (org-back-to-heading t)
9002 (setq end (save-excursion (outline-next-heading) (point)))
9003 (when (re-search-forward (if (eq what 'scheduled)
9004 org-scheduled-time-regexp
9005 org-deadline-time-regexp)
9006 end t)
9007 (setq ts (match-string 1)
9008 default-time
9009 (apply 'encode-time (org-parse-time-string ts))
9010 default-input (and ts (org-get-compact-tod ts))))))
9011 (when what
9012 ;; If necessary, get the time from the user
9013 (setq time (or time (org-read-date nil 'to-time nil nil
9014 default-time default-input))))
9016 (when (and org-insert-labeled-timestamps-at-point
9017 (member what '(scheduled deadline)))
9018 (insert
9019 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9020 (org-insert-time-stamp time org-time-was-given
9021 nil nil nil (list org-end-time-was-given))
9022 (setq what nil))
9023 (save-excursion
9024 (save-restriction
9025 (let (col list elt ts buffer-invisibility-spec)
9026 (org-back-to-heading t)
9027 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9028 (goto-char (match-end 1))
9029 (setq col (current-column))
9030 (goto-char (match-end 0))
9031 (if (eobp) (insert "\n") (forward-char 1))
9032 (if (and (not (looking-at outline-regexp))
9033 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9034 "[^\r\n]*"))
9035 (not (equal (match-string 1) org-clock-string)))
9036 (narrow-to-region (match-beginning 0) (match-end 0))
9037 (insert-before-markers "\n")
9038 (backward-char 1)
9039 (narrow-to-region (point) (point))
9040 (and org-adapt-indentation (org-indent-to-column col)))
9041 ;; Check if we have to remove something.
9042 (setq list (cons what remove))
9043 (while list
9044 (setq elt (pop list))
9045 (goto-char (point-min))
9046 (when (or (and (eq elt 'scheduled)
9047 (re-search-forward org-scheduled-time-regexp nil t))
9048 (and (eq elt 'deadline)
9049 (re-search-forward org-deadline-time-regexp nil t))
9050 (and (eq elt 'closed)
9051 (re-search-forward org-closed-time-regexp nil t)))
9052 (replace-match "")
9053 (if (looking-at "--+<[^>]+>") (replace-match ""))
9054 (if (looking-at " +") (replace-match ""))))
9055 (goto-char (point-max))
9056 (when what
9057 (insert
9058 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9059 (cond ((eq what 'scheduled) org-scheduled-string)
9060 ((eq what 'deadline) org-deadline-string)
9061 ((eq what 'closed) org-closed-string))
9062 " ")
9063 (setq ts (org-insert-time-stamp
9064 time
9065 (or org-time-was-given
9066 (and (eq what 'closed) org-log-done-with-time))
9067 (eq what 'closed)
9068 nil nil (list org-end-time-was-given)))
9069 (end-of-line 1))
9070 (goto-char (point-min))
9071 (widen)
9072 (if (and (looking-at "[ \t]+\n")
9073 (equal (char-before) ?\n))
9074 (delete-region (1- (point)) (point-at-eol)))
9075 ts)))))
9077 (defvar org-log-note-marker (make-marker))
9078 (defvar org-log-note-purpose nil)
9079 (defvar org-log-note-state nil)
9080 (defvar org-log-note-how nil)
9081 (defvar org-log-note-extra nil)
9082 (defvar org-log-note-window-configuration nil)
9083 (defvar org-log-note-return-to (make-marker))
9084 (defvar org-log-post-message nil
9085 "Message to be displayed after a log note has been stored.
9086 The auto-repeater uses this.")
9088 (defun org-add-note ()
9089 "Add a note to the current entry.
9090 This is done in the same way as adding a state change note."
9091 (interactive)
9092 (org-add-log-setup 'note nil 'findpos nil))
9094 (defvar org-property-end-re)
9095 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
9096 "Set up the post command hook to take a note.
9097 If this is about to TODO state change, the new state is expected in STATE.
9098 When FINDPOS is non-nil, find the correct position for the note in
9099 the current entry. If not, assume that it can be inserted at point.
9100 HOW is an indicator what kind of note should be created.
9101 EXTRA is additional text that will be inserted into the notes buffer."
9102 (save-restriction
9103 (save-excursion
9104 (when findpos
9105 (org-back-to-heading t)
9106 (narrow-to-region (point) (save-excursion
9107 (outline-next-heading) (point)))
9108 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9109 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9110 "[^\r\n]*\\)?"))
9111 (goto-char (match-end 0))
9112 (when (and org-log-state-notes-insert-after-drawers
9113 (save-excursion
9114 (forward-line) (looking-at org-drawer-regexp)))
9115 (progn (forward-line)
9116 (while (looking-at org-drawer-regexp)
9117 (goto-char (match-end 0))
9118 (re-search-forward org-property-end-re (point-max) t)
9119 (forward-line))
9120 (forward-line -1)))
9121 (unless org-log-states-order-reversed
9122 (and (= (char-after) ?\n) (forward-char 1))
9123 (org-skip-over-state-notes)
9124 (skip-chars-backward " \t\n\r")))
9125 (move-marker org-log-note-marker (point))
9126 (setq org-log-note-purpose purpose
9127 org-log-note-state state
9128 org-log-note-how how
9129 org-log-note-extra extra)
9130 (add-hook 'post-command-hook 'org-add-log-note 'append))))
9132 (defun org-skip-over-state-notes ()
9133 "Skip past the list of State notes in an entry."
9134 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9135 (while (looking-at "[ \t]*- State")
9136 (condition-case nil
9137 (org-next-item)
9138 (error (org-end-of-item)))))
9140 (defun org-add-log-note (&optional purpose)
9141 "Pop up a window for taking a note, and add this note later at point."
9142 (remove-hook 'post-command-hook 'org-add-log-note)
9143 (setq org-log-note-window-configuration (current-window-configuration))
9144 (delete-other-windows)
9145 (move-marker org-log-note-return-to (point))
9146 (switch-to-buffer (marker-buffer org-log-note-marker))
9147 (goto-char org-log-note-marker)
9148 (org-switch-to-buffer-other-window "*Org Note*")
9149 (erase-buffer)
9150 (if (memq org-log-note-how '(time state))
9151 (let (current-prefix-arg) (org-store-log-note))
9152 (let ((org-inhibit-startup t)) (org-mode))
9153 (insert (format "# Insert note for %s.
9154 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9155 (cond
9156 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9157 ((eq org-log-note-purpose 'done) "closed todo item")
9158 ((eq org-log-note-purpose 'state)
9159 (format "state change to \"%s\"" org-log-note-state))
9160 ((eq org-log-note-purpose 'note)
9161 "this entry")
9162 (t (error "This should not happen")))))
9163 (if org-log-note-extra (insert org-log-note-extra))
9164 (org-set-local 'org-finish-function 'org-store-log-note)))
9166 (defvar org-note-abort nil) ; dynamically scoped
9167 (defun org-store-log-note ()
9168 "Finish taking a log note, and insert it to where it belongs."
9169 (let ((txt (buffer-string))
9170 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9171 lines ind)
9172 (kill-buffer (current-buffer))
9173 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9174 (setq txt (replace-match "" t t txt)))
9175 (if (string-match "\\s-+\\'" txt)
9176 (setq txt (replace-match "" t t txt)))
9177 (setq lines (org-split-string txt "\n"))
9178 (when (and note (string-match "\\S-" note))
9179 (setq note
9180 (org-replace-escapes
9181 note
9182 (list (cons "%u" (user-login-name))
9183 (cons "%U" user-full-name)
9184 (cons "%t" (format-time-string
9185 (org-time-stamp-format 'long 'inactive)
9186 (current-time)))
9187 (cons "%s" (if org-log-note-state
9188 (concat "\"" org-log-note-state "\"")
9189 "")))))
9190 (if lines (setq note (concat note " \\\\")))
9191 (push note lines))
9192 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9193 (when lines
9194 (save-excursion
9195 (set-buffer (marker-buffer org-log-note-marker))
9196 (save-excursion
9197 (goto-char org-log-note-marker)
9198 (move-marker org-log-note-marker nil)
9199 (end-of-line 1)
9200 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9201 (indent-relative nil)
9202 (insert "- " (pop lines))
9203 (org-indent-line-function)
9204 (beginning-of-line 1)
9205 (looking-at "[ \t]*")
9206 (setq ind (concat (match-string 0) " "))
9207 (end-of-line 1)
9208 (while lines (insert "\n" ind (pop lines)))))))
9209 (set-window-configuration org-log-note-window-configuration)
9210 (with-current-buffer (marker-buffer org-log-note-return-to)
9211 (goto-char org-log-note-return-to))
9212 (move-marker org-log-note-return-to nil)
9213 (and org-log-post-message (message "%s" org-log-post-message)))
9215 (defun org-sparse-tree (&optional arg)
9216 "Create a sparse tree, prompt for the details.
9217 This command can create sparse trees. You first need to select the type
9218 of match used to create the tree:
9220 t Show entries with a specific TODO keyword.
9221 T Show entries selected by a tags match.
9222 p Enter a property name and its value (both with completion on existing
9223 names/values) and show entries with that property.
9224 r Show entries matching a regular expression
9225 d Show deadlines due within `org-deadline-warning-days'."
9226 (interactive "P")
9227 (let (ans kwd value)
9228 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9229 (setq ans (read-char-exclusive))
9230 (cond
9231 ((equal ans ?d)
9232 (call-interactively 'org-check-deadlines))
9233 ((equal ans ?b)
9234 (call-interactively 'org-check-before-date))
9235 ((equal ans ?t)
9236 (org-show-todo-tree '(4)))
9237 ((equal ans ?T)
9238 (call-interactively 'org-tags-sparse-tree))
9239 ((member ans '(?p ?P))
9240 (setq kwd (org-ido-completing-read "Property: "
9241 (mapcar 'list (org-buffer-property-keys))))
9242 (setq value (org-ido-completing-read "Value: "
9243 (mapcar 'list (org-property-values kwd))))
9244 (unless (string-match "\\`{.*}\\'" value)
9245 (setq value (concat "\"" value "\"")))
9246 (org-tags-sparse-tree arg (concat kwd "=" value)))
9247 ((member ans '(?r ?R ?/))
9248 (call-interactively 'org-occur))
9249 (t (error "No such sparse tree command \"%c\"" ans)))))
9251 (defvar org-occur-highlights nil
9252 "List of overlays used for occur matches.")
9253 (make-variable-buffer-local 'org-occur-highlights)
9254 (defvar org-occur-parameters nil
9255 "Parameters of the active org-occur calls.
9256 This is a list, each call to org-occur pushes as cons cell,
9257 containing the regular expression and the callback, onto the list.
9258 The list can contain several entries if `org-occur' has been called
9259 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9260 will only contain one set of parameters. When the highlights are
9261 removed (for example with `C-c C-c', or with the next edit (depending
9262 on `org-remove-highlights-with-change'), this variable is emptied
9263 as well.")
9264 (make-variable-buffer-local 'org-occur-parameters)
9266 (defun org-occur (regexp &optional keep-previous callback)
9267 "Make a compact tree which shows all matches of REGEXP.
9268 The tree will show the lines where the regexp matches, and all higher
9269 headlines above the match. It will also show the heading after the match,
9270 to make sure editing the matching entry is easy.
9271 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9272 call to `org-occur' will be kept, to allow stacking of calls to this
9273 command.
9274 If CALLBACK is non-nil, it is a function which is called to confirm
9275 that the match should indeed be shown."
9276 (interactive "sRegexp: \nP")
9277 (unless keep-previous
9278 (org-remove-occur-highlights nil nil t))
9279 (push (cons regexp callback) org-occur-parameters)
9280 (let ((cnt 0))
9281 (save-excursion
9282 (goto-char (point-min))
9283 (if (or (not keep-previous) ; do not want to keep
9284 (not org-occur-highlights)) ; no previous matches
9285 ;; hide everything
9286 (org-overview))
9287 (while (re-search-forward regexp nil t)
9288 (when (or (not callback)
9289 (save-match-data (funcall callback)))
9290 (setq cnt (1+ cnt))
9291 (when org-highlight-sparse-tree-matches
9292 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9293 (org-show-context 'occur-tree))))
9294 (when org-remove-highlights-with-change
9295 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9296 nil 'local))
9297 (unless org-sparse-tree-open-archived-trees
9298 (org-hide-archived-subtrees (point-min) (point-max)))
9299 (run-hooks 'org-occur-hook)
9300 (if (interactive-p)
9301 (message "%d match(es) for regexp %s" cnt regexp))
9302 cnt))
9304 (defun org-show-context (&optional key)
9305 "Make sure point and context and visible.
9306 How much context is shown depends upon the variables
9307 `org-show-hierarchy-above', `org-show-following-heading'. and
9308 `org-show-siblings'."
9309 (let ((heading-p (org-on-heading-p t))
9310 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9311 (following-p (org-get-alist-option org-show-following-heading key))
9312 (entry-p (org-get-alist-option org-show-entry-below key))
9313 (siblings-p (org-get-alist-option org-show-siblings key)))
9314 (catch 'exit
9315 ;; Show heading or entry text
9316 (if (and heading-p (not entry-p))
9317 (org-flag-heading nil) ; only show the heading
9318 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9319 (org-show-hidden-entry))) ; show entire entry
9320 (when following-p
9321 ;; Show next sibling, or heading below text
9322 (save-excursion
9323 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9324 (org-flag-heading nil))))
9325 (when siblings-p (org-show-siblings))
9326 (when hierarchy-p
9327 ;; show all higher headings, possibly with siblings
9328 (save-excursion
9329 (while (and (condition-case nil
9330 (progn (org-up-heading-all 1) t)
9331 (error nil))
9332 (not (bobp)))
9333 (org-flag-heading nil)
9334 (when siblings-p (org-show-siblings))))))))
9336 (defun org-reveal (&optional siblings)
9337 "Show current entry, hierarchy above it, and the following headline.
9338 This can be used to show a consistent set of context around locations
9339 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9340 not t for the search context.
9342 With optional argument SIBLINGS, on each level of the hierarchy all
9343 siblings are shown. This repairs the tree structure to what it would
9344 look like when opened with hierarchical calls to `org-cycle'."
9345 (interactive "P")
9346 (let ((org-show-hierarchy-above t)
9347 (org-show-following-heading t)
9348 (org-show-siblings (if siblings t org-show-siblings)))
9349 (org-show-context nil)))
9351 (defun org-highlight-new-match (beg end)
9352 "Highlight from BEG to END and mark the highlight is an occur headline."
9353 (let ((ov (org-make-overlay beg end)))
9354 (org-overlay-put ov 'face 'secondary-selection)
9355 (push ov org-occur-highlights)))
9357 (defun org-remove-occur-highlights (&optional beg end noremove)
9358 "Remove the occur highlights from the buffer.
9359 BEG and END are ignored. If NOREMOVE is nil, remove this function
9360 from the `before-change-functions' in the current buffer."
9361 (interactive)
9362 (unless org-inhibit-highlight-removal
9363 (mapc 'org-delete-overlay org-occur-highlights)
9364 (setq org-occur-highlights nil)
9365 (setq org-occur-parameters nil)
9366 (unless noremove
9367 (remove-hook 'before-change-functions
9368 'org-remove-occur-highlights 'local))))
9370 ;;;; Priorities
9372 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9373 "Regular expression matching the priority indicator.")
9375 (defvar org-remove-priority-next-time nil)
9377 (defun org-priority-up ()
9378 "Increase the priority of the current item."
9379 (interactive)
9380 (org-priority 'up))
9382 (defun org-priority-down ()
9383 "Decrease the priority of the current item."
9384 (interactive)
9385 (org-priority 'down))
9387 (defun org-priority (&optional action)
9388 "Change the priority of an item by ARG.
9389 ACTION can be `set', `up', `down', or a character."
9390 (interactive)
9391 (setq action (or action 'set))
9392 (let (current new news have remove)
9393 (save-excursion
9394 (org-back-to-heading)
9395 (if (looking-at org-priority-regexp)
9396 (setq current (string-to-char (match-string 2))
9397 have t)
9398 (setq current org-default-priority))
9399 (cond
9400 ((or (eq action 'set)
9401 (if (featurep 'xemacs) (characterp action) (integerp action)))
9402 (if (not (eq action 'set))
9403 (setq new action)
9404 (message "Priority %c-%c, SPC to remove: "
9405 org-highest-priority org-lowest-priority)
9406 (setq new (read-char-exclusive)))
9407 (if (and (= (upcase org-highest-priority) org-highest-priority)
9408 (= (upcase org-lowest-priority) org-lowest-priority))
9409 (setq new (upcase new)))
9410 (cond ((equal new ?\ ) (setq remove t))
9411 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9412 (error "Priority must be between `%c' and `%c'"
9413 org-highest-priority org-lowest-priority))))
9414 ((eq action 'up)
9415 (if (and (not have) (eq last-command this-command))
9416 (setq new org-lowest-priority)
9417 (setq new (if (and org-priority-start-cycle-with-default (not have))
9418 org-default-priority (1- current)))))
9419 ((eq action 'down)
9420 (if (and (not have) (eq last-command this-command))
9421 (setq new org-highest-priority)
9422 (setq new (if (and org-priority-start-cycle-with-default (not have))
9423 org-default-priority (1+ current)))))
9424 (t (error "Invalid action")))
9425 (if (or (< (upcase new) org-highest-priority)
9426 (> (upcase new) org-lowest-priority))
9427 (setq remove t))
9428 (setq news (format "%c" new))
9429 (if have
9430 (if remove
9431 (replace-match "" t t nil 1)
9432 (replace-match news t t nil 2))
9433 (if remove
9434 (error "No priority cookie found in line")
9435 (looking-at org-todo-line-regexp)
9436 (if (match-end 2)
9437 (progn
9438 (goto-char (match-end 2))
9439 (insert " [#" news "]"))
9440 (goto-char (match-beginning 3))
9441 (insert "[#" news "] ")))))
9442 (org-preserve-lc (org-set-tags nil 'align))
9443 (if remove
9444 (message "Priority removed")
9445 (message "Priority of current item set to %s" news))))
9448 (defun org-get-priority (s)
9449 "Find priority cookie and return priority."
9450 (save-match-data
9451 (if (not (string-match org-priority-regexp s))
9452 (* 1000 (- org-lowest-priority org-default-priority))
9453 (* 1000 (- org-lowest-priority
9454 (string-to-char (match-string 2 s)))))))
9456 ;;;; Tags
9458 (defvar org-agenda-archives-mode)
9459 (defun org-scan-tags (action matcher &optional todo-only)
9460 "Scan headline tags with inheritance and produce output ACTION.
9462 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9463 or `agenda' to produce an entry list for an agenda view. It can also be
9464 a Lisp form or a function that should be called at each matched headline, in
9465 this case the return value is a list of all return values from these calls.
9467 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9468 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9469 only lines with a TODO keyword are included in the output."
9470 (require 'org-agenda)
9471 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9472 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9473 (org-re
9474 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9475 (props (list 'face 'default
9476 'done-face 'org-done
9477 'undone-face 'default
9478 'mouse-face 'highlight
9479 'org-not-done-regexp org-not-done-regexp
9480 'org-todo-regexp org-todo-regexp
9481 'keymap org-agenda-keymap
9482 'help-echo
9483 (format "mouse-2 or RET jump to org file %s"
9484 (abbreviate-file-name
9485 (or (buffer-file-name (buffer-base-buffer))
9486 (buffer-name (buffer-base-buffer)))))))
9487 (case-fold-search nil)
9488 lspos tags tags-list
9489 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9490 (llast 0) rtn rtn1 level category i txt
9491 todo marker entry priority)
9492 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9493 (setq action (list 'lambda nil action)))
9494 (save-excursion
9495 (goto-char (point-min))
9496 (when (eq action 'sparse-tree)
9497 (org-overview)
9498 (org-remove-occur-highlights))
9499 (while (re-search-forward re nil t)
9500 (catch :skip
9501 (setq todo (if (match-end 1) (match-string 2))
9502 tags (if (match-end 4) (match-string 4)))
9503 (goto-char (setq lspos (1+ (match-beginning 0))))
9504 (setq level (org-reduced-level (funcall outline-level))
9505 category (org-get-category))
9506 (setq i llast llast level)
9507 ;; remove tag lists from same and sublevels
9508 (while (>= i level)
9509 (when (setq entry (assoc i tags-alist))
9510 (setq tags-alist (delete entry tags-alist)))
9511 (setq i (1- i)))
9512 ;; add the next tags
9513 (when tags
9514 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9515 tags-alist
9516 (cons (cons level tags) tags-alist)))
9517 ;; compile tags for current headline
9518 (setq tags-list
9519 (if org-use-tag-inheritance
9520 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9521 tags))
9522 (when org-use-tag-inheritance
9523 (setcdr (car tags-alist)
9524 (mapcar (lambda (x)
9525 (setq x (copy-sequence x))
9526 (org-add-prop-inherited x))
9527 (cdar tags-alist))))
9528 (when (and tags org-use-tag-inheritance
9529 (not (eq t org-use-tag-inheritance)))
9530 ;; selective inheritance, remove uninherited ones
9531 (setcdr (car tags-alist)
9532 (org-remove-uniherited-tags (cdar tags-alist))))
9533 (when (and (or (not todo-only)
9534 (and (member todo org-not-done-keywords)
9535 (or (not org-agenda-tags-todo-honor-ignore-options)
9536 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9537 (let ((case-fold-search t)) (eval matcher))
9539 (not (member org-archive-tag tags-list))
9540 ;; we have an archive tag, should we use this anyway?
9541 (or (not org-agenda-skip-archived-trees)
9542 (and (eq action 'agenda) org-agenda-archives-mode))))
9543 (unless (eq action 'sparse-tree) (org-agenda-skip))
9545 ;; select this headline
9547 (cond
9548 ((eq action 'sparse-tree)
9549 (and org-highlight-sparse-tree-matches
9550 (org-get-heading) (match-end 0)
9551 (org-highlight-new-match
9552 (match-beginning 0) (match-beginning 1)))
9553 (org-show-context 'tags-tree))
9554 ((eq action 'agenda)
9555 (setq txt (org-format-agenda-item
9557 (concat
9558 (if org-tags-match-list-sublevels
9559 (make-string (1- level) ?.) "")
9560 (org-get-heading))
9561 category (org-get-tags-at))
9562 priority (org-get-priority txt))
9563 (goto-char lspos)
9564 (setq marker (org-agenda-new-marker))
9565 (org-add-props txt props
9566 'org-marker marker 'org-hd-marker marker 'org-category category
9567 'priority priority 'type "tagsmatch")
9568 (push txt rtn))
9569 ((functionp action)
9570 (save-excursion
9571 (setq rtn1 (funcall action))
9572 (push rtn1 rtn))
9573 (goto-char (point-at-eol)))
9574 (t (error "Invalid action")))
9576 ;; if we are to skip sublevels, jump to end of subtree
9577 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9578 (when (and (eq action 'sparse-tree)
9579 (not org-sparse-tree-open-archived-trees))
9580 (org-hide-archived-subtrees (point-min) (point-max)))
9581 (nreverse rtn)))
9583 (defun org-remove-uniherited-tags (tags)
9584 "Remove all tags that are not inherited from the list TAGS."
9585 (cond
9586 ((eq org-use-tag-inheritance t)
9587 (if org-tags-exclude-from-inheritance
9588 (org-delete-all org-tags-exclude-from-inheritance tags)
9589 tags))
9590 ((not org-use-tag-inheritance) nil)
9591 ((stringp org-use-tag-inheritance)
9592 (delq nil (mapcar
9593 (lambda (x)
9594 (if (and (string-match org-use-tag-inheritance x)
9595 (not (member x org-tags-exclude-from-inheritance)))
9596 x nil))
9597 tags)))
9598 ((listp org-use-tag-inheritance)
9599 (delq nil (mapcar
9600 (lambda (x)
9601 (if (member x org-use-tag-inheritance) x nil))
9602 tags)))))
9604 (defvar todo-only) ;; dynamically scoped
9606 (defun org-tags-sparse-tree (&optional todo-only match)
9607 "Create a sparse tree according to tags string MATCH.
9608 MATCH can contain positive and negative selection of tags, like
9609 \"+WORK+URGENT-WITHBOSS\".
9610 If optional argument TODO-ONLY is non-nil, only select lines that are
9611 also TODO lines."
9612 (interactive "P")
9613 (org-prepare-agenda-buffers (list (current-buffer)))
9614 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9616 (defvar org-cached-props nil)
9617 (defun org-cached-entry-get (pom property)
9618 (if (or (eq t org-use-property-inheritance)
9619 (and (stringp org-use-property-inheritance)
9620 (string-match org-use-property-inheritance property))
9621 (and (listp org-use-property-inheritance)
9622 (member property org-use-property-inheritance)))
9623 ;; Caching is not possible, check it directly
9624 (org-entry-get pom property 'inherit)
9625 ;; Get all properties, so that we can do complicated checks easily
9626 (cdr (assoc property (or org-cached-props
9627 (setq org-cached-props
9628 (org-entry-properties pom)))))))
9630 (defun org-global-tags-completion-table (&optional files)
9631 "Return the list of all tags in all agenda buffer/files."
9632 (save-excursion
9633 (org-uniquify
9634 (delq nil
9635 (apply 'append
9636 (mapcar
9637 (lambda (file)
9638 (set-buffer (find-file-noselect file))
9639 (append (org-get-buffer-tags)
9640 (mapcar (lambda (x) (if (stringp (car-safe x))
9641 (list (car-safe x)) nil))
9642 org-tag-alist)))
9643 (if (and files (car files))
9644 files
9645 (org-agenda-files))))))))
9647 (defun org-make-tags-matcher (match)
9648 "Create the TAGS//TODO matcher form for the selection string MATCH."
9649 ;; todo-only is scoped dynamically into this function, and the function
9650 ;; may change it if the matcher asks for it.
9651 (unless match
9652 ;; Get a new match request, with completion
9653 (let ((org-last-tags-completion-table
9654 (org-global-tags-completion-table)))
9655 (setq match (org-completing-read
9656 "Match: " 'org-tags-completion-function nil nil nil
9657 'org-tags-history))))
9659 ;; Parse the string and create a lisp form
9660 (let ((match0 match)
9661 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9662 minus tag mm
9663 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9664 orterms term orlist re-p str-p level-p level-op time-p
9665 prop-p pn pv po cat-p gv rest)
9666 (if (string-match "/+" match)
9667 ;; match contains also a todo-matching request
9668 (progn
9669 (setq tagsmatch (substring match 0 (match-beginning 0))
9670 todomatch (substring match (match-end 0)))
9671 (if (string-match "^!" todomatch)
9672 (setq todo-only t todomatch (substring todomatch 1)))
9673 (if (string-match "^\\s-*$" todomatch)
9674 (setq todomatch nil)))
9675 ;; only matching tags
9676 (setq tagsmatch match todomatch nil))
9678 ;; Make the tags matcher
9679 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9680 (setq tagsmatcher t)
9681 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9682 (while (setq term (pop orterms))
9683 (while (and (equal (substring term -1) "\\") orterms)
9684 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9685 (while (string-match re term)
9686 (setq rest (substring term (match-end 0))
9687 minus (and (match-end 1)
9688 (equal (match-string 1 term) "-"))
9689 tag (match-string 2 term)
9690 re-p (equal (string-to-char tag) ?{)
9691 level-p (match-end 4)
9692 prop-p (match-end 5)
9693 mm (cond
9694 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9695 (level-p
9696 (setq level-op (org-op-to-function (match-string 3 term)))
9697 `(,level-op level ,(string-to-number
9698 (match-string 4 term))))
9699 (prop-p
9700 (setq pn (match-string 5 term)
9701 po (match-string 6 term)
9702 pv (match-string 7 term)
9703 cat-p (equal pn "CATEGORY")
9704 re-p (equal (string-to-char pv) ?{)
9705 str-p (equal (string-to-char pv) ?\")
9706 time-p (save-match-data
9707 (string-match "^\"[[<].*[]>]\"$" pv))
9708 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9709 (if time-p (setq pv (org-matcher-time pv)))
9710 (setq po (org-op-to-function po (if time-p 'time str-p)))
9711 (cond
9712 ((equal pn "CATEGORY")
9713 (setq gv '(get-text-property (point) 'org-category)))
9714 ((equal pn "TODO")
9715 (setq gv 'todo))
9717 (setq gv `(org-cached-entry-get nil ,pn))))
9718 (if re-p
9719 (if (eq po 'org<>)
9720 `(not (string-match ,pv (or ,gv "")))
9721 `(string-match ,pv (or ,gv "")))
9722 (if str-p
9723 `(,po (or ,gv "") ,pv)
9724 `(,po (string-to-number (or ,gv ""))
9725 ,(string-to-number pv) ))))
9726 (t `(member ,(downcase tag) tags-list)))
9727 mm (if minus (list 'not mm) mm)
9728 term rest)
9729 (push mm tagsmatcher))
9730 (push (if (> (length tagsmatcher) 1)
9731 (cons 'and tagsmatcher)
9732 (car tagsmatcher))
9733 orlist)
9734 (setq tagsmatcher nil))
9735 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9736 (setq tagsmatcher
9737 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9738 ;; Make the todo matcher
9739 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9740 (setq todomatcher t)
9741 (setq orterms (org-split-string todomatch "|") orlist nil)
9742 (while (setq term (pop orterms))
9743 (while (string-match re term)
9744 (setq minus (and (match-end 1)
9745 (equal (match-string 1 term) "-"))
9746 kwd (match-string 2 term)
9747 re-p (equal (string-to-char kwd) ?{)
9748 term (substring term (match-end 0))
9749 mm (if re-p
9750 `(string-match ,(substring kwd 1 -1) todo)
9751 (list 'equal 'todo kwd))
9752 mm (if minus (list 'not mm) mm))
9753 (push mm todomatcher))
9754 (push (if (> (length todomatcher) 1)
9755 (cons 'and todomatcher)
9756 (car todomatcher))
9757 orlist)
9758 (setq todomatcher nil))
9759 (setq todomatcher (if (> (length orlist) 1)
9760 (cons 'or orlist) (car orlist))))
9762 ;; Return the string and lisp forms of the matcher
9763 (setq matcher (if todomatcher
9764 (list 'and tagsmatcher todomatcher)
9765 tagsmatcher))
9766 (cons match0 matcher)))
9768 (defun org-op-to-function (op &optional stringp)
9769 "Turn an operator into the appropriate function."
9770 (setq op
9771 (cond
9772 ((equal op "<" ) '(< string< org-time<))
9773 ((equal op ">" ) '(> org-string> org-time>))
9774 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9775 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9776 ((member op '("=" "==")) '(= string= org-time=))
9777 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9778 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9780 (defun org<> (a b) (not (= a b)))
9781 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9782 (defun org-string>= (a b) (not (string< a b)))
9783 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9784 (defun org-string<> (a b) (not (string= 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) (> a b)))
9789 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9790 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9791 (defun org-2ft (s)
9792 "Convert S to a floating point time.
9793 If S is already a number, just return it. If it is a string, parse
9794 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9795 (cond
9796 ((numberp s) s)
9797 ((stringp s)
9798 (condition-case nil
9799 (float-time (apply 'encode-time (org-parse-time-string s)))
9800 (error 0.)))
9801 (t 0.)))
9803 (defun org-time-today ()
9804 "Time in seconds today at 0:00.
9805 Returns the float number of seconds since the beginning of the
9806 epoch to the beginning of today (00:00)."
9807 (float-time (apply 'encode-time
9808 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9810 (defun org-matcher-time (s)
9811 "Interpret a time comparison value."
9812 (save-match-data
9813 (cond
9814 ((string= s "<now>") (float-time))
9815 ((string= s "<today>") (org-time-today))
9816 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9817 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9818 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9819 (+ (org-time-today)
9820 (* (string-to-number (match-string 1 s))
9821 (cdr (assoc (match-string 2 s)
9822 '(("d" . 86400.0) ("w" . 604800.0)
9823 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9824 (t (org-2ft s)))))
9826 (defun org-match-any-p (re list)
9827 "Does re match any element of list?"
9828 (setq list (mapcar (lambda (x) (string-match re x)) list))
9829 (delq nil list))
9831 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9832 (defvar org-tags-overlay (org-make-overlay 1 1))
9833 (org-detach-overlay org-tags-overlay)
9835 (defun org-get-local-tags-at (&optional pos)
9836 "Get a list of tags defined in the current headline."
9837 (org-get-tags-at pos 'local))
9839 (defun org-get-local-tags ()
9840 "Get a list of tags defined in the current headline."
9841 (org-get-tags-at nil 'local))
9843 (defun org-get-tags-at (&optional pos local)
9844 "Get a list of all headline tags applicable at POS.
9845 POS defaults to point. If tags are inherited, the list contains
9846 the targets in the same sequence as the headlines appear, i.e.
9847 the tags of the current headline come last.
9848 When LOCAL is non-nil, only return tags from the current headline,
9849 ignore inherited ones."
9850 (interactive)
9851 (let (tags ltags lastpos parent)
9852 (save-excursion
9853 (save-restriction
9854 (widen)
9855 (goto-char (or pos (point)))
9856 (save-match-data
9857 (catch 'done
9858 (condition-case nil
9859 (progn
9860 (org-back-to-heading t)
9861 (while (not (equal lastpos (point)))
9862 (setq lastpos (point))
9863 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9864 (setq ltags (org-split-string
9865 (org-match-string-no-properties 1) ":"))
9866 (when parent
9867 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9868 (setq tags (append
9869 (if parent
9870 (org-remove-uniherited-tags ltags)
9871 ltags)
9872 tags)))
9873 (or org-use-tag-inheritance (throw 'done t))
9874 (if local (throw 'done t))
9875 (org-up-heading-all 1)
9876 (setq parent t)))
9877 (error nil)))))
9878 (append (org-remove-uniherited-tags org-file-tags) tags))))
9880 (defun org-add-prop-inherited (s)
9881 (add-text-properties 0 (length s) '(inherited t) s)
9884 (defun org-toggle-tag (tag &optional onoff)
9885 "Toggle the tag TAG for the current line.
9886 If ONOFF is `on' or `off', don't toggle but set to this state."
9887 (let (res current)
9888 (save-excursion
9889 (org-back-to-heading t)
9890 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9891 (point-at-eol) t)
9892 (progn
9893 (setq current (match-string 1))
9894 (replace-match ""))
9895 (setq current ""))
9896 (setq current (nreverse (org-split-string current ":")))
9897 (cond
9898 ((eq onoff 'on)
9899 (setq res t)
9900 (or (member tag current) (push tag current)))
9901 ((eq onoff 'off)
9902 (or (not (member tag current)) (setq current (delete tag current))))
9903 (t (if (member tag current)
9904 (setq current (delete tag current))
9905 (setq res t)
9906 (push tag current))))
9907 (end-of-line 1)
9908 (if current
9909 (progn
9910 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9911 (org-set-tags nil t))
9912 (delete-horizontal-space))
9913 (run-hooks 'org-after-tags-change-hook))
9914 res))
9916 (defun org-align-tags-here (to-col)
9917 ;; Assumes that this is a headline
9918 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9919 (beginning-of-line 1)
9920 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9921 (< pos (match-beginning 2)))
9922 (progn
9923 (setq tags-l (- (match-end 2) (match-beginning 2)))
9924 (goto-char (match-beginning 1))
9925 (insert " ")
9926 (delete-region (point) (1+ (match-beginning 2)))
9927 (setq ncol (max (1+ (current-column))
9928 (1+ col)
9929 (if (> to-col 0)
9930 to-col
9931 (- (abs to-col) tags-l))))
9932 (setq p (point))
9933 (insert (make-string (- ncol (current-column)) ?\ ))
9934 (setq ncol (current-column))
9935 (when indent-tabs-mode (tabify p (point-at-eol)))
9936 (org-move-to-column (min ncol col) t))
9937 (goto-char pos))))
9939 (defun org-set-tags-command (&optional arg just-align)
9940 "Call the set-tags command for the current entry."
9941 (interactive "P")
9942 (if (org-on-heading-p)
9943 (org-set-tags arg just-align)
9944 (save-excursion
9945 (org-back-to-heading t)
9946 (org-set-tags arg just-align))))
9948 (defun org-set-tags (&optional arg just-align)
9949 "Set the tags for the current headline.
9950 With prefix ARG, realign all tags in headings in the current buffer."
9951 (interactive "P")
9952 (let* ((re (concat "^" outline-regexp))
9953 (current (org-get-tags-string))
9954 (col (current-column))
9955 (org-setting-tags t)
9956 table current-tags inherited-tags ; computed below when needed
9957 tags p0 c0 c1 rpl)
9958 (if arg
9959 (save-excursion
9960 (goto-char (point-min))
9961 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9962 (while (re-search-forward re nil t)
9963 (org-set-tags nil t)
9964 (end-of-line 1)))
9965 (message "All tags realigned to column %d" org-tags-column))
9966 (if just-align
9967 (setq tags current)
9968 ;; Get a new set of tags from the user
9969 (save-excursion
9970 (setq table (or org-tag-alist (org-get-buffer-tags))
9971 org-last-tags-completion-table table
9972 current-tags (org-split-string current ":")
9973 inherited-tags (nreverse
9974 (nthcdr (length current-tags)
9975 (nreverse (org-get-tags-at))))
9976 tags
9977 (if (or (eq t org-use-fast-tag-selection)
9978 (and org-use-fast-tag-selection
9979 (delq nil (mapcar 'cdr table))))
9980 (org-fast-tag-selection
9981 current-tags inherited-tags table
9982 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9983 (let ((org-add-colon-after-tag-completion t))
9984 (org-trim
9985 (org-without-partial-completion
9986 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9987 nil nil current 'org-tags-history)))))))
9988 (while (string-match "[-+&]+" tags)
9989 ;; No boolean logic, just a list
9990 (setq tags (replace-match ":" t t tags))))
9992 (if (string-match "\\`[\t ]*\\'" tags)
9993 (setq tags "")
9994 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9995 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9997 ;; Insert new tags at the correct column
9998 (beginning-of-line 1)
9999 (cond
10000 ((and (equal current "") (equal tags "")))
10001 ((re-search-forward
10002 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10003 (point-at-eol) t)
10004 (if (equal tags "")
10005 (setq rpl "")
10006 (goto-char (match-beginning 0))
10007 (setq c0 (current-column) p0 (point)
10008 c1 (max (1+ c0) (if (> org-tags-column 0)
10009 org-tags-column
10010 (- (- org-tags-column) (length tags))))
10011 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10012 (replace-match rpl t t)
10013 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10014 tags)
10015 (t (error "Tags alignment failed")))
10016 (org-move-to-column col)
10017 (unless just-align
10018 (run-hooks 'org-after-tags-change-hook)))))
10020 (defun org-change-tag-in-region (beg end tag off)
10021 "Add or remove TAG for each entry in the region.
10022 This works in the agenda, and also in an org-mode buffer."
10023 (interactive
10024 (list (region-beginning) (region-end)
10025 (let ((org-last-tags-completion-table
10026 (if (org-mode-p)
10027 (org-get-buffer-tags)
10028 (org-global-tags-completion-table))))
10029 (org-ido-completing-read
10030 "Tag: " 'org-tags-completion-function nil nil nil
10031 'org-tags-history))
10032 (progn
10033 (message "[s]et or [r]emove? ")
10034 (equal (read-char-exclusive) ?r))))
10035 (if (fboundp 'deactivate-mark) (deactivate-mark))
10036 (let ((agendap (equal major-mode 'org-agenda-mode))
10037 l1 l2 m buf pos newhead (cnt 0))
10038 (goto-char end)
10039 (setq l2 (1- (org-current-line)))
10040 (goto-char beg)
10041 (setq l1 (org-current-line))
10042 (loop for l from l1 to l2 do
10043 (goto-line l)
10044 (setq m (get-text-property (point) 'org-hd-marker))
10045 (when (or (and (org-mode-p) (org-on-heading-p))
10046 (and agendap m))
10047 (setq buf (if agendap (marker-buffer m) (current-buffer))
10048 pos (if agendap m (point)))
10049 (with-current-buffer buf
10050 (save-excursion
10051 (save-restriction
10052 (goto-char pos)
10053 (setq cnt (1+ cnt))
10054 (org-toggle-tag tag (if off 'off 'on))
10055 (setq newhead (org-get-heading)))))
10056 (and agendap (org-agenda-change-all-lines newhead m))))
10057 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10059 (defun org-tags-completion-function (string predicate &optional flag)
10060 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10061 (confirm (lambda (x) (stringp (car x)))))
10062 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10063 (setq s1 (match-string 1 string)
10064 s2 (match-string 2 string))
10065 (setq s1 "" s2 string))
10066 (cond
10067 ((eq flag nil)
10068 ;; try completion
10069 (setq rtn (try-completion s2 ctable confirm))
10070 (if (stringp rtn)
10071 (setq rtn
10072 (concat s1 s2 (substring rtn (length s2))
10073 (if (and org-add-colon-after-tag-completion
10074 (assoc rtn ctable))
10075 ":" ""))))
10076 rtn)
10077 ((eq flag t)
10078 ;; all-completions
10079 (all-completions s2 ctable confirm)
10081 ((eq flag 'lambda)
10082 ;; exact match?
10083 (assoc s2 ctable)))
10086 (defun org-fast-tag-insert (kwd tags face &optional end)
10087 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10088 (insert (format "%-12s" (concat kwd ":"))
10089 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10090 (or end "")))
10092 (defun org-fast-tag-show-exit (flag)
10093 (save-excursion
10094 (goto-line 3)
10095 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10096 (replace-match ""))
10097 (when flag
10098 (end-of-line 1)
10099 (org-move-to-column (- (window-width) 19) t)
10100 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10102 (defun org-set-current-tags-overlay (current prefix)
10103 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10104 (if (featurep 'xemacs)
10105 (org-overlay-display org-tags-overlay (concat prefix s)
10106 'secondary-selection)
10107 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10108 (org-overlay-display org-tags-overlay (concat prefix s)))))
10110 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10111 "Fast tag selection with single keys.
10112 CURRENT is the current list of tags in the headline, INHERITED is the
10113 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10114 possibly with grouping information. TODO-TABLE is a similar table with
10115 TODO keywords, should these have keys assigned to them.
10116 If the keys are nil, a-z are automatically assigned.
10117 Returns the new tags string, or nil to not change the current settings."
10118 (let* ((fulltable (append table todo-table))
10119 (maxlen (apply 'max (mapcar
10120 (lambda (x)
10121 (if (stringp (car x)) (string-width (car x)) 0))
10122 fulltable)))
10123 (buf (current-buffer))
10124 (expert (eq org-fast-tag-selection-single-key 'expert))
10125 (buffer-tags nil)
10126 (fwidth (+ maxlen 3 1 3))
10127 (ncol (/ (- (window-width) 4) fwidth))
10128 (i-face 'org-done)
10129 (c-face 'org-todo)
10130 tg cnt e c char c1 c2 ntable tbl rtn
10131 ov-start ov-end ov-prefix
10132 (exit-after-next org-fast-tag-selection-single-key)
10133 (done-keywords org-done-keywords)
10134 groups ingroup)
10135 (save-excursion
10136 (beginning-of-line 1)
10137 (if (looking-at
10138 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10139 (setq ov-start (match-beginning 1)
10140 ov-end (match-end 1)
10141 ov-prefix "")
10142 (setq ov-start (1- (point-at-eol))
10143 ov-end (1+ ov-start))
10144 (skip-chars-forward "^\n\r")
10145 (setq ov-prefix
10146 (concat
10147 (buffer-substring (1- (point)) (point))
10148 (if (> (current-column) org-tags-column)
10150 (make-string (- org-tags-column (current-column)) ?\ ))))))
10151 (org-move-overlay org-tags-overlay ov-start ov-end)
10152 (save-window-excursion
10153 (if expert
10154 (set-buffer (get-buffer-create " *Org tags*"))
10155 (delete-other-windows)
10156 (split-window-vertically)
10157 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10158 (erase-buffer)
10159 (org-set-local 'org-done-keywords done-keywords)
10160 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10161 (org-fast-tag-insert "Current" current c-face "\n\n")
10162 (org-fast-tag-show-exit exit-after-next)
10163 (org-set-current-tags-overlay current ov-prefix)
10164 (setq tbl fulltable char ?a cnt 0)
10165 (while (setq e (pop tbl))
10166 (cond
10167 ((equal e '(:startgroup))
10168 (push '() groups) (setq ingroup t)
10169 (when (not (= cnt 0))
10170 (setq cnt 0)
10171 (insert "\n"))
10172 (insert "{ "))
10173 ((equal e '(:endgroup))
10174 (setq ingroup nil cnt 0)
10175 (insert "}\n"))
10177 (setq tg (car e) c2 nil)
10178 (if (cdr e)
10179 (setq c (cdr e))
10180 ;; automatically assign a character.
10181 (setq c1 (string-to-char
10182 (downcase (substring
10183 tg (if (= (string-to-char tg) ?@) 1 0)))))
10184 (if (or (rassoc c1 ntable) (rassoc c1 table))
10185 (while (or (rassoc char ntable) (rassoc char table))
10186 (setq char (1+ char)))
10187 (setq c2 c1))
10188 (setq c (or c2 char)))
10189 (if ingroup (push tg (car groups)))
10190 (setq tg (org-add-props tg nil 'face
10191 (cond
10192 ((not (assoc tg table))
10193 (org-get-todo-face tg))
10194 ((member tg current) c-face)
10195 ((member tg inherited) i-face)
10196 (t nil))))
10197 (if (and (= cnt 0) (not ingroup)) (insert " "))
10198 (insert "[" c "] " tg (make-string
10199 (- fwidth 4 (length tg)) ?\ ))
10200 (push (cons tg c) ntable)
10201 (when (= (setq cnt (1+ cnt)) ncol)
10202 (insert "\n")
10203 (if ingroup (insert " "))
10204 (setq cnt 0)))))
10205 (setq ntable (nreverse ntable))
10206 (insert "\n")
10207 (goto-char (point-min))
10208 (if (not expert) (org-fit-window-to-buffer))
10209 (setq rtn
10210 (catch 'exit
10211 (while t
10212 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10213 (if groups " [!] no groups" " [!]groups")
10214 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10215 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10216 (cond
10217 ((= c ?\r) (throw 'exit t))
10218 ((= c ?!)
10219 (setq groups (not groups))
10220 (goto-char (point-min))
10221 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10222 ((= c ?\C-c)
10223 (if (not expert)
10224 (org-fast-tag-show-exit
10225 (setq exit-after-next (not exit-after-next)))
10226 (setq expert nil)
10227 (delete-other-windows)
10228 (split-window-vertically)
10229 (org-switch-to-buffer-other-window " *Org tags*")
10230 (org-fit-window-to-buffer)))
10231 ((or (= c ?\C-g)
10232 (and (= c ?q) (not (rassoc c ntable))))
10233 (org-detach-overlay org-tags-overlay)
10234 (setq quit-flag t))
10235 ((= c ?\ )
10236 (setq current nil)
10237 (if exit-after-next (setq exit-after-next 'now)))
10238 ((= c ?\t)
10239 (condition-case nil
10240 (setq tg (org-ido-completing-read
10241 "Tag: "
10242 (or buffer-tags
10243 (with-current-buffer buf
10244 (org-get-buffer-tags)))))
10245 (quit (setq tg "")))
10246 (when (string-match "\\S-" tg)
10247 (add-to-list 'buffer-tags (list tg))
10248 (if (member tg current)
10249 (setq current (delete tg current))
10250 (push tg current)))
10251 (if exit-after-next (setq exit-after-next 'now)))
10252 ((setq e (rassoc c todo-table) tg (car e))
10253 (with-current-buffer buf
10254 (save-excursion (org-todo tg)))
10255 (if exit-after-next (setq exit-after-next 'now)))
10256 ((setq e (rassoc c ntable) tg (car e))
10257 (if (member tg current)
10258 (setq current (delete tg current))
10259 (loop for g in groups do
10260 (if (member tg g)
10261 (mapc (lambda (x)
10262 (setq current (delete x current)))
10263 g)))
10264 (push tg current))
10265 (if exit-after-next (setq exit-after-next 'now))))
10267 ;; Create a sorted list
10268 (setq current
10269 (sort current
10270 (lambda (a b)
10271 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10272 (if (eq exit-after-next 'now) (throw 'exit t))
10273 (goto-char (point-min))
10274 (beginning-of-line 2)
10275 (delete-region (point) (point-at-eol))
10276 (org-fast-tag-insert "Current" current c-face)
10277 (org-set-current-tags-overlay current ov-prefix)
10278 (while (re-search-forward
10279 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10280 (setq tg (match-string 1))
10281 (add-text-properties
10282 (match-beginning 1) (match-end 1)
10283 (list 'face
10284 (cond
10285 ((member tg current) c-face)
10286 ((member tg inherited) i-face)
10287 (t (get-text-property (match-beginning 1) 'face))))))
10288 (goto-char (point-min)))))
10289 (org-detach-overlay org-tags-overlay)
10290 (if rtn
10291 (mapconcat 'identity current ":")
10292 nil))))
10294 (defun org-get-tags-string ()
10295 "Get the TAGS string in the current headline."
10296 (unless (org-on-heading-p t)
10297 (error "Not on a heading"))
10298 (save-excursion
10299 (beginning-of-line 1)
10300 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10301 (org-match-string-no-properties 1)
10302 "")))
10304 (defun org-get-tags ()
10305 "Get the list of tags specified in the current headline."
10306 (org-split-string (org-get-tags-string) ":"))
10308 (defun org-get-buffer-tags ()
10309 "Get a table of all tags used in the buffer, for completion."
10310 (let (tags)
10311 (save-excursion
10312 (goto-char (point-min))
10313 (while (re-search-forward
10314 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10315 (when (equal (char-after (point-at-bol 0)) ?*)
10316 (mapc (lambda (x) (add-to-list 'tags x))
10317 (org-split-string (org-match-string-no-properties 1) ":")))))
10318 (mapcar 'list tags)))
10320 ;;;; The mapping API
10322 ;;;###autoload
10323 (defun org-map-entries (func &optional match scope &rest skip)
10324 "Call FUNC at each headline selected by MATCH in SCOPE.
10326 FUNC is a function or a lisp form. The function will be called without
10327 arguments, with the cursor positioned at the beginning of the headline.
10328 The return values of all calls to the function will be collected and
10329 returned as a list.
10331 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10332 Only headlines that are matched by this query will be considered during
10333 the iteration. When MATCH is nil or t, all headlines will be
10334 visited by the iteration.
10336 SCOPE determines the scope of this command. It can be any of:
10338 nil The current buffer, respecting the restriction if any
10339 tree The subtree started with the entry at point
10340 file The current buffer, without restriction
10341 file-with-archives
10342 The current buffer, and any archives associated with it
10343 agenda All agenda files
10344 agenda-with-archives
10345 All agenda files with any archive files associated with them
10346 \(file1 file2 ...)
10347 If this is a list, all files in the list will be scanned
10349 The remaining args are treated as settings for the skipping facilities of
10350 the scanner. The following items can be given here:
10352 archive skip trees with the archive tag.
10353 comment skip trees with the COMMENT keyword
10354 function or Emacs Lisp form:
10355 will be used as value for `org-agenda-skip-function', so whenever
10356 the the function returns t, FUNC will not be called for that
10357 entry and search will continue from the point where the
10358 function leaves it."
10359 (let* ((org-agenda-archives-mode nil) ; just to make sure
10360 (org-agenda-skip-archived-trees (memq 'archive skip))
10361 (org-agenda-skip-comment-trees (memq 'comment skip))
10362 (org-agenda-skip-function
10363 (car (org-delete-all '(comment archive) skip)))
10364 (org-tags-match-list-sublevels t)
10365 matcher file res
10366 org-todo-keywords-for-agenda
10367 org-done-keywords-for-agenda
10368 org-todo-keyword-alist-for-agenda
10369 org-tag-alist-for-agenda)
10371 (cond
10372 ((eq match t) (setq matcher t))
10373 ((eq match nil) (setq matcher t))
10374 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10376 (save-excursion
10377 (save-restriction
10378 (when (eq scope 'tree)
10379 (org-back-to-heading t)
10380 (org-narrow-to-subtree)
10381 (setq scope nil))
10383 (if (not scope)
10384 (progn
10385 (org-prepare-agenda-buffers
10386 (list (buffer-file-name (current-buffer))))
10387 (setq res (org-scan-tags func matcher)))
10388 ;; Get the right scope
10389 (cond
10390 ((and scope (listp scope) (symbolp (car scope)))
10391 (setq scope (eval scope)))
10392 ((eq scope 'agenda)
10393 (setq scope (org-agenda-files t)))
10394 ((eq scope 'agenda-with-archives)
10395 (setq scope (org-agenda-files t))
10396 (setq scope (org-add-archive-files scope)))
10397 ((eq scope 'file)
10398 (setq scope (list (buffer-file-name))))
10399 ((eq scope 'file-with-archives)
10400 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10401 (org-prepare-agenda-buffers scope)
10402 (while (setq file (pop scope))
10403 (with-current-buffer (org-find-base-buffer-visiting file)
10404 (save-excursion
10405 (save-restriction
10406 (widen)
10407 (goto-char (point-min))
10408 (setq res (append res (org-scan-tags func matcher))))))))))
10409 res))
10411 ;;;; Properties
10413 ;;; Setting and retrieving properties
10415 (defconst org-special-properties
10416 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10417 "TIMESTAMP" "TIMESTAMP_IA")
10418 "The special properties valid in Org-mode.
10420 These are properties that are not defined in the property drawer,
10421 but in some other way.")
10423 (defconst org-default-properties
10424 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10425 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10426 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10427 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10428 "Some properties that are used by Org-mode for various purposes.
10429 Being in this list makes sure that they are offered for completion.")
10431 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10432 "Regular expression matching the first line of a property drawer.")
10434 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10435 "Regular expression matching the first line of a property drawer.")
10437 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10438 "Regular expression matching the first line of a property drawer.")
10440 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10441 "Regular expression matching the first line of a property drawer.")
10443 (defconst org-property-drawer-re
10444 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10445 org-property-end-re "\\)\n?")
10446 "Matches an entire property drawer.")
10448 (defconst org-clock-drawer-re
10449 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10450 org-property-end-re "\\)\n?")
10451 "Matches an entire clock drawer.")
10453 (defun org-property-action ()
10454 "Do an action on properties."
10455 (interactive)
10456 (let (c)
10457 (org-at-property-p)
10458 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10459 (setq c (read-char-exclusive))
10460 (cond
10461 ((equal c ?s)
10462 (call-interactively 'org-set-property))
10463 ((equal c ?d)
10464 (call-interactively 'org-delete-property))
10465 ((equal c ?D)
10466 (call-interactively 'org-delete-property-globally))
10467 ((equal c ?c)
10468 (call-interactively 'org-compute-property-at-point))
10469 (t (error "No such property action %c" c)))))
10471 (defun org-at-property-p ()
10472 "Is the cursor in a property line?"
10473 ;; FIXME: Does not check if we are actually in the drawer.
10474 ;; FIXME: also returns true on any drawers.....
10475 ;; This is used by C-c C-c for property action.
10476 (save-excursion
10477 (beginning-of-line 1)
10478 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10480 (defun org-get-property-block (&optional beg end force)
10481 "Return the (beg . end) range of the body of the property drawer.
10482 BEG and END can be beginning and end of subtree, if not given
10483 they will be found.
10484 If the drawer does not exist and FORCE is non-nil, create the drawer."
10485 (catch 'exit
10486 (save-excursion
10487 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10488 (end (or end (progn (outline-next-heading) (point)))))
10489 (goto-char beg)
10490 (if (re-search-forward org-property-start-re end t)
10491 (setq beg (1+ (match-end 0)))
10492 (if force
10493 (save-excursion
10494 (org-insert-property-drawer)
10495 (setq end (progn (outline-next-heading) (point))))
10496 (throw 'exit nil))
10497 (goto-char beg)
10498 (if (re-search-forward org-property-start-re end t)
10499 (setq beg (1+ (match-end 0)))))
10500 (if (re-search-forward org-property-end-re end t)
10501 (setq end (match-beginning 0))
10502 (or force (throw 'exit nil))
10503 (goto-char beg)
10504 (setq end beg)
10505 (org-indent-line-function)
10506 (insert ":END:\n"))
10507 (cons beg end)))))
10509 (defun org-entry-properties (&optional pom which)
10510 "Get all properties of the entry at point-or-marker POM.
10511 This includes the TODO keyword, the tags, time strings for deadline,
10512 scheduled, and clocking, and any additional properties defined in the
10513 entry. The return value is an alist, keys may occur multiple times
10514 if the property key was used several times.
10515 POM may also be nil, in which case the current entry is used.
10516 If WHICH is nil or `all', get all properties. If WHICH is
10517 `special' or `standard', only get that subclass."
10518 (setq which (or which 'all))
10519 (org-with-point-at pom
10520 (let ((clockstr (substring org-clock-string 0 -1))
10521 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10522 beg end range props sum-props key value string clocksum)
10523 (save-excursion
10524 (when (condition-case nil
10525 (and (org-mode-p) (org-back-to-heading t))
10526 (error nil))
10527 (setq beg (point))
10528 (setq sum-props (get-text-property (point) 'org-summaries))
10529 (setq clocksum (get-text-property (point) :org-clock-minutes))
10530 (outline-next-heading)
10531 (setq end (point))
10532 (when (memq which '(all special))
10533 ;; Get the special properties, like TODO and tags
10534 (goto-char beg)
10535 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10536 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10537 (when (looking-at org-priority-regexp)
10538 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10539 (when (and (setq value (org-get-tags-string))
10540 (string-match "\\S-" value))
10541 (push (cons "TAGS" value) props))
10542 (when (setq value (org-get-tags-at))
10543 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10544 props))
10545 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10546 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10547 string (if (equal key clockstr)
10548 (org-no-properties
10549 (org-trim
10550 (buffer-substring
10551 (match-beginning 3) (goto-char (point-at-eol)))))
10552 (substring (org-match-string-no-properties 3) 1 -1)))
10553 (unless key
10554 (if (= (char-after (match-beginning 3)) ?\[)
10555 (setq key "TIMESTAMP_IA")
10556 (setq key "TIMESTAMP")))
10557 (when (or (equal key clockstr) (not (assoc key props)))
10558 (push (cons key string) props)))
10562 (when (memq which '(all standard))
10563 ;; Get the standard properties, like :PORP: ...
10564 (setq range (org-get-property-block beg end))
10565 (when range
10566 (goto-char (car range))
10567 (while (re-search-forward
10568 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10569 (cdr range) t)
10570 (setq key (org-match-string-no-properties 1)
10571 value (org-trim (or (org-match-string-no-properties 2) "")))
10572 (unless (member key excluded)
10573 (push (cons key (or value "")) props)))))
10574 (if clocksum
10575 (push (cons "CLOCKSUM"
10576 (org-columns-number-to-string (/ (float clocksum) 60.)
10577 'add_times))
10578 props))
10579 (unless (assoc "CATEGORY" props)
10580 (setq value (or (org-get-category)
10581 (progn (org-refresh-category-properties)
10582 (org-get-category))))
10583 (push (cons "CATEGORY" value) props))
10584 (append sum-props (nreverse props)))))))
10586 (defun org-entry-get (pom property &optional inherit)
10587 "Get value of PROPERTY for entry at point-or-marker POM.
10588 If INHERIT is non-nil and the entry does not have the property,
10589 then also check higher levels of the hierarchy.
10590 If INHERIT is the symbol `selective', use inheritance only if the setting
10591 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10592 If the property is present but empty, the return value is the empty string.
10593 If the property is not present at all, nil is returned."
10594 (org-with-point-at pom
10595 (if (and inherit (if (eq inherit 'selective)
10596 (org-property-inherit-p property)
10598 (org-entry-get-with-inheritance property)
10599 (if (member property org-special-properties)
10600 ;; We need a special property. Use brute force, get all properties.
10601 (cdr (assoc property (org-entry-properties nil 'special)))
10602 (let ((range (org-get-property-block)))
10603 (if (and range
10604 (goto-char (car range))
10605 (re-search-forward
10606 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10607 (cdr range) t))
10608 ;; Found the property, return it.
10609 (if (match-end 1)
10610 (org-match-string-no-properties 1)
10611 "")))))))
10613 (defun org-property-or-variable-value (var &optional inherit)
10614 "Check if there is a property fixing the value of VAR.
10615 If yes, return this value. If not, return the current value of the variable."
10616 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10617 (if (and prop (stringp prop) (string-match "\\S-" prop))
10618 (read prop)
10619 (symbol-value var))))
10621 (defun org-entry-delete (pom property)
10622 "Delete the property PROPERTY from entry at point-or-marker POM."
10623 (org-with-point-at pom
10624 (if (member property org-special-properties)
10625 nil ; cannot delete these properties.
10626 (let ((range (org-get-property-block)))
10627 (if (and range
10628 (goto-char (car range))
10629 (re-search-forward
10630 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10631 (cdr range) t))
10632 (progn
10633 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10635 nil)))))
10637 ;; Multi-values properties are properties that contain multiple values
10638 ;; These values are assumed to be single words, separated by whitespace.
10639 (defun org-entry-add-to-multivalued-property (pom property value)
10640 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10641 (let* ((old (org-entry-get pom property))
10642 (values (and old (org-split-string old "[ \t]"))))
10643 (setq value (org-entry-protect-space value))
10644 (unless (member value values)
10645 (setq values (cons value values))
10646 (org-entry-put pom property
10647 (mapconcat 'identity values " ")))))
10649 (defun org-entry-remove-from-multivalued-property (pom property value)
10650 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10651 (let* ((old (org-entry-get pom property))
10652 (values (and old (org-split-string old "[ \t]"))))
10653 (setq value (org-entry-protect-space value))
10654 (when (member value values)
10655 (setq values (delete value values))
10656 (org-entry-put pom property
10657 (mapconcat 'identity values " ")))))
10659 (defun org-entry-member-in-multivalued-property (pom property value)
10660 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10661 (let* ((old (org-entry-get pom property))
10662 (values (and old (org-split-string old "[ \t]"))))
10663 (setq value (org-entry-protect-space value))
10664 (member value values)))
10666 (defun org-entry-get-multivalued-property (pom property)
10667 "Return a list of values in a multivalued property."
10668 (let* ((value (org-entry-get pom property))
10669 (values (and value (org-split-string value "[ \t]"))))
10670 (mapcar 'org-entry-restore-space values)))
10672 (defun org-entry-put-multivalued-property (pom property &rest values)
10673 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10674 VALUES should be a list of strings. Spaces will be protected."
10675 (org-entry-put pom property
10676 (mapconcat 'org-entry-protect-space values " "))
10677 (let* ((value (org-entry-get pom property))
10678 (values (and value (org-split-string value "[ \t]"))))
10679 (mapcar 'org-entry-restore-space values)))
10681 (defun org-entry-protect-space (s)
10682 "Protect spaces and newline in string S."
10683 (while (string-match " " s)
10684 (setq s (replace-match "%20" t t s)))
10685 (while (string-match "\n" s)
10686 (setq s (replace-match "%0A" t t s)))
10689 (defun org-entry-restore-space (s)
10690 "Restore spaces and newline in string S."
10691 (while (string-match "%20" s)
10692 (setq s (replace-match " " t t s)))
10693 (while (string-match "%0A" s)
10694 (setq s (replace-match "\n" t t s)))
10697 (defvar org-entry-property-inherited-from (make-marker)
10698 "Marker pointing to the entry from where a property was inherited.
10699 Each call to `org-entry-get-with-inheritance' will set this marker to the
10700 location of the entry where the inheritance search matched. If there was
10701 no match, the marker will point nowhere.
10702 Note that also `org-entry-get' calls this function, if the INHERIT flag
10703 is set.")
10705 (defun org-entry-get-with-inheritance (property)
10706 "Get entry property, and search higher levels if not present."
10707 (move-marker org-entry-property-inherited-from nil)
10708 (let (tmp)
10709 (save-excursion
10710 (save-restriction
10711 (widen)
10712 (catch 'ex
10713 (while t
10714 (when (setq tmp (org-entry-get nil property))
10715 (org-back-to-heading t)
10716 (move-marker org-entry-property-inherited-from (point))
10717 (throw 'ex tmp))
10718 (or (org-up-heading-safe) (throw 'ex nil)))))
10719 (or tmp
10720 (cdr (assoc property org-file-properties))
10721 (cdr (assoc property org-global-properties))
10722 (cdr (assoc property org-global-properties-fixed))))))
10724 (defun org-entry-put (pom property value)
10725 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10726 (org-with-point-at pom
10727 (org-back-to-heading t)
10728 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10729 range)
10730 (cond
10731 ((equal property "TODO")
10732 (when (and (stringp value) (string-match "\\S-" value)
10733 (not (member value org-todo-keywords-1)))
10734 (error "\"%s\" is not a valid TODO state" value))
10735 (if (or (not value)
10736 (not (string-match "\\S-" value)))
10737 (setq value 'none))
10738 (org-todo value)
10739 (org-set-tags nil 'align))
10740 ((equal property "PRIORITY")
10741 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10742 (string-to-char value) ?\ ))
10743 (org-set-tags nil 'align))
10744 ((equal property "SCHEDULED")
10745 (if (re-search-forward org-scheduled-time-regexp end t)
10746 (cond
10747 ((eq value 'earlier) (org-timestamp-change -1 'day))
10748 ((eq value 'later) (org-timestamp-change 1 'day))
10749 (t (call-interactively 'org-schedule)))
10750 (call-interactively 'org-schedule)))
10751 ((equal property "DEADLINE")
10752 (if (re-search-forward org-deadline-time-regexp end t)
10753 (cond
10754 ((eq value 'earlier) (org-timestamp-change -1 'day))
10755 ((eq value 'later) (org-timestamp-change 1 'day))
10756 (t (call-interactively 'org-deadline)))
10757 (call-interactively 'org-deadline)))
10758 ((member property org-special-properties)
10759 (error "The %s property can not yet be set with `org-entry-put'"
10760 property))
10761 (t ; a non-special property
10762 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10763 (setq range (org-get-property-block beg end 'force))
10764 (goto-char (car range))
10765 (if (re-search-forward
10766 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10767 (progn
10768 (delete-region (match-beginning 1) (match-end 1))
10769 (goto-char (match-beginning 1)))
10770 (goto-char (cdr range))
10771 (insert "\n")
10772 (backward-char 1)
10773 (org-indent-line-function)
10774 (insert ":" property ":"))
10775 (and value (insert " " value))
10776 (org-indent-line-function)))))))
10778 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10779 "Get all property keys in the current buffer.
10780 With INCLUDE-SPECIALS, also list the special properties that reflect things
10781 like tags and TODO state.
10782 With INCLUDE-DEFAULTS, also include properties that has special meaning
10783 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10784 With INCLUDE-COLUMNS, also include property names given in COLUMN
10785 formats in the current buffer."
10786 (let (rtn range cfmt s p)
10787 (save-excursion
10788 (save-restriction
10789 (widen)
10790 (goto-char (point-min))
10791 (while (re-search-forward org-property-start-re nil t)
10792 (setq range (org-get-property-block))
10793 (goto-char (car range))
10794 (while (re-search-forward
10795 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10796 (cdr range) t)
10797 (add-to-list 'rtn (org-match-string-no-properties 1)))
10798 (outline-next-heading))))
10800 (when include-specials
10801 (setq rtn (append org-special-properties rtn)))
10803 (when include-defaults
10804 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10806 (when include-columns
10807 (save-excursion
10808 (save-restriction
10809 (widen)
10810 (goto-char (point-min))
10811 (while (re-search-forward
10812 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10813 nil t)
10814 (setq cfmt (match-string 2) s 0)
10815 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10816 cfmt s)
10817 (setq s (match-end 0)
10818 p (match-string 1 cfmt))
10819 (unless (or (equal p "ITEM")
10820 (member p org-special-properties))
10821 (add-to-list 'rtn (match-string 1 cfmt))))))))
10823 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10825 (defun org-property-values (key)
10826 "Return a list of all values of property KEY."
10827 (save-excursion
10828 (save-restriction
10829 (widen)
10830 (goto-char (point-min))
10831 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10832 values)
10833 (while (re-search-forward re nil t)
10834 (add-to-list 'values (org-trim (match-string 1))))
10835 (delete "" values)))))
10837 (defun org-insert-property-drawer ()
10838 "Insert a property drawer into the current entry."
10839 (interactive)
10840 (org-back-to-heading t)
10841 (looking-at outline-regexp)
10842 (let ((indent (- (match-end 0)(match-beginning 0)))
10843 (beg (point))
10844 (re (concat "^[ \t]*" org-keyword-time-regexp))
10845 end hiddenp)
10846 (outline-next-heading)
10847 (setq end (point))
10848 (goto-char beg)
10849 (while (re-search-forward re end t))
10850 (setq hiddenp (org-invisible-p))
10851 (end-of-line 1)
10852 (and (equal (char-after) ?\n) (forward-char 1))
10853 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10854 (beginning-of-line 2))
10855 (org-skip-over-state-notes)
10856 (skip-chars-backward " \t\n\r")
10857 (if (eq (char-before) ?*) (forward-char 1))
10858 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10859 (beginning-of-line 0)
10860 (org-indent-to-column indent)
10861 (beginning-of-line 2)
10862 (org-indent-to-column indent)
10863 (beginning-of-line 0)
10864 (if hiddenp
10865 (save-excursion
10866 (org-back-to-heading t)
10867 (hide-entry))
10868 (org-flag-drawer t))))
10870 (defun org-set-property (property value)
10871 "In the current entry, set PROPERTY to VALUE.
10872 When called interactively, this will prompt for a property name, offering
10873 completion on existing and default properties. And then it will prompt
10874 for a value, offering completion either on allowed values (via an inherited
10875 xxx_ALL property) or on existing values in other instances of this property
10876 in the current file."
10877 (interactive
10878 (let* ((completion-ignore-case t)
10879 (keys (org-buffer-property-keys nil t t))
10880 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10881 (prop (if (member prop0 keys)
10882 prop0
10883 (or (cdr (assoc (downcase prop0)
10884 (mapcar (lambda (x) (cons (downcase x) x))
10885 keys)))
10886 prop0)))
10887 (cur (org-entry-get nil prop))
10888 (allowed (org-property-get-allowed-values nil prop 'table))
10889 (existing (mapcar 'list (org-property-values prop)))
10890 (val (if allowed
10891 (org-completing-read "Value: " allowed nil 'req-match)
10892 (org-completing-read
10893 (concat "Value" (if (and cur (string-match "\\S-" cur))
10894 (concat "[" cur "]") "")
10895 ": ")
10896 existing nil nil "" nil cur))))
10897 (list prop (if (equal val "") cur val))))
10898 (unless (equal (org-entry-get nil property) value)
10899 (org-entry-put nil property value)))
10901 (defun org-delete-property (property)
10902 "In the current entry, delete PROPERTY."
10903 (interactive
10904 (let* ((completion-ignore-case t)
10905 (prop (org-ido-completing-read
10906 "Property: " (org-entry-properties nil 'standard))))
10907 (list prop)))
10908 (message "Property %s %s" property
10909 (if (org-entry-delete nil property)
10910 "deleted"
10911 "was not present in the entry")))
10913 (defun org-delete-property-globally (property)
10914 "Remove PROPERTY globally, from all entries."
10915 (interactive
10916 (let* ((completion-ignore-case t)
10917 (prop (org-ido-completing-read
10918 "Globally remove property: "
10919 (mapcar 'list (org-buffer-property-keys)))))
10920 (list prop)))
10921 (save-excursion
10922 (save-restriction
10923 (widen)
10924 (goto-char (point-min))
10925 (let ((cnt 0))
10926 (while (re-search-forward
10927 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10928 nil t)
10929 (setq cnt (1+ cnt))
10930 (replace-match ""))
10931 (message "Property \"%s\" removed from %d entries" property cnt)))))
10933 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10935 (defun org-compute-property-at-point ()
10936 "Compute the property at point.
10937 This looks for an enclosing column format, extracts the operator and
10938 then applies it to the property in the column format's scope."
10939 (interactive)
10940 (unless (org-at-property-p)
10941 (error "Not at a property"))
10942 (let ((prop (org-match-string-no-properties 2)))
10943 (org-columns-get-format-and-top-level)
10944 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10945 (error "No operator defined for property %s" prop))
10946 (org-columns-compute prop)))
10948 (defun org-property-get-allowed-values (pom property &optional table)
10949 "Get allowed values for the property PROPERTY.
10950 When TABLE is non-nil, return an alist that can directly be used for
10951 completion."
10952 (let (vals)
10953 (cond
10954 ((equal property "TODO")
10955 (setq vals (org-with-point-at pom
10956 (append org-todo-keywords-1 '("")))))
10957 ((equal property "PRIORITY")
10958 (let ((n org-lowest-priority))
10959 (while (>= n org-highest-priority)
10960 (push (char-to-string n) vals)
10961 (setq n (1- n)))))
10962 ((member property org-special-properties))
10964 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10966 (when (and vals (string-match "\\S-" vals))
10967 (setq vals (car (read-from-string (concat "(" vals ")"))))
10968 (setq vals (mapcar (lambda (x)
10969 (cond ((stringp x) x)
10970 ((numberp x) (number-to-string x))
10971 ((symbolp x) (symbol-name x))
10972 (t "???")))
10973 vals)))))
10974 (if table (mapcar 'list vals) vals)))
10976 (defun org-property-previous-allowed-value (&optional previous)
10977 "Switch to the next allowed value for this property."
10978 (interactive)
10979 (org-property-next-allowed-value t))
10981 (defun org-property-next-allowed-value (&optional previous)
10982 "Switch to the next allowed value for this property."
10983 (interactive)
10984 (unless (org-at-property-p)
10985 (error "Not at a property"))
10986 (let* ((key (match-string 2))
10987 (value (match-string 3))
10988 (allowed (or (org-property-get-allowed-values (point) key)
10989 (and (member value '("[ ]" "[-]" "[X]"))
10990 '("[ ]" "[X]"))))
10991 nval)
10992 (unless allowed
10993 (error "Allowed values for this property have not been defined"))
10994 (if previous (setq allowed (reverse allowed)))
10995 (if (member value allowed)
10996 (setq nval (car (cdr (member value allowed)))))
10997 (setq nval (or nval (car allowed)))
10998 (if (equal nval value)
10999 (error "Only one allowed value for this property"))
11000 (org-at-property-p)
11001 (replace-match (concat " :" key ": " nval) t t)
11002 (org-indent-line-function)
11003 (beginning-of-line 1)
11004 (skip-chars-forward " \t")))
11006 (defun org-find-entry-with-id (ident)
11007 "Locate the entry that contains the ID property with exact value IDENT.
11008 IDENT can be a string, a symbol or a number, this function will search for
11009 the string representation of it.
11010 Return the position where this entry starts, or nil if there is no such entry."
11011 (interactive "sID: ")
11012 (let ((id (cond
11013 ((stringp ident) ident)
11014 ((symbol-name ident) (symbol-name ident))
11015 ((numberp ident) (number-to-string ident))
11016 (t (error "IDENT %s must be a string, symbol or number" ident))))
11017 (case-fold-search nil))
11018 (save-excursion
11019 (save-restriction
11020 (widen)
11021 (goto-char (point-min))
11022 (when (re-search-forward
11023 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11024 nil t)
11025 (org-back-to-heading)
11026 (point))))))
11028 ;;;; Timestamps
11030 (defvar org-last-changed-timestamp nil)
11031 (defvar org-last-inserted-timestamp nil
11032 "The last time stamp inserted with `org-insert-time-stamp'.")
11033 (defvar org-time-was-given) ; dynamically scoped parameter
11034 (defvar org-end-time-was-given) ; dynamically scoped parameter
11035 (defvar org-ts-what) ; dynamically scoped parameter
11037 (defun org-time-stamp (arg &optional inactive)
11038 "Prompt for a date/time and insert a time stamp.
11039 If the user specifies a time like HH:MM, or if this command is called
11040 with a prefix argument, the time stamp will contain date and time.
11041 Otherwise, only the date will be included. All parts of a date not
11042 specified by the user will be filled in from the current date/time.
11043 So if you press just return without typing anything, the time stamp
11044 will represent the current date/time. If there is already a timestamp
11045 at the cursor, it will be modified."
11046 (interactive "P")
11047 (let* ((ts nil)
11048 (default-time
11049 ;; Default time is either today, or, when entering a range,
11050 ;; the range start.
11051 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11052 (save-excursion
11053 (re-search-backward
11054 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11055 (- (point) 20) t)))
11056 (apply 'encode-time (org-parse-time-string (match-string 1)))
11057 (current-time)))
11058 (default-input (and ts (org-get-compact-tod ts)))
11059 org-time-was-given org-end-time-was-given time)
11060 (cond
11061 ((and (org-at-timestamp-p t)
11062 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11063 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11064 (insert "--")
11065 (setq time (let ((this-command this-command))
11066 (org-read-date arg 'totime nil nil
11067 default-time default-input)))
11068 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11069 ((org-at-timestamp-p t)
11070 (setq time (let ((this-command this-command))
11071 (org-read-date arg 'totime nil nil default-time default-input)))
11072 (when (org-at-timestamp-p t) ; just to get the match data
11073 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11074 (replace-match "")
11075 (setq org-last-changed-timestamp
11076 (org-insert-time-stamp
11077 time (or org-time-was-given arg)
11078 inactive nil nil (list org-end-time-was-given))))
11079 (message "Timestamp updated"))
11081 (setq time (let ((this-command this-command))
11082 (org-read-date arg 'totime nil nil default-time default-input)))
11083 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11084 nil nil (list org-end-time-was-given))))))
11086 ;; FIXME: can we use this for something else, like computing time differences?
11087 (defun org-get-compact-tod (s)
11088 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11089 (let* ((t1 (match-string 1 s))
11090 (h1 (string-to-number (match-string 2 s)))
11091 (m1 (string-to-number (match-string 3 s)))
11092 (t2 (and (match-end 4) (match-string 5 s)))
11093 (h2 (and t2 (string-to-number (match-string 6 s))))
11094 (m2 (and t2 (string-to-number (match-string 7 s))))
11095 dh dm)
11096 (if (not t2)
11098 (setq dh (- h2 h1) dm (- m2 m1))
11099 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11100 (concat t1 "+" (number-to-string dh)
11101 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11103 (defun org-time-stamp-inactive (&optional arg)
11104 "Insert an inactive time stamp.
11105 An inactive time stamp is enclosed in square brackets instead of angle
11106 brackets. It is inactive in the sense that it does not trigger agenda entries,
11107 does not link to the calendar and cannot be changed with the S-cursor keys.
11108 So these are more for recording a certain time/date."
11109 (interactive "P")
11110 (org-time-stamp arg 'inactive))
11112 (defvar org-date-ovl (org-make-overlay 1 1))
11113 (org-overlay-put org-date-ovl 'face 'org-warning)
11114 (org-detach-overlay org-date-ovl)
11116 (defvar org-ans1) ; dynamically scoped parameter
11117 (defvar org-ans2) ; dynamically scoped parameter
11119 (defvar org-plain-time-of-day-regexp) ; defined below
11121 (defvar org-overriding-default-time nil) ; dynamically scoped
11122 (defvar org-read-date-overlay nil)
11123 (defvar org-dcst nil) ; dynamically scoped
11125 (defun org-read-date (&optional with-time to-time from-string prompt
11126 default-time default-input)
11127 "Read a date, possibly a time, and make things smooth for the user.
11128 The prompt will suggest to enter an ISO date, but you can also enter anything
11129 which will at least partially be understood by `parse-time-string'.
11130 Unrecognized parts of the date will default to the current day, month, year,
11131 hour and minute. If this command is called to replace a timestamp at point,
11132 of to enter the second timestamp of a range, the default time is taken from the
11133 existing stamp. For example,
11134 3-2-5 --> 2003-02-05
11135 feb 15 --> currentyear-02-15
11136 sep 12 9 --> 2009-09-12
11137 12:45 --> today 12:45
11138 22 sept 0:34 --> currentyear-09-22 0:34
11139 12 --> currentyear-currentmonth-12
11140 Fri --> nearest Friday (today or later)
11141 etc.
11143 Furthermore you can specify a relative date by giving, as the *first* thing
11144 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11145 change in days weeks, months, years.
11146 With a single plus or minus, the date is relative to today. With a double
11147 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11148 +4d --> four days from today
11149 +4 --> same as above
11150 +2w --> two weeks from today
11151 ++5 --> five days from default date
11153 The function understands only English month and weekday abbreviations,
11154 but this can be configured with the variables `parse-time-months' and
11155 `parse-time-weekdays'.
11157 While prompting, a calendar is popped up - you can also select the
11158 date with the mouse (button 1). The calendar shows a period of three
11159 months. To scroll it to other months, use the keys `>' and `<'.
11160 If you don't like the calendar, turn it off with
11161 \(setq org-read-date-popup-calendar nil)
11163 With optional argument TO-TIME, the date will immediately be converted
11164 to an internal time.
11165 With an optional argument WITH-TIME, the prompt will suggest to also
11166 insert a time. Note that when WITH-TIME is not set, you can still
11167 enter a time, and this function will inform the calling routine about
11168 this change. The calling routine may then choose to change the format
11169 used to insert the time stamp into the buffer to include the time.
11170 With optional argument FROM-STRING, read from this string instead from
11171 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11172 the time/date that is used for everything that is not specified by the
11173 user."
11174 (require 'parse-time)
11175 (let* ((org-time-stamp-rounding-minutes
11176 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11177 (org-dcst org-display-custom-times)
11178 (ct (org-current-time))
11179 (def (or org-overriding-default-time default-time ct))
11180 (defdecode (decode-time def))
11181 (dummy (progn
11182 (when (< (nth 2 defdecode) org-extend-today-until)
11183 (setcar (nthcdr 2 defdecode) -1)
11184 (setcar (nthcdr 1 defdecode) 59)
11185 (setq def (apply 'encode-time defdecode)
11186 defdecode (decode-time def)))))
11187 (calendar-move-hook nil)
11188 (calendar-view-diary-initially-flag nil)
11189 (view-diary-entries-initially nil)
11190 (calendar-view-holidays-initially-flag nil)
11191 (view-calendar-holidays-initially nil)
11192 (timestr (format-time-string
11193 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11194 (prompt (concat (if prompt (concat prompt " ") "")
11195 (format "Date+time [%s]: " timestr)))
11196 ans (org-ans0 "") org-ans1 org-ans2 final)
11198 (cond
11199 (from-string (setq ans from-string))
11200 (org-read-date-popup-calendar
11201 (save-excursion
11202 (save-window-excursion
11203 (calendar)
11204 (calendar-forward-day (- (time-to-days def)
11205 (calendar-absolute-from-gregorian
11206 (calendar-current-date))))
11207 (org-eval-in-calendar nil t)
11208 (let* ((old-map (current-local-map))
11209 (map (copy-keymap calendar-mode-map))
11210 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11211 (org-defkey map (kbd "RET") 'org-calendar-select)
11212 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11213 'org-calendar-select-mouse)
11214 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11215 'org-calendar-select-mouse)
11216 (org-defkey minibuffer-local-map [(meta shift left)]
11217 (lambda () (interactive)
11218 (org-eval-in-calendar '(calendar-backward-month 1))))
11219 (org-defkey minibuffer-local-map [(meta shift right)]
11220 (lambda () (interactive)
11221 (org-eval-in-calendar '(calendar-forward-month 1))))
11222 (org-defkey minibuffer-local-map [(meta shift up)]
11223 (lambda () (interactive)
11224 (org-eval-in-calendar '(calendar-backward-year 1))))
11225 (org-defkey minibuffer-local-map [(meta shift down)]
11226 (lambda () (interactive)
11227 (org-eval-in-calendar '(calendar-forward-year 1))))
11228 (org-defkey minibuffer-local-map [(shift up)]
11229 (lambda () (interactive)
11230 (org-eval-in-calendar '(calendar-backward-week 1))))
11231 (org-defkey minibuffer-local-map [(shift down)]
11232 (lambda () (interactive)
11233 (org-eval-in-calendar '(calendar-forward-week 1))))
11234 (org-defkey minibuffer-local-map [(shift left)]
11235 (lambda () (interactive)
11236 (org-eval-in-calendar '(calendar-backward-day 1))))
11237 (org-defkey minibuffer-local-map [(shift right)]
11238 (lambda () (interactive)
11239 (org-eval-in-calendar '(calendar-forward-day 1))))
11240 (org-defkey minibuffer-local-map ">"
11241 (lambda () (interactive)
11242 (org-eval-in-calendar '(scroll-calendar-left 1))))
11243 (org-defkey minibuffer-local-map "<"
11244 (lambda () (interactive)
11245 (org-eval-in-calendar '(scroll-calendar-right 1))))
11246 (unwind-protect
11247 (progn
11248 (use-local-map map)
11249 (add-hook 'post-command-hook 'org-read-date-display)
11250 (setq org-ans0 (read-string prompt default-input nil nil))
11251 ;; org-ans0: from prompt
11252 ;; org-ans1: from mouse click
11253 ;; org-ans2: from calendar motion
11254 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11255 (remove-hook 'post-command-hook 'org-read-date-display)
11256 (use-local-map old-map)
11257 (when org-read-date-overlay
11258 (org-delete-overlay org-read-date-overlay)
11259 (setq org-read-date-overlay nil)))))))
11261 (t ; Naked prompt only
11262 (unwind-protect
11263 (setq ans (read-string prompt default-input nil timestr))
11264 (when org-read-date-overlay
11265 (org-delete-overlay org-read-date-overlay)
11266 (setq org-read-date-overlay nil)))))
11268 (setq final (org-read-date-analyze ans def defdecode))
11270 (if to-time
11271 (apply 'encode-time final)
11272 (if (and (boundp 'org-time-was-given) org-time-was-given)
11273 (format "%04d-%02d-%02d %02d:%02d"
11274 (nth 5 final) (nth 4 final) (nth 3 final)
11275 (nth 2 final) (nth 1 final))
11276 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11277 (defvar def)
11278 (defvar defdecode)
11279 (defvar with-time)
11280 (defun org-read-date-display ()
11281 "Display the current date prompt interpretation in the minibuffer."
11282 (when org-read-date-display-live
11283 (when org-read-date-overlay
11284 (org-delete-overlay org-read-date-overlay))
11285 (let ((p (point)))
11286 (end-of-line 1)
11287 (while (not (equal (buffer-substring
11288 (max (point-min) (- (point) 4)) (point))
11289 " "))
11290 (insert " "))
11291 (goto-char p))
11292 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11293 " " (or org-ans1 org-ans2)))
11294 (org-end-time-was-given nil)
11295 (f (org-read-date-analyze ans def defdecode))
11296 (fmts (if org-dcst
11297 org-time-stamp-custom-formats
11298 org-time-stamp-formats))
11299 (fmt (if (or with-time
11300 (and (boundp 'org-time-was-given) org-time-was-given))
11301 (cdr fmts)
11302 (car fmts)))
11303 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11304 (when (and org-end-time-was-given
11305 (string-match org-plain-time-of-day-regexp txt))
11306 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11307 org-end-time-was-given
11308 (substring txt (match-end 0)))))
11309 (setq org-read-date-overlay
11310 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11311 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11313 (defun org-read-date-analyze (ans def defdecode)
11314 "Analyse the combined answer of the date prompt."
11315 ;; FIXME: cleanup and comment
11316 (let (delta deltan deltaw deltadef year month day
11317 hour minute second wday pm h2 m2 tl wday1
11318 iso-year iso-weekday iso-week iso-year iso-date)
11320 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11321 (setq ans "+0"))
11323 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11324 (setq ans (replace-match "" t t ans)
11325 deltan (car delta)
11326 deltaw (nth 1 delta)
11327 deltadef (nth 2 delta)))
11329 ;; Check if there is an iso week date in there
11330 ;; If yes, sore the info and postpone interpreting it until the rest
11331 ;; of the parsing is done
11332 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11333 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11334 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11335 iso-week (string-to-number (match-string 2 ans)))
11336 (setq ans (replace-match "" t t ans)))
11338 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11339 (when (string-match
11340 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11341 (setq year (if (match-end 2)
11342 (string-to-number (match-string 2 ans))
11343 (string-to-number (format-time-string "%Y")))
11344 month (string-to-number (match-string 3 ans))
11345 day (string-to-number (match-string 4 ans)))
11346 (if (< year 100) (setq year (+ 2000 year)))
11347 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11348 t nil ans)))
11349 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11350 ;; If there is a time with am/pm, and *no* time without it, we convert
11351 ;; so that matching will be successful.
11352 (loop for i from 1 to 2 do ; twice, for end time as well
11353 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11354 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11355 (setq hour (string-to-number (match-string 1 ans))
11356 minute (if (match-end 3)
11357 (string-to-number (match-string 3 ans))
11359 pm (equal ?p
11360 (string-to-char (downcase (match-string 4 ans)))))
11361 (if (and (= hour 12) (not pm))
11362 (setq hour 0)
11363 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11364 (setq ans (replace-match (format "%02d:%02d" hour minute)
11365 t t ans))))
11367 ;; Check if a time range is given as a duration
11368 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11369 (setq hour (string-to-number (match-string 1 ans))
11370 h2 (+ hour (string-to-number (match-string 3 ans)))
11371 minute (string-to-number (match-string 2 ans))
11372 m2 (+ minute (if (match-end 5) (string-to-number
11373 (match-string 5 ans))0)))
11374 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11375 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11376 t t ans)))
11378 ;; Check if there is a time range
11379 (when (boundp 'org-end-time-was-given)
11380 (setq org-time-was-given nil)
11381 (when (and (string-match org-plain-time-of-day-regexp ans)
11382 (match-end 8))
11383 (setq org-end-time-was-given (match-string 8 ans))
11384 (setq ans (concat (substring ans 0 (match-beginning 7))
11385 (substring ans (match-end 7))))))
11387 (setq tl (parse-time-string ans)
11388 day (or (nth 3 tl) (nth 3 defdecode))
11389 month (or (nth 4 tl)
11390 (if (and org-read-date-prefer-future
11391 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11392 (1+ (nth 4 defdecode))
11393 (nth 4 defdecode)))
11394 year (or (nth 5 tl)
11395 (if (and org-read-date-prefer-future
11396 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11397 (1+ (nth 5 defdecode))
11398 (nth 5 defdecode)))
11399 hour (or (nth 2 tl) (nth 2 defdecode))
11400 minute (or (nth 1 tl) (nth 1 defdecode))
11401 second (or (nth 0 tl) 0)
11402 wday (nth 6 tl))
11404 ;; Special date definitions below
11405 (cond
11406 (iso-week
11407 ;; There was an iso week
11408 (setq year (or iso-year year)
11409 day (or iso-weekday wday 1)
11410 wday nil ; to make sure that the trigger below does not match
11411 iso-date (calendar-gregorian-from-absolute
11412 (calendar-absolute-from-iso
11413 (list iso-week day year))))
11414 ; FIXME: Should we also push ISO weeks into the future?
11415 ; (when (and org-read-date-prefer-future
11416 ; (not iso-year)
11417 ; (< (calendar-absolute-from-gregorian iso-date)
11418 ; (time-to-days (current-time))))
11419 ; (setq year (1+ year)
11420 ; iso-date (calendar-gregorian-from-absolute
11421 ; (calendar-absolute-from-iso
11422 ; (list iso-week day year)))))
11423 (setq month (car iso-date)
11424 year (nth 2 iso-date)
11425 day (nth 1 iso-date)))
11426 (deltan
11427 (unless deltadef
11428 (let ((now (decode-time (current-time))))
11429 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11430 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11431 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11432 ((equal deltaw "m") (setq month (+ month deltan)))
11433 ((equal deltaw "y") (setq year (+ year deltan)))))
11434 ((and wday (not (nth 3 tl)))
11435 ;; Weekday was given, but no day, so pick that day in the week
11436 ;; on or after the derived date.
11437 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11438 (unless (equal wday wday1)
11439 (setq day (+ day (% (- wday wday1 -7) 7))))))
11440 (if (and (boundp 'org-time-was-given)
11441 (nth 2 tl))
11442 (setq org-time-was-given t))
11443 (if (< year 100) (setq year (+ 2000 year)))
11444 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11445 (list second minute hour day month year)))
11447 (defvar parse-time-weekdays)
11449 (defun org-read-date-get-relative (s today default)
11450 "Check string S for special relative date string.
11451 TODAY and DEFAULT are internal times, for today and for a default.
11452 Return shift list (N what def-flag)
11453 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11454 N is the number of WHATs to shift.
11455 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11456 the DEFAULT date rather than TODAY."
11457 (when (and
11458 (string-match
11459 (concat
11460 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11461 "\\([0-9]+\\)?"
11462 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11463 "\\([ \t]\\|$\\)") s)
11464 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11465 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11466 (string-to-char (substring (match-string 1 s) -1))
11467 ?+))
11468 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11469 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11470 (what (if (match-end 3) (match-string 3 s) "d"))
11471 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11472 (date (if rel default today))
11473 (wday (nth 6 (decode-time date)))
11474 delta)
11475 (if wday1
11476 (progn
11477 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11478 (if (= dir ?-) (setq delta (- delta 7)))
11479 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11480 (list delta "d" rel))
11481 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11483 (defun org-eval-in-calendar (form &optional keepdate)
11484 "Eval FORM in the calendar window and return to current window.
11485 Also, store the cursor date in variable org-ans2."
11486 (let ((sw (selected-window)))
11487 (select-window (get-buffer-window "*Calendar*"))
11488 (eval form)
11489 (when (and (not keepdate) (calendar-cursor-to-date))
11490 (let* ((date (calendar-cursor-to-date))
11491 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11492 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11493 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11494 (select-window sw)))
11496 (defun org-calendar-select ()
11497 "Return to `org-read-date' with the date currently selected.
11498 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11499 (interactive)
11500 (when (calendar-cursor-to-date)
11501 (let* ((date (calendar-cursor-to-date))
11502 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11503 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11504 (if (active-minibuffer-window) (exit-minibuffer))))
11506 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11507 "Insert a date stamp for the date given by the internal TIME.
11508 WITH-HM means, use the stamp format that includes the time of the day.
11509 INACTIVE means use square brackets instead of angular ones, so that the
11510 stamp will not contribute to the agenda.
11511 PRE and POST are optional strings to be inserted before and after the
11512 stamp.
11513 The command returns the inserted time stamp."
11514 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11515 stamp)
11516 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11517 (insert-before-markers (or pre ""))
11518 (insert-before-markers (setq stamp (format-time-string fmt time)))
11519 (when (listp extra)
11520 (setq extra (car extra))
11521 (if (and (stringp extra)
11522 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11523 (setq extra (format "-%02d:%02d"
11524 (string-to-number (match-string 1 extra))
11525 (string-to-number (match-string 2 extra))))
11526 (setq extra nil)))
11527 (when extra
11528 (backward-char 1)
11529 (insert-before-markers extra)
11530 (forward-char 1))
11531 (insert-before-markers (or post ""))
11532 (setq org-last-inserted-timestamp stamp)))
11534 (defun org-toggle-time-stamp-overlays ()
11535 "Toggle the use of custom time stamp formats."
11536 (interactive)
11537 (setq org-display-custom-times (not org-display-custom-times))
11538 (unless org-display-custom-times
11539 (let ((p (point-min)) (bmp (buffer-modified-p)))
11540 (while (setq p (next-single-property-change p 'display))
11541 (if (and (get-text-property p 'display)
11542 (eq (get-text-property p 'face) 'org-date))
11543 (remove-text-properties
11544 p (setq p (next-single-property-change p 'display))
11545 '(display t))))
11546 (set-buffer-modified-p bmp)))
11547 (if (featurep 'xemacs)
11548 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11549 (org-restart-font-lock)
11550 (setq org-table-may-need-update t)
11551 (if org-display-custom-times
11552 (message "Time stamps are overlayed with custom format")
11553 (message "Time stamp overlays removed")))
11555 (defun org-display-custom-time (beg end)
11556 "Overlay modified time stamp format over timestamp between BEG and END."
11557 (let* ((ts (buffer-substring beg end))
11558 t1 w1 with-hm tf time str w2 (off 0))
11559 (save-match-data
11560 (setq t1 (org-parse-time-string ts t))
11561 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11562 (setq off (- (match-end 0) (match-beginning 0)))))
11563 (setq end (- end off))
11564 (setq w1 (- end beg)
11565 with-hm (and (nth 1 t1) (nth 2 t1))
11566 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11567 time (org-fix-decoded-time t1)
11568 str (org-add-props
11569 (format-time-string
11570 (substring tf 1 -1) (apply 'encode-time time))
11571 nil 'mouse-face 'highlight)
11572 w2 (length str))
11573 (if (not (= w2 w1))
11574 (add-text-properties (1+ beg) (+ 2 beg)
11575 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11576 (if (featurep 'xemacs)
11577 (progn
11578 (put-text-property beg end 'invisible t)
11579 (put-text-property beg end 'end-glyph (make-glyph str)))
11580 (put-text-property beg end 'display str))))
11582 (defun org-translate-time (string)
11583 "Translate all timestamps in STRING to custom format.
11584 But do this only if the variable `org-display-custom-times' is set."
11585 (when org-display-custom-times
11586 (save-match-data
11587 (let* ((start 0)
11588 (re org-ts-regexp-both)
11589 t1 with-hm inactive tf time str beg end)
11590 (while (setq start (string-match re string start))
11591 (setq beg (match-beginning 0)
11592 end (match-end 0)
11593 t1 (save-match-data
11594 (org-parse-time-string (substring string beg end) t))
11595 with-hm (and (nth 1 t1) (nth 2 t1))
11596 inactive (equal (substring string beg (1+ beg)) "[")
11597 tf (funcall (if with-hm 'cdr 'car)
11598 org-time-stamp-custom-formats)
11599 time (org-fix-decoded-time t1)
11600 str (format-time-string
11601 (concat
11602 (if inactive "[" "<") (substring tf 1 -1)
11603 (if inactive "]" ">"))
11604 (apply 'encode-time time))
11605 string (replace-match str t t string)
11606 start (+ start (length str)))))))
11607 string)
11609 (defun org-fix-decoded-time (time)
11610 "Set 0 instead of nil for the first 6 elements of time.
11611 Don't touch the rest."
11612 (let ((n 0))
11613 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11615 (defun org-days-to-time (timestamp-string)
11616 "Difference between TIMESTAMP-STRING and now in days."
11617 (- (time-to-days (org-time-string-to-time timestamp-string))
11618 (time-to-days (current-time))))
11620 (defun org-deadline-close (timestamp-string &optional ndays)
11621 "Is the time in TIMESTAMP-STRING close to the current date?"
11622 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11623 (and (< (org-days-to-time timestamp-string) ndays)
11624 (not (org-entry-is-done-p))))
11626 (defun org-get-wdays (ts)
11627 "Get the deadline lead time appropriate for timestring TS."
11628 (cond
11629 ((<= org-deadline-warning-days 0)
11630 ;; 0 or negative, enforce this value no matter what
11631 (- org-deadline-warning-days))
11632 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11633 ;; lead time is specified.
11634 (floor (* (string-to-number (match-string 1 ts))
11635 (cdr (assoc (match-string 2 ts)
11636 '(("d" . 1) ("w" . 7)
11637 ("m" . 30.4) ("y" . 365.25)))))))
11638 ;; go for the default.
11639 (t org-deadline-warning-days)))
11641 (defun org-calendar-select-mouse (ev)
11642 "Return to `org-read-date' with the date currently selected.
11643 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11644 (interactive "e")
11645 (mouse-set-point ev)
11646 (when (calendar-cursor-to-date)
11647 (let* ((date (calendar-cursor-to-date))
11648 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11649 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11650 (if (active-minibuffer-window) (exit-minibuffer))))
11652 (defun org-check-deadlines (ndays)
11653 "Check if there are any deadlines due or past due.
11654 A deadline is considered due if it happens within `org-deadline-warning-days'
11655 days from today's date. If the deadline appears in an entry marked DONE,
11656 it is not shown. The prefix arg NDAYS can be used to test that many
11657 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11658 (interactive "P")
11659 (let* ((org-warn-days
11660 (cond
11661 ((equal ndays '(4)) 100000)
11662 (ndays (prefix-numeric-value ndays))
11663 (t (abs org-deadline-warning-days))))
11664 (case-fold-search nil)
11665 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11666 (callback
11667 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11669 (message "%d deadlines past-due or due within %d days"
11670 (org-occur regexp nil callback)
11671 org-warn-days)))
11673 (defun org-check-before-date (date)
11674 "Check if there are deadlines or scheduled entries before DATE."
11675 (interactive (list (org-read-date)))
11676 (let ((case-fold-search nil)
11677 (regexp (concat "\\<\\(" org-deadline-string
11678 "\\|" org-scheduled-string
11679 "\\) *<\\([^>]+\\)>"))
11680 (callback
11681 (lambda () (time-less-p
11682 (org-time-string-to-time (match-string 2))
11683 (org-time-string-to-time date)))))
11684 (message "%d entries before %s"
11685 (org-occur regexp nil callback) date)))
11687 (defun org-evaluate-time-range (&optional to-buffer)
11688 "Evaluate a time range by computing the difference between start and end.
11689 Normally the result is just printed in the echo area, but with prefix arg
11690 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11691 If the time range is actually in a table, the result is inserted into the
11692 next column.
11693 For time difference computation, a year is assumed to be exactly 365
11694 days in order to avoid rounding problems."
11695 (interactive "P")
11697 (org-clock-update-time-maybe)
11698 (save-excursion
11699 (unless (org-at-date-range-p t)
11700 (goto-char (point-at-bol))
11701 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11702 (if (not (org-at-date-range-p t))
11703 (error "Not at a time-stamp range, and none found in current line")))
11704 (let* ((ts1 (match-string 1))
11705 (ts2 (match-string 2))
11706 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11707 (match-end (match-end 0))
11708 (time1 (org-time-string-to-time ts1))
11709 (time2 (org-time-string-to-time ts2))
11710 (t1 (time-to-seconds time1))
11711 (t2 (time-to-seconds time2))
11712 (diff (abs (- t2 t1)))
11713 (negative (< (- t2 t1) 0))
11714 ;; (ys (floor (* 365 24 60 60)))
11715 (ds (* 24 60 60))
11716 (hs (* 60 60))
11717 (fy "%dy %dd %02d:%02d")
11718 (fy1 "%dy %dd")
11719 (fd "%dd %02d:%02d")
11720 (fd1 "%dd")
11721 (fh "%02d:%02d")
11722 y d h m align)
11723 (if havetime
11724 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11726 d (floor (/ diff ds)) diff (mod diff ds)
11727 h (floor (/ diff hs)) diff (mod diff hs)
11728 m (floor (/ diff 60)))
11729 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11731 d (floor (+ (/ diff ds) 0.5))
11732 h 0 m 0))
11733 (if (not to-buffer)
11734 (message "%s" (org-make-tdiff-string y d h m))
11735 (if (org-at-table-p)
11736 (progn
11737 (goto-char match-end)
11738 (setq align t)
11739 (and (looking-at " *|") (goto-char (match-end 0))))
11740 (goto-char match-end))
11741 (if (looking-at
11742 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11743 (replace-match ""))
11744 (if negative (insert " -"))
11745 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11746 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11747 (insert " " (format fh h m))))
11748 (if align (org-table-align))
11749 (message "Time difference inserted")))))
11751 (defun org-make-tdiff-string (y d h m)
11752 (let ((fmt "")
11753 (l nil))
11754 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11755 l (push y l)))
11756 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11757 l (push d l)))
11758 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11759 l (push h l)))
11760 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11761 l (push m l)))
11762 (apply 'format fmt (nreverse l))))
11764 (defun org-time-string-to-time (s)
11765 (apply 'encode-time (org-parse-time-string s)))
11767 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11768 "Convert a time stamp to an absolute day number.
11769 If there is a specifyer for a cyclic time stamp, get the closest date to
11770 DAYNR.
11771 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11772 (cond
11773 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11774 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11775 daynr
11776 (+ daynr 1000)))
11777 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11778 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11779 (time-to-days (current-time))) (match-string 0 s)
11780 prefer show-all))
11781 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11783 (defun org-days-to-iso-week (days)
11784 "Return the iso week number."
11785 (require 'cal-iso)
11786 (car (calendar-iso-from-absolute days)))
11788 (defun org-small-year-to-year (year)
11789 "Convert 2-digit years into 4-digit years.
11790 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11791 The year 2000 cannot be abbreviated. Any year larger than 99
11792 is returned unchanged."
11793 (if (< year 38)
11794 (setq year (+ 2000 year))
11795 (if (< year 100)
11796 (setq year (+ 1900 year))))
11797 year)
11799 (defun org-time-from-absolute (d)
11800 "Return the time corresponding to date D.
11801 D may be an absolute day number, or a calendar-type list (month day year)."
11802 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11803 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11805 (defun org-calendar-holiday ()
11806 "List of holidays, for Diary display in Org-mode."
11807 (require 'holidays)
11808 (let ((hl (funcall
11809 (if (fboundp 'calendar-check-holidays)
11810 'calendar-check-holidays 'check-calendar-holidays) date)))
11811 (if hl (mapconcat 'identity hl "; "))))
11813 (defun org-diary-sexp-entry (sexp entry date)
11814 "Process a SEXP diary ENTRY for DATE."
11815 (require 'diary-lib)
11816 (let ((result (if calendar-debug-sexp
11817 (let ((stack-trace-on-error t))
11818 (eval (car (read-from-string sexp))))
11819 (condition-case nil
11820 (eval (car (read-from-string sexp)))
11821 (error
11822 (beep)
11823 (message "Bad sexp at line %d in %s: %s"
11824 (org-current-line)
11825 (buffer-file-name) sexp)
11826 (sleep-for 2))))))
11827 (cond ((stringp result) result)
11828 ((and (consp result)
11829 (stringp (cdr result))) (cdr result))
11830 (result entry)
11831 (t nil))))
11833 (defun org-diary-to-ical-string (frombuf)
11834 "Get iCalendar entries from diary entries in buffer FROMBUF.
11835 This uses the icalendar.el library."
11836 (let* ((tmpdir (if (featurep 'xemacs)
11837 (temp-directory)
11838 temporary-file-directory))
11839 (tmpfile (make-temp-name
11840 (expand-file-name "orgics" tmpdir)))
11841 buf rtn b e)
11842 (save-excursion
11843 (set-buffer frombuf)
11844 (icalendar-export-region (point-min) (point-max) tmpfile)
11845 (setq buf (find-buffer-visiting tmpfile))
11846 (set-buffer buf)
11847 (goto-char (point-min))
11848 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11849 (setq b (match-beginning 0)))
11850 (goto-char (point-max))
11851 (if (re-search-backward "^END:VEVENT" nil t)
11852 (setq e (match-end 0)))
11853 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11854 (kill-buffer buf)
11855 (delete-file tmpfile)
11856 rtn))
11858 (defun org-closest-date (start current change prefer show-all)
11859 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11860 When PREFER is `past' return a date that is either CURRENT or past.
11861 When PREFER is `future', return a date that is either CURRENT or future.
11862 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11863 ;; Make the proper lists from the dates
11864 (catch 'exit
11865 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11866 dn dw sday cday n1 n2 n0
11867 d m y y1 y2 date1 date2 nmonths nm ny m2)
11869 (setq start (org-date-to-gregorian start)
11870 current (org-date-to-gregorian
11871 (if show-all
11872 current
11873 (time-to-days (current-time))))
11874 sday (calendar-absolute-from-gregorian start)
11875 cday (calendar-absolute-from-gregorian current))
11877 (if (<= cday sday) (throw 'exit sday))
11879 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11880 (setq dn (string-to-number (match-string 1 change))
11881 dw (cdr (assoc (match-string 2 change) a1)))
11882 (error "Invalid change specifyer: %s" change))
11883 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11884 (cond
11885 ((eq dw 'day)
11886 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11887 n2 (+ n1 dn)))
11888 ((eq dw 'year)
11889 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11890 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11891 (setq date1 (list m d y1)
11892 n1 (calendar-absolute-from-gregorian date1)
11893 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11894 n2 (calendar-absolute-from-gregorian date2)))
11895 ((eq dw 'month)
11896 ;; approx number of month between the two dates
11897 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11898 ;; How often does dn fit in there?
11899 (setq d (nth 1 start) m (car start) y (nth 2 start)
11900 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11901 m (+ m nm)
11902 ny (floor (/ m 12))
11903 y (+ y ny)
11904 m (- m (* ny 12)))
11905 (while (> m 12) (setq m (- m 12) y (1+ y)))
11906 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11907 (setq m2 (+ m dn) y2 y)
11908 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11909 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11910 (while (<= n2 cday)
11911 (setq n1 n2 m m2 y y2)
11912 (setq m2 (+ m dn) y2 y)
11913 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11914 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11915 ;; Make sure n1 is the earlier date
11916 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11917 (if show-all
11918 (cond
11919 ((eq prefer 'past) n1)
11920 ((eq prefer 'future) (if (= cday n1) n1 n2))
11921 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11922 (cond
11923 ((eq prefer 'past) n1)
11924 ((eq prefer 'future) (if (= cday n1) n1 n2))
11925 (t (if (= cday n1) n1 n2)))))))
11927 (defun org-date-to-gregorian (date)
11928 "Turn any specification of DATE into a gregorian date for the calendar."
11929 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11930 ((and (listp date) (= (length date) 3)) date)
11931 ((stringp date)
11932 (setq date (org-parse-time-string date))
11933 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11934 ((listp date)
11935 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11937 (defun org-parse-time-string (s &optional nodefault)
11938 "Parse the standard Org-mode time string.
11939 This should be a lot faster than the normal `parse-time-string'.
11940 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11941 hour and minute fields will be nil if not given."
11942 (if (string-match org-ts-regexp0 s)
11943 (list 0
11944 (if (or (match-beginning 8) (not nodefault))
11945 (string-to-number (or (match-string 8 s) "0")))
11946 (if (or (match-beginning 7) (not nodefault))
11947 (string-to-number (or (match-string 7 s) "0")))
11948 (string-to-number (match-string 4 s))
11949 (string-to-number (match-string 3 s))
11950 (string-to-number (match-string 2 s))
11951 nil nil nil)
11952 (make-list 9 0)))
11954 (defun org-timestamp-up (&optional arg)
11955 "Increase the date item at the cursor by one.
11956 If the cursor is on the year, change the year. If it is on the month or
11957 the day, change that.
11958 With prefix ARG, change by that many units."
11959 (interactive "p")
11960 (org-timestamp-change (prefix-numeric-value arg)))
11962 (defun org-timestamp-down (&optional arg)
11963 "Decrease the date item at the cursor by one.
11964 If the cursor is on the year, change the year. If it is on the month or
11965 the day, change that.
11966 With prefix ARG, change by that many units."
11967 (interactive "p")
11968 (org-timestamp-change (- (prefix-numeric-value arg))))
11970 (defun org-timestamp-up-day (&optional arg)
11971 "Increase the date in the time stamp by one day.
11972 With prefix ARG, change that many days."
11973 (interactive "p")
11974 (if (and (not (org-at-timestamp-p t))
11975 (org-on-heading-p))
11976 (org-todo 'up)
11977 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11979 (defun org-timestamp-down-day (&optional arg)
11980 "Decrease the date in the time stamp by one day.
11981 With prefix ARG, change that many days."
11982 (interactive "p")
11983 (if (and (not (org-at-timestamp-p t))
11984 (org-on-heading-p))
11985 (org-todo 'down)
11986 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11988 (defun org-at-timestamp-p (&optional inactive-ok)
11989 "Determine if the cursor is in or at a timestamp."
11990 (interactive)
11991 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11992 (pos (point))
11993 (ans (or (looking-at tsr)
11994 (save-excursion
11995 (skip-chars-backward "^[<\n\r\t")
11996 (if (> (point) (point-min)) (backward-char 1))
11997 (and (looking-at tsr)
11998 (> (- (match-end 0) pos) -1))))))
11999 (and ans
12000 (boundp 'org-ts-what)
12001 (setq org-ts-what
12002 (cond
12003 ((= pos (match-beginning 0)) 'bracket)
12004 ((= pos (1- (match-end 0))) 'bracket)
12005 ((org-pos-in-match-range pos 2) 'year)
12006 ((org-pos-in-match-range pos 3) 'month)
12007 ((org-pos-in-match-range pos 7) 'hour)
12008 ((org-pos-in-match-range pos 8) 'minute)
12009 ((or (org-pos-in-match-range pos 4)
12010 (org-pos-in-match-range pos 5)) 'day)
12011 ((and (> pos (or (match-end 8) (match-end 5)))
12012 (< pos (match-end 0)))
12013 (- pos (or (match-end 8) (match-end 5))))
12014 (t 'day))))
12015 ans))
12017 (defun org-toggle-timestamp-type ()
12018 "Toggle the type (<active> or [inactive]) of a time stamp."
12019 (interactive)
12020 (when (org-at-timestamp-p t)
12021 (let ((beg (match-beginning 0)) (end (match-end 0))
12022 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12023 (save-excursion
12024 (goto-char beg)
12025 (while (re-search-forward "[][<>]" end t)
12026 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12027 t t)))
12028 (message "Timestamp is now %sactive"
12029 (if (equal (char-after beg) ?<) "" "in")))))
12031 (defun org-timestamp-change (n &optional what)
12032 "Change the date in the time stamp at point.
12033 The date will be changed by N times WHAT. WHAT can be `day', `month',
12034 `year', `minute', `second'. If WHAT is not given, the cursor position
12035 in the timestamp determines what will be changed."
12036 (let ((pos (point))
12037 with-hm inactive
12038 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12039 org-ts-what
12040 extra rem
12041 ts time time0)
12042 (if (not (org-at-timestamp-p t))
12043 (error "Not at a timestamp"))
12044 (if (and (not what) (eq org-ts-what 'bracket))
12045 (org-toggle-timestamp-type)
12046 (if (and (not what) (not (eq org-ts-what 'day))
12047 org-display-custom-times
12048 (get-text-property (point) 'display)
12049 (not (get-text-property (1- (point)) 'display)))
12050 (setq org-ts-what 'day))
12051 (setq org-ts-what (or what org-ts-what)
12052 inactive (= (char-after (match-beginning 0)) ?\[)
12053 ts (match-string 0))
12054 (replace-match "")
12055 (if (string-match
12056 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12058 (setq extra (match-string 1 ts)))
12059 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12060 (setq with-hm t))
12061 (setq time0 (org-parse-time-string ts))
12062 (when (and (eq org-ts-what 'minute)
12063 (eq current-prefix-arg nil))
12064 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12065 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12066 (setcar (cdr time0) (+ (nth 1 time0)
12067 (if (> n 0) (- rem) (- dm rem))))))
12068 (setq time
12069 (encode-time (or (car time0) 0)
12070 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12071 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12072 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12073 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12074 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12075 (nthcdr 6 time0)))
12076 (when (integerp org-ts-what)
12077 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12078 (if (eq what 'calendar)
12079 (let ((cal-date (org-get-date-from-calendar)))
12080 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12081 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12082 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12083 (setcar time0 (or (car time0) 0))
12084 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12085 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12086 (setq time (apply 'encode-time time0))))
12087 (setq org-last-changed-timestamp
12088 (org-insert-time-stamp time with-hm inactive nil nil extra))
12089 (org-clock-update-time-maybe)
12090 (goto-char pos)
12091 ;; Try to recenter the calendar window, if any
12092 (if (and org-calendar-follow-timestamp-change
12093 (get-buffer-window "*Calendar*" t)
12094 (memq org-ts-what '(day month year)))
12095 (org-recenter-calendar (time-to-days time))))))
12097 (defun org-modify-ts-extra (s pos n dm)
12098 "Change the different parts of the lead-time and repeat fields in timestamp."
12099 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12100 ng h m new rem)
12101 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12102 (cond
12103 ((or (org-pos-in-match-range pos 2)
12104 (org-pos-in-match-range pos 3))
12105 (setq m (string-to-number (match-string 3 s))
12106 h (string-to-number (match-string 2 s)))
12107 (if (org-pos-in-match-range pos 2)
12108 (setq h (+ h n))
12109 (setq n (* dm (org-no-warnings (signum n))))
12110 (when (not (= 0 (setq rem (% m dm))))
12111 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12112 (setq m (+ m n)))
12113 (if (< m 0) (setq m (+ m 60) h (1- h)))
12114 (if (> m 59) (setq m (- m 60) h (1+ h)))
12115 (setq h (min 24 (max 0 h)))
12116 (setq ng 1 new (format "-%02d:%02d" h m)))
12117 ((org-pos-in-match-range pos 6)
12118 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12119 ((org-pos-in-match-range pos 5)
12120 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12122 ((org-pos-in-match-range pos 9)
12123 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12124 ((org-pos-in-match-range pos 8)
12125 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12127 (when ng
12128 (setq s (concat
12129 (substring s 0 (match-beginning ng))
12131 (substring s (match-end ng))))))
12134 (defun org-recenter-calendar (date)
12135 "If the calendar is visible, recenter it to DATE."
12136 (let* ((win (selected-window))
12137 (cwin (get-buffer-window "*Calendar*" t))
12138 (calendar-move-hook nil))
12139 (when cwin
12140 (select-window cwin)
12141 (calendar-goto-date (if (listp date) date
12142 (calendar-gregorian-from-absolute date)))
12143 (select-window win))))
12145 (defun org-goto-calendar (&optional arg)
12146 "Go to the Emacs calendar at the current date.
12147 If there is a time stamp in the current line, go to that date.
12148 A prefix ARG can be used to force the current date."
12149 (interactive "P")
12150 (let ((tsr org-ts-regexp) diff
12151 (calendar-move-hook nil)
12152 (calendar-view-holidays-initially-flag nil)
12153 (view-calendar-holidays-initially nil)
12154 (calendar-view-diary-initially-flag nil)
12155 (view-diary-entries-initially nil))
12156 (if (or (org-at-timestamp-p)
12157 (save-excursion
12158 (beginning-of-line 1)
12159 (looking-at (concat ".*" tsr))))
12160 (let ((d1 (time-to-days (current-time)))
12161 (d2 (time-to-days
12162 (org-time-string-to-time (match-string 1)))))
12163 (setq diff (- d2 d1))))
12164 (calendar)
12165 (calendar-goto-today)
12166 (if (and diff (not arg)) (calendar-forward-day diff))))
12168 (defun org-get-date-from-calendar ()
12169 "Return a list (month day year) of date at point in calendar."
12170 (with-current-buffer "*Calendar*"
12171 (save-match-data
12172 (calendar-cursor-to-date))))
12174 (defun org-date-from-calendar ()
12175 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12176 If there is already a time stamp at the cursor position, update it."
12177 (interactive)
12178 (if (org-at-timestamp-p t)
12179 (org-timestamp-change 0 'calendar)
12180 (let ((cal-date (org-get-date-from-calendar)))
12181 (org-insert-time-stamp
12182 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12184 (defun org-minutes-to-hh:mm-string (m)
12185 "Compute H:MM from a number of minutes."
12186 (let ((h (/ m 60)))
12187 (setq m (- m (* 60 h)))
12188 (format org-time-clocksum-format h m)))
12190 (defun org-hh:mm-string-to-minutes (s)
12191 "Convert a string H:MM to a number of minutes."
12192 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12193 (+ (* (string-to-number (match-string 1 s)) 60)
12194 (string-to-number (match-string 2 s)))
12197 ;;;; Agenda files
12199 ;;;###autoload
12200 (defun org-iswitchb (&optional arg)
12201 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12202 With a prefix argument, restrict available to files.
12203 With two prefix arguments, restrict available buffers to agenda files.
12205 Due to some yet unresolved reason, the global function
12206 `iswitchb-mode' needs to be active for this function to work."
12207 (interactive "P")
12208 (require 'iswitchb)
12209 (let ((enabled iswitchb-mode) blist)
12210 (or enabled (iswitchb-mode 1))
12211 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12212 ((equal arg '(16)) (org-buffer-list 'agenda))
12213 (t (org-buffer-list))))
12214 (unwind-protect
12215 (let ((iswitchb-make-buflist-hook
12216 (lambda ()
12217 (setq iswitchb-temp-buflist
12218 (mapcar 'buffer-name blist)))))
12219 (switch-to-buffer
12220 (iswitchb-read-buffer
12221 "Switch-to: " nil t))
12222 (or enabled (iswitchb-mode -1))))))
12224 ;;;###autoload
12225 (defun org-ido-switchb (&optional arg)
12226 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12227 With a prefix argument, restrict available to files.
12228 With two prefix arguments, restrict available buffers to agenda files."
12229 (interactive "P")
12230 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12231 ((equal arg '(16)) (org-buffer-list 'agenda))
12232 (t (org-buffer-list)))))
12233 (switch-to-buffer
12234 (org-ido-completing-read "Org buffer: "
12235 (mapcar 'buffer-name blist)
12236 nil t))))
12238 (defun org-buffer-list (&optional predicate exclude-tmp)
12239 "Return a list of Org buffers.
12240 PREDICATE can be `export', `files' or `agenda'.
12242 export restrict the list to Export buffers.
12243 files restrict the list to buffers visiting Org files.
12244 agenda restrict the list to buffers visiting agenda files.
12246 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12247 (let* ((bfn nil)
12248 (agenda-files (and (eq predicate 'agenda)
12249 (mapcar 'file-truename (org-agenda-files t))))
12250 (filter
12251 (cond
12252 ((eq predicate 'files)
12253 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12254 ((eq predicate 'export)
12255 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12256 ((eq predicate 'agenda)
12257 (lambda (b)
12258 (with-current-buffer b
12259 (and (eq major-mode 'org-mode)
12260 (setq bfn (buffer-file-name b))
12261 (member (file-truename bfn) agenda-files)))))
12262 (t (lambda (b) (with-current-buffer b
12263 (or (eq major-mode 'org-mode)
12264 (string-match "\*Org .*Export"
12265 (buffer-name b)))))))))
12266 (delq nil
12267 (mapcar
12268 (lambda(b)
12269 (if (and (funcall filter b)
12270 (or (not exclude-tmp)
12271 (not (string-match "tmp" (buffer-name b)))))
12273 nil))
12274 (buffer-list)))))
12276 (defun org-agenda-files (&optional unrestricted archives)
12277 "Get the list of agenda files.
12278 Optional UNRESTRICTED means return the full list even if a restriction
12279 is currently in place.
12280 When ARCHIVES is t, include all archive files hat are really being
12281 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12282 `org-agenda-archives-mode' is t."
12283 (let ((files
12284 (cond
12285 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12286 ((stringp org-agenda-files) (org-read-agenda-file-list))
12287 ((listp org-agenda-files) org-agenda-files)
12288 (t (error "Invalid value of `org-agenda-files'")))))
12289 (setq files (apply 'append
12290 (mapcar (lambda (f)
12291 (if (file-directory-p f)
12292 (directory-files
12293 f t org-agenda-file-regexp)
12294 (list f)))
12295 files)))
12296 (when org-agenda-skip-unavailable-files
12297 (setq files (delq nil
12298 (mapcar (function
12299 (lambda (file)
12300 (and (file-readable-p file) file)))
12301 files))))
12302 (when (or (eq archives t)
12303 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12304 (setq files (org-add-archive-files files)))
12305 files))
12307 (defun org-edit-agenda-file-list ()
12308 "Edit the list of agenda files.
12309 Depending on setup, this either uses customize to edit the variable
12310 `org-agenda-files', or it visits the file that is holding the list. In the
12311 latter case, the buffer is set up in a way that saving it automatically kills
12312 the buffer and restores the previous window configuration."
12313 (interactive)
12314 (if (stringp org-agenda-files)
12315 (let ((cw (current-window-configuration)))
12316 (find-file org-agenda-files)
12317 (org-set-local 'org-window-configuration cw)
12318 (org-add-hook 'after-save-hook
12319 (lambda ()
12320 (set-window-configuration
12321 (prog1 org-window-configuration
12322 (kill-buffer (current-buffer))))
12323 (org-install-agenda-files-menu)
12324 (message "New agenda file list installed"))
12325 nil 'local)
12326 (message "%s" (substitute-command-keys
12327 "Edit list and finish with \\[save-buffer]")))
12328 (customize-variable 'org-agenda-files)))
12330 (defun org-store-new-agenda-file-list (list)
12331 "Set new value for the agenda file list and save it correctly."
12332 (if (stringp org-agenda-files)
12333 (let ((f org-agenda-files) b)
12334 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12335 (with-temp-file f
12336 (insert (mapconcat 'identity list "\n") "\n")))
12337 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12338 (setq org-agenda-files list)
12339 (customize-save-variable 'org-agenda-files org-agenda-files))))
12341 (defun org-read-agenda-file-list ()
12342 "Read the list of agenda files from a file."
12343 (when (file-directory-p org-agenda-files)
12344 (error "`org-agenda-files' cannot be a single directory"))
12345 (when (stringp org-agenda-files)
12346 (with-temp-buffer
12347 (insert-file-contents org-agenda-files)
12348 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12351 ;;;###autoload
12352 (defun org-cycle-agenda-files ()
12353 "Cycle through the files in `org-agenda-files'.
12354 If the current buffer visits an agenda file, find the next one in the list.
12355 If the current buffer does not, find the first agenda file."
12356 (interactive)
12357 (let* ((fs (org-agenda-files t))
12358 (files (append fs (list (car fs))))
12359 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12360 file)
12361 (unless files (error "No agenda files"))
12362 (catch 'exit
12363 (while (setq file (pop files))
12364 (if (equal (file-truename file) tcf)
12365 (when (car files)
12366 (find-file (car files))
12367 (throw 'exit t))))
12368 (find-file (car fs)))
12369 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12371 (defun org-agenda-file-to-front (&optional to-end)
12372 "Move/add the current file to the top of the agenda file list.
12373 If the file is not present in the list, it is added to the front. If it is
12374 present, it is moved there. With optional argument TO-END, add/move to the
12375 end of the list."
12376 (interactive "P")
12377 (let ((org-agenda-skip-unavailable-files nil)
12378 (file-alist (mapcar (lambda (x)
12379 (cons (file-truename x) x))
12380 (org-agenda-files t)))
12381 (ctf (file-truename buffer-file-name))
12382 x had)
12383 (setq x (assoc ctf file-alist) had x)
12385 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12386 (if to-end
12387 (setq file-alist (append (delq x file-alist) (list x)))
12388 (setq file-alist (cons x (delq x file-alist))))
12389 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12390 (org-install-agenda-files-menu)
12391 (message "File %s to %s of agenda file list"
12392 (if had "moved" "added") (if to-end "end" "front"))))
12394 (defun org-remove-file (&optional file)
12395 "Remove current file from the list of files in variable `org-agenda-files'.
12396 These are the files which are being checked for agenda entries.
12397 Optional argument FILE means, use this file instead of the current."
12398 (interactive)
12399 (let* ((org-agenda-skip-unavailable-files nil)
12400 (file (or file buffer-file-name))
12401 (true-file (file-truename file))
12402 (afile (abbreviate-file-name file))
12403 (files (delq nil (mapcar
12404 (lambda (x)
12405 (if (equal true-file
12406 (file-truename x))
12407 nil x))
12408 (org-agenda-files t)))))
12409 (if (not (= (length files) (length (org-agenda-files t))))
12410 (progn
12411 (org-store-new-agenda-file-list files)
12412 (org-install-agenda-files-menu)
12413 (message "Removed file: %s" afile))
12414 (message "File was not in list: %s (not removed)" afile))))
12416 (defun org-file-menu-entry (file)
12417 (vector file (list 'find-file file) t))
12419 (defun org-check-agenda-file (file)
12420 "Make sure FILE exists. If not, ask user what to do."
12421 (when (not (file-exists-p file))
12422 (message "non-existent file %s. [R]emove from list or [A]bort?"
12423 (abbreviate-file-name file))
12424 (let ((r (downcase (read-char-exclusive))))
12425 (cond
12426 ((equal r ?r)
12427 (org-remove-file file)
12428 (throw 'nextfile t))
12429 (t (error "Abort"))))))
12431 (defun org-get-agenda-file-buffer (file)
12432 "Get a buffer visiting FILE. If the buffer needs to be created, add
12433 it to the list of buffers which might be released later."
12434 (let ((buf (org-find-base-buffer-visiting file)))
12435 (if buf
12436 buf ; just return it
12437 ;; Make a new buffer and remember it
12438 (setq buf (find-file-noselect file))
12439 (if buf (push buf org-agenda-new-buffers))
12440 buf)))
12442 (defun org-release-buffers (blist)
12443 "Release all buffers in list, asking the user for confirmation when needed.
12444 When a buffer is unmodified, it is just killed. When modified, it is saved
12445 \(if the user agrees) and then killed."
12446 (let (buf file)
12447 (while (setq buf (pop blist))
12448 (setq file (buffer-file-name buf))
12449 (when (and (buffer-modified-p buf)
12450 file
12451 (y-or-n-p (format "Save file %s? " file)))
12452 (with-current-buffer buf (save-buffer)))
12453 (kill-buffer buf))))
12455 (defun org-prepare-agenda-buffers (files)
12456 "Create buffers for all agenda files, protect archived trees and comments."
12457 (interactive)
12458 (let ((pa '(:org-archived t))
12459 (pc '(:org-comment t))
12460 (pall '(:org-archived t :org-comment t))
12461 (inhibit-read-only t)
12462 (rea (concat ":" org-archive-tag ":"))
12463 bmp file re)
12464 (save-excursion
12465 (save-restriction
12466 (while (setq file (pop files))
12467 (if (bufferp file)
12468 (set-buffer file)
12469 (org-check-agenda-file file)
12470 (set-buffer (org-get-agenda-file-buffer file)))
12471 (widen)
12472 (setq bmp (buffer-modified-p))
12473 (org-refresh-category-properties)
12474 (setq org-todo-keywords-for-agenda
12475 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12476 (setq org-done-keywords-for-agenda
12477 (append org-done-keywords-for-agenda org-done-keywords))
12478 (setq org-todo-keyword-alist-for-agenda
12479 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12480 (setq org-tag-alist-for-agenda
12481 (append org-tag-alist-for-agenda org-tag-alist))
12483 (save-excursion
12484 (remove-text-properties (point-min) (point-max) pall)
12485 (when org-agenda-skip-archived-trees
12486 (goto-char (point-min))
12487 (while (re-search-forward rea nil t)
12488 (if (org-on-heading-p t)
12489 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12490 (goto-char (point-min))
12491 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12492 (while (re-search-forward re nil t)
12493 (add-text-properties
12494 (match-beginning 0) (org-end-of-subtree t) pc)))
12495 (set-buffer-modified-p bmp))))
12496 (setq org-todo-keyword-alist-for-agenda
12497 (org-uniquify org-todo-keyword-alist-for-agenda)
12498 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12500 ;;;; Embedded LaTeX
12502 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12503 "Keymap for the minor `org-cdlatex-mode'.")
12505 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12506 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12507 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12508 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12509 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12511 (defvar org-cdlatex-texmathp-advice-is-done nil
12512 "Flag remembering if we have applied the advice to texmathp already.")
12514 (define-minor-mode org-cdlatex-mode
12515 "Toggle the minor `org-cdlatex-mode'.
12516 This mode supports entering LaTeX environment and math in LaTeX fragments
12517 in Org-mode.
12518 \\{org-cdlatex-mode-map}"
12519 nil " OCDL" nil
12520 (when org-cdlatex-mode (require 'cdlatex))
12521 (unless org-cdlatex-texmathp-advice-is-done
12522 (setq org-cdlatex-texmathp-advice-is-done t)
12523 (defadvice texmathp (around org-math-always-on activate)
12524 "Always return t in org-mode buffers.
12525 This is because we want to insert math symbols without dollars even outside
12526 the LaTeX math segments. If Orgmode thinks that point is actually inside
12527 an embedded LaTeX fragment, let texmathp do its job.
12528 \\[org-cdlatex-mode-map]"
12529 (interactive)
12530 (let (p)
12531 (cond
12532 ((not (org-mode-p)) ad-do-it)
12533 ((eq this-command 'cdlatex-math-symbol)
12534 (setq ad-return-value t
12535 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12537 (let ((p (org-inside-LaTeX-fragment-p)))
12538 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12539 (setq ad-return-value t
12540 texmathp-why '("Org-mode embedded math" . 0))
12541 (if p ad-do-it)))))))))
12543 (defun turn-on-org-cdlatex ()
12544 "Unconditionally turn on `org-cdlatex-mode'."
12545 (org-cdlatex-mode 1))
12547 (defun org-inside-LaTeX-fragment-p ()
12548 "Test if point is inside a LaTeX fragment.
12549 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12550 sequence appearing also before point.
12551 Even though the matchers for math are configurable, this function assumes
12552 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12553 delimiters are skipped when they have been removed by customization.
12554 The return value is nil, or a cons cell with the delimiter and
12555 and the position of this delimiter.
12557 This function does a reasonably good job, but can locally be fooled by
12558 for example currency specifications. For example it will assume being in
12559 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12560 fragments that are properly closed, but during editing, we have to live
12561 with the uncertainty caused by missing closing delimiters. This function
12562 looks only before point, not after."
12563 (catch 'exit
12564 (let ((pos (point))
12565 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12566 (lim (progn
12567 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12568 (point)))
12569 dd-on str (start 0) m re)
12570 (goto-char pos)
12571 (when dodollar
12572 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12573 re (nth 1 (assoc "$" org-latex-regexps)))
12574 (while (string-match re str start)
12575 (cond
12576 ((= (match-end 0) (length str))
12577 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12578 ((= (match-end 0) (- (length str) 5))
12579 (throw 'exit nil))
12580 (t (setq start (match-end 0))))))
12581 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12582 (goto-char pos)
12583 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12584 (and (match-beginning 2) (throw 'exit nil))
12585 ;; count $$
12586 (while (re-search-backward "\\$\\$" lim t)
12587 (setq dd-on (not dd-on)))
12588 (goto-char pos)
12589 (if dd-on (cons "$$" m))))))
12592 (defun org-try-cdlatex-tab ()
12593 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12594 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12595 - inside a LaTeX fragment, or
12596 - after the first word in a line, where an abbreviation expansion could
12597 insert a LaTeX environment."
12598 (when org-cdlatex-mode
12599 (cond
12600 ((save-excursion
12601 (skip-chars-backward "a-zA-Z0-9*")
12602 (skip-chars-backward " \t")
12603 (bolp))
12604 (cdlatex-tab) t)
12605 ((org-inside-LaTeX-fragment-p)
12606 (cdlatex-tab) t)
12607 (t nil))))
12609 (defun org-cdlatex-underscore-caret (&optional arg)
12610 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12611 Revert to the normal definition outside of these fragments."
12612 (interactive "P")
12613 (if (org-inside-LaTeX-fragment-p)
12614 (call-interactively 'cdlatex-sub-superscript)
12615 (let (org-cdlatex-mode)
12616 (call-interactively (key-binding (vector last-input-event))))))
12618 (defun org-cdlatex-math-modify (&optional arg)
12619 "Execute `cdlatex-math-modify' in LaTeX fragments.
12620 Revert to the normal definition outside of these fragments."
12621 (interactive "P")
12622 (if (org-inside-LaTeX-fragment-p)
12623 (call-interactively 'cdlatex-math-modify)
12624 (let (org-cdlatex-mode)
12625 (call-interactively (key-binding (vector last-input-event))))))
12627 (defvar org-latex-fragment-image-overlays nil
12628 "List of overlays carrying the images of latex fragments.")
12629 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12631 (defun org-remove-latex-fragment-image-overlays ()
12632 "Remove all overlays with LaTeX fragment images in current buffer."
12633 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12634 (setq org-latex-fragment-image-overlays nil))
12636 (defun org-preview-latex-fragment (&optional subtree)
12637 "Preview the LaTeX fragment at point, or all locally or globally.
12638 If the cursor is in a LaTeX fragment, create the image and overlay
12639 it over the source code. If there is no fragment at point, display
12640 all fragments in the current text, from one headline to the next. With
12641 prefix SUBTREE, display all fragments in the current subtree. With a
12642 double prefix `C-u C-u', or when the cursor is before the first headline,
12643 display all fragments in the buffer.
12644 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12645 (interactive "P")
12646 (org-remove-latex-fragment-image-overlays)
12647 (save-excursion
12648 (save-restriction
12649 (let (beg end at msg)
12650 (cond
12651 ((or (equal subtree '(16))
12652 (not (save-excursion
12653 (re-search-backward (concat "^" outline-regexp) nil t))))
12654 (setq beg (point-min) end (point-max)
12655 msg "Creating images for buffer...%s"))
12656 ((equal subtree '(4))
12657 (org-back-to-heading)
12658 (setq beg (point) end (org-end-of-subtree t)
12659 msg "Creating images for subtree...%s"))
12661 (if (setq at (org-inside-LaTeX-fragment-p))
12662 (goto-char (max (point-min) (- (cdr at) 2)))
12663 (org-back-to-heading))
12664 (setq beg (point) end (progn (outline-next-heading) (point))
12665 msg (if at "Creating image...%s"
12666 "Creating images for entry...%s"))))
12667 (message msg "")
12668 (narrow-to-region beg end)
12669 (goto-char beg)
12670 (org-format-latex
12671 (concat "ltxpng/" (file-name-sans-extension
12672 (file-name-nondirectory
12673 buffer-file-name)))
12674 default-directory 'overlays msg at 'forbuffer)
12675 (message msg "done. Use `C-c C-c' to remove images.")))))
12677 (defvar org-latex-regexps
12678 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12679 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12680 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12681 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12682 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12683 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12684 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12685 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12686 "Regular expressions for matching embedded LaTeX.")
12688 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12689 "Replace LaTeX fragments with links to an image, and produce images."
12690 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12691 (let* ((prefixnodir (file-name-nondirectory prefix))
12692 (absprefix (expand-file-name prefix dir))
12693 (todir (file-name-directory absprefix))
12694 (opt org-format-latex-options)
12695 (matchers (plist-get opt :matchers))
12696 (re-list org-latex-regexps)
12697 (cnt 0) txt link beg end re e checkdir
12698 m n block linkfile movefile ov)
12699 ;; Check if there are old images files with this prefix, and remove them
12700 (when (file-directory-p todir)
12701 (mapc 'delete-file
12702 (directory-files
12703 todir 'full
12704 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12705 ;; Check the different regular expressions
12706 (while (setq e (pop re-list))
12707 (setq m (car e) re (nth 1 e) n (nth 2 e)
12708 block (if (nth 3 e) "\n\n" ""))
12709 (when (member m matchers)
12710 (goto-char (point-min))
12711 (while (re-search-forward re nil t)
12712 (when (or (not at) (equal (cdr at) (match-beginning n)))
12713 (setq txt (match-string n)
12714 beg (match-beginning n) end (match-end n)
12715 cnt (1+ cnt)
12716 linkfile (format "%s_%04d.png" prefix cnt)
12717 movefile (format "%s_%04d.png" absprefix cnt)
12718 link (concat block "[[file:" linkfile "]]" block))
12719 (if msg (message msg cnt))
12720 (goto-char beg)
12721 (unless checkdir ; make sure the directory exists
12722 (setq checkdir t)
12723 (or (file-directory-p todir) (make-directory todir)))
12724 (org-create-formula-image
12725 txt movefile opt forbuffer)
12726 (if overlays
12727 (progn
12728 (setq ov (org-make-overlay beg end))
12729 (if (featurep 'xemacs)
12730 (progn
12731 (org-overlay-put ov 'invisible t)
12732 (org-overlay-put
12733 ov 'end-glyph
12734 (make-glyph (vector 'png :file movefile))))
12735 (org-overlay-put
12736 ov 'display
12737 (list 'image :type 'png :file movefile :ascent 'center)))
12738 (push ov org-latex-fragment-image-overlays)
12739 (goto-char end))
12740 (delete-region beg end)
12741 (insert link))))))))
12743 ;; This function borrows from Ganesh Swami's latex2png.el
12744 (defun org-create-formula-image (string tofile options buffer)
12745 (let* ((tmpdir (if (featurep 'xemacs)
12746 (temp-directory)
12747 temporary-file-directory))
12748 (texfilebase (make-temp-name
12749 (expand-file-name "orgtex" tmpdir)))
12750 (texfile (concat texfilebase ".tex"))
12751 (dvifile (concat texfilebase ".dvi"))
12752 (pngfile (concat texfilebase ".png"))
12753 (fnh (if (featurep 'xemacs)
12754 (font-height (get-face-font 'default))
12755 (face-attribute 'default :height nil)))
12756 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12757 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12758 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12759 "Black"))
12760 (bg (or (plist-get options (if buffer :background :html-background))
12761 "Transparent")))
12762 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12763 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12764 (with-temp-file texfile
12765 (insert org-format-latex-header
12766 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12767 (let ((dir default-directory))
12768 (condition-case nil
12769 (progn
12770 (cd tmpdir)
12771 (call-process "latex" nil nil nil texfile))
12772 (error nil))
12773 (cd dir))
12774 (if (not (file-exists-p dvifile))
12775 (progn (message "Failed to create dvi file from %s" texfile) nil)
12776 (condition-case nil
12777 (call-process "dvipng" nil nil nil
12778 "-E" "-fg" fg "-bg" bg
12779 "-D" dpi
12780 ;;"-x" scale "-y" scale
12781 "-T" "tight"
12782 "-o" pngfile
12783 dvifile)
12784 (error nil))
12785 (if (not (file-exists-p pngfile))
12786 (progn (message "Failed to create png file from %s" texfile) nil)
12787 ;; Use the requested file name and clean up
12788 (copy-file pngfile tofile 'replace)
12789 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12790 (delete-file (concat texfilebase e)))
12791 pngfile))))
12793 (defun org-dvipng-color (attr)
12794 "Return an rgb color specification for dvipng."
12795 (apply 'format "rgb %s %s %s"
12796 (mapcar 'org-normalize-color
12797 (color-values (face-attribute 'default attr nil)))))
12799 (defun org-normalize-color (value)
12800 "Return string to be used as color value for an RGB component."
12801 (format "%g" (/ value 65535.0)))
12803 ;;;; Key bindings
12805 ;; Make `C-c C-x' a prefix key
12806 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12808 ;; TAB key with modifiers
12809 (org-defkey org-mode-map "\C-i" 'org-cycle)
12810 (org-defkey org-mode-map [(tab)] 'org-cycle)
12811 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12812 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12813 (org-defkey org-mode-map "\M-\t" 'org-complete)
12814 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12815 ;; The following line is necessary under Suse GNU/Linux
12816 (unless (featurep 'xemacs)
12817 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12818 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12819 (define-key org-mode-map [backtab] 'org-shifttab)
12821 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12822 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12823 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12825 ;; Cursor keys with modifiers
12826 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12827 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12828 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12829 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12831 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12832 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12833 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12834 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12836 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12837 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12838 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12839 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12841 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12842 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12844 ;;; Extra keys for tty access.
12845 ;; We only set them when really needed because otherwise the
12846 ;; menus don't show the simple keys
12848 (when (or org-use-extra-keys
12849 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12850 (not window-system))
12851 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12852 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12853 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12854 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12855 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12856 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12857 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12858 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12859 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12860 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12861 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12862 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12863 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12864 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12865 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12866 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12867 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12868 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12869 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12870 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12871 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12872 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12874 ;; All the other keys
12876 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12877 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12878 (if (boundp 'narrow-map)
12879 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12880 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12881 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12882 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12883 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12884 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12885 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12886 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12887 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12888 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12889 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12890 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12891 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12892 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12893 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12894 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12895 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12896 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12897 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12898 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12899 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12900 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12901 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12902 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12903 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12904 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12905 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12906 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12907 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12908 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12909 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12910 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12911 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12912 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12913 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12914 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12915 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12916 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12917 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12918 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12919 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12920 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12921 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12922 (org-defkey org-mode-map "\C-c^" 'org-sort)
12923 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12924 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12925 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12926 (org-defkey org-mode-map "\C-m" 'org-return)
12927 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12928 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12929 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12930 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12931 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12932 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12933 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12934 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12935 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12936 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12937 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12938 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12939 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12940 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12941 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12942 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12943 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12945 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12946 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12947 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12948 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12950 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12951 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12952 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12953 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12954 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12955 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12956 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12957 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12958 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12959 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12960 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12961 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
12962 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12964 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12965 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12966 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12967 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12969 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12971 (when (featurep 'xemacs)
12972 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12974 (defvar org-table-auto-blank-field) ; defined in org-table.el
12975 (defun org-self-insert-command (N)
12976 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12977 If the cursor is in a table looking at whitespace, the whitespace is
12978 overwritten, and the table is not marked as requiring realignment."
12979 (interactive "p")
12980 (if (and (org-table-p)
12981 (progn
12982 ;; check if we blank the field, and if that triggers align
12983 (and (featurep 'org-table) org-table-auto-blank-field
12984 (member last-command
12985 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12986 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12987 ;; got extra space, this field does not determine column width
12988 (let (org-table-may-need-update) (org-table-blank-field))
12989 ;; no extra space, this field may determine column width
12990 (org-table-blank-field)))
12992 (eq N 1)
12993 (looking-at "[^|\n]* |"))
12994 (let (org-table-may-need-update)
12995 (goto-char (1- (match-end 0)))
12996 (delete-backward-char 1)
12997 (goto-char (match-beginning 0))
12998 (self-insert-command N))
12999 (setq org-table-may-need-update t)
13000 (self-insert-command N)
13001 (org-fix-tags-on-the-fly)))
13003 (defun org-fix-tags-on-the-fly ()
13004 (when (and (equal (char-after (point-at-bol)) ?*)
13005 (org-on-heading-p))
13006 (org-align-tags-here org-tags-column)))
13008 (defun org-delete-backward-char (N)
13009 "Like `delete-backward-char', insert whitespace at field end in tables.
13010 When deleting backwards, in tables this function will insert whitespace in
13011 front of the next \"|\" separator, to keep the table aligned. The table will
13012 still be marked for re-alignment if the field did fill the entire column,
13013 because, in this case the deletion might narrow the column."
13014 (interactive "p")
13015 (if (and (org-table-p)
13016 (eq N 1)
13017 (string-match "|" (buffer-substring (point-at-bol) (point)))
13018 (looking-at ".*?|"))
13019 (let ((pos (point))
13020 (noalign (looking-at "[^|\n\r]* |"))
13021 (c org-table-may-need-update))
13022 (backward-delete-char N)
13023 (skip-chars-forward "^|")
13024 (insert " ")
13025 (goto-char (1- pos))
13026 ;; noalign: if there were two spaces at the end, this field
13027 ;; does not determine the width of the column.
13028 (if noalign (setq org-table-may-need-update c)))
13029 (backward-delete-char N)
13030 (org-fix-tags-on-the-fly)))
13032 (defun org-delete-char (N)
13033 "Like `delete-char', but insert whitespace at field end in tables.
13034 When deleting characters, in tables this function will insert whitespace in
13035 front of the next \"|\" separator, to keep the table aligned. The table will
13036 still be marked for re-alignment if the field did fill the entire column,
13037 because, in this case the deletion might narrow the column."
13038 (interactive "p")
13039 (if (and (org-table-p)
13040 (not (bolp))
13041 (not (= (char-after) ?|))
13042 (eq N 1))
13043 (if (looking-at ".*?|")
13044 (let ((pos (point))
13045 (noalign (looking-at "[^|\n\r]* |"))
13046 (c org-table-may-need-update))
13047 (replace-match (concat
13048 (substring (match-string 0) 1 -1)
13049 " |"))
13050 (goto-char pos)
13051 ;; noalign: if there were two spaces at the end, this field
13052 ;; does not determine the width of the column.
13053 (if noalign (setq org-table-may-need-update c)))
13054 (delete-char N))
13055 (delete-char N)
13056 (org-fix-tags-on-the-fly)))
13058 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13059 (put 'org-self-insert-command 'delete-selection t)
13060 (put 'orgtbl-self-insert-command 'delete-selection t)
13061 (put 'org-delete-char 'delete-selection 'supersede)
13062 (put 'org-delete-backward-char 'delete-selection 'supersede)
13063 (put 'org-yank 'delete-selection 'yank)
13065 ;; Make `flyspell-mode' delay after some commands
13066 (put 'org-self-insert-command 'flyspell-delayed t)
13067 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13068 (put 'org-delete-char 'flyspell-delayed t)
13069 (put 'org-delete-backward-char 'flyspell-delayed t)
13071 ;; Make pabbrev-mode expand after org-mode commands
13072 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13073 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13075 ;; How to do this: Measure non-white length of current string
13076 ;; If equal to column width, we should realign.
13078 (defun org-remap (map &rest commands)
13079 "In MAP, remap the functions given in COMMANDS.
13080 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13081 (let (new old)
13082 (while commands
13083 (setq old (pop commands) new (pop commands))
13084 (if (fboundp 'command-remapping)
13085 (org-defkey map (vector 'remap old) new)
13086 (substitute-key-definition old new map global-map)))))
13088 (when (eq org-enable-table-editor 'optimized)
13089 ;; If the user wants maximum table support, we need to hijack
13090 ;; some standard editing functions
13091 (org-remap org-mode-map
13092 'self-insert-command 'org-self-insert-command
13093 'delete-char 'org-delete-char
13094 'delete-backward-char 'org-delete-backward-char)
13095 (org-defkey org-mode-map "|" 'org-force-self-insert))
13097 (defun org-modifier-cursor-error ()
13098 "Throw an error, a modified cursor command was applied in wrong context."
13099 (error "This command is active in special context like tables, headlines or items"))
13101 (defun org-shiftselect-error ()
13102 "Throw an error because Shift-Cursor command was applied in wrong context."
13103 (if (and (boundp 'shift-select-mode) shift-select-mode)
13104 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13105 (error "This command works only in special context like headlines or timestamps.")))
13107 (defun org-call-for-shift-select (cmd)
13108 (let ((this-command-keys-shift-translated t))
13109 (call-interactively cmd)))
13111 (defun org-shifttab (&optional arg)
13112 "Global visibility cycling or move to previous table field.
13113 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13114 on context.
13115 See the individual commands for more information."
13116 (interactive "P")
13117 (cond
13118 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13119 ((integerp arg)
13120 (message "Content view to level: %d" arg)
13121 (org-content (prefix-numeric-value arg))
13122 (setq org-cycle-global-status 'overview))
13123 (t (call-interactively 'org-global-cycle))))
13125 (defun org-shiftmetaleft ()
13126 "Promote subtree or delete table column.
13127 Calls `org-promote-subtree', `org-outdent-item',
13128 or `org-table-delete-column', depending on context.
13129 See the individual commands for more information."
13130 (interactive)
13131 (cond
13132 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13133 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13134 ((org-at-item-p) (call-interactively 'org-outdent-item))
13135 (t (org-modifier-cursor-error))))
13137 (defun org-shiftmetaright ()
13138 "Demote subtree or insert table column.
13139 Calls `org-demote-subtree', `org-indent-item',
13140 or `org-table-insert-column', depending on context.
13141 See the individual commands for more information."
13142 (interactive)
13143 (cond
13144 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13145 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13146 ((org-at-item-p) (call-interactively 'org-indent-item))
13147 (t (org-modifier-cursor-error))))
13149 (defun org-shiftmetaup (&optional arg)
13150 "Move subtree up or kill table row.
13151 Calls `org-move-subtree-up' or `org-table-kill-row' or
13152 `org-move-item-up' depending on context. See the individual commands
13153 for more information."
13154 (interactive "P")
13155 (cond
13156 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13157 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13158 ((org-at-item-p) (call-interactively 'org-move-item-up))
13159 (t (org-modifier-cursor-error))))
13160 (defun org-shiftmetadown (&optional arg)
13161 "Move subtree down or insert table row.
13162 Calls `org-move-subtree-down' or `org-table-insert-row' or
13163 `org-move-item-down', depending on context. See the individual
13164 commands for more information."
13165 (interactive "P")
13166 (cond
13167 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13168 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13169 ((org-at-item-p) (call-interactively 'org-move-item-down))
13170 (t (org-modifier-cursor-error))))
13172 (defun org-metaleft (&optional arg)
13173 "Promote heading or move table column to left.
13174 Calls `org-do-promote' or `org-table-move-column', depending on context.
13175 With no specific context, calls the Emacs default `backward-word'.
13176 See the individual commands for more information."
13177 (interactive "P")
13178 (cond
13179 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13180 ((or (org-on-heading-p) (org-region-active-p))
13181 (call-interactively 'org-do-promote))
13182 ((org-at-item-p) (call-interactively 'org-outdent-item))
13183 (t (call-interactively 'backward-word))))
13185 (defun org-metaright (&optional arg)
13186 "Demote subtree or move table column to right.
13187 Calls `org-do-demote' or `org-table-move-column', depending on context.
13188 With no specific context, calls the Emacs default `forward-word'.
13189 See the individual commands for more information."
13190 (interactive "P")
13191 (cond
13192 ((org-at-table-p) (call-interactively 'org-table-move-column))
13193 ((or (org-on-heading-p) (org-region-active-p))
13194 (call-interactively 'org-do-demote))
13195 ((org-at-item-p) (call-interactively 'org-indent-item))
13196 (t (call-interactively 'forward-word))))
13198 (defun org-metaup (&optional arg)
13199 "Move subtree up or move table row up.
13200 Calls `org-move-subtree-up' or `org-table-move-row' or
13201 `org-move-item-up', depending on context. See the individual commands
13202 for more information."
13203 (interactive "P")
13204 (cond
13205 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13206 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13207 ((org-at-item-p) (call-interactively 'org-move-item-up))
13208 (t (transpose-lines 1) (beginning-of-line -1))))
13210 (defun org-metadown (&optional arg)
13211 "Move subtree down or move table row down.
13212 Calls `org-move-subtree-down' or `org-table-move-row' or
13213 `org-move-item-down', depending on context. See the individual
13214 commands for more information."
13215 (interactive "P")
13216 (cond
13217 ((org-at-table-p) (call-interactively 'org-table-move-row))
13218 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13219 ((org-at-item-p) (call-interactively 'org-move-item-down))
13220 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13222 (defun org-shiftup (&optional arg)
13223 "Increase item in timestamp or increase priority of current headline.
13224 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13225 depending on context. See the individual commands for more information."
13226 (interactive "P")
13227 (cond
13228 ((and org-support-shift-select (org-region-active-p))
13229 (org-call-for-shift-select 'previous-line))
13230 ((org-at-timestamp-p t)
13231 (call-interactively (if org-edit-timestamp-down-means-later
13232 'org-timestamp-down 'org-timestamp-up)))
13233 ((and (not (eq org-support-shift-select 'always))
13234 (org-on-heading-p))
13235 (call-interactively 'org-priority-up))
13236 ((and (not org-support-shift-select) (org-at-item-p))
13237 (call-interactively 'org-previous-item))
13238 ((org-clocktable-try-shift 'up arg))
13239 (org-support-shift-select
13240 (org-call-for-shift-select 'previous-line))
13241 (t (org-shiftselect-error))))
13243 (defun org-shiftdown (&optional arg)
13244 "Decrease item in timestamp or decrease priority of current headline.
13245 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13246 depending on context. See the individual commands for more information."
13247 (interactive "P")
13248 (cond
13249 ((and org-support-shift-select (org-region-active-p))
13250 (org-call-for-shift-select 'next-line))
13251 ((org-at-timestamp-p t)
13252 (call-interactively (if org-edit-timestamp-down-means-later
13253 'org-timestamp-up 'org-timestamp-down)))
13254 ((and (not (eq org-support-shift-select 'always))
13255 (org-on-heading-p))
13256 (call-interactively 'org-priority-down))
13257 ((and (not org-support-shift-select) (org-at-item-p))
13258 (call-interactively 'org-next-item))
13259 ((org-clocktable-try-shift 'down arg))
13260 (org-support-shift-select
13261 (org-call-for-shift-select 'next-line))
13262 (t (org-shiftselect-error))))
13264 (defun org-shiftright (&optional arg)
13265 "Cycle the thing at point or in the current line, depending on context.
13266 Depending on context, this does one of the following:
13268 - switch a timestamp at point one day into the future
13269 - on a headline, switch to the next TODO keyword.
13270 - on an item, switch entire list to the next bullet type
13271 - on a property line, switch to the next allowed value
13272 - on a clocktable definition line, move time block into the future"
13273 (interactive "P")
13274 (cond
13275 ((and org-support-shift-select (org-region-active-p))
13276 (org-call-for-shift-select 'forward-char))
13277 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13278 ((and (not (eq org-support-shift-select 'always))
13279 (org-on-heading-p))
13280 (org-call-with-arg 'org-todo 'right))
13281 ((or (and org-support-shift-select
13282 (not (eq org-support-shift-select 'always))
13283 (org-at-item-bullet-p))
13284 (and (not org-support-shift-select) (org-at-item-p)))
13285 (org-call-with-arg 'org-cycle-list-bullet nil))
13286 ((and (not (eq org-support-shift-select 'always))
13287 (org-at-property-p))
13288 (call-interactively 'org-property-next-allowed-value))
13289 ((org-clocktable-try-shift 'right arg))
13290 (org-support-shift-select
13291 (org-call-for-shift-select 'forward-char))
13292 (t (org-shiftselect-error))))
13294 (defun org-shiftleft (&optional arg)
13295 "Cycle the thing at point or in the current line, depending on context.
13296 Depending on context, this does one of the following:
13298 - switch a timestamp at point one day into the past
13299 - on a headline, switch to the previous TODO keyword.
13300 - on an item, switch entire list to the previous bullet type
13301 - on a property line, switch to the previous allowed value
13302 - on a clocktable definition line, move time block into the past"
13303 (interactive "P")
13304 (cond
13305 ((and org-support-shift-select (org-region-active-p))
13306 (org-call-for-shift-select 'backward-char))
13307 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13308 ((and (not (eq org-support-shift-select 'always))
13309 (org-on-heading-p))
13310 (org-call-with-arg 'org-todo 'left))
13311 ((or (and org-support-shift-select
13312 (not (eq org-support-shift-select 'always))
13313 (org-at-item-bullet-p))
13314 (and (not org-support-shift-select) (org-at-item-p)))
13315 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13316 ((and (not (eq org-support-shift-select 'always))
13317 (org-at-property-p))
13318 (call-interactively 'org-property-previous-allowed-value))
13319 ((org-clocktable-try-shift 'left arg))
13320 (org-support-shift-select
13321 (org-call-for-shift-select 'backward-char))
13322 (t (org-shiftselect-error))))
13324 (defun org-shiftcontrolright ()
13325 "Switch to next TODO set."
13326 (interactive)
13327 (cond
13328 ((and org-support-shift-select (org-region-active-p))
13329 (org-call-for-shift-select 'forward-word))
13330 ((and (not (eq org-support-shift-select 'always))
13331 (org-on-heading-p))
13332 (org-call-with-arg 'org-todo 'nextset))
13333 (org-support-shift-select
13334 (org-call-for-shift-select 'forward-word))
13335 (t (org-shiftselect-error))))
13337 (defun org-shiftcontrolleft ()
13338 "Switch to previous TODO set."
13339 (interactive)
13340 (cond
13341 ((and org-support-shift-select (org-region-active-p))
13342 (org-call-for-shift-select 'backward-word))
13343 ((and (not (eq org-support-shift-select 'always))
13344 (org-on-heading-p))
13345 (org-call-with-arg 'org-todo 'previousset))
13346 (org-support-shift-select
13347 (org-call-for-shift-select 'backward-word))
13348 (t (org-shiftselect-error))))
13350 (defun org-ctrl-c-ret ()
13351 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13352 (interactive)
13353 (cond
13354 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13355 (t (call-interactively 'org-insert-heading))))
13357 (defun org-copy-special ()
13358 "Copy region in table or copy current subtree.
13359 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13360 See the individual commands for more information."
13361 (interactive)
13362 (call-interactively
13363 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13365 (defun org-cut-special ()
13366 "Cut region in table or cut current subtree.
13367 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13368 See the individual commands for more information."
13369 (interactive)
13370 (call-interactively
13371 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13373 (defun org-paste-special (arg)
13374 "Paste rectangular region into table, or past subtree relative to level.
13375 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13376 See the individual commands for more information."
13377 (interactive "P")
13378 (if (org-at-table-p)
13379 (org-table-paste-rectangle)
13380 (org-paste-subtree arg)))
13382 (defun org-edit-special ()
13383 "Call a special editor for the stuff at point.
13384 When at a table, call the formula editor with `org-table-edit-formulas'.
13385 When at the first line of an src example, call `org-edit-src-code'.
13386 When in an #+include line, visit the include file. Otherwise call
13387 `ffap' to visit the file at point."
13388 (interactive)
13389 (cond
13390 ((org-at-table-p)
13391 (call-interactively 'org-table-edit-formulas))
13392 ((save-excursion
13393 (beginning-of-line 1)
13394 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13395 (find-file (org-trim (match-string 1))))
13396 ((org-edit-src-code))
13397 ((org-edit-fixed-width-region))
13398 (t (call-interactively 'ffap))))
13400 (defun org-ctrl-c-ctrl-c (&optional arg)
13401 "Set tags in headline, or update according to changed information at point.
13403 This command does many different things, depending on context:
13405 - If the cursor is in a headline, prompt for tags and insert them
13406 into the current line, aligned to `org-tags-column'. When called
13407 with prefix arg, realign all tags in the current buffer.
13409 - If the cursor is in one of the special #+KEYWORD lines, this
13410 triggers scanning the buffer for these lines and updating the
13411 information.
13413 - If the cursor is inside a table, realign the table. This command
13414 works even if the automatic table editor has been turned off.
13416 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13417 the entire table.
13419 - If the cursor is at a footnote reference or definition, jump to
13420 the corresponding definition or references, respectively.
13422 - If the cursor is a the beginning of a dynamic block, update it.
13424 - If the cursor is inside a table created by the table.el package,
13425 activate that table.
13427 - If the current buffer is a remember buffer, close note and file
13428 it. A prefix argument of 1 files to the default location
13429 without further interaction. A prefix argument of 2 files to
13430 the currently clocking task.
13432 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13433 links in this buffer.
13435 - If the cursor is on a numbered item in a plain list, renumber the
13436 ordered list.
13438 - If the cursor is on a checkbox, toggle it."
13439 (interactive "P")
13440 (let ((org-enable-table-editor t))
13441 (cond
13442 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13443 org-occur-highlights
13444 org-latex-fragment-image-overlays)
13445 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13446 (org-remove-occur-highlights)
13447 (org-remove-latex-fragment-image-overlays)
13448 (message "Temporary highlights/overlays removed from current buffer"))
13449 ((and (local-variable-p 'org-finish-function (current-buffer))
13450 (fboundp org-finish-function))
13451 (funcall org-finish-function))
13452 ((org-at-property-p)
13453 (call-interactively 'org-property-action))
13454 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13455 ((org-on-heading-p) (call-interactively 'org-set-tags))
13456 ((org-at-table.el-p)
13457 (require 'table)
13458 (beginning-of-line 1)
13459 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13460 (call-interactively 'table-recognize-table))
13461 ((org-at-table-p)
13462 (org-table-maybe-eval-formula)
13463 (if arg
13464 (call-interactively 'org-table-recalculate)
13465 (org-table-maybe-recalculate-line))
13466 (call-interactively 'org-table-align))
13467 ((or (org-footnote-at-reference-p)
13468 (org-footnote-at-definition-p))
13469 (call-interactively 'org-footnote-action))
13470 ((org-at-item-checkbox-p)
13471 (call-interactively 'org-toggle-checkbox))
13472 ((org-at-item-p)
13473 (call-interactively 'org-maybe-renumber-ordered-list))
13474 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13475 ;; Dynamic block
13476 (beginning-of-line 1)
13477 (save-excursion (org-update-dblock)))
13478 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13479 (cond
13480 ((equal (match-string 1) "TBLFM")
13481 ;; Recalculate the table before this line
13482 (save-excursion
13483 (beginning-of-line 1)
13484 (skip-chars-backward " \r\n\t")
13485 (if (org-at-table-p)
13486 (org-call-with-arg 'org-table-recalculate t))))
13488 ; (org-set-regexps-and-options)
13489 ; (org-restart-font-lock)
13490 (let ((org-inhibit-startup t)) (org-mode-restart))
13491 (message "Local setup has been refreshed"))))
13492 (t (error "C-c C-c can do nothing useful at this location.")))))
13494 (defun org-mode-restart ()
13495 "Restart Org-mode, to scan again for special lines.
13496 Also updates the keyword regular expressions."
13497 (interactive)
13498 (org-mode)
13499 (message "Org-mode restarted"))
13501 (defun org-kill-note-or-show-branches ()
13502 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13503 (interactive)
13504 (if (not org-finish-function)
13505 (call-interactively 'show-branches)
13506 (let ((org-note-abort t))
13507 (funcall org-finish-function))))
13509 (defun org-return (&optional indent)
13510 "Goto next table row or insert a newline.
13511 Calls `org-table-next-row' or `newline', depending on context.
13512 See the individual commands for more information."
13513 (interactive)
13514 (cond
13515 ((bobp) (if indent (newline-and-indent) (newline)))
13516 ((and (org-at-heading-p)
13517 (looking-at
13518 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13519 (org-show-entry)
13520 (end-of-line 1)
13521 (newline))
13522 ((org-at-table-p)
13523 (org-table-justify-field-maybe)
13524 (call-interactively 'org-table-next-row))
13525 (t (if indent (newline-and-indent) (newline)))))
13527 (defun org-return-indent ()
13528 "Goto next table row or insert a newline and indent.
13529 Calls `org-table-next-row' or `newline-and-indent', depending on
13530 context. See the individual commands for more information."
13531 (interactive)
13532 (org-return t))
13534 (defun org-ctrl-c-star ()
13535 "Compute table, or change heading status of lines.
13536 Calls `org-table-recalculate' or `org-toggle-heading',
13537 depending on context."
13538 (interactive)
13539 (cond
13540 ((org-at-table-p)
13541 (call-interactively 'org-table-recalculate))
13543 ;; Convert all lines in region to list items
13544 (call-interactively 'org-toggle-heading))))
13546 (defun org-ctrl-c-minus ()
13547 "Insert separator line in table or modify bullet status of line.
13548 Also turns a plain line or a region of lines into list items.
13549 Calls `org-table-insert-hline', `org-toggle-item', or
13550 `org-cycle-list-bullet', depending on context."
13551 (interactive)
13552 (cond
13553 ((org-at-table-p)
13554 (call-interactively 'org-table-insert-hline))
13555 ((org-region-active-p)
13556 (call-interactively 'org-toggle-item))
13557 ((org-in-item-p)
13558 (call-interactively 'org-cycle-list-bullet))
13560 (call-interactively 'org-toggle-item))))
13562 (defun org-toggle-item ()
13563 "Convert headings or normal lines to items, items to normal lines.
13564 If there is no active region, only the current line is considered.
13566 If the first line in the region is a headline, convert all headlines to items.
13568 If the first line in the region is an item, convert all items to normal lines.
13570 If the first line is normal text, add an item bullet to each line."
13571 (interactive)
13572 (let (l2 l beg end)
13573 (if (org-region-active-p)
13574 (setq beg (region-beginning) end (region-end))
13575 (setq beg (point-at-bol)
13576 end (min (1+ (point-at-eol)) (point-max))))
13577 (save-excursion
13578 (goto-char end)
13579 (setq l2 (org-current-line))
13580 (goto-char beg)
13581 (beginning-of-line 1)
13582 (setq l (1- (org-current-line)))
13583 (if (org-at-item-p)
13584 ;; We already have items, de-itemize
13585 (while (< (setq l (1+ l)) l2)
13586 (when (org-at-item-p)
13587 (goto-char (match-beginning 2))
13588 (delete-region (match-beginning 2) (match-end 2))
13589 (and (looking-at "[ \t]+") (replace-match "")))
13590 (beginning-of-line 2))
13591 (if (org-on-heading-p)
13592 ;; Headings, convert to items
13593 (while (< (setq l (1+ l)) l2)
13594 (if (looking-at org-outline-regexp)
13595 (replace-match "- " t t))
13596 (beginning-of-line 2))
13597 ;; normal lines, turn them into items
13598 (while (< (setq l (1+ l)) l2)
13599 (unless (org-at-item-p)
13600 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13601 (replace-match "\\1- \\2")))
13602 (beginning-of-line 2)))))))
13604 (defun org-toggle-heading (&optional nstars)
13605 "Convert headings to normal text, or items or text to headings.
13606 If there is no active region, only the current line is considered.
13608 If the first line is a heading, remove the stars from all headlines
13609 in the region.
13611 If the first line is a plain list item, turn all plain list items into
13612 headings.
13614 If the first line is a normal line, turn each and every line in the region
13615 into a heading.
13617 When converting a line into a heading, the number of stars is chosen
13618 such that the lines become children of the current entry. However, when
13619 a prefix argument is given, its value determines the number of stars to add."
13620 (interactive "P")
13621 (let (l2 l itemp beg end)
13622 (if (org-region-active-p)
13623 (setq beg (region-beginning) end (region-end))
13624 (setq beg (point-at-bol)
13625 end (min (1+ (point-at-eol)) (point-max))))
13626 (save-excursion
13627 (goto-char end)
13628 (setq l2 (org-current-line))
13629 (goto-char beg)
13630 (beginning-of-line 1)
13631 (setq l (1- (org-current-line)))
13632 (if (org-on-heading-p)
13633 ;; We already have headlines, de-star them
13634 (while (< (setq l (1+ l)) l2)
13635 (when (org-on-heading-p t)
13636 (and (looking-at outline-regexp) (replace-match "")))
13637 (beginning-of-line 2))
13638 (setq itemp (org-at-item-p))
13639 (let* ((stars
13640 (if nstars
13641 (make-string (prefix-numeric-value current-prefix-arg)
13643 (save-excursion
13644 (re-search-backward org-complex-heading-regexp nil t)
13645 (or (match-string 1) "*"))))
13646 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13647 (rpl (concat stars add-stars " ")))
13648 (while (< (setq l (1+ l)) l2)
13649 (if itemp
13650 (and (org-at-item-p) (replace-match rpl t t))
13651 (unless (org-on-heading-p)
13652 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13653 (replace-match (concat rpl (match-string 2))))))
13654 (beginning-of-line 2)))))))
13656 (defun org-meta-return (&optional arg)
13657 "Insert a new heading or wrap a region in a table.
13658 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13659 See the individual commands for more information."
13660 (interactive "P")
13661 (cond
13662 ((org-at-table-p)
13663 (call-interactively 'org-table-wrap-region))
13664 (t (call-interactively 'org-insert-heading))))
13666 ;;; Menu entries
13668 ;; Define the Org-mode menus
13669 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13670 '("Tbl"
13671 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13672 ["Next Field" org-cycle (org-at-table-p)]
13673 ["Previous Field" org-shifttab (org-at-table-p)]
13674 ["Next Row" org-return (org-at-table-p)]
13675 "--"
13676 ["Blank Field" org-table-blank-field (org-at-table-p)]
13677 ["Edit Field" org-table-edit-field (org-at-table-p)]
13678 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13679 "--"
13680 ("Column"
13681 ["Move Column Left" org-metaleft (org-at-table-p)]
13682 ["Move Column Right" org-metaright (org-at-table-p)]
13683 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13684 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13685 ("Row"
13686 ["Move Row Up" org-metaup (org-at-table-p)]
13687 ["Move Row Down" org-metadown (org-at-table-p)]
13688 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13689 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13690 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13691 "--"
13692 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13693 ("Rectangle"
13694 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13695 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13696 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13697 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13698 "--"
13699 ("Calculate"
13700 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13701 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13702 ["Edit Formulas" org-edit-special (org-at-table-p)]
13703 "--"
13704 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13705 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13706 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13707 "--"
13708 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13709 "--"
13710 ["Sum Column/Rectangle" org-table-sum
13711 (or (org-at-table-p) (org-region-active-p))]
13712 ["Which Column?" org-table-current-column (org-at-table-p)])
13713 ["Debug Formulas"
13714 org-table-toggle-formula-debugger
13715 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13716 ["Show Col/Row Numbers"
13717 org-table-toggle-coordinate-overlays
13718 :style toggle
13719 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13720 "--"
13721 ["Create" org-table-create (and (not (org-at-table-p))
13722 org-enable-table-editor)]
13723 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13724 ["Import from File" org-table-import (not (org-at-table-p))]
13725 ["Export to File" org-table-export (org-at-table-p)]
13726 "--"
13727 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13729 (easy-menu-define org-org-menu org-mode-map "Org menu"
13730 '("Org"
13731 ("Show/Hide"
13732 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13733 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13734 ["Sparse Tree..." org-sparse-tree t]
13735 ["Reveal Context" org-reveal t]
13736 ["Show All" show-all t]
13737 "--"
13738 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13739 "--"
13740 ["New Heading" org-insert-heading t]
13741 ("Navigate Headings"
13742 ["Up" outline-up-heading t]
13743 ["Next" outline-next-visible-heading t]
13744 ["Previous" outline-previous-visible-heading t]
13745 ["Next Same Level" outline-forward-same-level t]
13746 ["Previous Same Level" outline-backward-same-level t]
13747 "--"
13748 ["Jump" org-goto t])
13749 ("Edit Structure"
13750 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13751 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13752 "--"
13753 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13754 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13755 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13756 "--"
13757 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13758 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13759 ["Demote Heading" org-metaright (not (org-at-table-p))]
13760 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13761 "--"
13762 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13763 "--"
13764 ["Convert to odd levels" org-convert-to-odd-levels t]
13765 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13766 ("Editing"
13767 ["Emphasis..." org-emphasize t]
13768 ["Edit Source Example" org-edit-special t]
13769 "--"
13770 ["Footnote new/jump" org-footnote-action t]
13771 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13772 ("Archive"
13773 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13774 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13775 ; :active t :keys "C-u C-c C-x C-a"]
13776 ["Sparse trees open ARCHIVE trees"
13777 (setq org-sparse-tree-open-archived-trees
13778 (not org-sparse-tree-open-archived-trees))
13779 :style toggle :selected org-sparse-tree-open-archived-trees]
13780 ["Cycling opens ARCHIVE trees"
13781 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13782 :style toggle :selected org-cycle-open-archived-trees]
13783 "--"
13784 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13785 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13786 ; ["Check and Move Children" (org-archive-subtree '(4))
13787 ; :active t :keys "C-u C-c C-x C-s"]
13789 "--"
13790 ("TODO Lists"
13791 ["TODO/DONE/-" org-todo t]
13792 ("Select keyword"
13793 ["Next keyword" org-shiftright (org-on-heading-p)]
13794 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13795 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13796 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13797 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13798 ["Show TODO Tree" org-show-todo-tree t]
13799 ["Global TODO list" org-todo-list t]
13800 "--"
13801 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
13802 :selected org-enforce-todo-dependencies :style toggle :active t]
13803 "Settings for tree at point"
13804 ["Do Children sequentially" org-toggle-ordered-property :style radio
13805 :selected (ignore-errors (org-entry-get nil "ORDERED"))
13806 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13807 ["Do Children parallel" org-toggle-ordered-property :style radio
13808 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
13809 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13810 "--"
13811 ["Set Priority" org-priority t]
13812 ["Priority Up" org-shiftup t]
13813 ["Priority Down" org-shiftdown t])
13814 ("TAGS and Properties"
13815 ["Set Tags" org-set-tags-command t]
13816 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13817 "--"
13818 ["Set property" org-set-property t]
13819 ["Column view of properties" org-columns t]
13820 ["Insert Column View DBlock" org-insert-columns-dblock t])
13821 ("Dates and Scheduling"
13822 ["Timestamp" org-time-stamp t]
13823 ["Timestamp (inactive)" org-time-stamp-inactive t]
13824 ("Change Date"
13825 ["1 Day Later" org-shiftright t]
13826 ["1 Day Earlier" org-shiftleft t]
13827 ["1 ... Later" org-shiftup t]
13828 ["1 ... Earlier" org-shiftdown t])
13829 ["Compute Time Range" org-evaluate-time-range t]
13830 ["Schedule Item" org-schedule t]
13831 ["Deadline" org-deadline t]
13832 "--"
13833 ["Custom time format" org-toggle-time-stamp-overlays
13834 :style radio :selected org-display-custom-times]
13835 "--"
13836 ["Goto Calendar" org-goto-calendar t]
13837 ["Date from Calendar" org-date-from-calendar t]
13838 "--"
13839 ["Start/Restart Timer" org-timer-start t]
13840 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13841 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13842 ["Insert Timer String" org-timer t]
13843 ["Insert Timer Item" org-timer-item t])
13844 ("Logging work"
13845 ["Clock in" org-clock-in t]
13846 ["Clock out" org-clock-out t]
13847 ["Clock cancel" org-clock-cancel t]
13848 ["Goto running clock" org-clock-goto t]
13849 ["Display times" org-clock-display t]
13850 ["Create clock table" org-clock-report t]
13851 "--"
13852 ["Record DONE time"
13853 (progn (setq org-log-done (not org-log-done))
13854 (message "Switching to %s will %s record a timestamp"
13855 (car org-done-keywords)
13856 (if org-log-done "automatically" "not")))
13857 :style toggle :selected org-log-done])
13858 "--"
13859 ["Agenda Command..." org-agenda t]
13860 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13861 ("File List for Agenda")
13862 ("Special views current file"
13863 ["TODO Tree" org-show-todo-tree t]
13864 ["Check Deadlines" org-check-deadlines t]
13865 ["Timeline" org-timeline t]
13866 ["Tags Tree" org-tags-sparse-tree t])
13867 "--"
13868 ("Hyperlinks"
13869 ["Store Link (Global)" org-store-link t]
13870 ["Insert Link" org-insert-link t]
13871 ["Follow Link" org-open-at-point t]
13872 "--"
13873 ["Next link" org-next-link t]
13874 ["Previous link" org-previous-link t]
13875 "--"
13876 ["Descriptive Links"
13877 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13878 :style radio
13879 :selected (member '(org-link) buffer-invisibility-spec)]
13880 ["Literal Links"
13881 (progn
13882 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13883 :style radio
13884 :selected (not (member '(org-link) buffer-invisibility-spec))])
13885 "--"
13886 ["Export/Publish..." org-export t]
13887 ("LaTeX"
13888 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13889 :selected org-cdlatex-mode]
13890 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13891 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13892 ["Modify math symbol" org-cdlatex-math-modify
13893 (org-inside-LaTeX-fragment-p)]
13894 ["Export LaTeX fragments as images"
13895 (if (featurep 'org-exp)
13896 (setq org-export-with-LaTeX-fragments
13897 (not org-export-with-LaTeX-fragments))
13898 (require 'org-exp))
13899 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13900 org-export-with-LaTeX-fragments)])
13901 "--"
13902 ("Documentation"
13903 ["Show Version" org-version t]
13904 ["Info Documentation" org-info t])
13905 ("Customize"
13906 ["Browse Org Group" org-customize t]
13907 "--"
13908 ["Expand This Menu" org-create-customize-menu
13909 (fboundp 'customize-menu-create)])
13910 "--"
13911 ["Refresh setup" org-mode-restart t]
13914 (defun org-info (&optional node)
13915 "Read documentation for Org-mode in the info system.
13916 With optional NODE, go directly to that node."
13917 (interactive)
13918 (info (format "(org)%s" (or node ""))))
13920 (defun org-install-agenda-files-menu ()
13921 (let ((bl (buffer-list)))
13922 (save-excursion
13923 (while bl
13924 (set-buffer (pop bl))
13925 (if (org-mode-p) (setq bl nil)))
13926 (when (org-mode-p)
13927 (easy-menu-change
13928 '("Org") "File List for Agenda"
13929 (append
13930 (list
13931 ["Edit File List" (org-edit-agenda-file-list) t]
13932 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13933 ["Remove Current File from List" org-remove-file t]
13934 ["Cycle through agenda files" org-cycle-agenda-files t]
13935 ["Occur in all agenda files" org-occur-in-agenda-files t]
13936 "--")
13937 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13939 ;;;; Documentation
13941 ;;;###autoload
13942 (defun org-require-autoloaded-modules ()
13943 (interactive)
13944 (mapc 'require
13945 '(org-agenda org-archive org-attach org-clock org-colview
13946 org-exp org-id org-export-latex org-publish
13947 org-remember org-table org-timer)))
13949 ;;;###autoload
13950 (defun org-customize ()
13951 "Call the customize function with org as argument."
13952 (interactive)
13953 (org-load-modules-maybe)
13954 (org-require-autoloaded-modules)
13955 (customize-browse 'org))
13957 (defun org-create-customize-menu ()
13958 "Create a full customization menu for Org-mode, insert it into the menu."
13959 (interactive)
13960 (org-load-modules-maybe)
13961 (org-require-autoloaded-modules)
13962 (if (fboundp 'customize-menu-create)
13963 (progn
13964 (easy-menu-change
13965 '("Org") "Customize"
13966 `(["Browse Org group" org-customize t]
13967 "--"
13968 ,(customize-menu-create 'org)
13969 ["Set" Custom-set t]
13970 ["Save" Custom-save t]
13971 ["Reset to Current" Custom-reset-current t]
13972 ["Reset to Saved" Custom-reset-saved t]
13973 ["Reset to Standard Settings" Custom-reset-standard t]))
13974 (message "\"Org\"-menu now contains full customization menu"))
13975 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13977 ;;;; Miscellaneous stuff
13979 ;;; Generally useful functions
13981 (defun org-find-text-property-in-string (prop s)
13982 "Return the first non-nil value of property PROP in string S."
13983 (or (get-text-property 0 prop s)
13984 (get-text-property (or (next-single-property-change 0 prop s) 0)
13985 prop s)))
13987 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13988 "Display the given MESSAGE as a warning."
13989 (if (fboundp 'display-warning)
13990 (display-warning 'org message
13991 (if (featurep 'xemacs)
13992 'warning
13993 :warning))
13994 (let ((buf (get-buffer-create "*Org warnings*")))
13995 (with-current-buffer buf
13996 (goto-char (point-max))
13997 (insert "Warning (Org): " message)
13998 (unless (bolp)
13999 (newline)))
14000 (display-buffer buf)
14001 (sit-for 0))))
14003 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14004 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14005 (if (and marker (marker-buffer marker)
14006 (buffer-live-p (marker-buffer marker)))
14007 (progn
14008 (switch-to-buffer (marker-buffer marker))
14009 (if (or (> marker (point-max)) (< marker (point-min)))
14010 (widen))
14011 (goto-char marker)
14012 (org-show-context 'org-goto))
14013 (if bookmark
14014 (bookmark-jump bookmark)
14015 (error "Cannot find location"))))
14017 (defun org-quote-csv-field (s)
14018 "Quote field for inclusion in CSV material."
14019 (if (string-match "[\",]" s)
14020 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14023 (defun org-plist-delete (plist property)
14024 "Delete PROPERTY from PLIST.
14025 This is in contrast to merely setting it to 0."
14026 (let (p)
14027 (while plist
14028 (if (not (eq property (car plist)))
14029 (setq p (plist-put p (car plist) (nth 1 plist))))
14030 (setq plist (cddr plist)))
14033 (defun org-force-self-insert (N)
14034 "Needed to enforce self-insert under remapping."
14035 (interactive "p")
14036 (self-insert-command N))
14038 (defun org-string-width (s)
14039 "Compute width of string, ignoring invisible characters.
14040 This ignores character with invisibility property `org-link', and also
14041 characters with property `org-cwidth', because these will become invisible
14042 upon the next fontification round."
14043 (let (b l)
14044 (when (or (eq t buffer-invisibility-spec)
14045 (assq 'org-link buffer-invisibility-spec))
14046 (while (setq b (text-property-any 0 (length s)
14047 'invisible 'org-link s))
14048 (setq s (concat (substring s 0 b)
14049 (substring s (or (next-single-property-change
14050 b 'invisible s) (length s)))))))
14051 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14052 (setq s (concat (substring s 0 b)
14053 (substring s (or (next-single-property-change
14054 b 'org-cwidth s) (length s))))))
14055 (setq l (string-width s) b -1)
14056 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14057 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14060 (defun org-get-indentation (&optional line)
14061 "Get the indentation of the current line, interpreting tabs.
14062 When LINE is given, assume it represents a line and compute its indentation."
14063 (if line
14064 (if (string-match "^ *" (org-remove-tabs line))
14065 (match-end 0))
14066 (save-excursion
14067 (beginning-of-line 1)
14068 (skip-chars-forward " \t")
14069 (current-column))))
14071 (defun org-remove-tabs (s &optional width)
14072 "Replace tabulators in S with spaces.
14073 Assumes that s is a single line, starting in column 0."
14074 (setq width (or width tab-width))
14075 (while (string-match "\t" s)
14076 (setq s (replace-match
14077 (make-string
14078 (- (* width (/ (+ (match-beginning 0) width) width))
14079 (match-beginning 0)) ?\ )
14080 t t s)))
14083 (defun org-fix-indentation (line ind)
14084 "Fix indentation in LINE.
14085 IND is a cons cell with target and minimum indentation.
14086 If the current indentation in LINE is smaller than the minimum,
14087 leave it alone. If it is larger than ind, set it to the target."
14088 (let* ((l (org-remove-tabs line))
14089 (i (org-get-indentation l))
14090 (i1 (car ind)) (i2 (cdr ind)))
14091 (if (>= i i2) (setq l (substring line i2)))
14092 (if (> i1 0)
14093 (concat (make-string i1 ?\ ) l)
14094 l)))
14096 (defun org-base-buffer (buffer)
14097 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14098 (if (not buffer)
14099 buffer
14100 (or (buffer-base-buffer buffer)
14101 buffer)))
14103 (defun org-trim (s)
14104 "Remove whitespace at beginning and end of string."
14105 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14106 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14109 (defun org-wrap (string &optional width lines)
14110 "Wrap string to either a number of lines, or a width in characters.
14111 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14112 that costs. If there is a word longer than WIDTH, the text is actually
14113 wrapped to the length of that word.
14114 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14115 many lines, whatever width that takes.
14116 The return value is a list of lines, without newlines at the end."
14117 (let* ((words (org-split-string string "[ \t\n]+"))
14118 (maxword (apply 'max (mapcar 'org-string-width words)))
14119 w ll)
14120 (cond (width
14121 (org-do-wrap words (max maxword width)))
14122 (lines
14123 (setq w maxword)
14124 (setq ll (org-do-wrap words maxword))
14125 (if (<= (length ll) lines)
14127 (setq ll words)
14128 (while (> (length ll) lines)
14129 (setq w (1+ w))
14130 (setq ll (org-do-wrap words w)))
14131 ll))
14132 (t (error "Cannot wrap this")))))
14134 (defun org-do-wrap (words width)
14135 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14136 (let (lines line)
14137 (while words
14138 (setq line (pop words))
14139 (while (and words (< (+ (length line) (length (car words))) width))
14140 (setq line (concat line " " (pop words))))
14141 (setq lines (push line lines)))
14142 (nreverse lines)))
14144 (defun org-split-string (string &optional separators)
14145 "Splits STRING into substrings at SEPARATORS.
14146 No empty strings are returned if there are matches at the beginning
14147 and end of string."
14148 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14149 (start 0)
14150 notfirst
14151 (list nil))
14152 (while (and (string-match rexp string
14153 (if (and notfirst
14154 (= start (match-beginning 0))
14155 (< start (length string)))
14156 (1+ start) start))
14157 (< (match-beginning 0) (length string)))
14158 (setq notfirst t)
14159 (or (eq (match-beginning 0) 0)
14160 (and (eq (match-beginning 0) (match-end 0))
14161 (eq (match-beginning 0) start))
14162 (setq list
14163 (cons (substring string start (match-beginning 0))
14164 list)))
14165 (setq start (match-end 0)))
14166 (or (eq start (length string))
14167 (setq list
14168 (cons (substring string start)
14169 list)))
14170 (nreverse list)))
14172 (defun org-context ()
14173 "Return a list of contexts of the current cursor position.
14174 If several contexts apply, all are returned.
14175 Each context entry is a list with a symbol naming the context, and
14176 two positions indicating start and end of the context. Possible
14177 contexts are:
14179 :headline anywhere in a headline
14180 :headline-stars on the leading stars in a headline
14181 :todo-keyword on a TODO keyword (including DONE) in a headline
14182 :tags on the TAGS in a headline
14183 :priority on the priority cookie in a headline
14184 :item on the first line of a plain list item
14185 :item-bullet on the bullet/number of a plain list item
14186 :checkbox on the checkbox in a plain list item
14187 :table in an org-mode table
14188 :table-special on a special filed in a table
14189 :table-table in a table.el table
14190 :link on a hyperlink
14191 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14192 :target on a <<target>>
14193 :radio-target on a <<<radio-target>>>
14194 :latex-fragment on a LaTeX fragment
14195 :latex-preview on a LaTeX fragment with overlayed preview image
14197 This function expects the position to be visible because it uses font-lock
14198 faces as a help to recognize the following contexts: :table-special, :link,
14199 and :keyword."
14200 (let* ((f (get-text-property (point) 'face))
14201 (faces (if (listp f) f (list f)))
14202 (p (point)) clist o)
14203 ;; First the large context
14204 (cond
14205 ((org-on-heading-p t)
14206 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14207 (when (progn
14208 (beginning-of-line 1)
14209 (looking-at org-todo-line-tags-regexp))
14210 (push (org-point-in-group p 1 :headline-stars) clist)
14211 (push (org-point-in-group p 2 :todo-keyword) clist)
14212 (push (org-point-in-group p 4 :tags) clist))
14213 (goto-char p)
14214 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14215 (if (looking-at "\\[#[A-Z0-9]\\]")
14216 (push (org-point-in-group p 0 :priority) clist)))
14218 ((org-at-item-p)
14219 (push (org-point-in-group p 2 :item-bullet) clist)
14220 (push (list :item (point-at-bol)
14221 (save-excursion (org-end-of-item) (point)))
14222 clist)
14223 (and (org-at-item-checkbox-p)
14224 (push (org-point-in-group p 0 :checkbox) clist)))
14226 ((org-at-table-p)
14227 (push (list :table (org-table-begin) (org-table-end)) clist)
14228 (if (memq 'org-formula faces)
14229 (push (list :table-special
14230 (previous-single-property-change p 'face)
14231 (next-single-property-change p 'face)) clist)))
14232 ((org-at-table-p 'any)
14233 (push (list :table-table) clist)))
14234 (goto-char p)
14236 ;; Now the small context
14237 (cond
14238 ((org-at-timestamp-p)
14239 (push (org-point-in-group p 0 :timestamp) clist))
14240 ((memq 'org-link faces)
14241 (push (list :link
14242 (previous-single-property-change p 'face)
14243 (next-single-property-change p 'face)) clist))
14244 ((memq 'org-special-keyword faces)
14245 (push (list :keyword
14246 (previous-single-property-change p 'face)
14247 (next-single-property-change p 'face)) clist))
14248 ((org-on-target-p)
14249 (push (org-point-in-group p 0 :target) clist)
14250 (goto-char (1- (match-beginning 0)))
14251 (if (looking-at org-radio-target-regexp)
14252 (push (org-point-in-group p 0 :radio-target) clist))
14253 (goto-char p))
14254 ((setq o (car (delq nil
14255 (mapcar
14256 (lambda (x)
14257 (if (memq x org-latex-fragment-image-overlays) x))
14258 (org-overlays-at (point))))))
14259 (push (list :latex-fragment
14260 (org-overlay-start o) (org-overlay-end o)) clist)
14261 (push (list :latex-preview
14262 (org-overlay-start o) (org-overlay-end o)) clist))
14263 ((org-inside-LaTeX-fragment-p)
14264 ;; FIXME: positions wrong.
14265 (push (list :latex-fragment (point) (point)) clist)))
14267 (setq clist (nreverse (delq nil clist)))
14268 clist))
14270 ;; FIXME: Compare with at-regexp-p Do we need both?
14271 (defun org-in-regexp (re &optional nlines visually)
14272 "Check if point is inside a match of regexp.
14273 Normally only the current line is checked, but you can include NLINES extra
14274 lines both before and after point into the search.
14275 If VISUALLY is set, require that the cursor is not after the match but
14276 really on, so that the block visually is on the match."
14277 (catch 'exit
14278 (let ((pos (point))
14279 (eol (point-at-eol (+ 1 (or nlines 0))))
14280 (inc (if visually 1 0)))
14281 (save-excursion
14282 (beginning-of-line (- 1 (or nlines 0)))
14283 (while (re-search-forward re eol t)
14284 (if (and (<= (match-beginning 0) pos)
14285 (>= (+ inc (match-end 0)) pos))
14286 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14288 (defun org-at-regexp-p (regexp)
14289 "Is point inside a match of REGEXP in the current line?"
14290 (catch 'exit
14291 (save-excursion
14292 (let ((pos (point)) (end (point-at-eol)))
14293 (beginning-of-line 1)
14294 (while (re-search-forward regexp end t)
14295 (if (and (<= (match-beginning 0) pos)
14296 (>= (match-end 0) pos))
14297 (throw 'exit t)))
14298 nil))))
14300 (defun org-occur-in-agenda-files (regexp &optional nlines)
14301 "Call `multi-occur' with buffers for all agenda files."
14302 (interactive "sOrg-files matching: \np")
14303 (let* ((files (org-agenda-files))
14304 (tnames (mapcar 'file-truename files))
14305 (extra org-agenda-text-search-extra-files)
14307 (when (eq (car extra) 'agenda-archives)
14308 (setq extra (cdr extra))
14309 (setq files (org-add-archive-files files)))
14310 (while (setq f (pop extra))
14311 (unless (member (file-truename f) tnames)
14312 (add-to-list 'files f 'append)
14313 (add-to-list 'tnames (file-truename f) 'append)))
14314 (multi-occur
14315 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14316 regexp)))
14318 (if (boundp 'occur-mode-find-occurrence-hook)
14319 ;; Emacs 23
14320 (add-hook 'occur-mode-find-occurrence-hook
14321 (lambda ()
14322 (when (org-mode-p)
14323 (org-reveal))))
14324 ;; Emacs 22
14325 (defadvice occur-mode-goto-occurrence
14326 (after org-occur-reveal activate)
14327 (and (org-mode-p) (org-reveal)))
14328 (defadvice occur-mode-goto-occurrence-other-window
14329 (after org-occur-reveal activate)
14330 (and (org-mode-p) (org-reveal)))
14331 (defadvice occur-mode-display-occurrence
14332 (after org-occur-reveal activate)
14333 (when (org-mode-p)
14334 (let ((pos (occur-mode-find-occurrence)))
14335 (with-current-buffer (marker-buffer pos)
14336 (save-excursion
14337 (goto-char pos)
14338 (org-reveal)))))))
14340 (defun org-uniquify (list)
14341 "Remove duplicate elements from LIST."
14342 (let (res)
14343 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14344 res))
14346 (defun org-delete-all (elts list)
14347 "Remove all elements in ELTS from LIST."
14348 (while elts
14349 (setq list (delete (pop elts) list)))
14350 list)
14352 (defun org-back-over-empty-lines ()
14353 "Move backwards over whitespace, to the beginning of the first empty line.
14354 Returns the number of empty lines passed."
14355 (let ((pos (point)))
14356 (skip-chars-backward " \t\n\r")
14357 (beginning-of-line 2)
14358 (goto-char (min (point) pos))
14359 (count-lines (point) pos)))
14361 (defun org-skip-whitespace ()
14362 (skip-chars-forward " \t\n\r"))
14364 (defun org-point-in-group (point group &optional context)
14365 "Check if POINT is in match-group GROUP.
14366 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14367 match. If the match group does ot exist or point is not inside it,
14368 return nil."
14369 (and (match-beginning group)
14370 (>= point (match-beginning group))
14371 (<= point (match-end group))
14372 (if context
14373 (list context (match-beginning group) (match-end group))
14374 t)))
14376 (defun org-switch-to-buffer-other-window (&rest args)
14377 "Switch to buffer in a second window on the current frame.
14378 In particular, do not allow pop-up frames."
14379 (let (pop-up-frames special-display-buffer-names special-display-regexps
14380 special-display-function)
14381 (apply 'switch-to-buffer-other-window args)))
14383 (defun org-combine-plists (&rest plists)
14384 "Create a single property list from all plists in PLISTS.
14385 The process starts by copying the first list, and then setting properties
14386 from the other lists. Settings in the last list are the most significant
14387 ones and overrule settings in the other lists."
14388 (let ((rtn (copy-sequence (pop plists)))
14389 p v ls)
14390 (while plists
14391 (setq ls (pop plists))
14392 (while ls
14393 (setq p (pop ls) v (pop ls))
14394 (setq rtn (plist-put rtn p v))))
14395 rtn))
14397 (defun org-move-line-down (arg)
14398 "Move the current line down. With prefix argument, move it past ARG lines."
14399 (interactive "p")
14400 (let ((col (current-column))
14401 beg end pos)
14402 (beginning-of-line 1) (setq beg (point))
14403 (beginning-of-line 2) (setq end (point))
14404 (beginning-of-line (+ 1 arg))
14405 (setq pos (move-marker (make-marker) (point)))
14406 (insert (delete-and-extract-region beg end))
14407 (goto-char pos)
14408 (org-move-to-column col)))
14410 (defun org-move-line-up (arg)
14411 "Move the current line up. With prefix argument, move it past ARG lines."
14412 (interactive "p")
14413 (let ((col (current-column))
14414 beg end pos)
14415 (beginning-of-line 1) (setq beg (point))
14416 (beginning-of-line 2) (setq end (point))
14417 (beginning-of-line (- arg))
14418 (setq pos (move-marker (make-marker) (point)))
14419 (insert (delete-and-extract-region beg end))
14420 (goto-char pos)
14421 (org-move-to-column col)))
14423 (defun org-replace-escapes (string table)
14424 "Replace %-escapes in STRING with values in TABLE.
14425 TABLE is an association list with keys like \"%a\" and string values.
14426 The sequences in STRING may contain normal field width and padding information,
14427 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14428 so values can contain further %-escapes if they are define later in TABLE."
14429 (let ((case-fold-search nil)
14430 e re rpl)
14431 (while (setq e (pop table))
14432 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14433 (while (string-match re string)
14434 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14435 (cdr e)))
14436 (setq string (replace-match rpl t t string))))
14437 string))
14440 (defun org-sublist (list start end)
14441 "Return a section of LIST, from START to END.
14442 Counting starts at 1."
14443 (let (rtn (c start))
14444 (setq list (nthcdr (1- start) list))
14445 (while (and list (<= c end))
14446 (push (pop list) rtn)
14447 (setq c (1+ c)))
14448 (nreverse rtn)))
14450 (defun org-find-base-buffer-visiting (file)
14451 "Like `find-buffer-visiting' but alway return the base buffer and
14452 not an indirect buffer."
14453 (let ((buf (find-buffer-visiting file)))
14454 (if buf
14455 (or (buffer-base-buffer buf) buf)
14456 nil)))
14458 (defun org-image-file-name-regexp (&optional extensions)
14459 "Return regexp matching the file names of images.
14460 If EXTENSIONS is given, only match these."
14461 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14462 (image-file-name-regexp)
14463 (let ((image-file-name-extensions
14464 (or extensions
14465 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14466 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14467 (concat "\\."
14468 (regexp-opt (nconc (mapcar 'upcase
14469 image-file-name-extensions)
14470 image-file-name-extensions)
14472 "\\'"))))
14474 (defun org-file-image-p (file &optional extensions)
14475 "Return non-nil if FILE is an image."
14476 (save-match-data
14477 (string-match (org-image-file-name-regexp extensions) file)))
14479 (defun org-get-cursor-date ()
14480 "Return the date at cursor in as a time.
14481 This works in the calendar and in the agenda, anywhere else it just
14482 returns the current time."
14483 (let (date day defd)
14484 (cond
14485 ((eq major-mode 'calendar-mode)
14486 (setq date (calendar-cursor-to-date)
14487 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14488 ((eq major-mode 'org-agenda-mode)
14489 (setq day (get-text-property (point) 'day))
14490 (if day
14491 (setq date (calendar-gregorian-from-absolute day)
14492 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14493 (nth 2 date))))))
14494 (or defd (current-time))))
14496 (defvar org-agenda-action-marker (make-marker)
14497 "Marker pointing to the entry for the next agenda action.")
14499 (defun org-mark-entry-for-agenda-action ()
14500 "Mark the current entry as target of an agenda action.
14501 Agenda actions are actions executed from the agenda with the key `k',
14502 which make use of the date at the cursor."
14503 (interactive)
14504 (move-marker org-agenda-action-marker
14505 (save-excursion (org-back-to-heading t) (point))
14506 (current-buffer))
14507 (message
14508 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14510 ;;; Paragraph filling stuff.
14511 ;; We want this to be just right, so use the full arsenal.
14513 (defun org-indent-line-function ()
14514 "Indent line like previous, but further if previous was headline or item."
14515 (interactive)
14516 (let* ((pos (point))
14517 (itemp (org-at-item-p))
14518 column bpos bcol tpos tcol bullet btype bullet-type)
14519 ;; Find the previous relevant line
14520 (beginning-of-line 1)
14521 (cond
14522 ((looking-at "#") (setq column 0))
14523 ((looking-at "\\*+ ") (setq column 0))
14525 (beginning-of-line 0)
14526 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14527 (beginning-of-line 0))
14528 (cond
14529 ((looking-at "\\*+[ \t]+")
14530 (if (not org-adapt-indentation)
14531 (setq column 0)
14532 (goto-char (match-end 0))
14533 (setq column (current-column))))
14534 ((org-in-item-p)
14535 (org-beginning-of-item)
14536 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14537 (setq bpos (match-beginning 1) tpos (match-end 0)
14538 bcol (progn (goto-char bpos) (current-column))
14539 tcol (progn (goto-char tpos) (current-column))
14540 bullet (match-string 1)
14541 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14542 (if (> tcol (+ bcol org-description-max-indent))
14543 (setq tcol (+ bcol 5)))
14544 (if (not itemp)
14545 (setq column tcol)
14546 (goto-char pos)
14547 (beginning-of-line 1)
14548 (if (looking-at "\\S-")
14549 (progn
14550 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14551 (setq bullet (match-string 1)
14552 btype (if (string-match "[0-9]" bullet) "n" bullet))
14553 (setq column (if (equal btype bullet-type) bcol tcol)))
14554 (setq column (org-get-indentation)))))
14555 (t (setq column (org-get-indentation))))))
14556 (goto-char pos)
14557 (if (<= (current-column) (current-indentation))
14558 (org-indent-line-to column)
14559 (save-excursion (org-indent-line-to column)))
14560 (setq column (current-column))
14561 (beginning-of-line 1)
14562 (if (looking-at
14563 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14564 (replace-match (concat "\\1" (format org-property-format
14565 (match-string 2) (match-string 3)))
14566 t nil))
14567 (org-move-to-column column)))
14569 (defun org-set-autofill-regexps ()
14570 (interactive)
14571 ;; In the paragraph separator we include headlines, because filling
14572 ;; text in a line directly attached to a headline would otherwise
14573 ;; fill the headline as well.
14574 (org-set-local 'comment-start-skip "^#+[ \t]*")
14575 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14576 ;; The paragraph starter includes hand-formatted lists.
14577 (org-set-local 'paragraph-start
14578 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14579 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14580 ;; But only if the user has not turned off tables or fixed-width regions
14581 (org-set-local
14582 'auto-fill-inhibit-regexp
14583 (concat "\\*+ \\|#\\+"
14584 "\\|[ \t]*" org-keyword-time-regexp
14585 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14586 (concat
14587 "\\|[ \t]*["
14588 (if org-enable-table-editor "|" "")
14589 (if org-enable-fixed-width-editor ":" "")
14590 "]"))))
14591 ;; We use our own fill-paragraph function, to make sure that tables
14592 ;; and fixed-width regions are not wrapped. That function will pass
14593 ;; through to `fill-paragraph' when appropriate.
14594 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14595 ; Adaptive filling: To get full control, first make sure that
14596 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14597 (org-set-local 'adaptive-fill-regexp "\000")
14598 (org-set-local 'adaptive-fill-function
14599 'org-adaptive-fill-function)
14600 (org-set-local
14601 'align-mode-rules-list
14602 '((org-in-buffer-settings
14603 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14604 (modes . '(org-mode))))))
14606 (defun org-fill-paragraph (&optional justify)
14607 "Re-align a table, pass through to fill-paragraph if no table."
14608 (let ((table-p (org-at-table-p))
14609 (table.el-p (org-at-table.el-p)))
14610 (cond ((and (equal (char-after (point-at-bol)) ?*)
14611 (save-excursion (goto-char (point-at-bol))
14612 (looking-at outline-regexp)))
14613 t) ; skip headlines
14614 (table.el-p t) ; skip table.el tables
14615 (table-p (org-table-align) t) ; align org-mode tables
14616 (t nil)))) ; call paragraph-fill
14618 ;; For reference, this is the default value of adaptive-fill-regexp
14619 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14621 (defun org-adaptive-fill-function ()
14622 "Return a fill prefix for org-mode files.
14623 In particular, this makes sure hanging paragraphs for hand-formatted lists
14624 work correctly."
14625 (cond ((looking-at "#[ \t]+")
14626 (match-string 0))
14627 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14628 (save-excursion
14629 (if (> (match-end 1) (+ (match-beginning 1)
14630 org-description-max-indent))
14631 (goto-char (+ (match-beginning 1) 5))
14632 (goto-char (match-end 0)))
14633 (make-string (current-column) ?\ )))
14634 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14635 (save-excursion
14636 (goto-char (match-end 0))
14637 (make-string (current-column) ?\ )))
14638 (t nil)))
14640 ;;; Other stuff.
14642 (defun org-toggle-fixed-width-section (arg)
14643 "Toggle the fixed-width export.
14644 If there is no active region, the QUOTE keyword at the current headline is
14645 inserted or removed. When present, it causes the text between this headline
14646 and the next to be exported as fixed-width text, and unmodified.
14647 If there is an active region, this command adds or removes a colon as the
14648 first character of this line. If the first character of a line is a colon,
14649 this line is also exported in fixed-width font."
14650 (interactive "P")
14651 (let* ((cc 0)
14652 (regionp (org-region-active-p))
14653 (beg (if regionp (region-beginning) (point)))
14654 (end (if regionp (region-end)))
14655 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14656 (case-fold-search nil)
14657 (re "[ \t]*\\(:\\)")
14658 off)
14659 (if regionp
14660 (save-excursion
14661 (goto-char beg)
14662 (setq cc (current-column))
14663 (beginning-of-line 1)
14664 (setq off (looking-at re))
14665 (while (> nlines 0)
14666 (setq nlines (1- nlines))
14667 (beginning-of-line 1)
14668 (cond
14669 (arg
14670 (org-move-to-column cc t)
14671 (insert ":\n")
14672 (forward-line -1))
14673 ((and off (looking-at re))
14674 (replace-match "" t t nil 1))
14675 ((not off) (org-move-to-column cc t) (insert ":")))
14676 (forward-line 1)))
14677 (save-excursion
14678 (org-back-to-heading)
14679 (if (looking-at (concat outline-regexp
14680 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14681 (replace-match "" t t nil 1)
14682 (if (looking-at outline-regexp)
14683 (progn
14684 (goto-char (match-end 0))
14685 (insert org-quote-string " "))))))))
14687 ;;;; Functions extending outline functionality
14689 (defun org-beginning-of-line (&optional arg)
14690 "Go to the beginning of the current line. If that is invisible, continue
14691 to a visible line beginning. This makes the function of C-a more intuitive.
14692 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14693 first attempt, and only move to after the tags when the cursor is already
14694 beyond the end of the headline."
14695 (interactive "P")
14696 (let ((pos (point)) refpos)
14697 (beginning-of-line 1)
14698 (if (bobp)
14700 (backward-char 1)
14701 (if (org-invisible-p)
14702 (while (and (not (bobp)) (org-invisible-p))
14703 (backward-char 1)
14704 (beginning-of-line 1))
14705 (forward-char 1)))
14706 (when org-special-ctrl-a/e
14707 (cond
14708 ((and (looking-at org-complex-heading-regexp)
14709 (= (char-after (match-end 1)) ?\ ))
14710 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14711 (point-at-eol)))
14712 (goto-char
14713 (if (eq org-special-ctrl-a/e t)
14714 (cond ((> pos refpos) refpos)
14715 ((= pos (point)) refpos)
14716 (t (point)))
14717 (cond ((> pos (point)) (point))
14718 ((not (eq last-command this-command)) (point))
14719 (t refpos)))))
14720 ((org-at-item-p)
14721 (goto-char
14722 (if (eq org-special-ctrl-a/e t)
14723 (cond ((> pos (match-end 4)) (match-end 4))
14724 ((= pos (point)) (match-end 4))
14725 (t (point)))
14726 (cond ((> pos (point)) (point))
14727 ((not (eq last-command this-command)) (point))
14728 (t (match-end 4))))))))
14729 (org-no-warnings
14730 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14732 (defun org-end-of-line (&optional arg)
14733 "Go to the end of the line.
14734 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14735 first attempt, and only move to after the tags when the cursor is already
14736 beyond the end of the headline."
14737 (interactive "P")
14738 (if (or (not org-special-ctrl-a/e)
14739 (not (org-on-heading-p)))
14740 (end-of-line arg)
14741 (let ((pos (point)))
14742 (beginning-of-line 1)
14743 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14744 (if (eq org-special-ctrl-a/e t)
14745 (if (or (< pos (match-beginning 1))
14746 (= pos (match-end 0)))
14747 (goto-char (match-beginning 1))
14748 (goto-char (match-end 0)))
14749 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14750 (goto-char (match-end 0))
14751 (goto-char (match-beginning 1))))
14752 (end-of-line arg))))
14753 (org-no-warnings
14754 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14757 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14758 (define-key org-mode-map "\C-e" 'org-end-of-line)
14760 (defun org-kill-line (&optional arg)
14761 "Kill line, to tags or end of line."
14762 (interactive "P")
14763 (cond
14764 ((or (not org-special-ctrl-k)
14765 (bolp)
14766 (not (org-on-heading-p)))
14767 (call-interactively 'kill-line))
14768 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14769 (kill-region (point) (match-beginning 1))
14770 (org-set-tags nil t))
14771 (t (kill-region (point) (point-at-eol)))))
14773 (define-key org-mode-map "\C-k" 'org-kill-line)
14775 (defun org-yank (&optional arg)
14776 "Yank. If the kill is a subtree, treat it specially.
14777 This command will look at the current kill and check if is a single
14778 subtree, or a series of subtrees[1]. If it passes the test, and if the
14779 cursor is at the beginning of a line or after the stars of a currently
14780 empty headline, then the yank is handled specially. How exactly depends
14781 on the value of the following variables, both set by default.
14783 org-yank-folded-subtrees
14784 When set, the subtree(s) will be folded after insertion, but only
14785 if doing so would now swallow text after the yanked text.
14787 org-yank-adjusted-subtrees
14788 When set, the subtree will be promoted or demoted in order to
14789 fit into the local outline tree structure, which means that the level
14790 will be adjusted so that it becomes the smaller one of the two
14791 *visible* surrounding headings.
14793 Any prefix to this command will cause `yank' to be called directly with
14794 no special treatment. In particular, a simple `C-u' prefix will just
14795 plainly yank the text as it is.
14797 \[1] Basically, the test checks if the first non-white line is a heading
14798 and if there are no other headings with fewer stars."
14799 (interactive "P")
14800 (setq this-command 'yank)
14801 (if arg
14802 (call-interactively 'yank)
14803 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14804 (and (org-kill-is-subtree-p)
14805 (or (bolp)
14806 (and (looking-at "[ \t]*$")
14807 (string-match
14808 "\\`\\*+\\'"
14809 (buffer-substring (point-at-bol) (point)))))))
14810 swallowp)
14811 (cond
14812 ((and subtreep org-yank-folded-subtrees)
14813 (let ((beg (point))
14814 end)
14815 (if (and subtreep org-yank-adjusted-subtrees)
14816 (org-paste-subtree nil nil 'for-yank)
14817 (call-interactively 'yank))
14818 (setq end (point))
14819 (goto-char beg)
14820 (when (and (bolp) subtreep
14821 (not (setq swallowp
14822 (org-yank-folding-would-swallow-text beg end))))
14823 (or (looking-at outline-regexp)
14824 (re-search-forward (concat "^" outline-regexp) end t))
14825 (while (and (< (point) end) (looking-at outline-regexp))
14826 (hide-subtree)
14827 (org-cycle-show-empty-lines 'folded)
14828 (condition-case nil
14829 (outline-forward-same-level 1)
14830 (error (goto-char end)))))
14831 (when swallowp
14832 (message
14833 "Yanked text not folded because that would swallow text"))
14834 (goto-char end)
14835 (skip-chars-forward " \t\n\r")
14836 (beginning-of-line 1)
14837 (push-mark beg 'nomsg)))
14838 ((and subtreep org-yank-adjusted-subtrees)
14839 (let ((beg (point-at-bol)))
14840 (org-paste-subtree nil nil 'for-yank)
14841 (push-mark beg 'nomsg)))
14843 (call-interactively 'yank))))))
14845 (defun org-yank-folding-would-swallow-text (beg end)
14846 "Would hide-subtree at BEG swallow any text after END?"
14847 (let (level)
14848 (save-excursion
14849 (goto-char beg)
14850 (when (or (looking-at outline-regexp)
14851 (re-search-forward (concat "^" outline-regexp) end t))
14852 (setq level (org-outline-level)))
14853 (goto-char end)
14854 (skip-chars-forward " \t\r\n\v\f")
14855 (if (or (eobp)
14856 (and (bolp) (looking-at org-outline-regexp)
14857 (<= (org-outline-level) level)))
14858 nil ; Nothing would be swallowed
14859 t)))) ; something would swallow
14861 (define-key org-mode-map "\C-y" 'org-yank)
14863 (defun org-invisible-p ()
14864 "Check if point is at a character currently not visible."
14865 ;; Early versions of noutline don't have `outline-invisible-p'.
14866 (if (fboundp 'outline-invisible-p)
14867 (outline-invisible-p)
14868 (get-char-property (point) 'invisible)))
14870 (defun org-invisible-p2 ()
14871 "Check if point is at a character currently not visible."
14872 (save-excursion
14873 (if (and (eolp) (not (bobp))) (backward-char 1))
14874 ;; Early versions of noutline don't have `outline-invisible-p'.
14875 (if (fboundp 'outline-invisible-p)
14876 (outline-invisible-p)
14877 (get-char-property (point) 'invisible))))
14879 (defun org-back-to-heading (&optional invisible-ok)
14880 "Call `outline-back-to-heading', but provide a better error message."
14881 (condition-case nil
14882 (outline-back-to-heading invisible-ok)
14883 (error (error "Before first headline at position %d in buffer %s"
14884 (point) (current-buffer)))))
14886 (defun org-before-first-heading-p ()
14887 "Before first heading?"
14888 (save-excursion
14889 (null (re-search-backward "^\\*+ " nil t))))
14891 (defalias 'org-on-heading-p 'outline-on-heading-p)
14892 (defalias 'org-at-heading-p 'outline-on-heading-p)
14893 (defun org-at-heading-or-item-p ()
14894 (or (org-on-heading-p) (org-at-item-p)))
14896 (defun org-on-target-p ()
14897 (or (org-in-regexp org-radio-target-regexp)
14898 (org-in-regexp org-target-regexp)))
14900 (defun org-up-heading-all (arg)
14901 "Move to the heading line of which the present line is a subheading.
14902 This function considers both visible and invisible heading lines.
14903 With argument, move up ARG levels."
14904 (if (fboundp 'outline-up-heading-all)
14905 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14906 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14908 (defun org-up-heading-safe ()
14909 "Move to the heading line of which the present line is a subheading.
14910 This version will not throw an error. It will return the level of the
14911 headline found, or nil if no higher level is found."
14912 (let (start-level re)
14913 (org-back-to-heading t)
14914 (setq start-level (funcall outline-level))
14915 (if (equal start-level 1)
14917 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14918 (if (re-search-backward re nil t)
14919 (funcall outline-level)))))
14921 (defun org-first-sibling-p ()
14922 "Is this heading the first child of its parents?"
14923 (interactive)
14924 (let ((re (concat "^" outline-regexp))
14925 level l)
14926 (unless (org-at-heading-p t)
14927 (error "Not at a heading"))
14928 (setq level (funcall outline-level))
14929 (save-excursion
14930 (if (not (re-search-backward re nil t))
14932 (setq l (funcall outline-level))
14933 (< l level)))))
14935 (defun org-goto-sibling (&optional previous)
14936 "Goto the next sibling, even if it is invisible.
14937 When PREVIOUS is set, go to the previous sibling instead. Returns t
14938 when a sibling was found. When none is found, return nil and don't
14939 move point."
14940 (let ((fun (if previous 're-search-backward 're-search-forward))
14941 (pos (point))
14942 (re (concat "^" outline-regexp))
14943 level l)
14944 (when (condition-case nil (org-back-to-heading t) (error nil))
14945 (setq level (funcall outline-level))
14946 (catch 'exit
14947 (or previous (forward-char 1))
14948 (while (funcall fun re nil t)
14949 (setq l (funcall outline-level))
14950 (when (< l level) (goto-char pos) (throw 'exit nil))
14951 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14952 (goto-char pos)
14953 nil))))
14955 (defun org-show-siblings ()
14956 "Show all siblings of the current headline."
14957 (save-excursion
14958 (while (org-goto-sibling) (org-flag-heading nil)))
14959 (save-excursion
14960 (while (org-goto-sibling 'previous)
14961 (org-flag-heading nil))))
14963 (defun org-show-hidden-entry ()
14964 "Show an entry where even the heading is hidden."
14965 (save-excursion
14966 (org-show-entry)))
14968 (defun org-flag-heading (flag &optional entry)
14969 "Flag the current heading. FLAG non-nil means make invisible.
14970 When ENTRY is non-nil, show the entire entry."
14971 (save-excursion
14972 (org-back-to-heading t)
14973 ;; Check if we should show the entire entry
14974 (if entry
14975 (progn
14976 (org-show-entry)
14977 (save-excursion
14978 (and (outline-next-heading)
14979 (org-flag-heading nil))))
14980 (outline-flag-region (max (point-min) (1- (point)))
14981 (save-excursion (outline-end-of-heading) (point))
14982 flag))))
14984 (defun org-forward-same-level (arg)
14985 "Move forward to the ARG'th subheading at same level as this one.
14986 Stop at the first and last subheadings of a superior heading.
14987 This is like outline-forward-same-level, but invisible headings are ok."
14988 (interactive "p")
14989 (org-back-to-heading t)
14990 (while (> arg 0)
14991 (let ((point-to-move-to (save-excursion
14992 (org-get-next-sibling))))
14993 (if point-to-move-to
14994 (progn
14995 (goto-char point-to-move-to)
14996 (setq arg (1- arg)))
14997 (progn
14998 (setq arg 0)
14999 (error "No following same-level heading"))))))
15001 (defun org-get-next-sibling ()
15002 "Move to next heading of the same level, and return point.
15003 If there is no such heading, return nil.
15004 This is like outline-next-sibling, but invisible headings are ok."
15005 (let ((level (funcall outline-level)))
15006 (outline-next-heading)
15007 (while (and (not (eobp)) (> (funcall outline-level) level))
15008 (outline-next-heading))
15009 (if (or (eobp) (< (funcall outline-level) level))
15011 (point))))
15013 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15014 ;; This is an exact copy of the original function, but it uses
15015 ;; `org-back-to-heading', to make it work also in invisible
15016 ;; trees. And is uses an invisible-OK argument.
15017 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15018 (org-back-to-heading invisible-OK)
15019 (let ((first t)
15020 (level (funcall outline-level)))
15021 (while (and (not (eobp))
15022 (or first (> (funcall outline-level) level)))
15023 (setq first nil)
15024 (outline-next-heading))
15025 (unless to-heading
15026 (if (memq (preceding-char) '(?\n ?\^M))
15027 (progn
15028 ;; Go to end of line before heading
15029 (forward-char -1)
15030 (if (memq (preceding-char) '(?\n ?\^M))
15031 ;; leave blank line before heading
15032 (forward-char -1))))))
15033 (point))
15035 (defun org-show-subtree ()
15036 "Show everything after this heading at deeper levels."
15037 (outline-flag-region
15038 (point)
15039 (save-excursion
15040 (outline-end-of-subtree) (outline-next-heading) (point))
15041 nil))
15043 (defun org-show-entry ()
15044 "Show the body directly following this heading.
15045 Show the heading too, if it is currently invisible."
15046 (interactive)
15047 (save-excursion
15048 (condition-case nil
15049 (progn
15050 (org-back-to-heading t)
15051 (outline-flag-region
15052 (max (point-min) (1- (point)))
15053 (save-excursion
15054 (re-search-forward
15055 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15056 (or (match-beginning 1) (point-max)))
15057 nil))
15058 (error nil))))
15060 (defun org-make-options-regexp (kwds)
15061 "Make a regular expression for keyword lines."
15062 (concat
15064 "#?[ \t]*\\+\\("
15065 (mapconcat 'regexp-quote kwds "\\|")
15066 "\\):[ \t]*"
15067 "\\(.+\\)"))
15069 ;; Make isearch reveal the necessary context
15070 (defun org-isearch-end ()
15071 "Reveal context after isearch exits."
15072 (when isearch-success ; only if search was successful
15073 (if (featurep 'xemacs)
15074 ;; Under XEmacs, the hook is run in the correct place,
15075 ;; we directly show the context.
15076 (org-show-context 'isearch)
15077 ;; In Emacs the hook runs *before* restoring the overlays.
15078 ;; So we have to use a one-time post-command-hook to do this.
15079 ;; (Emacs 22 has a special variable, see function `org-mode')
15080 (unless (and (boundp 'isearch-mode-end-hook-quit)
15081 isearch-mode-end-hook-quit)
15082 ;; Only when the isearch was not quitted.
15083 (org-add-hook 'post-command-hook 'org-isearch-post-command
15084 'append 'local)))))
15086 (defun org-isearch-post-command ()
15087 "Remove self from hook, and show context."
15088 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15089 (org-show-context 'isearch))
15092 ;;;; Integration with and fixes for other packages
15094 ;;; Imenu support
15096 (defvar org-imenu-markers nil
15097 "All markers currently used by Imenu.")
15098 (make-variable-buffer-local 'org-imenu-markers)
15100 (defun org-imenu-new-marker (&optional pos)
15101 "Return a new marker for use by Imenu, and remember the marker."
15102 (let ((m (make-marker)))
15103 (move-marker m (or pos (point)))
15104 (push m org-imenu-markers)
15107 (defun org-imenu-get-tree ()
15108 "Produce the index for Imenu."
15109 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15110 (setq org-imenu-markers nil)
15111 (let* ((n org-imenu-depth)
15112 (re (concat "^" outline-regexp))
15113 (subs (make-vector (1+ n) nil))
15114 (last-level 0)
15115 m level head)
15116 (save-excursion
15117 (save-restriction
15118 (widen)
15119 (goto-char (point-max))
15120 (while (re-search-backward re nil t)
15121 (setq level (org-reduced-level (funcall outline-level)))
15122 (when (<= level n)
15123 (looking-at org-complex-heading-regexp)
15124 (setq head (org-link-display-format
15125 (org-match-string-no-properties 4))
15126 m (org-imenu-new-marker))
15127 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15128 (if (>= level last-level)
15129 (push (cons head m) (aref subs level))
15130 (push (cons head (aref subs (1+ level))) (aref subs level))
15131 (loop for i from (1+ level) to n do (aset subs i nil)))
15132 (setq last-level level)))))
15133 (aref subs 1)))
15135 (eval-after-load "imenu"
15136 '(progn
15137 (add-hook 'imenu-after-jump-hook
15138 (lambda ()
15139 (if (eq major-mode 'org-mode)
15140 (org-show-context 'org-goto))))))
15142 (defun org-link-display-format (link)
15143 "Replace a link with either the description, or the link target
15144 if no description is present"
15145 (save-match-data
15146 (if (string-match org-bracket-link-analytic-regexp link)
15147 (replace-match (or (match-string 5 link)
15148 (concat (match-string 1 link)
15149 (match-string 3 link)))
15150 nil nil link)
15151 link)))
15153 ;; Speedbar support
15155 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15156 "Overlay marking the agenda restriction line in speedbar.")
15157 (org-overlay-put org-speedbar-restriction-lock-overlay
15158 'face 'org-agenda-restriction-lock)
15159 (org-overlay-put org-speedbar-restriction-lock-overlay
15160 'help-echo "Agendas are currently limited to this item.")
15161 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15163 (defun org-speedbar-set-agenda-restriction ()
15164 "Restrict future agenda commands to the location at point in speedbar.
15165 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15166 (interactive)
15167 (require 'org-agenda)
15168 (let (p m tp np dir txt)
15169 (cond
15170 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15171 'org-imenu t))
15172 (setq m (get-text-property p 'org-imenu-marker))
15173 (save-excursion
15174 (save-restriction
15175 (set-buffer (marker-buffer m))
15176 (goto-char m)
15177 (org-agenda-set-restriction-lock 'subtree))))
15178 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15179 'speedbar-function 'speedbar-find-file))
15180 (setq tp (previous-single-property-change
15181 (1+ p) 'speedbar-function)
15182 np (next-single-property-change
15183 tp 'speedbar-function)
15184 dir (speedbar-line-directory)
15185 txt (buffer-substring-no-properties (or tp (point-min))
15186 (or np (point-max))))
15187 (save-excursion
15188 (save-restriction
15189 (set-buffer (find-file-noselect
15190 (let ((default-directory dir))
15191 (expand-file-name txt))))
15192 (unless (org-mode-p)
15193 (error "Cannot restrict to non-Org-mode file"))
15194 (org-agenda-set-restriction-lock 'file))))
15195 (t (error "Don't know how to restrict Org-mode's agenda")))
15196 (org-move-overlay org-speedbar-restriction-lock-overlay
15197 (point-at-bol) (point-at-eol))
15198 (setq current-prefix-arg nil)
15199 (org-agenda-maybe-redo)))
15201 (eval-after-load "speedbar"
15202 '(progn
15203 (speedbar-add-supported-extension ".org")
15204 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15205 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15206 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15207 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15208 (add-hook 'speedbar-visiting-tag-hook
15209 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15212 ;;; Fixes and Hacks for problems with other packages
15214 ;; Make flyspell not check words in links, to not mess up our keymap
15215 (defun org-mode-flyspell-verify ()
15216 "Don't let flyspell put overlays at active buttons."
15217 (not (get-text-property (point) 'keymap)))
15219 ;; Make `bookmark-jump' show the jump location if it was hidden.
15220 (eval-after-load "bookmark"
15221 '(if (boundp 'bookmark-after-jump-hook)
15222 ;; We can use the hook
15223 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15224 ;; Hook not available, use advice
15225 (defadvice bookmark-jump (after org-make-visible activate)
15226 "Make the position visible."
15227 (org-bookmark-jump-unhide))))
15229 ;; Make sure saveplace show the location if it was hidden
15230 (eval-after-load "saveplace"
15231 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15232 "Make the position visible."
15233 (org-bookmark-jump-unhide)))
15235 (defun org-bookmark-jump-unhide ()
15236 "Unhide the current position, to show the bookmark location."
15237 (and (org-mode-p)
15238 (or (org-invisible-p)
15239 (save-excursion (goto-char (max (point-min) (1- (point))))
15240 (org-invisible-p)))
15241 (org-show-context 'bookmark-jump)))
15243 ;; Make session.el ignore our circular variable
15244 (eval-after-load "session"
15245 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15247 ;;;; Experimental code
15249 (defun org-closed-in-range ()
15250 "Sparse tree of items closed in a certain time range.
15251 Still experimental, may disappear in the future."
15252 (interactive)
15253 ;; Get the time interval from the user.
15254 (let* ((time1 (time-to-seconds
15255 (org-read-date nil 'to-time nil "Starting date: ")))
15256 (time2 (time-to-seconds
15257 (org-read-date nil 'to-time nil "End date:")))
15258 ;; callback function
15259 (callback (lambda ()
15260 (let ((time
15261 (time-to-seconds
15262 (apply 'encode-time
15263 (org-parse-time-string
15264 (match-string 1))))))
15265 ;; check if time in interval
15266 (and (>= time time1) (<= time time2))))))
15267 ;; make tree, check each match with the callback
15268 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15271 ;;;; Finish up
15273 (provide 'org)
15275 (run-hooks 'org-load-hook)
15277 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15279 ;;; org.el ends here