Release 6.20g
[org-mode/org-tableheadings.git] / lisp / org.el
blob956a4f529c71a7a36c7f24bc8f807f02e1946e9f
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.20g
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.20g"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
171 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
172 (const :tag " mew Links to Mew folders/messages" org-mew)
173 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
174 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
175 (const :tag " vm: Links to VM folders/messages" org-vm)
176 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
177 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
178 (const :tag " mouse: Additional mouse support" org-mouse)
180 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
181 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
182 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
183 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
184 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
185 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
186 (const :tag "C eval: Include command output as text" org-eval)
187 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
188 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
189 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
190 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
191 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
192 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
193 (const :tag "C mtags: Support for muse-like tags" org-mtags)
194 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
195 (const :tag "C registry: A registry for Org links" org-registry)
196 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
197 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
198 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
199 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
200 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
202 (defcustom org-support-shift-select nil
203 "Non-nil means, make shift-cursor commands select text when possible.
205 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
206 selecting a region, or enlarge thusly regions started in this way.
207 In Org-mode, in special contexts, these same keys are used for other
208 purposes, important enough to compete with shift selection. Org tries
209 to balance these needs by supporting `shift-select-mode' outside these
210 special contexts, under control of this variable.
212 The default of this variable is nil, to avoid confusing behavior. Shifted
213 cursor keys will then execute Org commands in the following contexts:
214 - on a headline, changing TODO state (left/right) and priority (up/down)
215 - on a time stamp, changing the time
216 - in a plain list item, changing the bullet type
217 - in a property definition line, switching between allowed values
218 - in the BEGIN line of a clock table (changing the time block).
219 Outside these contexts, the commands will throw an error.
221 When this variable is t and the cursor is not in a special context,
222 Org-mode will support shift-selection for making and enlarging regions.
223 To make this more effective, the bullet cycling will no longer happen
224 anywhere in an item line, but only if the cursor is exactly on the bullet.
226 If you set this variable to the symbol `always', then the keys
227 will not be special in headlines, property lines, and item lines, to make
228 shift selection work there as well. If this is what you want, you can
229 use the following alternative commands: `C-c C-t' and `C-c ,' to
230 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
231 TODO sets, `C-c -' to cycle item bullet types, and properties can be
232 edited by hand or in column view.
234 However, when the cursor is on a timestamp, shift-cursor commands
235 will still edit the time stamp - this is just too good to give up.
237 XEmacs user should have this variable set to nil, because shift-select-mode
238 is Emacs 23 only."
239 :group 'org
240 :type '(choice
241 (const :tag "Never" nil)
242 (const :tag "When outside special context" t)
243 (const :tag "Everywhere except timestamps" always)))
245 (defgroup org-startup nil
246 "Options concerning startup of Org-mode."
247 :tag "Org Startup"
248 :group 'org)
250 (defcustom org-startup-folded t
251 "Non-nil means, entering Org-mode will switch to OVERVIEW.
252 This can also be configured on a per-file basis by adding one of
253 the following lines anywhere in the buffer:
255 #+STARTUP: fold
256 #+STARTUP: nofold
257 #+STARTUP: content"
258 :group 'org-startup
259 :type '(choice
260 (const :tag "nofold: show all" nil)
261 (const :tag "fold: overview" t)
262 (const :tag "content: all headlines" content)))
264 (defcustom org-startup-truncated t
265 "Non-nil means, entering Org-mode will set `truncate-lines'.
266 This is useful since some lines containing links can be very long and
267 uninteresting. Also tables look terrible when wrapped."
268 :group 'org-startup
269 :type 'boolean)
271 (defcustom org-startup-align-all-tables nil
272 "Non-nil means, align all tables when visiting a file.
273 This is useful when the column width in tables is forced with <N> cookies
274 in table fields. Such tables will look correct only after the first re-align.
275 This can also be configured on a per-file basis by adding one of
276 the following lines anywhere in the buffer:
277 #+STARTUP: align
278 #+STARTUP: noalign"
279 :group 'org-startup
280 :type 'boolean)
282 (defcustom org-insert-mode-line-in-empty-file nil
283 "Non-nil means insert the first line setting Org-mode in empty files.
284 When the function `org-mode' is called interactively in an empty file, this
285 normally means that the file name does not automatically trigger Org-mode.
286 To ensure that the file will always be in Org-mode in the future, a
287 line enforcing Org-mode will be inserted into the buffer, if this option
288 has been set."
289 :group 'org-startup
290 :type 'boolean)
292 (defcustom org-replace-disputed-keys nil
293 "Non-nil means use alternative key bindings for some keys.
294 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
295 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
296 If you want to use Org-mode together with one of these other modes,
297 or more generally if you would like to move some Org-mode commands to
298 other keys, set this variable and configure the keys with the variable
299 `org-disputed-keys'.
301 This option is only relevant at load-time of Org-mode, and must be set
302 *before* org.el is loaded. Changing it requires a restart of Emacs to
303 become effective."
304 :group 'org-startup
305 :type 'boolean)
307 (defcustom org-use-extra-keys nil
308 "Non-nil means use extra key sequence definitions for certain
309 commands. This happens automatically if you run XEmacs or if
310 window-system is nil. This variable lets you do the same
311 manually. You must set it before loading org.
313 Example: on Carbon Emacs 22 running graphically, with an external
314 keyboard on a Powerbook, the default way of setting M-left might
315 not work for either Alt or ESC. Setting this variable will make
316 it work for ESC."
317 :group 'org-startup
318 :type 'boolean)
320 (if (fboundp 'defvaralias)
321 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
323 (defcustom org-disputed-keys
324 '(([(shift up)] . [(meta p)])
325 ([(shift down)] . [(meta n)])
326 ([(shift left)] . [(meta -)])
327 ([(shift right)] . [(meta +)])
328 ([(control shift right)] . [(meta shift +)])
329 ([(control shift left)] . [(meta shift -)]))
330 "Keys for which Org-mode and other modes compete.
331 This is an alist, cars are the default keys, second element specifies
332 the alternative to use when `org-replace-disputed-keys' is t.
334 Keys can be specified in any syntax supported by `define-key'.
335 The value of this option takes effect only at Org-mode's startup,
336 therefore you'll have to restart Emacs to apply it after changing."
337 :group 'org-startup
338 :type 'alist)
340 (defun org-key (key)
341 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
342 Or return the original if not disputed."
343 (if org-replace-disputed-keys
344 (let* ((nkey (key-description key))
345 (x (org-find-if (lambda (x)
346 (equal (key-description (car x)) nkey))
347 org-disputed-keys)))
348 (if x (cdr x) key))
349 key))
351 (defun org-find-if (predicate seq)
352 (catch 'exit
353 (while seq
354 (if (funcall predicate (car seq))
355 (throw 'exit (car seq))
356 (pop seq)))))
358 (defun org-defkey (keymap key def)
359 "Define a key, possibly translated, as returned by `org-key'."
360 (define-key keymap (org-key key) def))
362 (defcustom org-ellipsis nil
363 "The ellipsis to use in the Org-mode outline.
364 When nil, just use the standard three dots. When a string, use that instead,
365 When a face, use the standard 3 dots, but with the specified face.
366 The change affects only Org-mode (which will then use its own display table).
367 Changing this requires executing `M-x org-mode' in a buffer to become
368 effective."
369 :group 'org-startup
370 :type '(choice (const :tag "Default" nil)
371 (face :tag "Face" :value org-warning)
372 (string :tag "String" :value "...#")))
374 (defvar org-display-table nil
375 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
377 (defgroup org-keywords nil
378 "Keywords in Org-mode."
379 :tag "Org Keywords"
380 :group 'org)
382 (defcustom org-deadline-string "DEADLINE:"
383 "String to mark deadline entries.
384 A deadline is this string, followed by a time stamp. Should be a word,
385 terminated by a colon. You can insert a schedule keyword and
386 a timestamp with \\[org-deadline].
387 Changes become only effective after restarting Emacs."
388 :group 'org-keywords
389 :type 'string)
391 (defcustom org-scheduled-string "SCHEDULED:"
392 "String to mark scheduled TODO entries.
393 A schedule is this string, followed by a time stamp. Should be a word,
394 terminated by a colon. You can insert a schedule keyword and
395 a timestamp with \\[org-schedule].
396 Changes become only effective after restarting Emacs."
397 :group 'org-keywords
398 :type 'string)
400 (defcustom org-closed-string "CLOSED:"
401 "String used as the prefix for timestamps logging closing a TODO entry."
402 :group 'org-keywords
403 :type 'string)
405 (defcustom org-clock-string "CLOCK:"
406 "String used as prefix for timestamps clocking work hours on an item."
407 :group 'org-keywords
408 :type 'string)
410 (defcustom org-comment-string "COMMENT"
411 "Entries starting with this keyword will never be exported.
412 An entry can be toggled between COMMENT and normal with
413 \\[org-toggle-comment].
414 Changes become only effective after restarting Emacs."
415 :group 'org-keywords
416 :type 'string)
418 (defcustom org-quote-string "QUOTE"
419 "Entries starting with this keyword will be exported in fixed-width font.
420 Quoting applies only to the text in the entry following the headline, and does
421 not extend beyond the next headline, even if that is lower level.
422 An entry can be toggled between QUOTE and normal with
423 \\[org-toggle-fixed-width-section]."
424 :group 'org-keywords
425 :type 'string)
427 (defconst org-repeat-re
428 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
429 "Regular expression for specifying repeated events.
430 After a match, group 1 contains the repeat expression.")
432 (defgroup org-structure nil
433 "Options concerning the general structure of Org-mode files."
434 :tag "Org Structure"
435 :group 'org)
437 (defgroup org-reveal-location nil
438 "Options about how to make context of a location visible."
439 :tag "Org Reveal Location"
440 :group 'org-structure)
442 (defconst org-context-choice
443 '(choice
444 (const :tag "Always" t)
445 (const :tag "Never" nil)
446 (repeat :greedy t :tag "Individual contexts"
447 (cons
448 (choice :tag "Context"
449 (const agenda)
450 (const org-goto)
451 (const occur-tree)
452 (const tags-tree)
453 (const link-search)
454 (const mark-goto)
455 (const bookmark-jump)
456 (const isearch)
457 (const default))
458 (boolean))))
459 "Contexts for the reveal options.")
461 (defcustom org-show-hierarchy-above '((default . t))
462 "Non-nil means, show full hierarchy when revealing a location.
463 Org-mode often shows locations in an org-mode file which might have
464 been invisible before. When this is set, the hierarchy of headings
465 above the exposed location is shown.
466 Turning this off for example for sparse trees makes them very compact.
467 Instead of t, this can also be an alist specifying this option for different
468 contexts. Valid contexts are
469 agenda when exposing an entry from the agenda
470 org-goto when using the command `org-goto' on key C-c C-j
471 occur-tree when using the command `org-occur' on key C-c /
472 tags-tree when constructing a sparse tree based on tags matches
473 link-search when exposing search matches associated with a link
474 mark-goto when exposing the jump goal of a mark
475 bookmark-jump when exposing a bookmark location
476 isearch when exiting from an incremental search
477 default default for all contexts not set explicitly"
478 :group 'org-reveal-location
479 :type org-context-choice)
481 (defcustom org-show-following-heading '((default . nil))
482 "Non-nil means, show following heading when revealing a location.
483 Org-mode often shows locations in an org-mode file which might have
484 been invisible before. When this is set, the heading following the
485 match is shown.
486 Turning this off for example for sparse trees makes them very compact,
487 but makes it harder to edit the location of the match. In such a case,
488 use the command \\[org-reveal] to show more context.
489 Instead of t, this can also be an alist specifying this option for different
490 contexts. See `org-show-hierarchy-above' for valid contexts."
491 :group 'org-reveal-location
492 :type org-context-choice)
494 (defcustom org-show-siblings '((default . nil) (isearch t))
495 "Non-nil means, show all sibling heading when revealing a location.
496 Org-mode often shows locations in an org-mode file which might have
497 been invisible before. When this is set, the sibling of the current entry
498 heading are all made visible. If `org-show-hierarchy-above' is t,
499 the same happens on each level of the hierarchy above the current entry.
501 By default this is on for the isearch context, off for all other contexts.
502 Turning this off for example for sparse trees makes them very compact,
503 but makes it harder to edit the location of the match. In such a case,
504 use the command \\[org-reveal] to show more context.
505 Instead of t, this can also be an alist specifying this option for different
506 contexts. See `org-show-hierarchy-above' for valid contexts."
507 :group 'org-reveal-location
508 :type org-context-choice)
510 (defcustom org-show-entry-below '((default . nil))
511 "Non-nil means, show the entry below a headline when revealing a location.
512 Org-mode often shows locations in an org-mode file which might have
513 been invisible before. When this is set, the text below the headline that is
514 exposed is also shown.
516 By default this is off for all contexts.
517 Instead of t, this can also be an alist specifying this option for different
518 contexts. See `org-show-hierarchy-above' for valid contexts."
519 :group 'org-reveal-location
520 :type org-context-choice)
522 (defcustom org-indirect-buffer-display 'other-window
523 "How should indirect tree buffers be displayed?
524 This applies to indirect buffers created with the commands
525 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
526 Valid values are:
527 current-window Display in the current window
528 other-window Just display in another window.
529 dedicated-frame Create one new frame, and re-use it each time.
530 new-frame Make a new frame each time. Note that in this case
531 previously-made indirect buffers are kept, and you need to
532 kill these buffers yourself."
533 :group 'org-structure
534 :group 'org-agenda-windows
535 :type '(choice
536 (const :tag "In current window" current-window)
537 (const :tag "In current frame, other window" other-window)
538 (const :tag "Each time a new frame" new-frame)
539 (const :tag "One dedicated frame" dedicated-frame)))
541 (defgroup org-cycle nil
542 "Options concerning visibility cycling in Org-mode."
543 :tag "Org Cycle"
544 :group 'org-structure)
546 (defcustom org-drawers '("PROPERTIES" "CLOCK")
547 "Names of drawers. Drawers are not opened by cycling on the headline above.
548 Drawers only open with a TAB on the drawer line itself. A drawer looks like
549 this:
550 :DRAWERNAME:
551 .....
552 :END:
553 The drawer \"PROPERTIES\" is special for capturing properties through
554 the property API.
556 Drawers can be defined on the per-file basis with a line like:
558 #+DRAWERS: HIDDEN STATE PROPERTIES"
559 :group 'org-structure
560 :type '(repeat (string :tag "Drawer Name")))
562 (defcustom org-cycle-global-at-bob nil
563 "Cycle globally if cursor is at beginning of buffer and not at a headline.
564 This makes it possible to do global cycling without having to use S-TAB or
565 C-u TAB. For this special case to work, the first line of the buffer
566 must not be a headline - it may be empty ot some other text. When used in
567 this way, `org-cycle-hook' is disables temporarily, to make sure the
568 cursor stays at the beginning of the buffer.
569 When this option is nil, don't do anything special at the beginning
570 of the buffer."
571 :group 'org-cycle
572 :type 'boolean)
574 (defcustom org-cycle-emulate-tab t
575 "Where should `org-cycle' emulate TAB.
576 nil Never
577 white Only in completely white lines
578 whitestart Only at the beginning of lines, before the first non-white char
579 t Everywhere except in headlines
580 exc-hl-bol Everywhere except at the start of a headline
581 If TAB is used in a place where it does not emulate TAB, the current subtree
582 visibility is cycled."
583 :group 'org-cycle
584 :type '(choice (const :tag "Never" nil)
585 (const :tag "Only in completely white lines" white)
586 (const :tag "Before first char in a line" whitestart)
587 (const :tag "Everywhere except in headlines" t)
588 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
591 (defcustom org-cycle-separator-lines 2
592 "Number of empty lines needed to keep an empty line between collapsed trees.
593 If you leave an empty line between the end of a subtree and the following
594 headline, this empty line is hidden when the subtree is folded.
595 Org-mode will leave (exactly) one empty line visible if the number of
596 empty lines is equal or larger to the number given in this variable.
597 So the default 2 means, at least 2 empty lines after the end of a subtree
598 are needed to produce free space between a collapsed subtree and the
599 following headline.
601 Special case: when 0, never leave empty lines in collapsed view."
602 :group 'org-cycle
603 :type 'integer)
604 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
606 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
607 org-cycle-hide-drawers
608 org-cycle-show-empty-lines
609 org-optimize-window-after-visibility-change)
610 "Hook that is run after `org-cycle' has changed the buffer visibility.
611 The function(s) in this hook must accept a single argument which indicates
612 the new state that was set by the most recent `org-cycle' command. The
613 argument is a symbol. After a global state change, it can have the values
614 `overview', `content', or `all'. After a local state change, it can have
615 the values `folded', `children', or `subtree'."
616 :group 'org-cycle
617 :type 'hook)
619 (defgroup org-edit-structure nil
620 "Options concerning structure editing in Org-mode."
621 :tag "Org Edit Structure"
622 :group 'org-structure)
624 (defcustom org-odd-levels-only nil
625 "Non-nil means, skip even levels and only use odd levels for the outline.
626 This has the effect that two stars are being added/taken away in
627 promotion/demotion commands. It also influences how levels are
628 handled by the exporters.
629 Changing it requires restart of `font-lock-mode' to become effective
630 for fontification also in regions already fontified.
631 You may also set this on a per-file basis by adding one of the following
632 lines to the buffer:
634 #+STARTUP: odd
635 #+STARTUP: oddeven"
636 :group 'org-edit-structure
637 :group 'org-font-lock
638 :type 'boolean)
640 (defcustom org-adapt-indentation t
641 "Non-nil means, adapt indentation when promoting and demoting.
642 When this is set and the *entire* text in an entry is indented, the
643 indentation is increased by one space in a demotion command, and
644 decreased by one in a promotion command. If any line in the entry
645 body starts at column 0, indentation is not changed at all."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defcustom org-special-ctrl-a/e nil
650 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
651 When t, `C-a' will bring back the cursor to the beginning of the
652 headline text, i.e. after the stars and after a possible TODO keyword.
653 In an item, this will be the position after the bullet.
654 When the cursor is already at that position, another `C-a' will bring
655 it to the beginning of the line.
656 `C-e' will jump to the end of the headline, ignoring the presence of tags
657 in the headline. A second `C-e' will then jump to the true end of the
658 line, after any tags.
659 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
660 and only a directly following, identical keypress will bring the cursor
661 to the special positions."
662 :group 'org-edit-structure
663 :type '(choice
664 (const :tag "off" nil)
665 (const :tag "after bullet first" t)
666 (const :tag "border first" reversed)))
668 (if (fboundp 'defvaralias)
669 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
671 (defcustom org-special-ctrl-k nil
672 "Non-nil means `C-k' will behave specially in headlines.
673 When nil, `C-k' will call the default `kill-line' command.
674 When t, the following will happen while the cursor is in the headline:
676 - When the cursor is at the beginning of a headline, kill the entire
677 line and possible the folded subtree below the line.
678 - When in the middle of the headline text, kill the headline up to the tags.
679 - When after the headline text, kill the tags."
680 :group 'org-edit-structure
681 :type 'boolean)
683 (defcustom org-yank-folded-subtrees t
684 "Non-nil means, when yanking subtrees, fold them.
685 If the kill is a single subtree, or a sequence of subtrees, i.e. if
686 it starts with a heading and all other headings in it are either children
687 or siblings, then fold all the subtrees. However, do this only if no
688 text after the yank would be swallowed into a folded tree by this action."
689 :group 'org-edit-structure
690 :type 'boolean)
692 (defcustom org-yank-adjusted-subtrees t
693 "Non-nil means, when yanking subtrees, adjust the level.
694 With this setting, `org-paste-subtree' is used to insert the subtree, see
695 this function for details."
696 :group 'org-edit-structure
697 :type 'boolean)
699 (defcustom org-M-RET-may-split-line '((default . t))
700 "Non-nil means, M-RET will split the line at the cursor position.
701 When nil, it will go to the end of the line before making a
702 new line.
703 You may also set this option in a different way for different
704 contexts. Valid contexts are:
706 headline when creating a new headline
707 item when creating a new item
708 table in a table field
709 default the value to be used for all contexts not explicitly
710 customized"
711 :group 'org-structure
712 :group 'org-table
713 :type '(choice
714 (const :tag "Always" t)
715 (const :tag "Never" nil)
716 (repeat :greedy t :tag "Individual contexts"
717 (cons
718 (choice :tag "Context"
719 (const headline)
720 (const item)
721 (const table)
722 (const default))
723 (boolean)))))
726 (defcustom org-insert-heading-respect-content nil
727 "Non-nil means, insert new headings after the current subtree.
728 When nil, the new heading is created directly after the current line.
729 The commands \\[org-insert-heading-respect-content] and
730 \\[org-insert-todo-heading-respect-content] turn this variable on
731 for the duration of the command."
732 :group 'org-structure
733 :type 'boolean)
735 (defcustom org-blank-before-new-entry '((heading . auto)
736 (plain-list-item . auto))
737 "Should `org-insert-heading' leave a blank line before new heading/item?
738 The value is an alist, with `heading' and `plain-list-item' as car,
739 and a boolean flag as cdr."
740 :group 'org-edit-structure
741 :type '(list
742 (cons (const heading)
743 (choice (const :tag "Never" nil)
744 (const :tag "Always" t)
745 (const :tag "Auto" auto)))
746 (cons (const plain-list-item)
747 (choice (const :tag "Never" nil)
748 (const :tag "Always" t)
749 (const :tag "Auto" auto)))))
751 (defcustom org-insert-heading-hook nil
752 "Hook being run after inserting a new heading."
753 :group 'org-edit-structure
754 :type 'hook)
756 (defcustom org-enable-fixed-width-editor t
757 "Non-nil means, lines starting with \":\" are treated as fixed-width.
758 This currently only means, they are never auto-wrapped.
759 When nil, such lines will be treated like ordinary lines.
760 See also the QUOTE keyword."
761 :group 'org-edit-structure
762 :type 'boolean)
764 (defcustom org-edit-src-region-extra nil
765 "Additional regexps to identify regions for editing with `org-edit-src-code'.
766 For examples see the function `org-edit-src-find-region-and-lang'.
767 The regular expression identifying the begin marker should end with a newline,
768 and the regexp marking the end line should start with a newline, to make sure
769 there are kept outside the narrowed region."
770 :group 'org-edit-structure
771 :type '(repeat
772 (list
773 (regexp :tag "begin regexp")
774 (regexp :tag "end regexp")
775 (choice :tag "language"
776 (string :tag "specify")
777 (integer :tag "from match group")
778 (const :tag "from `lang' element")
779 (const :tag "from `style' element")))))
781 (defcustom org-coderef-label-format "(ref:%s)"
782 "The default coderef format.
783 This format string will be used to search for coderef labels in literal
784 examples (EXAMPLE and SRC blocks). The format can be overwritten
785 an individual literal example with the -f option, like
787 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
789 #+END_SRC
791 If you want to use this for HTML export, make sure that the format does
792 not introduce special font-locking, and avoid the HTML special
793 characters `<', `>', and `&'. The reason for this restriction is that
794 the labels are searched for only after htmlize has done its job."
795 :group 'org-edit-structure ; FIXME this is not in the right group
796 :type 'string)
798 (defcustom org-edit-fixed-width-region-mode 'artist-mode
799 "The mode that should be used to edit fixed-width regions.
800 These are the regions where each line starts with a colon."
801 :group 'org-edit-structure
802 :type '(choice
803 (const artist-mode)
804 (const picture-mode)
805 (const fundamental-mode)
806 (function :tag "Other (specify)")))
808 (defcustom org-goto-auto-isearch t
809 "Non-nil means, typing characters in org-goto starts incremental search."
810 :group 'org-edit-structure
811 :type 'boolean)
813 (defgroup org-sparse-trees nil
814 "Options concerning sparse trees in Org-mode."
815 :tag "Org Sparse Trees"
816 :group 'org-structure)
818 (defcustom org-highlight-sparse-tree-matches t
819 "Non-nil means, highlight all matches that define a sparse tree.
820 The highlights will automatically disappear the next time the buffer is
821 changed by an edit command."
822 :group 'org-sparse-trees
823 :type 'boolean)
825 (defcustom org-remove-highlights-with-change t
826 "Non-nil means, any change to the buffer will remove temporary highlights.
827 Such highlights are created by `org-occur' and `org-clock-display'.
828 When nil, `C-c C-c needs to be used to get rid of the highlights.
829 The highlights created by `org-preview-latex-fragment' always need
830 `C-c C-c' to be removed."
831 :group 'org-sparse-trees
832 :group 'org-time
833 :type 'boolean)
836 (defcustom org-occur-hook '(org-first-headline-recenter)
837 "Hook that is run after `org-occur' has constructed a sparse tree.
838 This can be used to recenter the window to show as much of the structure
839 as possible."
840 :group 'org-sparse-trees
841 :type 'hook)
843 (defgroup org-imenu-and-speedbar nil
844 "Options concerning imenu and speedbar in Org-mode."
845 :tag "Org Imenu and Speedbar"
846 :group 'org-structure)
848 (defcustom org-imenu-depth 2
849 "The maximum level for Imenu access to Org-mode headlines.
850 This also applied for speedbar access."
851 :group 'org-imenu-and-speedbar
852 :type 'number)
854 (defgroup org-table nil
855 "Options concerning tables in Org-mode."
856 :tag "Org Table"
857 :group 'org)
859 (defcustom org-enable-table-editor 'optimized
860 "Non-nil means, lines starting with \"|\" are handled by the table editor.
861 When nil, such lines will be treated like ordinary lines.
863 When equal to the symbol `optimized', the table editor will be optimized to
864 do the following:
865 - Automatic overwrite mode in front of whitespace in table fields.
866 This makes the structure of the table stay in tact as long as the edited
867 field does not exceed the column width.
868 - Minimize the number of realigns. Normally, the table is aligned each time
869 TAB or RET are pressed to move to another field. With optimization this
870 happens only if changes to a field might have changed the column width.
871 Optimization requires replacing the functions `self-insert-command',
872 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
873 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
874 very good at guessing when a re-align will be necessary, but you can always
875 force one with \\[org-ctrl-c-ctrl-c].
877 If you would like to use the optimized version in Org-mode, but the
878 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
880 This variable can be used to turn on and off the table editor during a session,
881 but in order to toggle optimization, a restart is required.
883 See also the variable `org-table-auto-blank-field'."
884 :group 'org-table
885 :type '(choice
886 (const :tag "off" nil)
887 (const :tag "on" t)
888 (const :tag "on, optimized" optimized)))
890 (defcustom org-table-tab-recognizes-table.el t
891 "Non-nil means, TAB will automatically notice a table.el table.
892 When it sees such a table, it moves point into it and - if necessary -
893 calls `table-recognize-table'."
894 :group 'org-table-editing
895 :type 'boolean)
897 (defgroup org-link nil
898 "Options concerning links in Org-mode."
899 :tag "Org Link"
900 :group 'org)
902 (defvar org-link-abbrev-alist-local nil
903 "Buffer-local version of `org-link-abbrev-alist', which see.
904 The value of this is taken from the #+LINK lines.")
905 (make-variable-buffer-local 'org-link-abbrev-alist-local)
907 (defcustom org-link-abbrev-alist nil
908 "Alist of link abbreviations.
909 The car of each element is a string, to be replaced at the start of a link.
910 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
911 links in Org-mode buffers can have an optional tag after a double colon, e.g.
913 [[linkkey:tag][description]]
915 If REPLACE is a string, the tag will simply be appended to create the link.
916 If the string contains \"%s\", the tag will be inserted there. Alternatively,
917 the placeholder \"%h\" will cause a url-encoded version of the tag to
918 be inserted at that point (see the function `url-hexify-string').
920 REPLACE may also be a function that will be called with the tag as the
921 only argument to create the link, which should be returned as a string.
923 See the manual for examples."
924 :group 'org-link
925 :type '(repeat
926 (cons
927 (string :tag "Protocol")
928 (choice
929 (string :tag "Format")
930 (function)))))
932 (defcustom org-descriptive-links t
933 "Non-nil means, hide link part and only show description of bracket links.
934 Bracket links are like [[link][description]]. This variable sets the initial
935 state in new org-mode buffers. The setting can then be toggled on a
936 per-buffer basis from the Org->Hyperlinks menu."
937 :group 'org-link
938 :type 'boolean)
940 (defcustom org-link-file-path-type 'adaptive
941 "How the path name in file links should be stored.
942 Valid values are:
944 relative Relative to the current directory, i.e. the directory of the file
945 into which the link is being inserted.
946 absolute Absolute path, if possible with ~ for home directory.
947 noabbrev Absolute path, no abbreviation of home directory.
948 adaptive Use relative path for files in the current directory and sub-
949 directories of it. For other files, use an absolute path."
950 :group 'org-link
951 :type '(choice
952 (const relative)
953 (const absolute)
954 (const noabbrev)
955 (const adaptive)))
957 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
958 "Types of links that should be activated in Org-mode files.
959 This is a list of symbols, each leading to the activation of a certain link
960 type. In principle, it does not hurt to turn on most link types - there may
961 be a small gain when turning off unused link types. The types are:
963 bracket The recommended [[link][description]] or [[link]] links with hiding.
964 angular Links in angular brackets that may contain whitespace like
965 <bbdb:Carsten Dominik>.
966 plain Plain links in normal text, no whitespace, like http://google.com.
967 radio Text that is matched by a radio target, see manual for details.
968 tag Tag settings in a headline (link to tag search).
969 date Time stamps (link to calendar).
970 footnote Footnote labels.
972 Changing this variable requires a restart of Emacs to become effective."
973 :group 'org-link
974 :type '(set :greedy t
975 (const :tag "Double bracket links (new style)" bracket)
976 (const :tag "Angular bracket links (old style)" angular)
977 (const :tag "Plain text links" plain)
978 (const :tag "Radio target matches" radio)
979 (const :tag "Tags" tag)
980 (const :tag "Timestamps" date)
981 (const :tag "Footnotes" footnote)))
983 (defcustom org-make-link-description-function nil
984 "Function to use to generate link descriptions from links. If
985 nil the link location will be used. This function must take two
986 parameters; the first is the link and the second the description
987 org-insert-link has generated, and should return the description
988 to use."
989 :group 'org-link
990 :type 'function)
992 (defgroup org-link-store nil
993 "Options concerning storing links in Org-mode."
994 :tag "Org Store Link"
995 :group 'org-link)
997 (defcustom org-email-link-description-format "Email %c: %.30s"
998 "Format of the description part of a link to an email or usenet message.
999 The following %-escapes will be replaced by corresponding information:
1001 %F full \"From\" field
1002 %f name, taken from \"From\" field, address if no name
1003 %T full \"To\" field
1004 %t first name in \"To\" field, address if no name
1005 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1006 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1007 %s subject
1008 %m message-id.
1010 You may use normal field width specification between the % and the letter.
1011 This is for example useful to limit the length of the subject.
1013 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1014 :group 'org-link-store
1015 :type 'string)
1017 (defcustom org-from-is-user-regexp
1018 (let (r1 r2)
1019 (when (and user-mail-address (not (string= user-mail-address "")))
1020 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1021 (when (and user-full-name (not (string= user-full-name "")))
1022 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1023 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1024 "Regexp matched against the \"From:\" header of an email or usenet message.
1025 It should match if the message is from the user him/herself."
1026 :group 'org-link-store
1027 :type 'regexp)
1029 (defcustom org-link-to-org-use-id 'create-if-interactive
1030 "Non-nil means, storing a link to an Org file will use entry IDs.
1032 Note that before this variable is even considered, org-id must be loaded,
1033 to please customize `org-modules' and turn it on.
1035 The variable can have the following values:
1037 t Create an ID if needed to make a link to the current entry.
1039 create-if-interactive
1040 If `org-store-link' is called directly (interactively, as a user
1041 command), do create an ID to support the link. But when doing the
1042 job for remember, only use the ID if it already exists. The
1043 purpose of this setting is to avoid proliferation of unwanted
1044 IDs, just because you happen to be in an Org file when you
1045 call `org-remember' that automatically and preemptively
1046 creates a link. If you do want to get an ID link in a remember
1047 template to an entry not having an ID, create it first by
1048 explicitly creating a link to it, using `C-c C-l' first.
1050 use-existing
1051 Use existing ID, do not create one.
1053 nil Never use an ID to make a link, instead link using a text search for
1054 the headline text."
1055 :group 'org-link-store
1056 :type '(choice
1057 (const :tag "Create ID to make link" t)
1058 (const :tag "Create if string link interactively"
1059 'create-if-interactive)
1060 (const :tag "Only use existing" 'use-existing)
1061 (const :tag "Do not use ID to create link" nil)))
1063 (defcustom org-context-in-file-links t
1064 "Non-nil means, file links from `org-store-link' contain context.
1065 A search string will be added to the file name with :: as separator and
1066 used to find the context when the link is activated by the command
1067 `org-open-at-point'.
1068 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1069 negates this setting for the duration of the command."
1070 :group 'org-link-store
1071 :type 'boolean)
1073 (defcustom org-keep-stored-link-after-insertion nil
1074 "Non-nil means, keep link in list for entire session.
1076 The command `org-store-link' adds a link pointing to the current
1077 location to an internal list. These links accumulate during a session.
1078 The command `org-insert-link' can be used to insert links into any
1079 Org-mode file (offering completion for all stored links). When this
1080 option is nil, every link which has been inserted once using \\[org-insert-link]
1081 will be removed from the list, to make completing the unused links
1082 more efficient."
1083 :group 'org-link-store
1084 :type 'boolean)
1086 (defgroup org-link-follow nil
1087 "Options concerning following links in Org-mode."
1088 :tag "Org Follow Link"
1089 :group 'org-link)
1091 (defcustom org-link-translation-function nil
1092 "Function to translate links with different syntax to Org syntax.
1093 This can be used to translate links created for example by the Planner
1094 or emacs-wiki packages to Org syntax.
1095 The function must accept two parameters, a TYPE containing the link
1096 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1097 which is everything after the link protocol. It should return a cons
1098 with possibly modified values of type and path.
1099 Org contains a function for this, so if you set this variable to
1100 `org-translate-link-from-planner', you should be able follow many
1101 links created by planner."
1102 :group 'org-link-follow
1103 :type 'function)
1105 (defcustom org-follow-link-hook nil
1106 "Hook that is run after a link has been followed."
1107 :group 'org-link-follow
1108 :type 'hook)
1110 (defcustom org-tab-follows-link nil
1111 "Non-nil means, on links TAB will follow the link.
1112 Needs to be set before org.el is loaded."
1113 :group 'org-link-follow
1114 :type 'boolean)
1116 (defcustom org-return-follows-link nil
1117 "Non-nil means, on links RET will follow the link.
1118 Needs to be set before org.el is loaded."
1119 :group 'org-link-follow
1120 :type 'boolean)
1122 (defcustom org-mouse-1-follows-link
1123 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1124 "Non-nil means, mouse-1 on a link will follow the link.
1125 A longer mouse click will still set point. Does not work on XEmacs.
1126 Needs to be set before org.el is loaded."
1127 :group 'org-link-follow
1128 :type 'boolean)
1130 (defcustom org-mark-ring-length 4
1131 "Number of different positions to be recorded in the ring
1132 Changing this requires a restart of Emacs to work correctly."
1133 :group 'org-link-follow
1134 :type 'integer)
1136 (defcustom org-link-frame-setup
1137 '((vm . vm-visit-folder-other-frame)
1138 (gnus . gnus-other-frame)
1139 (file . find-file-other-window))
1140 "Setup the frame configuration for following links.
1141 When following a link with Emacs, it may often be useful to display
1142 this link in another window or frame. This variable can be used to
1143 set this up for the different types of links.
1144 For VM, use any of
1145 `vm-visit-folder'
1146 `vm-visit-folder-other-frame'
1147 For Gnus, use any of
1148 `gnus'
1149 `gnus-other-frame'
1150 `org-gnus-no-new-news'
1151 For FILE, use any of
1152 `find-file'
1153 `find-file-other-window'
1154 `find-file-other-frame'
1155 For the calendar, use the variable `calendar-setup'.
1156 For BBDB, it is currently only possible to display the matches in
1157 another window."
1158 :group 'org-link-follow
1159 :type '(list
1160 (cons (const vm)
1161 (choice
1162 (const vm-visit-folder)
1163 (const vm-visit-folder-other-window)
1164 (const vm-visit-folder-other-frame)))
1165 (cons (const gnus)
1166 (choice
1167 (const gnus)
1168 (const gnus-other-frame)
1169 (const org-gnus-no-new-news)))
1170 (cons (const file)
1171 (choice
1172 (const find-file)
1173 (const find-file-other-window)
1174 (const find-file-other-frame)))))
1176 (defcustom org-display-internal-link-with-indirect-buffer nil
1177 "Non-nil means, use indirect buffer to display infile links.
1178 Activating internal links (from one location in a file to another location
1179 in the same file) normally just jumps to the location. When the link is
1180 activated with a C-u prefix (or with mouse-3), the link is displayed in
1181 another window. When this option is set, the other window actually displays
1182 an indirect buffer clone of the current buffer, to avoid any visibility
1183 changes to the current buffer."
1184 :group 'org-link-follow
1185 :type 'boolean)
1187 (defcustom org-open-non-existing-files nil
1188 "Non-nil means, `org-open-file' will open non-existing files.
1189 When nil, an error will be generated."
1190 :group 'org-link-follow
1191 :type 'boolean)
1193 (defcustom org-open-directory-means-index-dot-org nil
1194 "Non-nil means, a link to a directory really means to index.org.
1195 When nil, following a directory link will run dired or open a finder/explorer
1196 window on that directory."
1197 :group 'org-link-follow
1198 :type 'boolean)
1200 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1201 "Function and arguments to call for following mailto links.
1202 This is a list with the first element being a lisp function, and the
1203 remaining elements being arguments to the function. In string arguments,
1204 %a will be replaced by the address, and %s will be replaced by the subject
1205 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1206 :group 'org-link-follow
1207 :type '(choice
1208 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1209 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1210 (const :tag "message-mail" (message-mail "%a" "%s"))
1211 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1213 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1214 "Non-nil means, ask for confirmation before executing shell links.
1215 Shell links can be dangerous: just think about a link
1217 [[shell:rm -rf ~/*][Google Search]]
1219 This link would show up in your Org-mode document as \"Google Search\",
1220 but really it would remove your entire home directory.
1221 Therefore we advise against setting this variable to nil.
1222 Just change it to `y-or-n-p' of you want to confirm with a
1223 single keystroke rather than having to type \"yes\"."
1224 :group 'org-link-follow
1225 :type '(choice
1226 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1227 (const :tag "with y-or-n (faster)" y-or-n-p)
1228 (const :tag "no confirmation (dangerous)" nil)))
1230 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1231 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1232 Elisp links can be dangerous: just think about a link
1234 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1236 This link would show up in your Org-mode document as \"Google Search\",
1237 but really it would remove your entire home directory.
1238 Therefore we advise against setting this variable to nil.
1239 Just change it to `y-or-n-p' of you want to confirm with a
1240 single keystroke rather than having to type \"yes\"."
1241 :group 'org-link-follow
1242 :type '(choice
1243 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1244 (const :tag "with y-or-n (faster)" y-or-n-p)
1245 (const :tag "no confirmation (dangerous)" nil)))
1247 (defconst org-file-apps-defaults-gnu
1248 '((remote . emacs)
1249 (system . mailcap)
1250 (t . mailcap))
1251 "Default file applications on a UNIX or GNU/Linux system.
1252 See `org-file-apps'.")
1254 (defconst org-file-apps-defaults-macosx
1255 '((remote . emacs)
1256 (t . "open %s")
1257 (system . "open %s")
1258 ("ps.gz" . "gv %s")
1259 ("eps.gz" . "gv %s")
1260 ("dvi" . "xdvi %s")
1261 ("fig" . "xfig %s"))
1262 "Default file applications on a MacOS X system.
1263 The system \"open\" is known as a default, but we use X11 applications
1264 for some files for which the OS does not have a good default.
1265 See `org-file-apps'.")
1267 (defconst org-file-apps-defaults-windowsnt
1268 (list
1269 '(remote . emacs)
1270 (cons t
1271 (list (if (featurep 'xemacs)
1272 'mswindows-shell-execute
1273 'w32-shell-execute)
1274 "open" 'file))
1275 (cons 'system
1276 (list (if (featurep 'xemacs)
1277 'mswindows-shell-execute
1278 'w32-shell-execute)
1279 "open" 'file)))
1280 "Default file applications on a Windows NT system.
1281 The system \"open\" is used for most files.
1282 See `org-file-apps'.")
1284 (defcustom org-file-apps
1286 (auto-mode . emacs)
1287 ("\\.x?html?\\'" . default)
1288 ("\\.pdf\\'" . default)
1290 "External applications for opening `file:path' items in a document.
1291 Org-mode uses system defaults for different file types, but
1292 you can use this variable to set the application for a given file
1293 extension. The entries in this list are cons cells where the car identifies
1294 files and the cdr the corresponding command. Possible values for the
1295 file identifier are
1296 \"regex\" Regular expression matched against the file name. For backward
1297 compatibility, this can also be a string with only alphanumeric
1298 characters, which is then interpreted as an extension.
1299 `directory' Matches a directory
1300 `remote' Matches a remote file, accessible through tramp or efs.
1301 Remote files most likely should be visited through Emacs
1302 because external applications cannot handle such paths.
1303 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1304 so all files Emacs knows how to handle. Using this with
1305 command `emacs' will open most files in Emacs. Beware that this
1306 will also open html files inside Emacs, unless you add
1307 (\"html\" . default) to the list as well.
1308 t Default for files not matched by any of the other options.
1309 `system' The system command to open files, like `open' on Windows
1310 and Mac OS X, and mailcap under GNU/Linux. This is the command
1311 that will be selected if you call `C-c C-o' with a double
1312 `C-u C-u' prefix.
1314 Possible values for the command are:
1315 `emacs' The file will be visited by the current Emacs process.
1316 `default' Use the default application for this file type, which is the
1317 association for t in the list, most likely in the system-specific
1318 part.
1319 This can be used to overrule an unwanted setting in the
1320 system-specific variable.
1321 `system' Use the system command for opening files, like \"open\".
1322 This command is specified by the entry whose car is `system'.
1323 Most likely, the system-specific version of this variable
1324 does define this command, but you can overrule/replace it
1325 here.
1326 string A command to be executed by a shell; %s will be replaced
1327 by the path to the file.
1328 sexp A Lisp form which will be evaluated. The file path will
1329 be available in the Lisp variable `file'.
1330 For more examples, see the system specific constants
1331 `org-file-apps-defaults-macosx'
1332 `org-file-apps-defaults-windowsnt'
1333 `org-file-apps-defaults-gnu'."
1334 :group 'org-link-follow
1335 :type '(repeat
1336 (cons (choice :value ""
1337 (string :tag "Extension")
1338 (const :tag "System command to open files" system)
1339 (const :tag "Default for unrecognized files" t)
1340 (const :tag "Remote file" remote)
1341 (const :tag "Links to a directory" directory)
1342 (const :tag "Any files that have Emacs modes"
1343 auto-mode))
1344 (choice :value ""
1345 (const :tag "Visit with Emacs" emacs)
1346 (const :tag "Use default" default)
1347 (const :tag "Use the system command" system)
1348 (string :tag "Command")
1349 (sexp :tag "Lisp form")))))
1351 (defgroup org-refile nil
1352 "Options concerning refiling entries in Org-mode."
1353 :tag "Org Refile"
1354 :group 'org)
1356 (defcustom org-directory "~/org"
1357 "Directory with org files.
1358 This directory will be used as default to prompt for org files.
1359 Used by the hooks for remember.el."
1360 :group 'org-refile
1361 :group 'org-remember
1362 :type 'directory)
1364 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1365 "Default target for storing notes.
1366 Used by the hooks for remember.el. This can be a string, or nil to mean
1367 the value of `remember-data-file'.
1368 You can set this on a per-template basis with the variable
1369 `org-remember-templates'."
1370 :group 'org-refile
1371 :group 'org-remember
1372 :type '(choice
1373 (const :tag "Default from remember-data-file" nil)
1374 file))
1376 (defcustom org-goto-interface 'outline
1377 "The default interface to be used for `org-goto'.
1378 Allowed values are:
1379 outline The interface shows an outline of the relevant file
1380 and the correct heading is found by moving through
1381 the outline or by searching with incremental search.
1382 outline-path-completion Headlines in the current buffer are offered via
1383 completion. This is the interface also used by
1384 the refile command."
1385 :group 'org-refile
1386 :type '(choice
1387 (const :tag "Outline" outline)
1388 (const :tag "Outline-path-completion" outline-path-completion)))
1390 (defcustom org-goto-max-level 5
1391 "Maximum level to be considered when running org-goto with refile interface."
1392 :group 'org-refile
1393 :type 'number)
1395 (defcustom org-reverse-note-order nil
1396 "Non-nil means, store new notes at the beginning of a file or entry.
1397 When nil, new notes will be filed to the end of a file or entry.
1398 This can also be a list with cons cells of regular expressions that
1399 are matched against file names, and values."
1400 :group 'org-remember
1401 :group 'org-refile
1402 :type '(choice
1403 (const :tag "Reverse always" t)
1404 (const :tag "Reverse never" nil)
1405 (repeat :tag "By file name regexp"
1406 (cons regexp boolean))))
1408 (defcustom org-refile-targets nil
1409 "Targets for refiling entries with \\[org-refile].
1410 This is list of cons cells. Each cell contains:
1411 - a specification of the files to be considered, either a list of files,
1412 or a symbol whose function or variable value will be used to retrieve
1413 a file name or a list of file names. If you use `org-agenda-files' for
1414 that, all agenda files will be scanned for targets. Nil means, consider
1415 headings in the current buffer.
1416 - A specification of how to select find candidate refile targets. This
1417 may be any of
1418 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1419 This tag has to be present in all target headlines, inheritance will
1420 not be considered.
1421 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1422 todo keyword.
1423 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1424 headlines that are refiling targets.
1425 - a cons cell (:level . N). Any headline of level N is considered a target.
1426 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1428 When this variable is nil, all top-level headlines in the current buffer
1429 are used, equivalent to the value `((nil . (:level . 1))'."
1430 :group 'org-refile
1431 :type '(repeat
1432 (cons
1433 (choice :value org-agenda-files
1434 (const :tag "All agenda files" org-agenda-files)
1435 (const :tag "Current buffer" nil)
1436 (function) (variable) (file))
1437 (choice :tag "Identify target headline by"
1438 (cons :tag "Specific tag" (const :value :tag) (string))
1439 (cons :tag "TODO keyword" (const :value :todo) (string))
1440 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1441 (cons :tag "Level number" (const :value :level) (integer))
1442 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1444 (defcustom org-refile-use-outline-path nil
1445 "Non-nil means, provide refile targets as paths.
1446 So a level 3 headline will be available as level1/level2/level3.
1447 When the value is `file', also include the file name (without directory)
1448 into the path. When `full-file-path', include the full file path."
1449 :group 'org-refile
1450 :type '(choice
1451 (const :tag "Not" nil)
1452 (const :tag "Yes" t)
1453 (const :tag "Start with file name" file)
1454 (const :tag "Start with full file path" full-file-path)))
1456 (defcustom org-outline-path-complete-in-steps t
1457 "Non-nil means, complete the outline path in hierarchical steps.
1458 When Org-mode uses the refile interface to select an outline path
1459 \(see variable `org-refile-use-outline-path'), the completion of
1460 the path can be done is a single go, or if can be done in steps down
1461 the headline hierarchy. Going in steps is probably the best if you
1462 do not use a special completion package like `ido' or `icicles'.
1463 However, when using these packages, going in one step can be very
1464 fast, while still showing the whole path to the entry."
1465 :group 'org-refile
1466 :type 'boolean)
1468 (defgroup org-todo nil
1469 "Options concerning TODO items in Org-mode."
1470 :tag "Org TODO"
1471 :group 'org)
1473 (defgroup org-progress nil
1474 "Options concerning Progress logging in Org-mode."
1475 :tag "Org Progress"
1476 :group 'org-time)
1478 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1479 "List of TODO entry keyword sequences and their interpretation.
1480 \\<org-mode-map>This is a list of sequences.
1482 Each sequence starts with a symbol, either `sequence' or `type',
1483 indicating if the keywords should be interpreted as a sequence of
1484 action steps, or as different types of TODO items. The first
1485 keywords are states requiring action - these states will select a headline
1486 for inclusion into the global TODO list Org-mode produces. If one of
1487 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1488 signify that no further action is necessary. If \"|\" is not found,
1489 the last keyword is treated as the only DONE state of the sequence.
1491 The command \\[org-todo] cycles an entry through these states, and one
1492 additional state where no keyword is present. For details about this
1493 cycling, see the manual.
1495 TODO keywords and interpretation can also be set on a per-file basis with
1496 the special #+SEQ_TODO and #+TYP_TODO lines.
1498 Each keyword can optionally specify a character for fast state selection
1499 \(in combination with the variable `org-use-fast-todo-selection')
1500 and specifiers for state change logging, using the same syntax
1501 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1502 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1503 indicates to record a time stamp each time this state is selected.
1505 Each keyword may also specify if a timestamp or a note should be
1506 recorded when entering or leaving the state, by adding additional
1507 characters in the parenthesis after the keyword. This looks like this:
1508 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1509 record only the time of the state change. With X and Y being either
1510 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1511 Y when leaving the state if and only if the *target* state does not
1512 define X. You may omit any of the fast-selection key or X or /Y,
1513 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1515 For backward compatibility, this variable may also be just a list
1516 of keywords - in this case the interpretation (sequence or type) will be
1517 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1518 :group 'org-todo
1519 :group 'org-keywords
1520 :type '(choice
1521 (repeat :tag "Old syntax, just keywords"
1522 (string :tag "Keyword"))
1523 (repeat :tag "New syntax"
1524 (cons
1525 (choice
1526 :tag "Interpretation"
1527 (const :tag "Sequence (cycling hits every state)" sequence)
1528 (const :tag "Type (cycling directly to DONE)" type))
1529 (repeat
1530 (string :tag "Keyword"))))))
1532 (defvar org-todo-keywords-1 nil
1533 "All TODO and DONE keywords active in a buffer.")
1534 (make-variable-buffer-local 'org-todo-keywords-1)
1535 (defvar org-todo-keywords-for-agenda nil)
1536 (defvar org-done-keywords-for-agenda nil)
1537 (defvar org-todo-keyword-alist-for-agenda nil)
1538 (defvar org-tag-alist-for-agenda nil)
1539 (defvar org-agenda-contributing-files nil)
1540 (defvar org-not-done-keywords nil)
1541 (make-variable-buffer-local 'org-not-done-keywords)
1542 (defvar org-done-keywords nil)
1543 (make-variable-buffer-local 'org-done-keywords)
1544 (defvar org-todo-heads nil)
1545 (make-variable-buffer-local 'org-todo-heads)
1546 (defvar org-todo-sets nil)
1547 (make-variable-buffer-local 'org-todo-sets)
1548 (defvar org-todo-log-states nil)
1549 (make-variable-buffer-local 'org-todo-log-states)
1550 (defvar org-todo-kwd-alist nil)
1551 (make-variable-buffer-local 'org-todo-kwd-alist)
1552 (defvar org-todo-key-alist nil)
1553 (make-variable-buffer-local 'org-todo-key-alist)
1554 (defvar org-todo-key-trigger nil)
1555 (make-variable-buffer-local 'org-todo-key-trigger)
1557 (defcustom org-todo-interpretation 'sequence
1558 "Controls how TODO keywords are interpreted.
1559 This variable is in principle obsolete and is only used for
1560 backward compatibility, if the interpretation of todo keywords is
1561 not given already in `org-todo-keywords'. See that variable for
1562 more information."
1563 :group 'org-todo
1564 :group 'org-keywords
1565 :type '(choice (const sequence)
1566 (const type)))
1568 (defcustom org-use-fast-todo-selection 'prefix
1569 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1570 This variable describes if and under what circumstances the cycling
1571 mechanism for TODO keywords will be replaced by a single-key, direct
1572 selection scheme.
1574 When nil, fast selection is never used.
1576 When the symbol `prefix', it will be used when `org-todo' is called with
1577 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1578 in an agenda buffer.
1580 When t, fast selection is used by default. In this case, the prefix
1581 argument forces cycling instead.
1583 In all cases, the special interface is only used if access keys have actually
1584 been assigned by the user, i.e. if keywords in the configuration are followed
1585 by a letter in parenthesis, like TODO(t)."
1586 :group 'org-todo
1587 :type '(choice
1588 (const :tag "Never" nil)
1589 (const :tag "By default" t)
1590 (const :tag "Only with C-u C-c C-t" prefix)))
1592 (defcustom org-provide-todo-statistics t
1593 "Non-nil means, update todo statistics after insert and toggle.
1594 When this is set, todo statistics is updated in the parent of the current
1595 entry each time a todo state is changed."
1596 :group 'org-todo
1597 :type 'boolean)
1599 (defcustom org-after-todo-state-change-hook nil
1600 "Hook which is run after the state of a TODO item was changed.
1601 The new state (a string with a TODO keyword, or nil) is available in the
1602 Lisp variable `state'."
1603 :group 'org-todo
1604 :type 'hook)
1606 (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 You need to set this variable through the customize interface, or to
1640 restart emacs after changing the value."
1641 :set (lambda (var val)
1642 (set var val)
1643 (if val
1644 (add-hook 'org-blocker-hook 'org-block-todo-from-children-or-siblings)
1645 (remove-hook 'org-blocker-hook 'org-block-todo-from-children-or-siblings)))
1646 :group 'org-todo
1647 :type 'boolean)
1649 (defcustom org-todo-state-tags-triggers nil
1650 "Tag changes that should be triggered by TODO state changes.
1651 This is a list. Each entry is
1653 (state-change (tag . flag) .......)
1655 State-change can be a string with a state, and empty string to indicate the
1656 state that has no TODO keyword, or it can be one of the symbols `todo'
1657 or `done', meaning any not-done or done state, respectively."
1658 :group 'org-todo
1659 :group 'org-tags
1660 :type '(repeat
1661 (cons (choice :tag "When changing to"
1662 (const :tag "Not-done state" todo)
1663 (const :tag "Done state" done)
1664 (string :tag "State"))
1665 (repeat
1666 (cons :tag "Tag action"
1667 (string :tag "Tag")
1668 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1670 (defcustom org-log-done nil
1671 "Information to record when a task moves to the DONE state.
1673 Possible values are:
1675 nil Don't add anything, just change the keyword
1676 time Add a time stamp to the task
1677 note Prompt a closing note and add it with template `org-log-note-headings'
1679 This option can also be set with on a per-file-basis with
1681 #+STARTUP: nologdone
1682 #+STARTUP: logdone
1683 #+STARTUP: lognotedone
1685 You can have local logging settings for a subtree by setting the LOGGING
1686 property to one or more of these keywords."
1687 :group 'org-todo
1688 :group 'org-progress
1689 :type '(choice
1690 (const :tag "No logging" nil)
1691 (const :tag "Record CLOSED timestamp" time)
1692 (const :tag "Record CLOSED timestamp with closing note." note)))
1694 ;; Normalize old uses of org-log-done.
1695 (cond
1696 ((eq org-log-done t) (setq org-log-done 'time))
1697 ((and (listp org-log-done) (memq 'done org-log-done))
1698 (setq org-log-done 'note)))
1700 (defcustom org-log-note-clock-out nil
1701 "Non-nil means, record a note when clocking out of an item.
1702 This can also be configured on a per-file basis by adding one of
1703 the following lines anywhere in the buffer:
1705 #+STARTUP: lognoteclock-out
1706 #+STARTUP: nolognoteclock-out"
1707 :group 'org-todo
1708 :group 'org-progress
1709 :type 'boolean)
1711 (defcustom org-log-done-with-time t
1712 "Non-nil means, the CLOSED time stamp will contain date and time.
1713 When nil, only the date will be recorded."
1714 :group 'org-progress
1715 :type 'boolean)
1717 (defcustom org-log-note-headings
1718 '((done . "CLOSING NOTE %t")
1719 (state . "State %-12s %t")
1720 (note . "Note taken on %t")
1721 (clock-out . ""))
1722 "Headings for notes added to entries.
1723 The value is an alist, with the car being a symbol indicating the note
1724 context, and the cdr is the heading to be used. The heading may also be the
1725 empty string.
1726 %t in the heading will be replaced by a time stamp.
1727 %s will be replaced by the new TODO state, in double quotes.
1728 %u will be replaced by the user name.
1729 %U will be replaced by the full user name."
1730 :group 'org-todo
1731 :group 'org-progress
1732 :type '(list :greedy t
1733 (cons (const :tag "Heading when closing an item" done) string)
1734 (cons (const :tag
1735 "Heading when changing todo state (todo sequence only)"
1736 state) string)
1737 (cons (const :tag "Heading when just taking a note" note) string)
1738 (cons (const :tag "Heading when clocking out" clock-out) string)))
1740 (unless (assq 'note org-log-note-headings)
1741 (push '(note . "%t") org-log-note-headings))
1743 (defcustom org-log-state-notes-insert-after-drawers nil
1744 "Non-nil means, insert state change notes after any drawers in entry.
1745 Only the drawers that *immediately* follow the headline and the
1746 deadline/scheduled line are skipped.
1747 When nil, insert notes right after the heading and perhaps the line
1748 with deadline/scheduling if present."
1749 :group 'org-todo
1750 :group 'org-progress
1751 :type 'boolean)
1753 (defcustom org-log-states-order-reversed t
1754 "Non-nil means, the latest state change note will be directly after heading.
1755 When nil, the notes will be orderer according to time."
1756 :group 'org-todo
1757 :group 'org-progress
1758 :type 'boolean)
1760 (defcustom org-log-repeat 'time
1761 "Non-nil means, record moving through the DONE state when triggering repeat.
1762 An auto-repeating tasks is immediately switched back to TODO when marked
1763 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1764 the TODO keyword definition, or recording a closing note by setting
1765 `org-log-done', there will be no record of the task moving through DONE.
1766 This variable forces taking a note anyway. Possible values are:
1768 nil Don't force a record
1769 time Record a time stamp
1770 note Record a note
1772 This option can also be set with on a per-file-basis with
1774 #+STARTUP: logrepeat
1775 #+STARTUP: lognoterepeat
1776 #+STARTUP: nologrepeat
1778 You can have local logging settings for a subtree by setting the LOGGING
1779 property to one or more of these keywords."
1780 :group 'org-todo
1781 :group 'org-progress
1782 :type '(choice
1783 (const :tag "Don't force a record" nil)
1784 (const :tag "Force recording the DONE state" time)
1785 (const :tag "Force recording a note with the DONE state" note)))
1788 (defgroup org-priorities nil
1789 "Priorities in Org-mode."
1790 :tag "Org Priorities"
1791 :group 'org-todo)
1793 (defcustom org-highest-priority ?A
1794 "The highest priority of TODO items. A character like ?A, ?B etc.
1795 Must have a smaller ASCII number than `org-lowest-priority'."
1796 :group 'org-priorities
1797 :type 'character)
1799 (defcustom org-lowest-priority ?C
1800 "The lowest priority of TODO items. A character like ?A, ?B etc.
1801 Must have a larger ASCII number than `org-highest-priority'."
1802 :group 'org-priorities
1803 :type 'character)
1805 (defcustom org-default-priority ?B
1806 "The default priority of TODO items.
1807 This is the priority an item get if no explicit priority is given."
1808 :group 'org-priorities
1809 :type 'character)
1811 (defcustom org-priority-start-cycle-with-default t
1812 "Non-nil means, start with default priority when starting to cycle.
1813 When this is nil, the first step in the cycle will be (depending on the
1814 command used) one higher or lower that the default priority."
1815 :group 'org-priorities
1816 :type 'boolean)
1818 (defgroup org-time nil
1819 "Options concerning time stamps and deadlines in Org-mode."
1820 :tag "Org Time"
1821 :group 'org)
1823 (defcustom org-insert-labeled-timestamps-at-point nil
1824 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1825 When nil, these labeled time stamps are forces into the second line of an
1826 entry, just after the headline. When scheduling from the global TODO list,
1827 the time stamp will always be forced into the second line."
1828 :group 'org-time
1829 :type 'boolean)
1831 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1832 "Formats for `format-time-string' which are used for time stamps.
1833 It is not recommended to change this constant.")
1835 (defcustom org-time-stamp-rounding-minutes '(0 5)
1836 "Number of minutes to round time stamps to.
1837 These are two values, the first applies when first creating a time stamp.
1838 The second applies when changing it with the commands `S-up' and `S-down'.
1839 When changing the time stamp, this means that it will change in steps
1840 of N minutes, as given by the second value.
1842 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1843 numbers should be factors of 60, so for example 5, 10, 15.
1845 When this is larger than 1, you can still force an exact time-stamp by using
1846 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1847 and by using a prefix arg to `S-up/down' to specify the exact number
1848 of minutes to shift."
1849 :group 'org-time
1850 :get '(lambda (var) ; Make sure all entries have 5 elements
1851 (if (integerp (default-value var))
1852 (list (default-value var) 5)
1853 (default-value var)))
1854 :type '(list
1855 (integer :tag "when inserting times")
1856 (integer :tag "when modifying times")))
1858 ;; Normalize old customizations of this variable.
1859 (when (integerp org-time-stamp-rounding-minutes)
1860 (setq org-time-stamp-rounding-minutes
1861 (list org-time-stamp-rounding-minutes
1862 org-time-stamp-rounding-minutes)))
1864 (defcustom org-display-custom-times nil
1865 "Non-nil means, overlay custom formats over all time stamps.
1866 The formats are defined through the variable `org-time-stamp-custom-formats'.
1867 To turn this on on a per-file basis, insert anywhere in the file:
1868 #+STARTUP: customtime"
1869 :group 'org-time
1870 :set 'set-default
1871 :type 'sexp)
1872 (make-variable-buffer-local 'org-display-custom-times)
1874 (defcustom org-time-stamp-custom-formats
1875 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1876 "Custom formats for time stamps. See `format-time-string' for the syntax.
1877 These are overlayed over the default ISO format if the variable
1878 `org-display-custom-times' is set. Time like %H:%M should be at the
1879 end of the second format."
1880 :group 'org-time
1881 :type 'sexp)
1883 (defun org-time-stamp-format (&optional long inactive)
1884 "Get the right format for a time string."
1885 (let ((f (if long (cdr org-time-stamp-formats)
1886 (car org-time-stamp-formats))))
1887 (if inactive
1888 (concat "[" (substring f 1 -1) "]")
1889 f)))
1891 (defcustom org-time-clocksum-format "%d:%02d"
1892 "The format string used when creating CLOCKSUM lines, or when
1893 org-mode generates a time duration."
1894 :group 'org-time
1895 :type 'string)
1897 (defcustom org-deadline-warning-days 14
1898 "No. of days before expiration during which a deadline becomes active.
1899 This variable governs the display in sparse trees and in the agenda.
1900 When 0 or negative, it means use this number (the absolute value of it)
1901 even if a deadline has a different individual lead time specified."
1902 :group 'org-time
1903 :group 'org-agenda-daily/weekly
1904 :type 'number)
1906 (defcustom org-read-date-prefer-future t
1907 "Non-nil means, assume future for incomplete date input from user.
1908 This affects the following situations:
1909 1. The user gives a day, but no month.
1910 For example, if today is the 15th, and you enter \"3\", Org-mode will
1911 read this as the third of *next* month. However, if you enter \"17\",
1912 it will be considered as *this* month.
1913 2. The user gives a month but not a year.
1914 For example, if it is april and you enter \"feb 2\", this will be read
1915 as feb 2, *next* year. \"May 5\", however, will be this year.
1917 Currently this does not work for ISO week specifications.
1919 When this option is nil, the current month and year will always be used
1920 as defaults."
1921 :group 'org-time
1922 :type 'boolean)
1924 (defcustom org-read-date-display-live t
1925 "Non-nil means, display current interpretation of date prompt live.
1926 This display will be in an overlay, in the minibuffer."
1927 :group 'org-time
1928 :type 'boolean)
1930 (defcustom org-read-date-popup-calendar t
1931 "Non-nil means, pop up a calendar when prompting for a date.
1932 In the calendar, the date can be selected with mouse-1. However, the
1933 minibuffer will also be active, and you can simply enter the date as well.
1934 When nil, only the minibuffer will be available."
1935 :group 'org-time
1936 :type 'boolean)
1937 (if (fboundp 'defvaralias)
1938 (defvaralias 'org-popup-calendar-for-date-prompt
1939 'org-read-date-popup-calendar))
1941 (defcustom org-extend-today-until 0
1942 "The hour when your day really ends. Must be an integer.
1943 This has influence for the following applications:
1944 - When switching the agenda to \"today\". It it is still earlier than
1945 the time given here, the day recognized as TODAY is actually yesterday.
1946 - When a date is read from the user and it is still before the time given
1947 here, the current date and time will be assumed to be yesterday, 23:59.
1948 Also, timestamps inserted in remember templates follow this rule.
1950 IMPORTANT: This is a feature whose implementation is and likely will
1951 remain incomplete. Really, it is only here because past midnight seems to
1952 be the favorite working time of John Wiegley :-)"
1953 :group 'org-time
1954 :type 'number)
1956 (defcustom org-edit-timestamp-down-means-later nil
1957 "Non-nil means, S-down will increase the time in a time stamp.
1958 When nil, S-up will increase."
1959 :group 'org-time
1960 :type 'boolean)
1962 (defcustom org-calendar-follow-timestamp-change t
1963 "Non-nil means, make the calendar window follow timestamp changes.
1964 When a timestamp is modified and the calendar window is visible, it will be
1965 moved to the new date."
1966 :group 'org-time
1967 :type 'boolean)
1969 (defgroup org-tags nil
1970 "Options concerning tags in Org-mode."
1971 :tag "Org Tags"
1972 :group 'org)
1974 (defcustom org-tag-alist nil
1975 "List of tags allowed in Org-mode files.
1976 When this list is nil, Org-mode will base TAG input on what is already in the
1977 buffer.
1978 The value of this variable is an alist, the car of each entry must be a
1979 keyword as a string, the cdr may be a character that is used to select
1980 that tag through the fast-tag-selection interface.
1981 See the manual for details."
1982 :group 'org-tags
1983 :type '(repeat
1984 (choice
1985 (cons (string :tag "Tag name")
1986 (character :tag "Access char"))
1987 (const :tag "Start radio group" (:startgroup))
1988 (const :tag "End radio group" (:endgroup)))))
1990 (defvar org-file-tags nil
1991 "List of tags that can be inherited by all entries in the file.
1992 The tags will be inherited if the variable `org-use-tag-inheritance'
1993 says they should be.
1994 This variable is populated from #+TAG lines.")
1996 (defcustom org-use-fast-tag-selection 'auto
1997 "Non-nil means, use fast tag selection scheme.
1998 This is a special interface to select and deselect tags with single keys.
1999 When nil, fast selection is never used.
2000 When the symbol `auto', fast selection is used if and only if selection
2001 characters for tags have been configured, either through the variable
2002 `org-tag-alist' or through a #+TAGS line in the buffer.
2003 When t, fast selection is always used and selection keys are assigned
2004 automatically if necessary."
2005 :group 'org-tags
2006 :type '(choice
2007 (const :tag "Always" t)
2008 (const :tag "Never" nil)
2009 (const :tag "When selection characters are configured" 'auto)))
2011 (defcustom org-fast-tag-selection-single-key nil
2012 "Non-nil means, fast tag selection exits after first change.
2013 When nil, you have to press RET to exit it.
2014 During fast tag selection, you can toggle this flag with `C-c'.
2015 This variable can also have the value `expert'. In this case, the window
2016 displaying the tags menu is not even shown, until you press C-c again."
2017 :group 'org-tags
2018 :type '(choice
2019 (const :tag "No" nil)
2020 (const :tag "Yes" t)
2021 (const :tag "Expert" expert)))
2023 (defvar org-fast-tag-selection-include-todo nil
2024 "Non-nil means, fast tags selection interface will also offer TODO states.
2025 This is an undocumented feature, you should not rely on it.")
2027 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
2028 "The column to which tags should be indented in a headline.
2029 If this number is positive, it specifies the column. If it is negative,
2030 it means that the tags should be flushright to that column. For example,
2031 -80 works well for a normal 80 character screen."
2032 :group 'org-tags
2033 :type 'integer)
2035 (defcustom org-auto-align-tags t
2036 "Non-nil means, realign tags after pro/demotion of TODO state change.
2037 These operations change the length of a headline and therefore shift
2038 the tags around. With this options turned on, after each such operation
2039 the tags are again aligned to `org-tags-column'."
2040 :group 'org-tags
2041 :type 'boolean)
2043 (defcustom org-use-tag-inheritance t
2044 "Non-nil means, tags in levels apply also for sublevels.
2045 When nil, only the tags directly given in a specific line apply there.
2046 This may also be a list of tags that should be inherited, or a regexp that
2047 matches tags that should be inherited. Additional control is possible
2048 with the variable `org-tags-exclude-from-inheritance' which gives an
2049 explicit list of tags to be excluded from inheritance., even if the value of
2050 `org-use-tag-inheritance' would select it for inheritance.
2052 If this option is t, a match early-on in a tree can lead to a large
2053 number of matches in the subtree when constructing the agenda or creating
2054 a sparse tree. If you only want to see the first match in a tree during
2055 a search, check out the variable `org-tags-match-list-sublevels'."
2056 :group 'org-tags
2057 :type '(choice
2058 (const :tag "Not" nil)
2059 (const :tag "Always" t)
2060 (repeat :tag "Specific tags" (string :tag "Tag"))
2061 (regexp :tag "Tags matched by regexp")))
2063 (defcustom org-tags-exclude-from-inheritance nil
2064 "List of tags that should never be inherited.
2065 This is a way to exclude a few tags from inheritance. For way to do
2066 the opposite, to actively allow inheritance for selected tags,
2067 see the variable `org-use-tag-inheritance'."
2068 :group 'org-tags
2069 :type '(repeat (string :tag "Tag")))
2071 (defun org-tag-inherit-p (tag)
2072 "Check if TAG is one that should be inherited."
2073 (cond
2074 ((member tag org-tags-exclude-from-inheritance) nil)
2075 ((eq org-use-tag-inheritance t) t)
2076 ((not org-use-tag-inheritance) nil)
2077 ((stringp org-use-tag-inheritance)
2078 (string-match org-use-tag-inheritance tag))
2079 ((listp org-use-tag-inheritance)
2080 (member tag org-use-tag-inheritance))
2081 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2083 (defcustom org-tags-match-list-sublevels t
2084 "Non-nil means list also sublevels of headlines matching tag search.
2085 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2086 the sublevels of a headline matching a tag search often also match
2087 the same search. Listing all of them can create very long lists.
2088 Setting this variable to nil causes subtrees of a match to be skipped.
2089 This option is off by default, because inheritance in on. If you turn
2090 inheritance off, you very likely want to turn this option on.
2092 As a special case, if the tag search is restricted to TODO items, the
2093 value of this variable is ignored and sublevels are always checked, to
2094 make sure all corresponding TODO items find their way into the list.
2096 This variable is semi-obsolete and probably should always be true. It
2097 is better to limit inheritance to certain tags using the variables
2098 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2099 :group 'org-tags
2100 :type 'boolean)
2102 (defvar org-tags-history nil
2103 "History of minibuffer reads for tags.")
2104 (defvar org-last-tags-completion-table nil
2105 "The last used completion table for tags.")
2106 (defvar org-after-tags-change-hook nil
2107 "Hook that is run after the tags in a line have changed.")
2109 (defgroup org-properties nil
2110 "Options concerning properties in Org-mode."
2111 :tag "Org Properties"
2112 :group 'org)
2114 (defcustom org-property-format "%-10s %s"
2115 "How property key/value pairs should be formatted by `indent-line'.
2116 When `indent-line' hits a property definition, it will format the line
2117 according to this format, mainly to make sure that the values are
2118 lined-up with respect to each other."
2119 :group 'org-properties
2120 :type 'string)
2122 (defcustom org-use-property-inheritance nil
2123 "Non-nil means, properties apply also for sublevels.
2125 This setting is chiefly used during property searches. Turning it on can
2126 cause significant overhead when doing a search, which is why it is not
2127 on by default.
2129 When nil, only the properties directly given in the current entry count.
2130 When t, every property is inherited. The value may also be a list of
2131 properties that should have inheritance, or a regular expression matching
2132 properties that should be inherited.
2134 However, note that some special properties use inheritance under special
2135 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2136 and the properties ending in \"_ALL\" when they are used as descriptor
2137 for valid values of a property.
2139 Note for programmers:
2140 When querying an entry with `org-entry-get', you can control if inheritance
2141 should be used. By default, `org-entry-get' looks only at the local
2142 properties. You can request inheritance by setting the inherit argument
2143 to t (to force inheritance) or to `selective' (to respect the setting
2144 in this variable)."
2145 :group 'org-properties
2146 :type '(choice
2147 (const :tag "Not" nil)
2148 (const :tag "Always" t)
2149 (repeat :tag "Specific properties" (string :tag "Property"))
2150 (regexp :tag "Properties matched by regexp")))
2152 (defun org-property-inherit-p (property)
2153 "Check if PROPERTY is one that should be inherited."
2154 (cond
2155 ((eq org-use-property-inheritance t) t)
2156 ((not org-use-property-inheritance) nil)
2157 ((stringp org-use-property-inheritance)
2158 (string-match org-use-property-inheritance property))
2159 ((listp org-use-property-inheritance)
2160 (member property org-use-property-inheritance))
2161 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2163 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2164 "The default column format, if no other format has been defined.
2165 This variable can be set on the per-file basis by inserting a line
2167 #+COLUMNS: %25ITEM ....."
2168 :group 'org-properties
2169 :type 'string)
2171 (defcustom org-columns-ellipses ".."
2172 "The ellipses to be used when a field in column view is truncated.
2173 When this is the empty string, as many characters as possible are shown,
2174 but then there will be no visual indication that the field has been truncated.
2175 When this is a string of length N, the last N characters of a truncated
2176 field are replaced by this string. If the column is narrower than the
2177 ellipses string, only part of the ellipses string will be shown."
2178 :group 'org-properties
2179 :type 'string)
2181 (defcustom org-columns-modify-value-for-display-function nil
2182 "Function that modifies values for display in column view.
2183 For example, it can be used to cut out a certain part from a time stamp.
2184 The function must take 2 arguments:
2186 column-title The title of the column (*not* the property name)
2187 value The value that should be modified.
2189 The function should return the value that should be displayed,
2190 or nil if the normal value should be used."
2191 :group 'org-properties
2192 :type 'function)
2194 (defcustom org-effort-property "Effort"
2195 "The property that is being used to keep track of effort estimates.
2196 Effort estimates given in this property need to have the format H:MM."
2197 :group 'org-properties
2198 :group 'org-progress
2199 :type '(string :tag "Property"))
2201 (defconst org-global-properties-fixed
2202 '(("VISIBILITY_ALL" . "folded children content all"))
2203 "List of property/value pairs that can be inherited by any entry.
2204 These are fixed values, for the preset properties.")
2207 (defcustom org-global-properties nil
2208 "List of property/value pairs that can be inherited by any entry.
2209 You can set buffer-local values for the same purpose in the variable
2210 `org-file-properties' this by adding lines like
2212 #+PROPERTY: NAME VALUE"
2213 :group 'org-properties
2214 :type '(repeat
2215 (cons (string :tag "Property")
2216 (string :tag "Value"))))
2218 (defvar org-file-properties nil
2219 "List of property/value pairs that can be inherited by any entry.
2220 Valid for the current buffer.
2221 This variable is populated from #+PROPERTY lines.")
2222 (make-variable-buffer-local 'org-file-properties)
2224 (defgroup org-agenda nil
2225 "Options concerning agenda views in Org-mode."
2226 :tag "Org Agenda"
2227 :group 'org)
2229 (defvar org-category nil
2230 "Variable used by org files to set a category for agenda display.
2231 Such files should use a file variable to set it, for example
2233 # -*- mode: org; org-category: \"ELisp\"
2235 or contain a special line
2237 #+CATEGORY: ELisp
2239 If the file does not specify a category, then file's base name
2240 is used instead.")
2241 (make-variable-buffer-local 'org-category)
2242 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2244 (defcustom org-agenda-files nil
2245 "The files to be used for agenda display.
2246 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2247 \\[org-remove-file]. You can also use customize to edit the list.
2249 If an entry is a directory, all files in that directory that are matched by
2250 `org-agenda-file-regexp' will be part of the file list.
2252 If the value of the variable is not a list but a single file name, then
2253 the list of agenda files is actually stored and maintained in that file, one
2254 agenda file per line."
2255 :group 'org-agenda
2256 :type '(choice
2257 (repeat :tag "List of files and directories" file)
2258 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2260 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2261 "Regular expression to match files for `org-agenda-files'.
2262 If any element in the list in that variable contains a directory instead
2263 of a normal file, all files in that directory that are matched by this
2264 regular expression will be included."
2265 :group 'org-agenda
2266 :type 'regexp)
2268 (defcustom org-agenda-text-search-extra-files nil
2269 "List of extra files to be searched by text search commands.
2270 These files will be search in addition to the agenda files by the
2271 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2272 Note that these files will only be searched for text search commands,
2273 not for the other agenda views like todo lists, tag searches or the weekly
2274 agenda. This variable is intended to list notes and possibly archive files
2275 that should also be searched by these two commands.
2276 In fact, if the first element in the list is the symbol `agenda-archives',
2277 than all archive files of all agenda files will be added to the search
2278 scope."
2279 :group 'org-agenda
2280 :type '(set :greedy t
2281 (const :tag "Agenda Archives" agenda-archives)
2282 (repeat :inline t (file))))
2284 (if (fboundp 'defvaralias)
2285 (defvaralias 'org-agenda-multi-occur-extra-files
2286 'org-agenda-text-search-extra-files))
2288 (defcustom org-agenda-skip-unavailable-files nil
2289 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2290 A nil value means to remove them, after a query, from the list."
2291 :group 'org-agenda
2292 :type 'boolean)
2294 (defcustom org-calendar-to-agenda-key [?c]
2295 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2296 The command `org-calendar-goto-agenda' will be bound to this key. The
2297 default is the character `c' because then `c' can be used to switch back and
2298 forth between agenda and calendar."
2299 :group 'org-agenda
2300 :type 'sexp)
2302 (defcustom org-calendar-agenda-action-key [?k]
2303 "The key to be installed in `calendar-mode-map' for agenda-action.
2304 The command `org-agenda-action' will be bound to this key. The
2305 default is the character `k' because we use the same key in the agenda."
2306 :group 'org-agenda
2307 :type 'sexp)
2309 (eval-after-load "calendar"
2310 '(progn
2311 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2312 'org-calendar-goto-agenda)
2313 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2314 'org-agenda-action)))
2316 (defgroup org-latex nil
2317 "Options for embedding LaTeX code into Org-mode."
2318 :tag "Org LaTeX"
2319 :group 'org)
2321 (defcustom org-format-latex-options
2322 '(:foreground default :background default :scale 1.0
2323 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2324 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2325 "Options for creating images from LaTeX fragments.
2326 This is a property list with the following properties:
2327 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2328 `default' means use the foreground of the default face.
2329 :background the background color, or \"Transparent\".
2330 `default' means use the background of the default face.
2331 :scale a scaling factor for the size of the images.
2332 :html-foreground, :html-background, :html-scale
2333 the same numbers for HTML export.
2334 :matchers a list indicating which matchers should be used to
2335 find LaTeX fragments. Valid members of this list are:
2336 \"begin\" find environments
2337 \"$1\" find single characters surrounded by $.$
2338 \"$\" find math expressions surrounded by $...$
2339 \"$$\" find math expressions surrounded by $$....$$
2340 \"\\(\" find math expressions surrounded by \\(...\\)
2341 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2342 :group 'org-latex
2343 :type 'plist)
2345 (defcustom org-format-latex-header "\\documentclass{article}
2346 \\usepackage{fullpage} % do not remove
2347 \\usepackage{amssymb}
2348 \\usepackage[usenames]{color}
2349 \\usepackage{amsmath}
2350 \\usepackage{latexsym}
2351 \\usepackage[mathscr]{eucal}
2352 \\pagestyle{empty} % do not remove"
2353 "The document header used for processing LaTeX fragments."
2354 :group 'org-latex
2355 :type 'string)
2358 (defgroup org-font-lock nil
2359 "Font-lock settings for highlighting in Org-mode."
2360 :tag "Org Font Lock"
2361 :group 'org)
2363 (defcustom org-level-color-stars-only nil
2364 "Non-nil means fontify only the stars in each headline.
2365 When nil, the entire headline is fontified.
2366 Changing it requires restart of `font-lock-mode' to become effective
2367 also in regions already fontified."
2368 :group 'org-font-lock
2369 :type 'boolean)
2371 (defcustom org-hide-leading-stars nil
2372 "Non-nil means, hide the first N-1 stars in a headline.
2373 This works by using the face `org-hide' for these stars. This
2374 face is white for a light background, and black for a dark
2375 background. You may have to customize the face `org-hide' to
2376 make this work.
2377 Changing it requires restart of `font-lock-mode' to become effective
2378 also in regions already fontified.
2379 You may also set this on a per-file basis by adding one of the following
2380 lines to the buffer:
2382 #+STARTUP: hidestars
2383 #+STARTUP: showstars"
2384 :group 'org-font-lock
2385 :type 'boolean)
2387 (defcustom org-fontify-done-headline nil
2388 "Non-nil means, change the face of a headline if it is marked DONE.
2389 Normally, only the TODO/DONE keyword indicates the state of a headline.
2390 When this is non-nil, the headline after the keyword is set to the
2391 `org-headline-done' as an additional indication."
2392 :group 'org-font-lock
2393 :type 'boolean)
2395 (defcustom org-fontify-emphasized-text t
2396 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2397 Changing this variable requires a restart of Emacs to take effect."
2398 :group 'org-font-lock
2399 :type 'boolean)
2401 (defcustom org-highlight-latex-fragments-and-specials nil
2402 "Non-nil means, fontify what is treated specially by the exporters."
2403 :group 'org-font-lock
2404 :type 'boolean)
2406 (defcustom org-hide-emphasis-markers nil
2407 "Non-nil mean font-lock should hide the emphasis marker characters."
2408 :group 'org-font-lock
2409 :type 'boolean)
2411 (defvar org-emph-re nil
2412 "Regular expression for matching emphasis.")
2413 (defvar org-verbatim-re nil
2414 "Regular expression for matching verbatim text.")
2415 (defvar org-emphasis-regexp-components) ; defined just below
2416 (defvar org-emphasis-alist) ; defined just below
2417 (defun org-set-emph-re (var val)
2418 "Set variable and compute the emphasis regular expression."
2419 (set var val)
2420 (when (and (boundp 'org-emphasis-alist)
2421 (boundp 'org-emphasis-regexp-components)
2422 org-emphasis-alist org-emphasis-regexp-components)
2423 (let* ((e org-emphasis-regexp-components)
2424 (pre (car e))
2425 (post (nth 1 e))
2426 (border (nth 2 e))
2427 (body (nth 3 e))
2428 (nl (nth 4 e))
2429 (body1 (concat body "*?"))
2430 (markers (mapconcat 'car org-emphasis-alist ""))
2431 (vmarkers (mapconcat
2432 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2433 org-emphasis-alist "")))
2434 ;; make sure special characters appear at the right position in the class
2435 (if (string-match "\\^" markers)
2436 (setq markers (concat (replace-match "" t t markers) "^")))
2437 (if (string-match "-" markers)
2438 (setq markers (concat (replace-match "" t t markers) "-")))
2439 (if (string-match "\\^" vmarkers)
2440 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2441 (if (string-match "-" vmarkers)
2442 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2443 (if (> nl 0)
2444 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2445 (int-to-string nl) "\\}")))
2446 ;; Make the regexp
2447 (setq org-emph-re
2448 (concat "\\([" pre "]\\|^\\)"
2449 "\\("
2450 "\\([" markers "]\\)"
2451 "\\("
2452 "[^" border "]\\|"
2453 "[^" border "]"
2454 body1
2455 "[^" border "]"
2456 "\\)"
2457 "\\3\\)"
2458 "\\([" post "]\\|$\\)"))
2459 (setq org-verbatim-re
2460 (concat "\\([" pre "]\\|^\\)"
2461 "\\("
2462 "\\([" vmarkers "]\\)"
2463 "\\("
2464 "[^" border "]\\|"
2465 "[^" border "]"
2466 body1
2467 "[^" border "]"
2468 "\\)"
2469 "\\3\\)"
2470 "\\([" post "]\\|$\\)")))))
2472 (defcustom org-emphasis-regexp-components
2473 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2474 "Components used to build the regular expression for emphasis.
2475 This is a list with 6 entries. Terminology: In an emphasis string
2476 like \" *strong word* \", we call the initial space PREMATCH, the final
2477 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2478 and \"trong wor\" is the body. The different components in this variable
2479 specify what is allowed/forbidden in each part:
2481 pre Chars allowed as prematch. Beginning of line will be allowed too.
2482 post Chars allowed as postmatch. End of line will be allowed too.
2483 border The chars *forbidden* as border characters.
2484 body-regexp A regexp like \".\" to match a body character. Don't use
2485 non-shy groups here, and don't allow newline here.
2486 newline The maximum number of newlines allowed in an emphasis exp.
2488 Use customize to modify this, or restart Emacs after changing it."
2489 :group 'org-font-lock
2490 :set 'org-set-emph-re
2491 :type '(list
2492 (sexp :tag "Allowed chars in pre ")
2493 (sexp :tag "Allowed chars in post ")
2494 (sexp :tag "Forbidden chars in border ")
2495 (sexp :tag "Regexp for body ")
2496 (integer :tag "number of newlines allowed")
2497 (option (boolean :tag "Please ignore this button"))))
2499 (defcustom org-emphasis-alist
2500 `(("*" bold "<b>" "</b>")
2501 ("/" italic "<i>" "</i>")
2502 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2503 ("=" org-code "<code>" "</code>" verbatim)
2504 ("~" org-verbatim "<code>" "</code>" verbatim)
2505 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2506 "<del>" "</del>")
2508 "Special syntax for emphasized text.
2509 Text starting and ending with a special character will be emphasized, for
2510 example *bold*, _underlined_ and /italic/. This variable sets the marker
2511 characters, the face to be used by font-lock for highlighting in Org-mode
2512 Emacs buffers, and the HTML tags to be used for this.
2513 Use customize to modify this, or restart Emacs after changing it."
2514 :group 'org-font-lock
2515 :set 'org-set-emph-re
2516 :type '(repeat
2517 (list
2518 (string :tag "Marker character")
2519 (choice
2520 (face :tag "Font-lock-face")
2521 (plist :tag "Face property list"))
2522 (string :tag "HTML start tag")
2523 (string :tag "HTML end tag")
2524 (option (const verbatim)))))
2526 ;;; Miscellaneous options
2528 (defgroup org-completion nil
2529 "Completion in Org-mode."
2530 :tag "Org Completion"
2531 :group 'org)
2533 (defcustom org-completion-use-ido nil
2534 "Non-nil means, use ido completion wherever possible.
2535 Note that `ido-mode' must be active for this variable to be relevant.
2536 If you decide to turn this variable on, you might well want to turn off
2537 `org-outline-path-complete-in-steps'."
2538 :group 'org-completion
2539 :type 'boolean)
2541 (defcustom org-completion-fallback-command 'hippie-expand
2542 "The expansion command called by \\[org-complete] in normal context.
2543 Normal means, no org-mode-specific context."
2544 :group 'org-completion
2545 :type 'function)
2547 ;;; Functions and variables from ther packages
2548 ;; Declared here to avoid compiler warnings
2550 ;; XEmacs only
2551 (defvar outline-mode-menu-heading)
2552 (defvar outline-mode-menu-show)
2553 (defvar outline-mode-menu-hide)
2554 (defvar zmacs-regions) ; XEmacs regions
2556 ;; Emacs only
2557 (defvar mark-active)
2559 ;; Various packages
2560 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2561 (declare-function calendar-forward-day "cal-move" (arg))
2562 (declare-function calendar-goto-date "cal-move" (date))
2563 (declare-function calendar-goto-today "cal-move" ())
2564 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2565 (defvar calc-embedded-close-formula)
2566 (defvar calc-embedded-open-formula)
2567 (declare-function cdlatex-tab "ext:cdlatex" ())
2568 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2569 (defvar font-lock-unfontify-region-function)
2570 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2571 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2572 (defvar iswitchb-temp-buflist)
2573 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2574 (defvar org-agenda-tags-todo-honor-ignore-options)
2575 (declare-function org-agenda-skip "org-agenda" ())
2576 (declare-function org-format-agenda-item "org-agenda"
2577 (extra txt &optional category tags dotime noprefix remove-re))
2578 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2579 (declare-function org-agenda-change-all-lines "org-agenda"
2580 (newhead hdmarker &optional fixface just-this))
2581 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2582 (declare-function org-agenda-maybe-redo "org-agenda" ())
2583 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2584 (beg end))
2585 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2586 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2587 "org-agenda" (&optional end))
2589 (declare-function parse-time-string "parse-time" (string))
2590 (declare-function remember "remember" (&optional initial))
2591 (declare-function remember-buffer-desc "remember" ())
2592 (declare-function remember-finalize "remember" ())
2593 (defvar remember-save-after-remembering)
2594 (defvar remember-data-file)
2595 (defvar remember-register)
2596 (defvar remember-buffer)
2597 (defvar remember-handler-functions)
2598 (defvar remember-annotation-functions)
2599 (defvar texmathp-why)
2600 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2601 (declare-function table--at-cell-p "table" (position &optional object at-column))
2603 (defvar w3m-current-url)
2604 (defvar w3m-current-title)
2606 (defvar org-latex-regexps)
2608 ;;; Autoload and prepare some org modules
2610 ;; Some table stuff that needs to be defined here, because it is used
2611 ;; by the functions setting up org-mode or checking for table context.
2613 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2614 "Detects an org-type or table-type table.")
2615 (defconst org-table-line-regexp "^[ \t]*|"
2616 "Detects an org-type table line.")
2617 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2618 "Detects an org-type table line.")
2619 (defconst org-table-hline-regexp "^[ \t]*|-"
2620 "Detects an org-type table hline.")
2621 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2622 "Detects a table-type table hline.")
2623 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2624 "Searching from within a table (any type) this finds the first line
2625 outside the table.")
2627 ;; Autoload the functions in org-table.el that are needed by functions here.
2629 (eval-and-compile
2630 (org-autoload "org-table"
2631 '(org-table-align org-table-begin org-table-blank-field
2632 org-table-convert org-table-convert-region org-table-copy-down
2633 org-table-copy-region org-table-create
2634 org-table-create-or-convert-from-region
2635 org-table-create-with-table.el org-table-current-dline
2636 org-table-cut-region org-table-delete-column org-table-edit-field
2637 org-table-edit-formulas org-table-end org-table-eval-formula
2638 org-table-export org-table-field-info
2639 org-table-get-stored-formulas org-table-goto-column
2640 org-table-hline-and-move org-table-import org-table-insert-column
2641 org-table-insert-hline org-table-insert-row org-table-iterate
2642 org-table-justify-field-maybe org-table-kill-row
2643 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2644 org-table-move-column org-table-move-column-left
2645 org-table-move-column-right org-table-move-row
2646 org-table-move-row-down org-table-move-row-up
2647 org-table-next-field org-table-next-row org-table-paste-rectangle
2648 org-table-previous-field org-table-recalculate
2649 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2650 org-table-toggle-coordinate-overlays
2651 org-table-toggle-formula-debugger org-table-wrap-region
2652 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2654 (defun org-at-table-p (&optional table-type)
2655 "Return t if the cursor is inside an org-type table.
2656 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2657 (if org-enable-table-editor
2658 (save-excursion
2659 (beginning-of-line 1)
2660 (looking-at (if table-type org-table-any-line-regexp
2661 org-table-line-regexp)))
2662 nil))
2663 (defsubst org-table-p () (org-at-table-p))
2665 (defun org-at-table.el-p ()
2666 "Return t if and only if we are at a table.el table."
2667 (and (org-at-table-p 'any)
2668 (save-excursion
2669 (goto-char (org-table-begin 'any))
2670 (looking-at org-table1-hline-regexp))))
2671 (defun org-table-recognize-table.el ()
2672 "If there is a table.el table nearby, recognize it and move into it."
2673 (if org-table-tab-recognizes-table.el
2674 (if (org-at-table.el-p)
2675 (progn
2676 (beginning-of-line 1)
2677 (if (looking-at org-table-dataline-regexp)
2679 (if (looking-at org-table1-hline-regexp)
2680 (progn
2681 (beginning-of-line 2)
2682 (if (looking-at org-table-any-border-regexp)
2683 (beginning-of-line -1)))))
2684 (if (re-search-forward "|" (org-table-end t) t)
2685 (progn
2686 (require 'table)
2687 (if (table--at-cell-p (point))
2689 (message "recognizing table.el table...")
2690 (table-recognize-table)
2691 (message "recognizing table.el table...done")))
2692 (error "This should not happen..."))
2694 nil)
2695 nil))
2697 (defun org-at-table-hline-p ()
2698 "Return t if the cursor is inside a hline in a table."
2699 (if org-enable-table-editor
2700 (save-excursion
2701 (beginning-of-line 1)
2702 (looking-at org-table-hline-regexp))
2703 nil))
2705 (defvar org-table-clean-did-remove-column nil)
2707 (defun org-table-map-tables (function)
2708 "Apply FUNCTION to the start of all tables in the buffer."
2709 (save-excursion
2710 (save-restriction
2711 (widen)
2712 (goto-char (point-min))
2713 (while (re-search-forward org-table-any-line-regexp nil t)
2714 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2715 (beginning-of-line 1)
2716 (if (looking-at org-table-line-regexp)
2717 (save-excursion (funcall function)))
2718 (re-search-forward org-table-any-border-regexp nil 1))))
2719 (message "Mapping tables: done"))
2721 ;; Declare and autoload functions from org-exp.el
2723 (declare-function org-default-export-plist "org-exp")
2724 (declare-function org-infile-export-plist "org-exp")
2725 (declare-function org-get-current-options "org-exp")
2726 (eval-and-compile
2727 (org-autoload "org-exp"
2728 '(org-export org-export-as-ascii org-export-visible
2729 org-insert-export-options-template org-export-as-html-and-open
2730 org-export-as-html-batch org-export-as-html-to-buffer
2731 org-replace-region-by-html org-export-region-as-html
2732 org-export-as-html org-export-icalendar-this-file
2733 org-export-icalendar-all-agenda-files
2734 org-table-clean-before-export
2735 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2737 ;; Declare and autoload functions from org-agenda.el
2739 (eval-and-compile
2740 (org-autoload "org-agenda"
2741 '(org-agenda org-agenda-list org-search-view
2742 org-todo-list org-tags-view org-agenda-list-stuck-projects
2743 org-diary org-agenda-to-appt
2744 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2746 ;; Autoload org-remember
2748 (eval-and-compile
2749 (org-autoload "org-remember"
2750 '(org-remember-insinuate org-remember-annotation
2751 org-remember-apply-template org-remember org-remember-handler)))
2753 ;; Autoload org-clock.el
2756 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2757 (beg end))
2758 (declare-function org-clock-update-mode-line "org-clock" ())
2759 (defvar org-clock-start-time)
2760 (defvar org-clock-marker (make-marker)
2761 "Marker recording the last clock-in.")
2763 (eval-and-compile
2764 (org-autoload
2765 "org-clock"
2766 '(org-clock-in org-clock-out org-clock-cancel
2767 org-clock-goto org-clock-sum org-clock-display
2768 org-clock-remove-overlays org-clock-report
2769 org-clocktable-shift org-dblock-write:clocktable
2770 org-get-clocktable)))
2772 (defun org-clock-update-time-maybe ()
2773 "If this is a CLOCK line, update it and return t.
2774 Otherwise, return nil."
2775 (interactive)
2776 (save-excursion
2777 (beginning-of-line 1)
2778 (skip-chars-forward " \t")
2779 (when (looking-at org-clock-string)
2780 (let ((re (concat "[ \t]*" org-clock-string
2781 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2782 "\\([ \t]*=>.*\\)?\\)?"))
2783 ts te h m s neg)
2784 (cond
2785 ((not (looking-at re))
2786 nil)
2787 ((not (match-end 2))
2788 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2789 (> org-clock-marker (point))
2790 (<= org-clock-marker (point-at-eol)))
2791 ;; The clock is running here
2792 (setq org-clock-start-time
2793 (apply 'encode-time
2794 (org-parse-time-string (match-string 1))))
2795 (org-clock-update-mode-line)))
2797 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2798 (end-of-line 1)
2799 (setq ts (match-string 1)
2800 te (match-string 3))
2801 (setq s (- (time-to-seconds
2802 (apply 'encode-time (org-parse-time-string te)))
2803 (time-to-seconds
2804 (apply 'encode-time (org-parse-time-string ts))))
2805 neg (< s 0)
2806 s (abs s)
2807 h (floor (/ s 3600))
2808 s (- s (* 3600 h))
2809 m (floor (/ s 60))
2810 s (- s (* 60 s)))
2811 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2812 t))))))
2814 (defun org-check-running-clock ()
2815 "Check if the current buffer contains the running clock.
2816 If yes, offer to stop it and to save the buffer with the changes."
2817 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2818 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2819 (buffer-name))))
2820 (org-clock-out)
2821 (when (y-or-n-p "Save changed buffer?")
2822 (save-buffer))))
2824 (defun org-clocktable-try-shift (dir n)
2825 "Check if this line starts a clock table, if yes, shift the time block."
2826 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2827 (org-clocktable-shift dir n)))
2829 ;; Autoload org-timer.el
2831 ;(declare-function org-timer "org-timer")
2833 (eval-and-compile
2834 (org-autoload
2835 "org-timer"
2836 '(org-timer-start org-timer org-timer-item
2837 org-timer-change-times-in-region)))
2840 ;; Autoload archiving code
2841 ;; The stuff that is needed for cycling and tags has to be defined here.
2843 (defgroup org-archive nil
2844 "Options concerning archiving in Org-mode."
2845 :tag "Org Archive"
2846 :group 'org-structure)
2848 (defcustom org-archive-location "%s_archive::"
2849 "The location where subtrees should be archived.
2851 The value of this variable is a string, consisting of two parts,
2852 separated by a double-colon. The first part is a filename and
2853 the second part is a headline.
2855 When the filename is omitted, archiving happens in the same file.
2856 %s in the filename will be replaced by the current file
2857 name (without the directory part). Archiving to a different file
2858 is useful to keep archived entries from contributing to the
2859 Org-mode Agenda.
2861 The archived entries will be filed as subtrees of the specified
2862 headline. When the headline is omitted, the subtrees are simply
2863 filed away at the end of the file, as top-level entries. Also in
2864 the heading you can use %s to represent the file name, this can be
2865 useful when using the same archive for a number of different files.
2867 Here are a few examples:
2868 \"%s_archive::\"
2869 If the current file is Projects.org, archive in file
2870 Projects.org_archive, as top-level trees. This is the default.
2872 \"::* Archived Tasks\"
2873 Archive in the current file, under the top-level headline
2874 \"* Archived Tasks\".
2876 \"~/org/archive.org::\"
2877 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2879 \"~/org/archive.org::From %s\"
2880 Archive in file ~/org/archive.org (absolute path), und headlines
2881 \"From FILENAME\" where file name is the current file name.
2883 \"basement::** Finished Tasks\"
2884 Archive in file ./basement (relative path), as level 3 trees
2885 below the level 2 heading \"** Finished Tasks\".
2887 You may set this option on a per-file basis by adding to the buffer a
2888 line like
2890 #+ARCHIVE: basement::** Finished Tasks
2892 You may also define it locally for a subtree by setting an ARCHIVE property
2893 in the entry. If such a property is found in an entry, or anywhere up
2894 the hierarchy, it will be used."
2895 :group 'org-archive
2896 :type 'string)
2898 (defcustom org-archive-tag "ARCHIVE"
2899 "The tag that marks a subtree as archived.
2900 An archived subtree does not open during visibility cycling, and does
2901 not contribute to the agenda listings.
2902 After changing this, font-lock must be restarted in the relevant buffers to
2903 get the proper fontification."
2904 :group 'org-archive
2905 :group 'org-keywords
2906 :type 'string)
2908 (defcustom org-agenda-skip-archived-trees t
2909 "Non-nil means, the agenda will skip any items located in archived trees.
2910 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2911 variable is no longer recommended, you should leave it at the value t.
2912 Instead, use the key `v' to cycle the archives-mode in the agenda."
2913 :group 'org-archive
2914 :group 'org-agenda-skip
2915 :type 'boolean)
2917 (defcustom org-cycle-open-archived-trees nil
2918 "Non-nil means, `org-cycle' will open archived trees.
2919 An archived tree is a tree marked with the tag ARCHIVE.
2920 When nil, archived trees will stay folded. You can still open them with
2921 normal outline commands like `show-all', but not with the cycling commands."
2922 :group 'org-archive
2923 :group 'org-cycle
2924 :type 'boolean)
2926 (defcustom org-sparse-tree-open-archived-trees nil
2927 "Non-nil means sparse tree construction shows matches in archived trees.
2928 When nil, matches in these trees are highlighted, but the trees are kept in
2929 collapsed state."
2930 :group 'org-archive
2931 :group 'org-sparse-trees
2932 :type 'boolean)
2934 (defun org-cycle-hide-archived-subtrees (state)
2935 "Re-hide all archived subtrees after a visibility state change."
2936 (when (and (not org-cycle-open-archived-trees)
2937 (not (memq state '(overview folded))))
2938 (save-excursion
2939 (let* ((globalp (memq state '(contents all)))
2940 (beg (if globalp (point-min) (point)))
2941 (end (if globalp (point-max) (org-end-of-subtree t))))
2942 (org-hide-archived-subtrees beg end)
2943 (goto-char beg)
2944 (if (looking-at (concat ".*:" org-archive-tag ":"))
2945 (message "%s" (substitute-command-keys
2946 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2948 (defun org-force-cycle-archived ()
2949 "Cycle subtree even if it is archived."
2950 (interactive)
2951 (setq this-command 'org-cycle)
2952 (let ((org-cycle-open-archived-trees t))
2953 (call-interactively 'org-cycle)))
2955 (defun org-hide-archived-subtrees (beg end)
2956 "Re-hide all archived subtrees after a visibility state change."
2957 (save-excursion
2958 (let* ((re (concat ":" org-archive-tag ":")))
2959 (goto-char beg)
2960 (while (re-search-forward re end t)
2961 (and (org-on-heading-p) (hide-subtree))
2962 (org-end-of-subtree t)))))
2964 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2966 (eval-and-compile
2967 (org-autoload "org-archive"
2968 '(org-add-archive-files org-archive-subtree
2969 org-archive-to-archive-sibling org-toggle-archive-tag)))
2971 ;; Autoload Column View Code
2973 (declare-function org-columns-number-to-string "org-colview")
2974 (declare-function org-columns-get-format-and-top-level "org-colview")
2975 (declare-function org-columns-compute "org-colview")
2977 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2978 '(org-columns-number-to-string org-columns-get-format-and-top-level
2979 org-columns-compute org-agenda-columns org-columns-remove-overlays
2980 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2982 ;; Autoload ID code
2984 (declare-function org-id-store-link "org-id")
2985 (org-autoload "org-id"
2986 '(org-id-get-create org-id-new org-id-copy org-id-get
2987 org-id-get-with-outline-path-completion
2988 org-id-get-with-outline-drilling
2989 org-id-goto org-id-find org-id-store-link))
2991 ;;; Variables for pre-computed regular expressions, all buffer local
2993 (defvar org-drawer-regexp nil
2994 "Matches first line of a hidden block.")
2995 (make-variable-buffer-local 'org-drawer-regexp)
2996 (defvar org-todo-regexp nil
2997 "Matches any of the TODO state keywords.")
2998 (make-variable-buffer-local 'org-todo-regexp)
2999 (defvar org-not-done-regexp nil
3000 "Matches any of the TODO state keywords except the last one.")
3001 (make-variable-buffer-local 'org-not-done-regexp)
3002 (defvar org-todo-line-regexp nil
3003 "Matches a headline and puts TODO state into group 2 if present.")
3004 (make-variable-buffer-local 'org-todo-line-regexp)
3005 (defvar org-complex-heading-regexp nil
3006 "Matches a headline and puts everything into groups:
3007 group 1: the stars
3008 group 2: The todo keyword, maybe
3009 group 3: Priority cookie
3010 group 4: True headline
3011 group 5: Tags")
3012 (make-variable-buffer-local 'org-complex-heading-regexp)
3013 (defvar org-todo-line-tags-regexp nil
3014 "Matches a headline and puts TODO state into group 2 if present.
3015 Also put tags into group 4 if tags are present.")
3016 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3017 (defvar org-nl-done-regexp nil
3018 "Matches newline followed by a headline with the DONE keyword.")
3019 (make-variable-buffer-local 'org-nl-done-regexp)
3020 (defvar org-looking-at-done-regexp nil
3021 "Matches the DONE keyword a point.")
3022 (make-variable-buffer-local 'org-looking-at-done-regexp)
3023 (defvar org-ds-keyword-length 12
3024 "Maximum length of the Deadline and SCHEDULED keywords.")
3025 (make-variable-buffer-local 'org-ds-keyword-length)
3026 (defvar org-deadline-regexp nil
3027 "Matches the DEADLINE keyword.")
3028 (make-variable-buffer-local 'org-deadline-regexp)
3029 (defvar org-deadline-time-regexp nil
3030 "Matches the DEADLINE keyword together with a time stamp.")
3031 (make-variable-buffer-local 'org-deadline-time-regexp)
3032 (defvar org-deadline-line-regexp nil
3033 "Matches the DEADLINE keyword and the rest of the line.")
3034 (make-variable-buffer-local 'org-deadline-line-regexp)
3035 (defvar org-scheduled-regexp nil
3036 "Matches the SCHEDULED keyword.")
3037 (make-variable-buffer-local 'org-scheduled-regexp)
3038 (defvar org-scheduled-time-regexp nil
3039 "Matches the SCHEDULED keyword together with a time stamp.")
3040 (make-variable-buffer-local 'org-scheduled-time-regexp)
3041 (defvar org-closed-time-regexp nil
3042 "Matches the CLOSED keyword together with a time stamp.")
3043 (make-variable-buffer-local 'org-closed-time-regexp)
3045 (defvar org-keyword-time-regexp nil
3046 "Matches any of the 4 keywords, together with the time stamp.")
3047 (make-variable-buffer-local 'org-keyword-time-regexp)
3048 (defvar org-keyword-time-not-clock-regexp nil
3049 "Matches any of the 3 keywords, together with the time stamp.")
3050 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3051 (defvar org-maybe-keyword-time-regexp nil
3052 "Matches a timestamp, possibly preceeded by a keyword.")
3053 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3054 (defvar org-planning-or-clock-line-re nil
3055 "Matches a line with planning or clock info.")
3056 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3058 (defconst org-plain-time-of-day-regexp
3059 (concat
3060 "\\(\\<[012]?[0-9]"
3061 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3062 "\\(--?"
3063 "\\(\\<[012]?[0-9]"
3064 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3065 "\\)?")
3066 "Regular expression to match a plain time or time range.
3067 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3068 groups carry important information:
3069 0 the full match
3070 1 the first time, range or not
3071 8 the second time, if it is a range.")
3073 (defconst org-plain-time-extension-regexp
3074 (concat
3075 "\\(\\<[012]?[0-9]"
3076 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3077 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3078 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3079 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3080 groups carry important information:
3081 0 the full match
3082 7 hours of duration
3083 9 minutes of duration")
3085 (defconst org-stamp-time-of-day-regexp
3086 (concat
3087 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3088 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3089 "\\(--?"
3090 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3091 "Regular expression to match a timestamp time or time range.
3092 After a match, the following groups carry important information:
3093 0 the full match
3094 1 date plus weekday, for backreferencing to make sure both times on same day
3095 2 the first time, range or not
3096 4 the second time, if it is a range.")
3098 (defconst org-startup-options
3099 '(("fold" org-startup-folded t)
3100 ("overview" org-startup-folded t)
3101 ("nofold" org-startup-folded nil)
3102 ("showall" org-startup-folded nil)
3103 ("content" org-startup-folded content)
3104 ("hidestars" org-hide-leading-stars t)
3105 ("showstars" org-hide-leading-stars nil)
3106 ("odd" org-odd-levels-only t)
3107 ("oddeven" org-odd-levels-only nil)
3108 ("align" org-startup-align-all-tables t)
3109 ("noalign" org-startup-align-all-tables nil)
3110 ("customtime" org-display-custom-times t)
3111 ("logdone" org-log-done time)
3112 ("lognotedone" org-log-done note)
3113 ("nologdone" org-log-done nil)
3114 ("lognoteclock-out" org-log-note-clock-out t)
3115 ("nolognoteclock-out" org-log-note-clock-out nil)
3116 ("logrepeat" org-log-repeat state)
3117 ("lognoterepeat" org-log-repeat note)
3118 ("nologrepeat" org-log-repeat nil)
3119 ("fninline" org-footnote-define-inline t)
3120 ("nofninline" org-footnote-define-inline nil)
3121 ("fnlocal" org-footnote-section nil)
3122 ("fnauto" org-footnote-auto-label t)
3123 ("fnprompt" org-footnote-auto-label nil)
3124 ("fnconfirm" org-footnote-auto-label confirm)
3125 ("fnplain" org-footnote-auto-label plain)
3126 ("constcgs" constants-unit-system cgs)
3127 ("constSI" constants-unit-system SI))
3128 "Variable associated with STARTUP options for org-mode.
3129 Each element is a list of three items: The startup options as written
3130 in the #+STARTUP line, the corresponding variable, and the value to
3131 set this variable to if the option is found. An optional forth element PUSH
3132 means to push this value onto the list in the variable.")
3134 (defun org-set-regexps-and-options ()
3135 "Precompute regular expressions for current buffer."
3136 (when (org-mode-p)
3137 (org-set-local 'org-todo-kwd-alist nil)
3138 (org-set-local 'org-todo-key-alist nil)
3139 (org-set-local 'org-todo-key-trigger nil)
3140 (org-set-local 'org-todo-keywords-1 nil)
3141 (org-set-local 'org-done-keywords nil)
3142 (org-set-local 'org-todo-heads nil)
3143 (org-set-local 'org-todo-sets nil)
3144 (org-set-local 'org-todo-log-states nil)
3145 (org-set-local 'org-file-properties nil)
3146 (org-set-local 'org-file-tags nil)
3147 (let ((re (org-make-options-regexp
3148 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3149 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3150 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3151 (splitre "[ \t]+")
3152 kwds kws0 kwsa key log value cat arch tags const links hw dws
3153 tail sep kws1 prio props ftags drawers
3154 ext-setup-or-nil setup-contents (start 0))
3155 (save-excursion
3156 (save-restriction
3157 (widen)
3158 (goto-char (point-min))
3159 (while (or (and ext-setup-or-nil
3160 (string-match re ext-setup-or-nil start)
3161 (setq start (match-end 0)))
3162 (and (setq ext-setup-or-nil nil start 0)
3163 (re-search-forward re nil t)))
3164 (setq key (upcase (match-string 1 ext-setup-or-nil))
3165 value (org-match-string-no-properties 2 ext-setup-or-nil))
3166 (cond
3167 ((equal key "CATEGORY")
3168 (if (string-match "[ \t]+$" value)
3169 (setq value (replace-match "" t t value)))
3170 (setq cat value))
3171 ((member key '("SEQ_TODO" "TODO"))
3172 (push (cons 'sequence (org-split-string value splitre)) kwds))
3173 ((equal key "TYP_TODO")
3174 (push (cons 'type (org-split-string value splitre)) kwds))
3175 ((equal key "TAGS")
3176 (setq tags (append tags (org-split-string value splitre))))
3177 ((equal key "COLUMNS")
3178 (org-set-local 'org-columns-default-format value))
3179 ((equal key "LINK")
3180 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3181 (push (cons (match-string 1 value)
3182 (org-trim (match-string 2 value)))
3183 links)))
3184 ((equal key "PRIORITIES")
3185 (setq prio (org-split-string value " +")))
3186 ((equal key "PROPERTY")
3187 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3188 (push (cons (match-string 1 value) (match-string 2 value))
3189 props)))
3190 ((equal key "FILETAGS")
3191 (when (string-match "\\S-" value)
3192 (setq ftags
3193 (append
3194 ftags
3195 (apply 'append
3196 (mapcar (lambda (x) (org-split-string x ":"))
3197 (org-split-string value)))))))
3198 ((equal key "DRAWERS")
3199 (setq drawers (org-split-string value splitre)))
3200 ((equal key "CONSTANTS")
3201 (setq const (append const (org-split-string value splitre))))
3202 ((equal key "STARTUP")
3203 (let ((opts (org-split-string value splitre))
3204 l var val)
3205 (while (setq l (pop opts))
3206 (when (setq l (assoc l org-startup-options))
3207 (setq var (nth 1 l) val (nth 2 l))
3208 (if (not (nth 3 l))
3209 (set (make-local-variable var) val)
3210 (if (not (listp (symbol-value var)))
3211 (set (make-local-variable var) nil))
3212 (set (make-local-variable var) (symbol-value var))
3213 (add-to-list var val))))))
3214 ((equal key "ARCHIVE")
3215 (string-match " *$" value)
3216 (setq arch (replace-match "" t t value))
3217 (remove-text-properties 0 (length arch)
3218 '(face t fontified t) arch))
3219 ((equal key "SETUPFILE")
3220 (setq setup-contents (org-file-contents
3221 (expand-file-name
3222 (org-remove-double-quotes value))
3223 'noerror))
3224 (if (not ext-setup-or-nil)
3225 (setq ext-setup-or-nil setup-contents start 0)
3226 (setq ext-setup-or-nil
3227 (concat (substring ext-setup-or-nil 0 start)
3228 "\n" setup-contents "\n"
3229 (substring ext-setup-or-nil start)))))
3230 ))))
3231 (when cat
3232 (org-set-local 'org-category (intern cat))
3233 (push (cons "CATEGORY" cat) props))
3234 (when prio
3235 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3236 (setq prio (mapcar 'string-to-char prio))
3237 (org-set-local 'org-highest-priority (nth 0 prio))
3238 (org-set-local 'org-lowest-priority (nth 1 prio))
3239 (org-set-local 'org-default-priority (nth 2 prio)))
3240 (and props (org-set-local 'org-file-properties (nreverse props)))
3241 (and ftags (org-set-local 'org-file-tags ftags))
3242 (and drawers (org-set-local 'org-drawers drawers))
3243 (and arch (org-set-local 'org-archive-location arch))
3244 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3245 ;; Process the TODO keywords
3246 (unless kwds
3247 ;; Use the global values as if they had been given locally.
3248 (setq kwds (default-value 'org-todo-keywords))
3249 (if (stringp (car kwds))
3250 (setq kwds (list (cons org-todo-interpretation
3251 (default-value 'org-todo-keywords)))))
3252 (setq kwds (reverse kwds)))
3253 (setq kwds (nreverse kwds))
3254 (let (inter kws kw)
3255 (while (setq kws (pop kwds))
3256 (setq inter (pop kws) sep (member "|" kws)
3257 kws0 (delete "|" (copy-sequence kws))
3258 kwsa nil
3259 kws1 (mapcar
3260 (lambda (x)
3261 ;; 1 2
3262 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3263 (progn
3264 (setq kw (match-string 1 x)
3265 key (and (match-end 2) (match-string 2 x))
3266 log (org-extract-log-state-settings x))
3267 (push (cons kw (and key (string-to-char key))) kwsa)
3268 (and log (push log org-todo-log-states))
3270 (error "Invalid TODO keyword %s" x)))
3271 kws0)
3272 kwsa (if kwsa (append '((:startgroup))
3273 (nreverse kwsa)
3274 '((:endgroup))))
3275 hw (car kws1)
3276 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3277 tail (list inter hw (car dws) (org-last dws)))
3278 (add-to-list 'org-todo-heads hw 'append)
3279 (push kws1 org-todo-sets)
3280 (setq org-done-keywords (append org-done-keywords dws nil))
3281 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3282 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3283 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3284 (setq org-todo-sets (nreverse org-todo-sets)
3285 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3286 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3287 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3288 ;; Process the constants
3289 (when const
3290 (let (e cst)
3291 (while (setq e (pop const))
3292 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3293 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3294 (setq org-table-formula-constants-local cst)))
3296 ;; Process the tags.
3297 (when tags
3298 (let (e tgs)
3299 (while (setq e (pop tags))
3300 (cond
3301 ((equal e "{") (push '(:startgroup) tgs))
3302 ((equal e "}") (push '(:endgroup) tgs))
3303 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3304 (push (cons (match-string 1 e)
3305 (string-to-char (match-string 2 e)))
3306 tgs))
3307 (t (push (list e) tgs))))
3308 (org-set-local 'org-tag-alist nil)
3309 (while (setq e (pop tgs))
3310 (or (and (stringp (car e))
3311 (assoc (car e) org-tag-alist))
3312 (push e org-tag-alist)))))
3314 ;; Compute the regular expressions and other local variables
3315 (if (not org-done-keywords)
3316 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3317 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3318 (length org-scheduled-string)
3319 (length org-clock-string)
3320 (length org-closed-string)))
3321 org-drawer-regexp
3322 (concat "^[ \t]*:\\("
3323 (mapconcat 'regexp-quote org-drawers "\\|")
3324 "\\):[ \t]*$")
3325 org-not-done-keywords
3326 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3327 org-todo-regexp
3328 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3329 "\\|") "\\)\\>")
3330 org-not-done-regexp
3331 (concat "\\<\\("
3332 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3333 "\\)\\>")
3334 org-todo-line-regexp
3335 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3336 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3337 "\\)\\>\\)?[ \t]*\\(.*\\)")
3338 org-complex-heading-regexp
3339 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3340 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3341 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3342 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3343 org-nl-done-regexp
3344 (concat "\n\\*+[ \t]+"
3345 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3346 "\\)" "\\>")
3347 org-todo-line-tags-regexp
3348 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3349 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3350 (org-re
3351 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3352 org-looking-at-done-regexp
3353 (concat "^" "\\(?:"
3354 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3355 "\\>")
3356 org-deadline-regexp (concat "\\<" org-deadline-string)
3357 org-deadline-time-regexp
3358 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3359 org-deadline-line-regexp
3360 (concat "\\<\\(" org-deadline-string "\\).*")
3361 org-scheduled-regexp
3362 (concat "\\<" org-scheduled-string)
3363 org-scheduled-time-regexp
3364 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3365 org-closed-time-regexp
3366 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3367 org-keyword-time-regexp
3368 (concat "\\<\\(" org-scheduled-string
3369 "\\|" org-deadline-string
3370 "\\|" org-closed-string
3371 "\\|" org-clock-string "\\)"
3372 " *[[<]\\([^]>]+\\)[]>]")
3373 org-keyword-time-not-clock-regexp
3374 (concat "\\<\\(" org-scheduled-string
3375 "\\|" org-deadline-string
3376 "\\|" org-closed-string
3377 "\\)"
3378 " *[[<]\\([^]>]+\\)[]>]")
3379 org-maybe-keyword-time-regexp
3380 (concat "\\(\\<\\(" org-scheduled-string
3381 "\\|" org-deadline-string
3382 "\\|" org-closed-string
3383 "\\|" org-clock-string "\\)\\)?"
3384 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3385 org-planning-or-clock-line-re
3386 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3387 "\\|" org-deadline-string
3388 "\\|" org-closed-string "\\|" org-clock-string
3389 "\\)\\>\\)")
3391 (org-compute-latex-and-specials-regexp)
3392 (org-set-font-lock-defaults))))
3394 (defun org-file-contents (file &optional noerror)
3395 "Return the contents of FILE, as a string."
3396 (if (or (not file)
3397 (not (file-readable-p file)))
3398 (if noerror
3399 (progn
3400 (message "Cannot read file %s" file)
3401 (ding) (sit-for 2)
3403 (error "Cannot read file %s" file))
3404 (with-temp-buffer
3405 (insert-file-contents file)
3406 (buffer-string))))
3408 (defun org-extract-log-state-settings (x)
3409 "Extract the log state setting from a TODO keyword string.
3410 This will extract info from a string like \"WAIT(w@/!)\"."
3411 (let (kw key log1 log2)
3412 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3413 (setq kw (match-string 1 x)
3414 key (and (match-end 2) (match-string 2 x))
3415 log1 (and (match-end 3) (match-string 3 x))
3416 log2 (and (match-end 4) (match-string 4 x)))
3417 (and (or log1 log2)
3418 (list kw
3419 (and log1 (if (equal log1 "!") 'time 'note))
3420 (and log2 (if (equal log2 "!") 'time 'note)))))))
3422 (defun org-remove-keyword-keys (list)
3423 "Remove a pair of parenthesis at the end of each string in LIST."
3424 (mapcar (lambda (x)
3425 (if (string-match "(.*)$" x)
3426 (substring x 0 (match-beginning 0))
3428 list))
3430 ;; FIXME: this could be done much better, using second characters etc.
3431 (defun org-assign-fast-keys (alist)
3432 "Assign fast keys to a keyword-key alist.
3433 Respect keys that are already there."
3434 (let (new e k c c1 c2 (char ?a))
3435 (while (setq e (pop alist))
3436 (cond
3437 ((equal e '(:startgroup)) (push e new))
3438 ((equal e '(:endgroup)) (push e new))
3440 (setq k (car e) c2 nil)
3441 (if (cdr e)
3442 (setq c (cdr e))
3443 ;; automatically assign a character.
3444 (setq c1 (string-to-char
3445 (downcase (substring
3446 k (if (= (string-to-char k) ?@) 1 0)))))
3447 (if (or (rassoc c1 new) (rassoc c1 alist))
3448 (while (or (rassoc char new) (rassoc char alist))
3449 (setq char (1+ char)))
3450 (setq c2 c1))
3451 (setq c (or c2 char)))
3452 (push (cons k c) new))))
3453 (nreverse new)))
3455 ;;; Some variables used in various places
3457 (defvar org-window-configuration nil
3458 "Used in various places to store a window configuration.")
3459 (defvar org-finish-function nil
3460 "Function to be called when `C-c C-c' is used.
3461 This is for getting out of special buffers like remember.")
3464 ;; FIXME: Occasionally check by commenting these, to make sure
3465 ;; no other functions uses these, forgetting to let-bind them.
3466 (defvar entry)
3467 (defvar state)
3468 (defvar last-state)
3469 (defvar date)
3470 (defvar description)
3472 ;; Defined somewhere in this file, but used before definition.
3473 (defvar org-html-entities)
3474 (defvar org-struct-menu)
3475 (defvar org-org-menu)
3476 (defvar org-tbl-menu)
3477 (defvar org-agenda-keymap)
3479 ;;;; Define the Org-mode
3481 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3482 (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."))
3485 ;; We use a before-change function to check if a table might need
3486 ;; an update.
3487 (defvar org-table-may-need-update t
3488 "Indicates that a table might need an update.
3489 This variable is set by `org-before-change-function'.
3490 `org-table-align' sets it back to nil.")
3491 (defun org-before-change-function (beg end)
3492 "Every change indicates that a table might need an update."
3493 (setq org-table-may-need-update t))
3494 (defvar org-mode-map)
3495 (defvar org-mode-hook nil
3496 "Mode hook for Org-mode, run after the mode was turned on.")
3497 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3498 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3499 (defvar org-table-buffer-is-an nil)
3500 (defconst org-outline-regexp "\\*+ ")
3502 ;;;###autoload
3503 (define-derived-mode org-mode outline-mode "Org"
3504 "Outline-based notes management and organizer, alias
3505 \"Carsten's outline-mode for keeping track of everything.\"
3507 Org-mode develops organizational tasks around a NOTES file which
3508 contains information about projects as plain text. Org-mode is
3509 implemented on top of outline-mode, which is ideal to keep the content
3510 of large files well structured. It supports ToDo items, deadlines and
3511 time stamps, which magically appear in the diary listing of the Emacs
3512 calendar. Tables are easily created with a built-in table editor.
3513 Plain text URL-like links connect to websites, emails (VM), Usenet
3514 messages (Gnus), BBDB entries, and any files related to the project.
3515 For printing and sharing of notes, an Org-mode file (or a part of it)
3516 can be exported as a structured ASCII or HTML file.
3518 The following commands are available:
3520 \\{org-mode-map}"
3522 ;; Get rid of Outline menus, they are not needed
3523 ;; Need to do this here because define-derived-mode sets up
3524 ;; the keymap so late. Still, it is a waste to call this each time
3525 ;; we switch another buffer into org-mode.
3526 (if (featurep 'xemacs)
3527 (when (boundp 'outline-mode-menu-heading)
3528 ;; Assume this is Greg's port, it used easymenu
3529 (easy-menu-remove outline-mode-menu-heading)
3530 (easy-menu-remove outline-mode-menu-show)
3531 (easy-menu-remove outline-mode-menu-hide))
3532 (define-key org-mode-map [menu-bar headings] 'undefined)
3533 (define-key org-mode-map [menu-bar hide] 'undefined)
3534 (define-key org-mode-map [menu-bar show] 'undefined))
3536 (org-load-modules-maybe)
3537 (easy-menu-add org-org-menu)
3538 (easy-menu-add org-tbl-menu)
3539 (org-install-agenda-files-menu)
3540 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3541 (org-add-to-invisibility-spec '(org-cwidth))
3542 (when (featurep 'xemacs)
3543 (org-set-local 'line-move-ignore-invisible t))
3544 (org-set-local 'outline-regexp org-outline-regexp)
3545 (org-set-local 'outline-level 'org-outline-level)
3546 (when (and org-ellipsis
3547 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3548 (fboundp 'make-glyph-code))
3549 (unless org-display-table
3550 (setq org-display-table (make-display-table)))
3551 (set-display-table-slot
3552 org-display-table 4
3553 (vconcat (mapcar
3554 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3555 org-ellipsis)))
3556 (if (stringp org-ellipsis) org-ellipsis "..."))))
3557 (setq buffer-display-table org-display-table))
3558 (org-set-regexps-and-options)
3559 (when (and org-tag-faces (not org-tags-special-faces-re))
3560 ;; tag faces set outside customize.... force initialization.
3561 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3562 ;; Calc embedded
3563 (org-set-local 'calc-embedded-open-mode "# ")
3564 (modify-syntax-entry ?# "<")
3565 (modify-syntax-entry ?@ "w")
3566 (if org-startup-truncated (setq truncate-lines t))
3567 (org-set-local 'font-lock-unfontify-region-function
3568 'org-unfontify-region)
3569 ;; Activate before-change-function
3570 (org-set-local 'org-table-may-need-update t)
3571 (org-add-hook 'before-change-functions 'org-before-change-function nil
3572 'local)
3573 ;; Check for running clock before killing a buffer
3574 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3575 ;; Paragraphs and auto-filling
3576 (org-set-autofill-regexps)
3577 (setq indent-line-function 'org-indent-line-function)
3578 (org-update-radio-target-regexp)
3580 ;; Comment characters
3581 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3582 (org-set-local 'comment-padding " ")
3584 ;; Align options lines
3585 (org-set-local
3586 'align-mode-rules-list
3587 '((org-in-buffer-settings
3588 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3589 (modes . '(org-mode)))))
3591 ;; Imenu
3592 (org-set-local 'imenu-create-index-function
3593 'org-imenu-get-tree)
3595 ;; Make isearch reveal context
3596 (if (or (featurep 'xemacs)
3597 (not (boundp 'outline-isearch-open-invisible-function)))
3598 ;; Emacs 21 and XEmacs make use of the hook
3599 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3600 ;; Emacs 22 deals with this through a special variable
3601 (org-set-local 'outline-isearch-open-invisible-function
3602 (lambda (&rest ignore) (org-show-context 'isearch))))
3604 ;; If empty file that did not turn on org-mode automatically, make it to.
3605 (if (and org-insert-mode-line-in-empty-file
3606 (interactive-p)
3607 (= (point-min) (point-max)))
3608 (insert "# -*- mode: org -*-\n\n"))
3610 (unless org-inhibit-startup
3611 (when org-startup-align-all-tables
3612 (let ((bmp (buffer-modified-p)))
3613 (org-table-map-tables 'org-table-align)
3614 (set-buffer-modified-p bmp)))
3615 (org-set-startup-visibility)))
3617 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3619 (defun org-current-time ()
3620 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3621 (if (> (car org-time-stamp-rounding-minutes) 1)
3622 (let ((r (car org-time-stamp-rounding-minutes))
3623 (time (decode-time)))
3624 (apply 'encode-time
3625 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3626 (nthcdr 2 time))))
3627 (current-time)))
3629 ;;;; Font-Lock stuff, including the activators
3631 (defvar org-mouse-map (make-sparse-keymap))
3632 (org-defkey org-mouse-map
3633 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3634 (org-defkey org-mouse-map
3635 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3636 (when org-mouse-1-follows-link
3637 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3638 (when org-tab-follows-link
3639 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3640 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3641 (when org-return-follows-link
3642 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3643 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3645 (require 'font-lock)
3647 (defconst org-non-link-chars "]\t\n\r<>")
3648 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3649 "shell" "elisp"))
3650 (defvar org-link-types-re nil
3651 "Matches a link that has a url-like prefix like \"http:\"")
3652 (defvar org-link-re-with-space nil
3653 "Matches a link with spaces, optional angular brackets around it.")
3654 (defvar org-link-re-with-space2 nil
3655 "Matches a link with spaces, optional angular brackets around it.")
3656 (defvar org-link-re-with-space3 nil
3657 "Matches a link with spaces, only for internal part in bracket links.")
3658 (defvar org-angle-link-re nil
3659 "Matches link with angular brackets, spaces are allowed.")
3660 (defvar org-plain-link-re nil
3661 "Matches plain link, without spaces.")
3662 (defvar org-bracket-link-regexp nil
3663 "Matches a link in double brackets.")
3664 (defvar org-bracket-link-analytic-regexp nil
3665 "Regular expression used to analyze links.
3666 Here is what the match groups contain after a match:
3667 1: http:
3668 2: http
3669 3: path
3670 4: [desc]
3671 5: desc")
3672 (defvar org-bracket-link-analytic-regexp++ nil
3673 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3674 (defvar org-any-link-re nil
3675 "Regular expression matching any link.")
3677 (defun org-make-link-regexps ()
3678 "Update the link regular expressions.
3679 This should be called after the variable `org-link-types' has changed."
3680 (setq org-link-types-re
3681 (concat
3682 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3683 org-link-re-with-space
3684 (concat
3685 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3686 "\\([^" org-non-link-chars " ]"
3687 "[^" org-non-link-chars "]*"
3688 "[^" org-non-link-chars " ]\\)>?")
3689 org-link-re-with-space2
3690 (concat
3691 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3692 "\\([^" org-non-link-chars " ]"
3693 "[^\t\n\r]*"
3694 "[^" org-non-link-chars " ]\\)>?")
3695 org-link-re-with-space3
3696 (concat
3697 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3698 "\\([^" org-non-link-chars " ]"
3699 "[^\t\n\r]*\\)")
3700 org-angle-link-re
3701 (concat
3702 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3703 "\\([^" org-non-link-chars " ]"
3704 "[^" org-non-link-chars "]*"
3705 "\\)>")
3706 org-plain-link-re
3707 (concat
3708 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3709 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3710 org-bracket-link-regexp
3711 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3712 org-bracket-link-analytic-regexp
3713 (concat
3714 "\\[\\["
3715 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3716 "\\([^]]+\\)"
3717 "\\]"
3718 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3719 "\\]")
3720 org-bracket-link-analytic-regexp++
3721 (concat
3722 "\\[\\["
3723 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3724 "\\([^]]+\\)"
3725 "\\]"
3726 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3727 "\\]")
3728 org-any-link-re
3729 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3730 org-angle-link-re "\\)\\|\\("
3731 org-plain-link-re "\\)")))
3733 (org-make-link-regexps)
3735 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3736 "Regular expression for fast time stamp matching.")
3737 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3738 "Regular expression for fast time stamp matching.")
3739 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3740 "Regular expression matching time strings for analysis.
3741 This one does not require the space after the date, so it can be used
3742 on a string that terminates immediately after the date.")
3743 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3744 "Regular expression matching time strings for analysis.")
3745 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3746 "Regular expression matching time stamps, with groups.")
3747 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3748 "Regular expression matching time stamps (also [..]), with groups.")
3749 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3750 "Regular expression matching a time stamp range.")
3751 (defconst org-tr-regexp-both
3752 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3753 "Regular expression matching a time stamp range.")
3754 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3755 org-ts-regexp "\\)?")
3756 "Regular expression matching a time stamp or time stamp range.")
3757 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3758 org-ts-regexp-both "\\)?")
3759 "Regular expression matching a time stamp or time stamp range.
3760 The time stamps may be either active or inactive.")
3762 (defvar org-emph-face nil)
3764 (defun org-do-emphasis-faces (limit)
3765 "Run through the buffer and add overlays to links."
3766 (let (rtn)
3767 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3768 (if (not (= (char-after (match-beginning 3))
3769 (char-after (match-beginning 4))))
3770 (progn
3771 (setq rtn t)
3772 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3773 'face
3774 (nth 1 (assoc (match-string 3)
3775 org-emphasis-alist)))
3776 (add-text-properties (match-beginning 2) (match-end 2)
3777 '(font-lock-multiline t))
3778 (when org-hide-emphasis-markers
3779 (add-text-properties (match-end 4) (match-beginning 5)
3780 '(invisible org-link))
3781 (add-text-properties (match-beginning 3) (match-end 3)
3782 '(invisible org-link)))))
3783 (backward-char 1))
3784 rtn))
3786 (defun org-emphasize (&optional char)
3787 "Insert or change an emphasis, i.e. a font like bold or italic.
3788 If there is an active region, change that region to a new emphasis.
3789 If there is no region, just insert the marker characters and position
3790 the cursor between them.
3791 CHAR should be either the marker character, or the first character of the
3792 HTML tag associated with that emphasis. If CHAR is a space, the means
3793 to remove the emphasis of the selected region.
3794 If char is not given (for example in an interactive call) it
3795 will be prompted for."
3796 (interactive)
3797 (let ((eal org-emphasis-alist) e det
3798 (erc org-emphasis-regexp-components)
3799 (prompt "")
3800 (string "") beg end move tag c s)
3801 (if (org-region-active-p)
3802 (setq beg (region-beginning) end (region-end)
3803 string (buffer-substring beg end))
3804 (setq move t))
3806 (while (setq e (pop eal))
3807 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3808 c (aref tag 0))
3809 (push (cons c (string-to-char (car e))) det)
3810 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3811 (substring tag 1)))))
3812 (setq det (nreverse det))
3813 (unless char
3814 (message "%s" (concat "Emphasis marker or tag:" prompt))
3815 (setq char (read-char-exclusive)))
3816 (setq char (or (cdr (assoc char det)) char))
3817 (if (equal char ?\ )
3818 (setq s "" move nil)
3819 (unless (assoc (char-to-string char) org-emphasis-alist)
3820 (error "No such emphasis marker: \"%c\"" char))
3821 (setq s (char-to-string char)))
3822 (while (and (> (length string) 1)
3823 (equal (substring string 0 1) (substring string -1))
3824 (assoc (substring string 0 1) org-emphasis-alist))
3825 (setq string (substring string 1 -1)))
3826 (setq string (concat s string s))
3827 (if beg (delete-region beg end))
3828 (unless (or (bolp)
3829 (string-match (concat "[" (nth 0 erc) "\n]")
3830 (char-to-string (char-before (point)))))
3831 (insert " "))
3832 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3833 (char-to-string (char-after (point))))
3834 (insert " ") (backward-char 1))
3835 (insert string)
3836 (and move (backward-char 1))))
3838 (defconst org-nonsticky-props
3839 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3842 (defun org-activate-plain-links (limit)
3843 "Run through the buffer and add overlays to links."
3844 (catch 'exit
3845 (let (f)
3846 (while (re-search-forward org-plain-link-re limit t)
3847 (setq f (get-text-property (match-beginning 0) 'face))
3848 (if (or (eq f 'org-tag)
3849 (and (listp f) (memq 'org-tag f)))
3851 (add-text-properties (match-beginning 0) (match-end 0)
3852 (list 'mouse-face 'highlight
3853 'rear-nonsticky org-nonsticky-props
3854 'keymap org-mouse-map
3856 (throw 'exit t))))))
3858 (defun org-activate-code (limit)
3859 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3860 (progn
3861 (remove-text-properties (match-beginning 0) (match-end 0)
3862 '(display t invisible t intangible t))
3863 t)))
3865 (defun org-activate-angle-links (limit)
3866 "Run through the buffer and add overlays to links."
3867 (if (re-search-forward org-angle-link-re limit t)
3868 (progn
3869 (add-text-properties (match-beginning 0) (match-end 0)
3870 (list 'mouse-face 'highlight
3871 'rear-nonsticky org-nonsticky-props
3872 'keymap org-mouse-map
3874 t)))
3876 (defun org-activate-footnote-links (limit)
3877 "Run through the buffer and add overlays to links."
3878 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3879 limit t)
3880 (progn
3881 (add-text-properties (match-beginning 2) (match-end 2)
3882 (list 'mouse-face 'highlight
3883 'rear-nonsticky org-nonsticky-props
3884 'keymap org-mouse-map
3885 'help-echo
3886 (if (= (point-at-bol) (match-beginning 2))
3887 "Footnote definition"
3888 "Footnote reference")
3890 t)))
3892 (defun org-activate-bracket-links (limit)
3893 "Run through the buffer and add overlays to bracketed links."
3894 (if (re-search-forward org-bracket-link-regexp limit t)
3895 (let* ((help (concat "LINK: "
3896 (org-match-string-no-properties 1)))
3897 ;; FIXME: above we should remove the escapes.
3898 ;; but that requires another match, protecting match data,
3899 ;; a lot of overhead for font-lock.
3900 (ip (org-maybe-intangible
3901 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3902 'keymap org-mouse-map 'mouse-face 'highlight
3903 'font-lock-multiline t 'help-echo help)))
3904 (vp (list 'rear-nonsticky org-nonsticky-props
3905 'keymap org-mouse-map 'mouse-face 'highlight
3906 ' font-lock-multiline t 'help-echo help)))
3907 ;; We need to remove the invisible property here. Table narrowing
3908 ;; may have made some of this invisible.
3909 (remove-text-properties (match-beginning 0) (match-end 0)
3910 '(invisible nil))
3911 (if (match-end 3)
3912 (progn
3913 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3914 (add-text-properties (match-beginning 3) (match-end 3) vp)
3915 (add-text-properties (match-end 3) (match-end 0) ip))
3916 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3917 (add-text-properties (match-beginning 1) (match-end 1) vp)
3918 (add-text-properties (match-end 1) (match-end 0) ip))
3919 t)))
3921 (defun org-activate-dates (limit)
3922 "Run through the buffer and add overlays to dates."
3923 (if (re-search-forward org-tsr-regexp-both limit t)
3924 (progn
3925 (add-text-properties (match-beginning 0) (match-end 0)
3926 (list 'mouse-face 'highlight
3927 'rear-nonsticky org-nonsticky-props
3928 'keymap org-mouse-map))
3929 (when org-display-custom-times
3930 (if (match-end 3)
3931 (org-display-custom-time (match-beginning 3) (match-end 3)))
3932 (org-display-custom-time (match-beginning 1) (match-end 1)))
3933 t)))
3935 (defvar org-target-link-regexp nil
3936 "Regular expression matching radio targets in plain text.")
3937 (make-variable-buffer-local 'org-target-link-regexp)
3938 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3939 "Regular expression matching a link target.")
3940 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3941 "Regular expression matching a radio target.")
3942 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3943 "Regular expression matching any target.")
3945 (defun org-activate-target-links (limit)
3946 "Run through the buffer and add overlays to target matches."
3947 (when org-target-link-regexp
3948 (let ((case-fold-search t))
3949 (if (re-search-forward org-target-link-regexp limit t)
3950 (progn
3951 (add-text-properties (match-beginning 0) (match-end 0)
3952 (list 'mouse-face 'highlight
3953 'rear-nonsticky org-nonsticky-props
3954 'keymap org-mouse-map
3955 'help-echo "Radio target link"
3956 'org-linked-text t))
3957 t)))))
3959 (defun org-update-radio-target-regexp ()
3960 "Find all radio targets in this file and update the regular expression."
3961 (interactive)
3962 (when (memq 'radio org-activate-links)
3963 (setq org-target-link-regexp
3964 (org-make-target-link-regexp (org-all-targets 'radio)))
3965 (org-restart-font-lock)))
3967 (defun org-hide-wide-columns (limit)
3968 (let (s e)
3969 (setq s (text-property-any (point) (or limit (point-max))
3970 'org-cwidth t))
3971 (when s
3972 (setq e (next-single-property-change s 'org-cwidth))
3973 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3974 (goto-char e)
3975 t)))
3977 (defvar org-latex-and-specials-regexp nil
3978 "Regular expression for highlighting export special stuff.")
3979 (defvar org-match-substring-regexp)
3980 (defvar org-match-substring-with-braces-regexp)
3981 (defvar org-export-html-special-string-regexps)
3983 (defun org-compute-latex-and-specials-regexp ()
3984 "Compute regular expression for stuff treated specially by exporters."
3985 (if (not org-highlight-latex-fragments-and-specials)
3986 (org-set-local 'org-latex-and-specials-regexp nil)
3987 (require 'org-exp)
3988 (let*
3989 ((matchers (plist-get org-format-latex-options :matchers))
3990 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3991 org-latex-regexps)))
3992 (options (org-combine-plists (org-default-export-plist)
3993 (org-infile-export-plist)))
3994 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3995 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3996 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3997 (org-export-html-expand (plist-get options :expand-quoted-html))
3998 (org-export-with-special-strings (plist-get options :special-strings))
3999 (re-sub
4000 (cond
4001 ((equal org-export-with-sub-superscripts '{})
4002 (list org-match-substring-with-braces-regexp))
4003 (org-export-with-sub-superscripts
4004 (list org-match-substring-regexp))
4005 (t nil)))
4006 (re-latex
4007 (if org-export-with-LaTeX-fragments
4008 (mapcar (lambda (x) (nth 1 x)) latexs)))
4009 (re-macros
4010 (if org-export-with-TeX-macros
4011 (list (concat "\\\\"
4012 (regexp-opt
4013 (append (mapcar 'car org-html-entities)
4014 (if (boundp 'org-latex-entities)
4015 org-latex-entities nil))
4016 'words))) ; FIXME
4018 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4019 (re-special (if org-export-with-special-strings
4020 (mapcar (lambda (x) (car x))
4021 org-export-html-special-string-regexps)))
4022 (re-rest
4023 (delq nil
4024 (list
4025 (if org-export-html-expand "@<[^>\n]+>")
4026 ))))
4027 (org-set-local
4028 'org-latex-and-specials-regexp
4029 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4030 re-rest) "\\|")))))
4032 (defun org-do-latex-and-special-faces (limit)
4033 "Run through the buffer and add overlays to links."
4034 (when org-latex-and-specials-regexp
4035 (let (rtn d)
4036 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4037 limit t))
4038 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4039 'face))
4040 '(org-code org-verbatim underline)))
4041 (progn
4042 (setq rtn t
4043 d (cond ((member (char-after (1+ (match-beginning 0)))
4044 '(?_ ?^)) 1)
4045 (t 0)))
4046 (font-lock-prepend-text-property
4047 (+ d (match-beginning 0)) (match-end 0)
4048 'face 'org-latex-and-export-specials)
4049 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4050 '(font-lock-multiline t)))))
4051 rtn)))
4053 (defun org-restart-font-lock ()
4054 "Restart font-lock-mode, to force refontification."
4055 (when (and (boundp 'font-lock-mode) font-lock-mode)
4056 (font-lock-mode -1)
4057 (font-lock-mode 1)))
4059 (defun org-all-targets (&optional radio)
4060 "Return a list of all targets in this file.
4061 With optional argument RADIO, only find radio targets."
4062 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4063 rtn)
4064 (save-excursion
4065 (goto-char (point-min))
4066 (while (re-search-forward re nil t)
4067 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4068 rtn)))
4070 (defun org-make-target-link-regexp (targets)
4071 "Make regular expression matching all strings in TARGETS.
4072 The regular expression finds the targets also if there is a line break
4073 between words."
4074 (and targets
4075 (concat
4076 "\\<\\("
4077 (mapconcat
4078 (lambda (x)
4079 (while (string-match " +" x)
4080 (setq x (replace-match "\\s-+" t t x)))
4082 targets
4083 "\\|")
4084 "\\)\\>")))
4086 (defun org-activate-tags (limit)
4087 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4088 (progn
4089 (add-text-properties (match-beginning 1) (match-end 1)
4090 (list 'mouse-face 'highlight
4091 'rear-nonsticky org-nonsticky-props
4092 'keymap org-mouse-map))
4093 t)))
4095 (defun org-outline-level ()
4096 (save-excursion
4097 (looking-at outline-regexp)
4098 (if (match-beginning 1)
4099 (+ (org-get-string-indentation (match-string 1)) 1000)
4100 (1- (- (match-end 0) (match-beginning 0))))))
4102 (defvar org-font-lock-keywords nil)
4104 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4105 "Regular expression matching a property line.")
4107 (defvar org-font-lock-hook nil
4108 "Functions to be called for special font lock stuff.")
4110 (defun org-font-lock-hook (limit)
4111 (run-hook-with-args 'org-font-lock-hook limit))
4113 (defun org-set-font-lock-defaults ()
4114 (let* ((em org-fontify-emphasized-text)
4115 (lk org-activate-links)
4116 (org-font-lock-extra-keywords
4117 (list
4118 ;; Call the hook
4119 '(org-font-lock-hook)
4120 ;; Headlines
4121 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4122 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4123 ;; Table lines
4124 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4125 (1 'org-table t))
4126 ;; Table internals
4127 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4128 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4129 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4130 ;; Drawers
4131 (list org-drawer-regexp '(0 'org-special-keyword t))
4132 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4133 ;; Properties
4134 (list org-property-re
4135 '(1 'org-special-keyword t)
4136 '(3 'org-property-value t))
4137 (if org-format-transports-properties-p
4138 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4139 ;; Links
4140 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4141 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4142 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4143 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4144 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4145 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4146 (if (memq 'footnote lk) '(org-activate-footnote-links
4147 (2 'org-footnote t)))
4148 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4149 '(org-hide-wide-columns (0 nil append))
4150 ;; TODO lines
4151 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4152 '(1 (org-get-todo-face 1) t))
4153 ;; DONE
4154 (if org-fontify-done-headline
4155 (list (concat "^[*]+ +\\<\\("
4156 (mapconcat 'regexp-quote org-done-keywords "\\|")
4157 "\\)\\(.*\\)")
4158 '(2 'org-headline-done t))
4159 nil)
4160 ;; Priorities
4161 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4162 ;; Tags
4163 '(org-font-lock-add-tag-faces)
4164 ;; Special keywords
4165 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4166 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4167 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4168 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4169 ;; Emphasis
4170 (if em
4171 (if (featurep 'xemacs)
4172 '(org-do-emphasis-faces (0 nil append))
4173 '(org-do-emphasis-faces)))
4174 ;; Checkboxes
4175 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4176 2 'bold prepend)
4177 (if org-provide-checkbox-statistics
4178 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4179 (0 (org-get-checkbox-statistics-face) t)))
4180 ;; Description list items
4181 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4182 2 'bold prepend)
4183 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4184 '(1 'org-archived prepend))
4185 ;; Specials
4186 '(org-do-latex-and-special-faces)
4187 ;; Code
4188 '(org-activate-code (1 'org-code t))
4189 ;; COMMENT
4190 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4191 "\\|" org-quote-string "\\)\\>")
4192 '(1 'org-special-keyword t))
4193 '("^#.*" (0 'font-lock-comment-face t))
4195 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4196 ;; Now set the full font-lock-keywords
4197 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4198 (org-set-local 'font-lock-defaults
4199 '(org-font-lock-keywords t nil nil backward-paragraph))
4200 (kill-local-variable 'font-lock-keywords) nil))
4202 (defvar org-m nil)
4203 (defvar org-l nil)
4204 (defvar org-f nil)
4205 (defun org-get-level-face (n)
4206 "Get the right face for match N in font-lock matching of headlines."
4207 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4208 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4209 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4210 (cond
4211 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4212 ((eq n 2) org-f)
4213 (t (if org-level-color-stars-only nil org-f))))
4215 (defun org-get-todo-face (kwd)
4216 "Get the right face for a TODO keyword KWD.
4217 If KWD is a number, get the corresponding match group."
4218 (if (numberp kwd) (setq kwd (match-string kwd)))
4219 (or (cdr (assoc kwd org-todo-keyword-faces))
4220 (and (member kwd org-done-keywords) 'org-done)
4221 'org-todo))
4223 (defun org-font-lock-add-tag-faces (limit)
4224 "Add the special tag faces."
4225 (when (and org-tag-faces org-tags-special-faces-re)
4226 (while (re-search-forward org-tags-special-faces-re limit t)
4227 (add-text-properties (match-beginning 1) (match-end 1)
4228 (list 'face (org-get-tag-face 1)
4229 'font-lock-fontified t))
4230 (backward-char 1))))
4232 (defun org-get-tag-face (kwd)
4233 "Get the right face for a TODO keyword KWD.
4234 If KWD is a number, get the corresponding match group."
4235 (if (numberp kwd) (setq kwd (match-string kwd)))
4236 (or (cdr (assoc kwd org-tag-faces))
4237 'org-tag))
4239 (defun org-unfontify-region (beg end &optional maybe_loudly)
4240 "Remove fontification and activation overlays from links."
4241 (font-lock-default-unfontify-region beg end)
4242 (let* ((buffer-undo-list t)
4243 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4244 (inhibit-modification-hooks t)
4245 deactivate-mark buffer-file-name buffer-file-truename)
4246 (remove-text-properties beg end
4247 '(mouse-face t keymap t org-linked-text t
4248 invisible t intangible t))))
4250 ;;;; Visibility cycling, including org-goto and indirect buffer
4252 ;;; Cycling
4254 (defvar org-cycle-global-status nil)
4255 (make-variable-buffer-local 'org-cycle-global-status)
4256 (defvar org-cycle-subtree-status nil)
4257 (make-variable-buffer-local 'org-cycle-subtree-status)
4259 ;;;###autoload
4260 (defun org-cycle (&optional arg)
4261 "Visibility cycling for Org-mode.
4263 - When this function is called with a prefix argument, rotate the entire
4264 buffer through 3 states (global cycling)
4265 1. OVERVIEW: Show only top-level headlines.
4266 2. CONTENTS: Show all headlines of all levels, but no body text.
4267 3. SHOW ALL: Show everything.
4268 When called with two C-u C-u prefixes, switch to the startup visibility,
4269 determined by the variable `org-startup-folded', and by any VISIBILITY
4270 properties in the buffer.
4271 When called with three C-u C-u C-u prefixed, show the entire buffer,
4272 including drawers.
4274 - When point is at the beginning of a headline, rotate the subtree started
4275 by this line through 3 different states (local cycling)
4276 1. FOLDED: Only the main headline is shown.
4277 2. CHILDREN: The main headline and the direct children are shown.
4278 From this state, you can move to one of the children
4279 and zoom in further.
4280 3. SUBTREE: Show the entire subtree, including body text.
4282 - When there is a numeric prefix, go up to a heading with level ARG, do
4283 a `show-subtree' and return to the previous cursor position. If ARG
4284 is negative, go up that many levels.
4286 - When point is not at the beginning of a headline, execute the global
4287 binding for TAB, which is re-indenting the line. See the option
4288 `org-cycle-emulate-tab' for details.
4290 - Special case: if point is at the beginning of the buffer and there is
4291 no headline in line 1, this function will act as if called with prefix arg.
4292 But only if also the variable `org-cycle-global-at-bob' is t."
4293 (interactive "P")
4294 (org-load-modules-maybe)
4295 (let* ((outline-regexp
4296 (if (and (org-mode-p) org-cycle-include-plain-lists)
4297 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4298 outline-regexp))
4299 (bob-special (and org-cycle-global-at-bob (bobp)
4300 (not (looking-at outline-regexp))))
4301 (org-cycle-hook
4302 (if bob-special
4303 (delq 'org-optimize-window-after-visibility-change
4304 (copy-sequence org-cycle-hook))
4305 org-cycle-hook))
4306 (pos (point)))
4308 (if (or bob-special (equal arg '(4)))
4309 ;; special case: use global cycling
4310 (setq arg t))
4312 (cond
4314 ((equal arg '(16))
4315 (org-set-startup-visibility)
4316 (message "Startup visibility, plus VISIBILITY properties"))
4318 ((equal arg '(64))
4319 (show-all)
4320 (message "Entire buffer visible, including drawers"))
4322 ((org-at-table-p 'any)
4323 ;; Enter the table or move to the next field in the table
4324 (or (org-table-recognize-table.el)
4325 (progn
4326 (if arg (org-table-edit-field t)
4327 (org-table-justify-field-maybe)
4328 (call-interactively 'org-table-next-field)))))
4330 ((eq arg t) ;; Global cycling
4332 (cond
4333 ((and (eq last-command this-command)
4334 (eq org-cycle-global-status 'overview))
4335 ;; We just created the overview - now do table of contents
4336 ;; This can be slow in very large buffers, so indicate action
4337 (message "CONTENTS...")
4338 (org-content)
4339 (message "CONTENTS...done")
4340 (setq org-cycle-global-status 'contents)
4341 (run-hook-with-args 'org-cycle-hook 'contents))
4343 ((and (eq last-command this-command)
4344 (eq org-cycle-global-status 'contents))
4345 ;; We just showed the table of contents - now show everything
4346 (show-all)
4347 (message "SHOW ALL")
4348 (setq org-cycle-global-status 'all)
4349 (run-hook-with-args 'org-cycle-hook 'all))
4352 ;; Default action: go to overview
4353 (org-overview)
4354 (message "OVERVIEW")
4355 (setq org-cycle-global-status 'overview)
4356 (run-hook-with-args 'org-cycle-hook 'overview))))
4358 ((and org-drawers org-drawer-regexp
4359 (save-excursion
4360 (beginning-of-line 1)
4361 (looking-at org-drawer-regexp)))
4362 ;; Toggle block visibility
4363 (org-flag-drawer
4364 (not (get-char-property (match-end 0) 'invisible))))
4366 ((integerp arg)
4367 ;; Show-subtree, ARG levels up from here.
4368 (save-excursion
4369 (org-back-to-heading)
4370 (outline-up-heading (if (< arg 0) (- arg)
4371 (- (funcall outline-level) arg)))
4372 (org-show-subtree)))
4374 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4375 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4376 ;; At a heading: rotate between three different views
4377 (org-back-to-heading)
4378 (let ((goal-column 0) eoh eol eos)
4379 ;; First, some boundaries
4380 (save-excursion
4381 (org-back-to-heading)
4382 (save-excursion
4383 (beginning-of-line 2)
4384 (while (and (not (eobp)) ;; this is like `next-line'
4385 (get-char-property (1- (point)) 'invisible))
4386 (beginning-of-line 2)) (setq eol (point)))
4387 (outline-end-of-heading) (setq eoh (point))
4388 (org-end-of-subtree t)
4389 (unless (eobp)
4390 (skip-chars-forward " \t\n")
4391 (beginning-of-line 1) ; in case this is an item
4393 (setq eos (1- (point))))
4394 ;; Find out what to do next and set `this-command'
4395 (cond
4396 ((= eos eoh)
4397 ;; Nothing is hidden behind this heading
4398 (message "EMPTY ENTRY")
4399 (setq org-cycle-subtree-status nil)
4400 (save-excursion
4401 (goto-char eos)
4402 (outline-next-heading)
4403 (if (org-invisible-p) (org-flag-heading nil))))
4404 ((or (>= eol eos)
4405 (not (string-match "\\S-" (buffer-substring eol eos))))
4406 ;; Entire subtree is hidden in one line: open it
4407 (org-show-entry)
4408 (show-children)
4409 (message "CHILDREN")
4410 (save-excursion
4411 (goto-char eos)
4412 (outline-next-heading)
4413 (if (org-invisible-p) (org-flag-heading nil)))
4414 (setq org-cycle-subtree-status 'children)
4415 (run-hook-with-args 'org-cycle-hook 'children))
4416 ((and (eq last-command this-command)
4417 (eq org-cycle-subtree-status 'children))
4418 ;; We just showed the children, now show everything.
4419 (org-show-subtree)
4420 (message "SUBTREE")
4421 (setq org-cycle-subtree-status 'subtree)
4422 (run-hook-with-args 'org-cycle-hook 'subtree))
4424 ;; Default action: hide the subtree.
4425 (hide-subtree)
4426 (message "FOLDED")
4427 (setq org-cycle-subtree-status 'folded)
4428 (run-hook-with-args 'org-cycle-hook 'folded)))))
4430 ;; TAB emulation and template completion
4431 (buffer-read-only (org-back-to-heading))
4433 ((org-try-structure-completion))
4435 ((org-try-cdlatex-tab))
4437 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4438 (or (not (bolp))
4439 (not (looking-at outline-regexp))))
4440 (call-interactively (global-key-binding "\t")))
4442 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4443 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4444 (or (and (eq org-cycle-emulate-tab 'white)
4445 (= (match-end 0) (point-at-eol)))
4446 (and (eq org-cycle-emulate-tab 'whitestart)
4447 (>= (match-end 0) pos))))
4449 (eq org-cycle-emulate-tab t))
4450 (call-interactively (global-key-binding "\t")))
4452 (t (save-excursion
4453 (org-back-to-heading)
4454 (org-cycle))))))
4456 ;;;###autoload
4457 (defun org-global-cycle (&optional arg)
4458 "Cycle the global visibility. For details see `org-cycle'.
4459 With C-u prefix arg, switch to startup visibility.
4460 With a numeric prefix, show all headlines up to that level."
4461 (interactive "P")
4462 (let ((org-cycle-include-plain-lists
4463 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4464 (cond
4465 ((integerp arg)
4466 (show-all)
4467 (hide-sublevels arg)
4468 (setq org-cycle-global-status 'contents))
4469 ((equal arg '(4))
4470 (org-set-startup-visibility)
4471 (message "Startup visibility, plus VISIBILITY properties."))
4473 (org-cycle '(4))))))
4475 (defun org-set-startup-visibility ()
4476 "Set the visibility required by startup options and properties."
4477 (cond
4478 ((eq org-startup-folded t)
4479 (org-cycle '(4)))
4480 ((eq org-startup-folded 'content)
4481 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4482 (org-cycle '(4)) (org-cycle '(4)))))
4483 (org-set-visibility-according-to-property 'no-cleanup)
4484 (org-cycle-hide-archived-subtrees 'all)
4485 (org-cycle-hide-drawers 'all)
4486 (org-cycle-show-empty-lines 'all))
4488 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4489 "Switch subtree visibilities according to :VISIBILITY: property."
4490 (interactive)
4491 (let (org-show-entry-below state)
4492 (save-excursion
4493 (goto-char (point-min))
4494 (while (re-search-forward
4495 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4496 nil t)
4497 (setq state (match-string 1))
4498 (save-excursion
4499 (org-back-to-heading t)
4500 (hide-subtree)
4501 (org-reveal)
4502 (cond
4503 ((equal state '("fold" "folded"))
4504 (hide-subtree))
4505 ((equal state "children")
4506 (org-show-hidden-entry)
4507 (show-children))
4508 ((equal state "content")
4509 (save-excursion
4510 (save-restriction
4511 (org-narrow-to-subtree)
4512 (org-content))))
4513 ((member state '("all" "showall"))
4514 (show-subtree)))))
4515 (unless no-cleanup
4516 (org-cycle-hide-archived-subtrees 'all)
4517 (org-cycle-hide-drawers 'all)
4518 (org-cycle-show-empty-lines 'all)))))
4520 (defun org-overview ()
4521 "Switch to overview mode, showing only top-level headlines.
4522 Really, this shows all headlines with level equal or greater than the level
4523 of the first headline in the buffer. This is important, because if the
4524 first headline is not level one, then (hide-sublevels 1) gives confusing
4525 results."
4526 (interactive)
4527 (let ((level (save-excursion
4528 (goto-char (point-min))
4529 (if (re-search-forward (concat "^" outline-regexp) nil t)
4530 (progn
4531 (goto-char (match-beginning 0))
4532 (funcall outline-level))))))
4533 (and level (hide-sublevels level))))
4535 (defun org-content (&optional arg)
4536 "Show all headlines in the buffer, like a table of contents.
4537 With numerical argument N, show content up to level N."
4538 (interactive "P")
4539 (save-excursion
4540 ;; Visit all headings and show their offspring
4541 (and (integerp arg) (org-overview))
4542 (goto-char (point-max))
4543 (catch 'exit
4544 (while (and (progn (condition-case nil
4545 (outline-previous-visible-heading 1)
4546 (error (goto-char (point-min))))
4548 (looking-at outline-regexp))
4549 (if (integerp arg)
4550 (show-children (1- arg))
4551 (show-branches))
4552 (if (bobp) (throw 'exit nil))))))
4555 (defun org-optimize-window-after-visibility-change (state)
4556 "Adjust the window after a change in outline visibility.
4557 This function is the default value of the hook `org-cycle-hook'."
4558 (when (get-buffer-window (current-buffer))
4559 (cond
4560 ; ((eq state 'overview) (org-first-headline-recenter 1))
4561 ; ((eq state 'overview) (org-beginning-of-line))
4562 ((eq state 'content) nil)
4563 ((eq state 'all) nil)
4564 ((eq state 'folded) nil)
4565 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4566 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4568 (defun org-compact-display-after-subtree-move ()
4569 "Show a compacter version of the tree of the entry's parent."
4570 (save-excursion
4571 (if (org-up-heading-safe)
4572 (progn
4573 (hide-subtree)
4574 (show-entry)
4575 (show-children)
4576 (org-cycle-show-empty-lines 'children)
4577 (org-cycle-hide-drawers 'children))
4578 (org-overview))))
4580 (defun org-cycle-show-empty-lines (state)
4581 "Show empty lines above all visible headlines.
4582 The region to be covered depends on STATE when called through
4583 `org-cycle-hook'. Lisp program can use t for STATE to get the
4584 entire buffer covered. Note that an empty line is only shown if there
4585 are at least `org-cycle-separator-lines' empty lines before the headline."
4586 (when (> org-cycle-separator-lines 0)
4587 (save-excursion
4588 (let* ((n org-cycle-separator-lines)
4589 (re (cond
4590 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4591 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4592 (t (let ((ns (number-to-string (- n 2))))
4593 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4594 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4595 beg end)
4596 (cond
4597 ((memq state '(overview contents t))
4598 (setq beg (point-min) end (point-max)))
4599 ((memq state '(children folded))
4600 (setq beg (point) end (progn (org-end-of-subtree t t)
4601 (beginning-of-line 2)
4602 (point)))))
4603 (when beg
4604 (goto-char beg)
4605 (while (re-search-forward re end t)
4606 (if (not (get-char-property (match-end 1) 'invisible))
4607 (outline-flag-region
4608 (match-beginning 1) (match-end 1) nil)))))))
4609 ;; Never hide empty lines at the end of the file.
4610 (save-excursion
4611 (goto-char (point-max))
4612 (outline-previous-heading)
4613 (outline-end-of-heading)
4614 (if (and (looking-at "[ \t\n]+")
4615 (= (match-end 0) (point-max)))
4616 (outline-flag-region (point) (match-end 0) nil))))
4618 (defun org-show-empty-lines-in-parent ()
4619 "Move to the parent and re-show empty lines before visible headlines."
4620 (save-excursion
4621 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4622 (org-cycle-show-empty-lines context))))
4624 (defun org-cycle-hide-drawers (state)
4625 "Re-hide all drawers after a visibility state change."
4626 (when (and (org-mode-p)
4627 (not (memq state '(overview folded))))
4628 (save-excursion
4629 (let* ((globalp (memq state '(contents all)))
4630 (beg (if globalp (point-min) (point)))
4631 (end (if globalp (point-max) (org-end-of-subtree t))))
4632 (goto-char beg)
4633 (while (re-search-forward org-drawer-regexp end t)
4634 (org-flag-drawer t))))))
4636 (defun org-flag-drawer (flag)
4637 (save-excursion
4638 (beginning-of-line 1)
4639 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4640 (let ((b (match-end 0))
4641 (outline-regexp org-outline-regexp))
4642 (if (re-search-forward
4643 "^[ \t]*:END:"
4644 (save-excursion (outline-next-heading) (point)) t)
4645 (outline-flag-region b (point-at-eol) flag)
4646 (error ":END: line missing"))))))
4648 (defun org-subtree-end-visible-p ()
4649 "Is the end of the current subtree visible?"
4650 (pos-visible-in-window-p
4651 (save-excursion (org-end-of-subtree t) (point))))
4653 (defun org-first-headline-recenter (&optional N)
4654 "Move cursor to the first headline and recenter the headline.
4655 Optional argument N means, put the headline into the Nth line of the window."
4656 (goto-char (point-min))
4657 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4658 (beginning-of-line)
4659 (recenter (prefix-numeric-value N))))
4661 ;;; Org-goto
4663 (defvar org-goto-window-configuration nil)
4664 (defvar org-goto-marker nil)
4665 (defvar org-goto-map
4666 (let ((map (make-sparse-keymap)))
4667 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4668 (while (setq cmd (pop cmds))
4669 (substitute-key-definition cmd cmd map global-map)))
4670 (suppress-keymap map)
4671 (org-defkey map "\C-m" 'org-goto-ret)
4672 (org-defkey map [(return)] 'org-goto-ret)
4673 (org-defkey map [(left)] 'org-goto-left)
4674 (org-defkey map [(right)] 'org-goto-right)
4675 (org-defkey map [(control ?g)] 'org-goto-quit)
4676 (org-defkey map "\C-i" 'org-cycle)
4677 (org-defkey map [(tab)] 'org-cycle)
4678 (org-defkey map [(down)] 'outline-next-visible-heading)
4679 (org-defkey map [(up)] 'outline-previous-visible-heading)
4680 (if org-goto-auto-isearch
4681 (if (fboundp 'define-key-after)
4682 (define-key-after map [t] 'org-goto-local-auto-isearch)
4683 nil)
4684 (org-defkey map "q" 'org-goto-quit)
4685 (org-defkey map "n" 'outline-next-visible-heading)
4686 (org-defkey map "p" 'outline-previous-visible-heading)
4687 (org-defkey map "f" 'outline-forward-same-level)
4688 (org-defkey map "b" 'outline-backward-same-level)
4689 (org-defkey map "u" 'outline-up-heading))
4690 (org-defkey map "/" 'org-occur)
4691 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4692 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4693 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4694 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4695 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4696 map))
4698 (defconst org-goto-help
4699 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4700 RET=jump to location [Q]uit and return to previous location
4701 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4703 (defvar org-goto-start-pos) ; dynamically scoped parameter
4705 ;; FIXME: Docstring doe not mention both interfaces
4706 (defun org-goto (&optional alternative-interface)
4707 "Look up a different location in the current file, keeping current visibility.
4709 When you want look-up or go to a different location in a document, the
4710 fastest way is often to fold the entire buffer and then dive into the tree.
4711 This method has the disadvantage, that the previous location will be folded,
4712 which may not be what you want.
4714 This command works around this by showing a copy of the current buffer
4715 in an indirect buffer, in overview mode. You can dive into the tree in
4716 that copy, use org-occur and incremental search to find a location.
4717 When pressing RET or `Q', the command returns to the original buffer in
4718 which the visibility is still unchanged. After RET is will also jump to
4719 the location selected in the indirect buffer and expose the
4720 the headline hierarchy above."
4721 (interactive "P")
4722 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4723 (org-refile-use-outline-path t)
4724 (interface
4725 (if (not alternative-interface)
4726 org-goto-interface
4727 (if (eq org-goto-interface 'outline)
4728 'outline-path-completion
4729 'outline)))
4730 (org-goto-start-pos (point))
4731 (selected-point
4732 (if (eq interface 'outline)
4733 (car (org-get-location (current-buffer) org-goto-help))
4734 (nth 3 (org-refile-get-location "Goto: ")))))
4735 (if selected-point
4736 (progn
4737 (org-mark-ring-push org-goto-start-pos)
4738 (goto-char selected-point)
4739 (if (or (org-invisible-p) (org-invisible-p2))
4740 (org-show-context 'org-goto)))
4741 (message "Quit"))))
4743 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4744 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4745 (defvar org-goto-local-auto-isearch-map) ; defined below
4747 (defun org-get-location (buf help)
4748 "Let the user select a location in the Org-mode buffer BUF.
4749 This function uses a recursive edit. It returns the selected position
4750 or nil."
4751 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4752 (isearch-hide-immediately nil)
4753 (isearch-search-fun-function
4754 (lambda () 'org-goto-local-search-headings))
4755 (org-goto-selected-point org-goto-exit-command))
4756 (save-excursion
4757 (save-window-excursion
4758 (delete-other-windows)
4759 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4760 (switch-to-buffer
4761 (condition-case nil
4762 (make-indirect-buffer (current-buffer) "*org-goto*")
4763 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4764 (with-output-to-temp-buffer "*Help*"
4765 (princ help))
4766 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4767 (setq buffer-read-only nil)
4768 (let ((org-startup-truncated t)
4769 (org-startup-folded nil)
4770 (org-startup-align-all-tables nil))
4771 (org-mode)
4772 (org-overview))
4773 (setq buffer-read-only t)
4774 (if (and (boundp 'org-goto-start-pos)
4775 (integer-or-marker-p org-goto-start-pos))
4776 (let ((org-show-hierarchy-above t)
4777 (org-show-siblings t)
4778 (org-show-following-heading t))
4779 (goto-char org-goto-start-pos)
4780 (and (org-invisible-p) (org-show-context)))
4781 (goto-char (point-min)))
4782 (org-beginning-of-line)
4783 (message "Select location and press RET")
4784 (use-local-map org-goto-map)
4785 (recursive-edit)
4787 (kill-buffer "*org-goto*")
4788 (cons org-goto-selected-point org-goto-exit-command)))
4790 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4791 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4792 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4793 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4795 (defun org-goto-local-search-headings (string bound noerror)
4796 "Search and make sure that any matches are in headlines."
4797 (catch 'return
4798 (while (if isearch-forward
4799 (search-forward string bound noerror)
4800 (search-backward string bound noerror))
4801 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4802 (and (member :headline context)
4803 (not (member :tags context))))
4804 (throw 'return (point))))))
4806 (defun org-goto-local-auto-isearch ()
4807 "Start isearch."
4808 (interactive)
4809 (goto-char (point-min))
4810 (let ((keys (this-command-keys)))
4811 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4812 (isearch-mode t)
4813 (isearch-process-search-char (string-to-char keys)))))
4815 (defun org-goto-ret (&optional arg)
4816 "Finish `org-goto' by going to the new location."
4817 (interactive "P")
4818 (setq org-goto-selected-point (point)
4819 org-goto-exit-command 'return)
4820 (throw 'exit nil))
4822 (defun org-goto-left ()
4823 "Finish `org-goto' by going to the new location."
4824 (interactive)
4825 (if (org-on-heading-p)
4826 (progn
4827 (beginning-of-line 1)
4828 (setq org-goto-selected-point (point)
4829 org-goto-exit-command 'left)
4830 (throw 'exit nil))
4831 (error "Not on a heading")))
4833 (defun org-goto-right ()
4834 "Finish `org-goto' by going to the new location."
4835 (interactive)
4836 (if (org-on-heading-p)
4837 (progn
4838 (setq org-goto-selected-point (point)
4839 org-goto-exit-command 'right)
4840 (throw 'exit nil))
4841 (error "Not on a heading")))
4843 (defun org-goto-quit ()
4844 "Finish `org-goto' without cursor motion."
4845 (interactive)
4846 (setq org-goto-selected-point nil)
4847 (setq org-goto-exit-command 'quit)
4848 (throw 'exit nil))
4850 ;;; Indirect buffer display of subtrees
4852 (defvar org-indirect-dedicated-frame nil
4853 "This is the frame being used for indirect tree display.")
4854 (defvar org-last-indirect-buffer nil)
4856 (defun org-tree-to-indirect-buffer (&optional arg)
4857 "Create indirect buffer and narrow it to current subtree.
4858 With numerical prefix ARG, go up to this level and then take that tree.
4859 If ARG is negative, go up that many levels.
4860 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4861 indirect buffer previously made with this command, to avoid proliferation of
4862 indirect buffers. However, when you call the command with a `C-u' prefix, or
4863 when `org-indirect-buffer-display' is `new-frame', the last buffer
4864 is kept so that you can work with several indirect buffers at the same time.
4865 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4866 requests that a new frame be made for the new buffer, so that the dedicated
4867 frame is not changed."
4868 (interactive "P")
4869 (let ((cbuf (current-buffer))
4870 (cwin (selected-window))
4871 (pos (point))
4872 beg end level heading ibuf)
4873 (save-excursion
4874 (org-back-to-heading t)
4875 (when (numberp arg)
4876 (setq level (org-outline-level))
4877 (if (< arg 0) (setq arg (+ level arg)))
4878 (while (> (setq level (org-outline-level)) arg)
4879 (outline-up-heading 1 t)))
4880 (setq beg (point)
4881 heading (org-get-heading))
4882 (org-end-of-subtree t) (setq end (point)))
4883 (if (and (buffer-live-p org-last-indirect-buffer)
4884 (not (eq org-indirect-buffer-display 'new-frame))
4885 (not arg))
4886 (kill-buffer org-last-indirect-buffer))
4887 (setq ibuf (org-get-indirect-buffer cbuf)
4888 org-last-indirect-buffer ibuf)
4889 (cond
4890 ((or (eq org-indirect-buffer-display 'new-frame)
4891 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4892 (select-frame (make-frame))
4893 (delete-other-windows)
4894 (switch-to-buffer ibuf)
4895 (org-set-frame-title heading))
4896 ((eq org-indirect-buffer-display 'dedicated-frame)
4897 (raise-frame
4898 (select-frame (or (and org-indirect-dedicated-frame
4899 (frame-live-p org-indirect-dedicated-frame)
4900 org-indirect-dedicated-frame)
4901 (setq org-indirect-dedicated-frame (make-frame)))))
4902 (delete-other-windows)
4903 (switch-to-buffer ibuf)
4904 (org-set-frame-title (concat "Indirect: " heading)))
4905 ((eq org-indirect-buffer-display 'current-window)
4906 (switch-to-buffer ibuf))
4907 ((eq org-indirect-buffer-display 'other-window)
4908 (pop-to-buffer ibuf))
4909 (t (error "Invalid value.")))
4910 (if (featurep 'xemacs)
4911 (save-excursion (org-mode) (turn-on-font-lock)))
4912 (narrow-to-region beg end)
4913 (show-all)
4914 (goto-char pos)
4915 (and (window-live-p cwin) (select-window cwin))))
4917 (defun org-get-indirect-buffer (&optional buffer)
4918 (setq buffer (or buffer (current-buffer)))
4919 (let ((n 1) (base (buffer-name buffer)) bname)
4920 (while (buffer-live-p
4921 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4922 (setq n (1+ n)))
4923 (condition-case nil
4924 (make-indirect-buffer buffer bname 'clone)
4925 (error (make-indirect-buffer buffer bname)))))
4927 (defun org-set-frame-title (title)
4928 "Set the title of the current frame to the string TITLE."
4929 ;; FIXME: how to name a single frame in XEmacs???
4930 (unless (featurep 'xemacs)
4931 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4933 ;;;; Structure editing
4935 ;;; Inserting headlines
4937 (defun org-previous-line-empty-p ()
4938 (save-excursion
4939 (and (not (bobp))
4940 (or (beginning-of-line 0) t)
4941 (save-match-data
4942 (looking-at "[ \t]*$")))))
4944 (defun org-insert-heading (&optional force-heading)
4945 "Insert a new heading or item with same depth at point.
4946 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4947 If point is at the beginning of a headline, insert a sibling before the
4948 current headline. If point is not at the beginning, do not split the line,
4949 but create the new headline after the current line."
4950 (interactive "P")
4951 (if (= (buffer-size) 0)
4952 (insert "\n* ")
4953 (when (or force-heading (not (org-insert-item)))
4954 (let* ((empty-line-p nil)
4955 (head (save-excursion
4956 (condition-case nil
4957 (progn
4958 (org-back-to-heading)
4959 (setq empty-line-p (org-previous-line-empty-p))
4960 (match-string 0))
4961 (error "*"))))
4962 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4963 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4964 pos hide-previous previous-pos)
4965 (cond
4966 ((and (org-on-heading-p) (bolp)
4967 (or (bobp)
4968 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4969 ;; insert before the current line
4970 (open-line (if blank 2 1)))
4971 ((and (bolp)
4972 (or (bobp)
4973 (save-excursion
4974 (backward-char 1) (not (org-invisible-p)))))
4975 ;; insert right here
4976 nil)
4978 ;; somewhere in the line
4979 (save-excursion
4980 (setq previous-pos (point-at-bol))
4981 (end-of-line)
4982 (setq hide-previous (org-invisible-p)))
4983 (and org-insert-heading-respect-content (org-show-subtree))
4984 (let ((split
4985 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4986 (save-excursion
4987 (let ((p (point)))
4988 (goto-char (point-at-bol))
4989 (and (looking-at org-complex-heading-regexp)
4990 (> p (match-beginning 4)))))))
4991 tags pos)
4992 (cond
4993 (org-insert-heading-respect-content
4994 (org-end-of-subtree nil t)
4995 (or (bolp) (newline))
4996 (or (org-previous-line-empty-p)
4997 (and blank (newline)))
4998 (open-line 1))
4999 ((org-on-heading-p)
5000 (when hide-previous
5001 (show-children)
5002 (org-show-entry))
5003 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5004 (setq tags (and (match-end 2) (match-string 2)))
5005 (and (match-end 1)
5006 (delete-region (match-beginning 1) (match-end 1)))
5007 (setq pos (point-at-bol))
5008 (or split (end-of-line 1))
5009 (delete-horizontal-space)
5010 (newline (if blank 2 1))
5011 (when tags
5012 (save-excursion
5013 (goto-char pos)
5014 (end-of-line 1)
5015 (insert " " tags)
5016 (org-set-tags nil 'align))))
5018 (or split (end-of-line 1))
5019 (newline (if blank 2 1)))))))
5020 (insert head) (just-one-space)
5021 (setq pos (point))
5022 (end-of-line 1)
5023 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5024 (when (and org-insert-heading-respect-content hide-previous)
5025 (save-excursion
5026 (goto-char previous-pos)
5027 (hide-subtree)))
5028 (run-hooks 'org-insert-heading-hook)))))
5030 (defun org-get-heading (&optional no-tags)
5031 "Return the heading of the current entry, without the stars."
5032 (save-excursion
5033 (org-back-to-heading t)
5034 (if (looking-at
5035 (if no-tags
5036 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5037 "\\*+[ \t]+\\([^\r\n]*\\)"))
5038 (match-string 1) "")))
5040 (defun org-heading-components ()
5041 "Return the components of the current heading.
5042 This is a list with the following elements:
5043 - the level as an integer
5044 - the reduced level, different if `org-odd-levels-only' is set.
5045 - the TODO keyword, or nil
5046 - the priority character, like ?A, or nil if no priority is given
5047 - the headline text itself, or the tags string if no headline text
5048 - the tags string, or nil."
5049 (save-excursion
5050 (org-back-to-heading t)
5051 (if (looking-at org-complex-heading-regexp)
5052 (list (length (match-string 1))
5053 (org-reduced-level (length (match-string 1)))
5054 (org-match-string-no-properties 2)
5055 (and (match-end 3) (aref (match-string 3) 2))
5056 (org-match-string-no-properties 4)
5057 (org-match-string-no-properties 5)))))
5059 (defun org-insert-heading-after-current ()
5060 "Insert a new heading with same level as current, after current subtree."
5061 (interactive)
5062 (org-back-to-heading)
5063 (org-insert-heading)
5064 (org-move-subtree-down)
5065 (end-of-line 1))
5067 (defun org-insert-heading-respect-content ()
5068 (interactive)
5069 (let ((org-insert-heading-respect-content t))
5070 (org-insert-heading t)))
5072 (defun org-insert-todo-heading-respect-content (&optional force-state)
5073 (interactive "P")
5074 (let ((org-insert-heading-respect-content t))
5075 (org-insert-todo-heading force-state t)))
5077 (defun org-insert-todo-heading (arg &optional force-heading)
5078 "Insert a new heading with the same level and TODO state as current heading.
5079 If the heading has no TODO state, or if the state is DONE, use the first
5080 state (TODO by default). Also with prefix arg, force first state."
5081 (interactive "P")
5082 (when (or force-heading (not (org-insert-item 'checkbox)))
5083 (org-insert-heading force-heading)
5084 (save-excursion
5085 (org-back-to-heading)
5086 (outline-previous-heading)
5087 (looking-at org-todo-line-regexp))
5088 (if (or arg
5089 (not (match-beginning 2))
5090 (member (match-string 2) org-done-keywords))
5091 (insert (car org-todo-keywords-1) " ")
5092 (insert (match-string 2) " "))
5093 (when org-provide-todo-statistics
5094 (org-update-parent-todo-statistics))))
5096 (defun org-insert-subheading (arg)
5097 "Insert a new subheading and demote it.
5098 Works for outline headings and for plain lists alike."
5099 (interactive "P")
5100 (org-insert-heading arg)
5101 (cond
5102 ((org-on-heading-p) (org-do-demote))
5103 ((org-at-item-p) (org-indent-item 1))))
5105 (defun org-insert-todo-subheading (arg)
5106 "Insert a new subheading with TODO keyword or checkbox and demote it.
5107 Works for outline headings and for plain lists alike."
5108 (interactive "P")
5109 (org-insert-todo-heading arg)
5110 (cond
5111 ((org-on-heading-p) (org-do-demote))
5112 ((org-at-item-p) (org-indent-item 1))))
5114 ;;; Promotion and Demotion
5116 (defun org-promote-subtree ()
5117 "Promote the entire subtree.
5118 See also `org-promote'."
5119 (interactive)
5120 (save-excursion
5121 (org-map-tree 'org-promote))
5122 (org-fix-position-after-promote))
5124 (defun org-demote-subtree ()
5125 "Demote the entire subtree. See `org-demote'.
5126 See also `org-promote'."
5127 (interactive)
5128 (save-excursion
5129 (org-map-tree 'org-demote))
5130 (org-fix-position-after-promote))
5133 (defun org-do-promote ()
5134 "Promote the current heading higher up the tree.
5135 If the region is active in `transient-mark-mode', promote all headings
5136 in the region."
5137 (interactive)
5138 (save-excursion
5139 (if (org-region-active-p)
5140 (org-map-region 'org-promote (region-beginning) (region-end))
5141 (org-promote)))
5142 (org-fix-position-after-promote))
5144 (defun org-do-demote ()
5145 "Demote the current heading lower down the tree.
5146 If the region is active in `transient-mark-mode', demote all headings
5147 in the region."
5148 (interactive)
5149 (save-excursion
5150 (if (org-region-active-p)
5151 (org-map-region 'org-demote (region-beginning) (region-end))
5152 (org-demote)))
5153 (org-fix-position-after-promote))
5155 (defun org-fix-position-after-promote ()
5156 "Make sure that after pro/demotion cursor position is right."
5157 (let ((pos (point)))
5158 (when (save-excursion
5159 (beginning-of-line 1)
5160 (looking-at org-todo-line-regexp)
5161 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5162 (cond ((eobp) (insert " "))
5163 ((eolp) (insert " "))
5164 ((equal (char-after) ?\ ) (forward-char 1))))))
5166 (defun org-reduced-level (l)
5167 "Compute the effective level of a heading.
5168 This takes into account the setting of `org-odd-levels-only'."
5169 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5171 (defun org-get-valid-level (level &optional change)
5172 "Rectify a level change under the influence of `org-odd-levels-only'
5173 LEVEL is a current level, CHANGE is by how much the level should be
5174 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5175 even level numbers will become the next higher odd number."
5176 (if org-odd-levels-only
5177 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5178 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5179 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5180 (max 1 (+ level change))))
5182 (if (boundp 'define-obsolete-function-alias)
5183 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5184 (define-obsolete-function-alias 'org-get-legal-level
5185 'org-get-valid-level)
5186 (define-obsolete-function-alias 'org-get-legal-level
5187 'org-get-valid-level "23.1")))
5189 (defun org-promote ()
5190 "Promote the current heading higher up the tree.
5191 If the region is active in `transient-mark-mode', promote all headings
5192 in the region."
5193 (org-back-to-heading t)
5194 (let* ((level (save-match-data (funcall outline-level)))
5195 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5196 (diff (abs (- level (length up-head) -1))))
5197 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5198 (replace-match up-head nil t)
5199 ;; Fixup tag positioning
5200 (and org-auto-align-tags (org-set-tags nil t))
5201 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5203 (defun org-demote ()
5204 "Demote the current heading lower down the tree.
5205 If the region is active in `transient-mark-mode', demote all headings
5206 in the region."
5207 (org-back-to-heading t)
5208 (let* ((level (save-match-data (funcall outline-level)))
5209 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5210 (diff (abs (- level (length down-head) -1))))
5211 (replace-match down-head nil t)
5212 ;; Fixup tag positioning
5213 (and org-auto-align-tags (org-set-tags nil t))
5214 (if org-adapt-indentation (org-fixup-indentation diff))))
5216 (defun org-map-tree (fun)
5217 "Call FUN for every heading underneath the current one."
5218 (org-back-to-heading)
5219 (let ((level (funcall outline-level)))
5220 (save-excursion
5221 (funcall fun)
5222 (while (and (progn
5223 (outline-next-heading)
5224 (> (funcall outline-level) level))
5225 (not (eobp)))
5226 (funcall fun)))))
5228 (defun org-map-region (fun beg end)
5229 "Call FUN for every heading between BEG and END."
5230 (let ((org-ignore-region t))
5231 (save-excursion
5232 (setq end (copy-marker end))
5233 (goto-char beg)
5234 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5235 (< (point) end))
5236 (funcall fun))
5237 (while (and (progn
5238 (outline-next-heading)
5239 (< (point) end))
5240 (not (eobp)))
5241 (funcall fun)))))
5243 (defun org-fixup-indentation (diff)
5244 "Change the indentation in the current entry by DIFF
5245 However, if any line in the current entry has no indentation, or if it
5246 would end up with no indentation after the change, nothing at all is done."
5247 (save-excursion
5248 (let ((end (save-excursion (outline-next-heading)
5249 (point-marker)))
5250 (prohibit (if (> diff 0)
5251 "^\\S-"
5252 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5253 col)
5254 (unless (save-excursion (end-of-line 1)
5255 (re-search-forward prohibit end t))
5256 (while (and (< (point) end)
5257 (re-search-forward "^[ \t]+" end t))
5258 (goto-char (match-end 0))
5259 (setq col (current-column))
5260 (if (< diff 0) (replace-match ""))
5261 (org-indent-to-column (+ diff col))))
5262 (move-marker end nil))))
5264 (defun org-convert-to-odd-levels ()
5265 "Convert an org-mode file with all levels allowed to one with odd levels.
5266 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5267 level 5 etc."
5268 (interactive)
5269 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5270 (let ((org-odd-levels-only nil) n)
5271 (save-excursion
5272 (goto-char (point-min))
5273 (while (re-search-forward "^\\*\\*+ " nil t)
5274 (setq n (- (length (match-string 0)) 2))
5275 (while (>= (setq n (1- n)) 0)
5276 (org-demote))
5277 (end-of-line 1))))))
5280 (defun org-convert-to-oddeven-levels ()
5281 "Convert an org-mode file with only odd levels to one with odd and even levels.
5282 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5283 section with an even level, conversion would destroy the structure of the file. An error
5284 is signaled in this case."
5285 (interactive)
5286 (goto-char (point-min))
5287 ;; First check if there are no even levels
5288 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5289 (org-show-context t)
5290 (error "Not all levels are odd in this file. Conversion not possible."))
5291 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5292 (let ((org-odd-levels-only nil) n)
5293 (save-excursion
5294 (goto-char (point-min))
5295 (while (re-search-forward "^\\*\\*+ " nil t)
5296 (setq n (/ (1- (length (match-string 0))) 2))
5297 (while (>= (setq n (1- n)) 0)
5298 (org-promote))
5299 (end-of-line 1))))))
5301 (defun org-tr-level (n)
5302 "Make N odd if required."
5303 (if org-odd-levels-only (1+ (/ n 2)) n))
5305 ;;; Vertical tree motion, cutting and pasting of subtrees
5307 (defun org-move-subtree-up (&optional arg)
5308 "Move the current subtree up past ARG headlines of the same level."
5309 (interactive "p")
5310 (org-move-subtree-down (- (prefix-numeric-value arg))))
5312 (defun org-move-subtree-down (&optional arg)
5313 "Move the current subtree down past ARG headlines of the same level."
5314 (interactive "p")
5315 (setq arg (prefix-numeric-value arg))
5316 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5317 'outline-get-last-sibling))
5318 (ins-point (make-marker))
5319 (cnt (abs arg))
5320 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5321 ;; Select the tree
5322 (org-back-to-heading)
5323 (setq beg0 (point))
5324 (save-excursion
5325 (setq ne-beg (org-back-over-empty-lines))
5326 (setq beg (point)))
5327 (save-match-data
5328 (save-excursion (outline-end-of-heading)
5329 (setq folded (org-invisible-p)))
5330 (outline-end-of-subtree))
5331 (outline-next-heading)
5332 (setq ne-end (org-back-over-empty-lines))
5333 (setq end (point))
5334 (goto-char beg0)
5335 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5336 ;; include less whitespace
5337 (save-excursion
5338 (goto-char beg)
5339 (forward-line (- ne-beg ne-end))
5340 (setq beg (point))))
5341 ;; Find insertion point, with error handling
5342 (while (> cnt 0)
5343 (or (and (funcall movfunc) (looking-at outline-regexp))
5344 (progn (goto-char beg0)
5345 (error "Cannot move past superior level or buffer limit")))
5346 (setq cnt (1- cnt)))
5347 (if (> arg 0)
5348 ;; Moving forward - still need to move over subtree
5349 (progn (org-end-of-subtree t t)
5350 (save-excursion
5351 (org-back-over-empty-lines)
5352 (or (bolp) (newline)))))
5353 (setq ne-ins (org-back-over-empty-lines))
5354 (move-marker ins-point (point))
5355 (setq txt (buffer-substring beg end))
5356 (org-save-markers-in-region beg end)
5357 (delete-region beg end)
5358 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5359 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5360 (let ((bbb (point)))
5361 (insert-before-markers txt)
5362 (org-reinstall-markers-in-region bbb)
5363 (move-marker ins-point bbb))
5364 (or (bolp) (insert "\n"))
5365 (setq ins-end (point))
5366 (goto-char ins-point)
5367 (org-skip-whitespace)
5368 (when (and (< arg 0)
5369 (org-first-sibling-p)
5370 (> ne-ins ne-beg))
5371 ;; Move whitespace back to beginning
5372 (save-excursion
5373 (goto-char ins-end)
5374 (let ((kill-whole-line t))
5375 (kill-line (- ne-ins ne-beg)) (point)))
5376 (insert (make-string (- ne-ins ne-beg) ?\n)))
5377 (move-marker ins-point nil)
5378 (org-compact-display-after-subtree-move)
5379 (org-show-empty-lines-in-parent)
5380 (unless folded
5381 (org-show-entry)
5382 (show-children)
5383 (org-cycle-hide-drawers 'children))))
5385 (defvar org-subtree-clip ""
5386 "Clipboard for cut and paste of subtrees.
5387 This is actually only a copy of the kill, because we use the normal kill
5388 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5390 (defvar org-subtree-clip-folded nil
5391 "Was the last copied subtree folded?
5392 This is used to fold the tree back after pasting.")
5394 (defun org-cut-subtree (&optional n)
5395 "Cut the current subtree into the clipboard.
5396 With prefix arg N, cut this many sequential subtrees.
5397 This is a short-hand for marking the subtree and then cutting it."
5398 (interactive "p")
5399 (org-copy-subtree n 'cut))
5401 (defun org-copy-subtree (&optional n cut force-store-markers)
5402 "Cut the current subtree into the clipboard.
5403 With prefix arg N, cut this many sequential subtrees.
5404 This is a short-hand for marking the subtree and then copying it.
5405 If CUT is non-nil, actually cut the subtree.
5406 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5407 of some markers in the region, even if CUT is non-nil. This is
5408 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5409 (interactive "p")
5410 (let (beg end folded (beg0 (point)))
5411 (if (interactive-p)
5412 (org-back-to-heading nil) ; take what looks like a subtree
5413 (org-back-to-heading t)) ; take what is really there
5414 (org-back-over-empty-lines)
5415 (setq beg (point))
5416 (skip-chars-forward " \t\r\n")
5417 (save-match-data
5418 (save-excursion (outline-end-of-heading)
5419 (setq folded (org-invisible-p)))
5420 (condition-case nil
5421 (outline-forward-same-level (1- n))
5422 (error nil))
5423 (org-end-of-subtree t t))
5424 (org-back-over-empty-lines)
5425 (setq end (point))
5426 (goto-char beg0)
5427 (when (> end beg)
5428 (setq org-subtree-clip-folded folded)
5429 (when (or cut force-store-markers)
5430 (org-save-markers-in-region beg end))
5431 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5432 (setq org-subtree-clip (current-kill 0))
5433 (message "%s: Subtree(s) with %d characters"
5434 (if cut "Cut" "Copied")
5435 (length org-subtree-clip)))))
5437 (defun org-paste-subtree (&optional level tree for-yank)
5438 "Paste the clipboard as a subtree, with modification of headline level.
5439 The entire subtree is promoted or demoted in order to match a new headline
5440 level.
5442 If the cursor is at the beginning of a headline, the same level as
5443 that headline is used to paste the tree
5445 If not, the new level is derived from the *visible* headings
5446 before and after the insertion point, and taken to be the inferior headline
5447 level of the two. So if the previous visible heading is level 3 and the
5448 next is level 4 (or vice versa), level 4 will be used for insertion.
5449 This makes sure that the subtree remains an independent subtree and does
5450 not swallow low level entries.
5452 You can also force a different level, either by using a numeric prefix
5453 argument, or by inserting the heading marker by hand. For example, if the
5454 cursor is after \"*****\", then the tree will be shifted to level 5.
5456 If optional TREE is given, use this text instead of the kill ring.
5458 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5459 move back over whitespace before inserting, and move point to the end of
5460 the inserted text when done."
5461 (interactive "P")
5462 (unless (org-kill-is-subtree-p tree)
5463 (error "%s"
5464 (substitute-command-keys
5465 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5466 (let* ((visp (not (org-invisible-p)))
5467 (txt (or tree (and kill-ring (current-kill 0))))
5468 (^re (concat "^\\(" outline-regexp "\\)"))
5469 (re (concat "\\(" outline-regexp "\\)"))
5470 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5472 (old-level (if (string-match ^re txt)
5473 (- (match-end 0) (match-beginning 0) 1)
5474 -1))
5475 (force-level (cond (level (prefix-numeric-value level))
5476 ((and (looking-at "[ \t]*$")
5477 (string-match
5478 ^re_ (buffer-substring
5479 (point-at-bol) (point))))
5480 (- (match-end 1) (match-beginning 1)))
5481 ((and (bolp)
5482 (looking-at org-outline-regexp))
5483 (- (match-end 0) (point) 1))
5484 (t nil)))
5485 (previous-level (save-excursion
5486 (condition-case nil
5487 (progn
5488 (outline-previous-visible-heading 1)
5489 (if (looking-at re)
5490 (- (match-end 0) (match-beginning 0) 1)
5492 (error 1))))
5493 (next-level (save-excursion
5494 (condition-case nil
5495 (progn
5496 (or (looking-at outline-regexp)
5497 (outline-next-visible-heading 1))
5498 (if (looking-at re)
5499 (- (match-end 0) (match-beginning 0) 1)
5501 (error 1))))
5502 (new-level (or force-level (max previous-level next-level)))
5503 (shift (if (or (= old-level -1)
5504 (= new-level -1)
5505 (= old-level new-level))
5507 (- new-level old-level)))
5508 (delta (if (> shift 0) -1 1))
5509 (func (if (> shift 0) 'org-demote 'org-promote))
5510 (org-odd-levels-only nil)
5511 beg end newend)
5512 ;; Remove the forced level indicator
5513 (if force-level
5514 (delete-region (point-at-bol) (point)))
5515 ;; Paste
5516 (beginning-of-line 1)
5517 (unless for-yank (org-back-over-empty-lines))
5518 (setq beg (point))
5519 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5520 (insert-before-markers txt)
5521 (unless (string-match "\n\\'" txt) (insert "\n"))
5522 (setq newend (point))
5523 (org-reinstall-markers-in-region beg)
5524 (setq end (point))
5525 (goto-char beg)
5526 (skip-chars-forward " \t\n\r")
5527 (setq beg (point))
5528 (if (and (org-invisible-p) visp)
5529 (save-excursion (outline-show-heading)))
5530 ;; Shift if necessary
5531 (unless (= shift 0)
5532 (save-restriction
5533 (narrow-to-region beg end)
5534 (while (not (= shift 0))
5535 (org-map-region func (point-min) (point-max))
5536 (setq shift (+ delta shift)))
5537 (goto-char (point-min))
5538 (setq newend (point-max))))
5539 (when (or (interactive-p) for-yank)
5540 (message "Clipboard pasted as level %d subtree" new-level))
5541 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5542 kill-ring
5543 (eq org-subtree-clip (current-kill 0))
5544 org-subtree-clip-folded)
5545 ;; The tree was folded before it was killed/copied
5546 (hide-subtree))
5547 (and for-yank (goto-char newend))))
5549 (defun org-kill-is-subtree-p (&optional txt)
5550 "Check if the current kill is an outline subtree, or a set of trees.
5551 Returns nil if kill does not start with a headline, or if the first
5552 headline level is not the largest headline level in the tree.
5553 So this will actually accept several entries of equal levels as well,
5554 which is OK for `org-paste-subtree'.
5555 If optional TXT is given, check this string instead of the current kill."
5556 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5557 (start-level (and kill
5558 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5559 org-outline-regexp "\\)")
5560 kill)
5561 (- (match-end 2) (match-beginning 2) 1)))
5562 (re (concat "^" org-outline-regexp))
5563 (start (1+ (or (match-beginning 2) -1))))
5564 (if (not start-level)
5565 (progn
5566 nil) ;; does not even start with a heading
5567 (catch 'exit
5568 (while (setq start (string-match re kill (1+ start)))
5569 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5570 (throw 'exit nil)))
5571 t))))
5573 (defvar org-markers-to-move nil
5574 "Markers that should be moved with a cut-and-paste operation.
5575 Those markers are stored together with their positions relative to
5576 the start of the region.")
5578 (defun org-save-markers-in-region (beg end)
5579 "Check markers in region.
5580 If these markers are between BEG and END, record their position relative
5581 to BEG, so that after moving the block of text, we can put the markers back
5582 into place.
5583 This function gets called just before an entry or tree gets cut from the
5584 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5585 called immediately, to move the markers with the entries."
5586 (setq org-markers-to-move nil)
5587 (when (featurep 'org-clock)
5588 (org-clock-save-markers-for-cut-and-paste beg end))
5589 (when (featurep 'org-agenda)
5590 (org-agenda-save-markers-for-cut-and-paste beg end)))
5592 (defun org-check-and-save-marker (marker beg end)
5593 "Check if MARKER is between BEG and END.
5594 If yes, remember the marker and the distance to BEG."
5595 (when (and (marker-buffer marker)
5596 (equal (marker-buffer marker) (current-buffer)))
5597 (if (and (>= marker beg) (< marker end))
5598 (push (cons marker (- marker beg)) org-markers-to-move))))
5600 (defun org-reinstall-markers-in-region (beg)
5601 "Move all remembered markers to their position relative to BEG."
5602 (mapc (lambda (x)
5603 (move-marker (car x) (+ beg (cdr x))))
5604 org-markers-to-move)
5605 (setq org-markers-to-move nil))
5607 (defun org-narrow-to-subtree ()
5608 "Narrow buffer to the current subtree."
5609 (interactive)
5610 (save-excursion
5611 (save-match-data
5612 (narrow-to-region
5613 (progn (org-back-to-heading) (point))
5614 (progn (org-end-of-subtree t) (point))))))
5617 ;;; Outline Sorting
5619 (defun org-sort (with-case)
5620 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5621 Optional argument WITH-CASE means sort case-sensitively."
5622 (interactive "P")
5623 (if (org-at-table-p)
5624 (org-call-with-arg 'org-table-sort-lines with-case)
5625 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5627 (defun org-sort-remove-invisible (s)
5628 (remove-text-properties 0 (length s) org-rm-props s)
5629 (while (string-match org-bracket-link-regexp s)
5630 (setq s (replace-match (if (match-end 2)
5631 (match-string 3 s)
5632 (match-string 1 s)) t t s)))
5635 (defvar org-priority-regexp) ; defined later in the file
5637 (defun org-sort-entries-or-items
5638 (&optional with-case sorting-type getkey-func compare-func property)
5639 "Sort entries on a certain level of an outline tree.
5640 If there is an active region, the entries in the region are sorted.
5641 Else, if the cursor is before the first entry, sort the top-level items.
5642 Else, the children of the entry at point are sorted.
5644 Sorting can be alphabetically, numerically, and by date/time as given by
5645 the first time stamp in the entry. The command prompts for the sorting
5646 type unless it has been given to the function through the SORTING-TYPE
5647 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5648 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5649 called with point at the beginning of the record. It must return either
5650 a string or a number that should serve as the sorting key for that record.
5652 Comparing entries ignores case by default. However, with an optional argument
5653 WITH-CASE, the sorting considers case as well."
5654 (interactive "P")
5655 (let ((case-func (if with-case 'identity 'downcase))
5656 start beg end stars re re2
5657 txt what tmp plain-list-p)
5658 ;; Find beginning and end of region to sort
5659 (cond
5660 ((org-region-active-p)
5661 ;; we will sort the region
5662 (setq end (region-end)
5663 what "region")
5664 (goto-char (region-beginning))
5665 (if (not (org-on-heading-p)) (outline-next-heading))
5666 (setq start (point)))
5667 ((org-at-item-p)
5668 ;; we will sort this plain list
5669 (org-beginning-of-item-list) (setq start (point))
5670 (org-end-of-item-list) (setq end (point))
5671 (goto-char start)
5672 (setq plain-list-p t
5673 what "plain list"))
5674 ((or (org-on-heading-p)
5675 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5676 ;; we will sort the children of the current headline
5677 (org-back-to-heading)
5678 (setq start (point)
5679 end (progn (org-end-of-subtree t t)
5680 (org-back-over-empty-lines)
5681 (point))
5682 what "children")
5683 (goto-char start)
5684 (show-subtree)
5685 (outline-next-heading))
5687 ;; we will sort the top-level entries in this file
5688 (goto-char (point-min))
5689 (or (org-on-heading-p) (outline-next-heading))
5690 (setq start (point) end (point-max) what "top-level")
5691 (goto-char start)
5692 (show-all)))
5694 (setq beg (point))
5695 (if (>= beg end) (error "Nothing to sort"))
5697 (unless plain-list-p
5698 (looking-at "\\(\\*+\\)")
5699 (setq stars (match-string 1)
5700 re (concat "^" (regexp-quote stars) " +")
5701 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5702 txt (buffer-substring beg end))
5703 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5704 (if (and (not (equal stars "*")) (string-match re2 txt))
5705 (error "Region to sort contains a level above the first entry")))
5707 (unless sorting-type
5708 (message
5709 (if plain-list-p
5710 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5711 "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:")
5712 what)
5713 (setq sorting-type (read-char-exclusive))
5715 (and (= (downcase sorting-type) ?f)
5716 (setq getkey-func
5717 (org-ido-completing-read "Sort using function: "
5718 obarray 'fboundp t nil nil))
5719 (setq getkey-func (intern getkey-func)))
5721 (and (= (downcase sorting-type) ?r)
5722 (setq property
5723 (org-ido-completing-read "Property: "
5724 (mapcar 'list (org-buffer-property-keys t))
5725 nil t))))
5727 (message "Sorting entries...")
5729 (save-restriction
5730 (narrow-to-region start end)
5732 (let ((dcst (downcase sorting-type))
5733 (now (current-time)))
5734 (sort-subr
5735 (/= dcst sorting-type)
5736 ;; This function moves to the beginning character of the "record" to
5737 ;; be sorted.
5738 (if plain-list-p
5739 (lambda nil
5740 (if (org-at-item-p) t (goto-char (point-max))))
5741 (lambda nil
5742 (if (re-search-forward re nil t)
5743 (goto-char (match-beginning 0))
5744 (goto-char (point-max)))))
5745 ;; This function moves to the last character of the "record" being
5746 ;; sorted.
5747 (if plain-list-p
5748 'org-end-of-item
5749 (lambda nil
5750 (save-match-data
5751 (condition-case nil
5752 (outline-forward-same-level 1)
5753 (error
5754 (goto-char (point-max)))))))
5756 ;; This function returns the value that gets sorted against.
5757 (if plain-list-p
5758 (lambda nil
5759 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5760 (cond
5761 ((= dcst ?n)
5762 (string-to-number (buffer-substring (match-end 0)
5763 (point-at-eol))))
5764 ((= dcst ?a)
5765 (buffer-substring (match-end 0) (point-at-eol)))
5766 ((= dcst ?t)
5767 (if (re-search-forward org-ts-regexp
5768 (point-at-eol) t)
5769 (org-time-string-to-time (match-string 0))
5770 now))
5771 ((= dcst ?f)
5772 (if getkey-func
5773 (progn
5774 (setq tmp (funcall getkey-func))
5775 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5776 tmp)
5777 (error "Invalid key function `%s'" getkey-func)))
5778 (t (error "Invalid sorting type `%c'" sorting-type)))))
5779 (lambda nil
5780 (cond
5781 ((= dcst ?n)
5782 (if (looking-at org-complex-heading-regexp)
5783 (string-to-number (match-string 4))
5784 nil))
5785 ((= dcst ?a)
5786 (if (looking-at org-complex-heading-regexp)
5787 (funcall case-func (match-string 4))
5788 nil))
5789 ((= dcst ?t)
5790 (if (re-search-forward org-ts-regexp
5791 (save-excursion
5792 (forward-line 2)
5793 (point)) t)
5794 (org-time-string-to-time (match-string 0))
5795 now))
5796 ((= dcst ?p)
5797 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5798 (string-to-char (match-string 2))
5799 org-default-priority))
5800 ((= dcst ?r)
5801 (or (org-entry-get nil property) ""))
5802 ((= dcst ?o)
5803 (if (looking-at org-complex-heading-regexp)
5804 (- 9999 (length (member (match-string 2)
5805 org-todo-keywords-1)))))
5806 ((= dcst ?f)
5807 (if getkey-func
5808 (progn
5809 (setq tmp (funcall getkey-func))
5810 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5811 tmp)
5812 (error "Invalid key function `%s'" getkey-func)))
5813 (t (error "Invalid sorting type `%c'" sorting-type)))))
5815 (cond
5816 ((= dcst ?a) 'string<)
5817 ((= dcst ?t) 'time-less-p)
5818 ((= dcst ?f) compare-func)
5819 (t nil)))))
5820 (message "Sorting entries...done")))
5822 (defun org-do-sort (table what &optional with-case sorting-type)
5823 "Sort TABLE of WHAT according to SORTING-TYPE.
5824 The user will be prompted for the SORTING-TYPE if the call to this
5825 function does not specify it. WHAT is only for the prompt, to indicate
5826 what is being sorted. The sorting key will be extracted from
5827 the car of the elements of the table.
5828 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5829 (unless sorting-type
5830 (message
5831 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5832 what)
5833 (setq sorting-type (read-char-exclusive)))
5834 (let ((dcst (downcase sorting-type))
5835 extractfun comparefun)
5836 ;; Define the appropriate functions
5837 (cond
5838 ((= dcst ?n)
5839 (setq extractfun 'string-to-number
5840 comparefun (if (= dcst sorting-type) '< '>)))
5841 ((= dcst ?a)
5842 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5843 (lambda(x) (downcase (org-sort-remove-invisible x))))
5844 comparefun (if (= dcst sorting-type)
5845 'string<
5846 (lambda (a b) (and (not (string< a b))
5847 (not (string= a b)))))))
5848 ((= dcst ?t)
5849 (setq extractfun
5850 (lambda (x)
5851 (if (string-match org-ts-regexp x)
5852 (time-to-seconds
5853 (org-time-string-to-time (match-string 0 x)))
5855 comparefun (if (= dcst sorting-type) '< '>)))
5856 (t (error "Invalid sorting type `%c'" sorting-type)))
5858 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5859 table)
5860 (lambda (a b) (funcall comparefun (car a) (car b))))))
5862 ;;; Editing source examples
5864 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5865 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5866 (defvar org-edit-src-force-single-line nil)
5867 (defvar org-edit-src-from-org-mode nil)
5868 (defvar org-edit-src-picture nil)
5870 (define-minor-mode org-exit-edit-mode
5871 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5873 (defun org-edit-src-code ()
5874 "Edit the source code example at point.
5875 An indirect buffer is created, and that buffer is then narrowed to the
5876 example at point and switched to the correct language mode. When done,
5877 exit by killing the buffer with \\[org-edit-src-exit]."
5878 (interactive)
5879 (let ((line (org-current-line))
5880 (case-fold-search t)
5881 (msg (substitute-command-keys
5882 "Edit, then exit with C-c ' (C-c and single quote)"))
5883 (info (org-edit-src-find-region-and-lang))
5884 (org-mode-p (eq major-mode 'org-mode))
5885 beg end lang lang-f single lfmt)
5886 (if (not info)
5888 (setq beg (nth 0 info)
5889 end (nth 1 info)
5890 lang (nth 2 info)
5891 single (nth 3 info)
5892 lfmt (nth 4 info)
5893 lang-f (intern (concat lang "-mode")))
5894 (unless (functionp lang-f)
5895 (error "No such language mode: %s" lang-f))
5896 (goto-line line)
5897 (if (get-buffer "*Org Edit Src Example*")
5898 (kill-buffer "*Org Edit Src Example*"))
5899 (switch-to-buffer (make-indirect-buffer (current-buffer)
5900 "*Org Edit Src Example*"))
5901 (narrow-to-region beg end)
5902 (remove-text-properties beg end '(display nil invisible nil
5903 intangible nil))
5904 (let ((org-inhibit-startup t))
5905 (funcall lang-f))
5906 (set (make-local-variable 'org-edit-src-force-single-line) single)
5907 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5908 (when lfmt
5909 (set (make-local-variable 'org-coderef-label-format) lfmt))
5910 (when org-mode-p
5911 (goto-char (point-min))
5912 (while (re-search-forward "^," nil t)
5913 (replace-match "")))
5914 (goto-line line)
5915 (org-exit-edit-mode)
5916 (org-set-local 'header-line-format msg)
5917 (message "%s" msg)
5918 t)))
5920 (defun org-edit-fixed-width-region ()
5921 "Edit the fixed-width ascii drawing at point.
5922 This must be a region where each line starts with a colon followed by
5923 a space character.
5924 An indirect buffer is created, and that buffer is then narrowed to the
5925 example at point and switched to artist-mode. When done,
5926 exit by killing the buffer with \\[org-edit-src-exit]."
5927 (interactive)
5928 (let ((line (org-current-line))
5929 (case-fold-search t)
5930 (msg (substitute-command-keys
5931 "Edit, then exit with C-c ' (C-c and single quote)"))
5932 (org-mode-p (eq major-mode 'org-mode))
5933 beg end)
5934 (beginning-of-line 1)
5935 (if (looking-at "[ \t]*[^:\n \t]")
5937 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5938 (setq beg (point) end beg)
5939 (save-excursion
5940 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5941 (setq beg (point-at-bol 2))
5942 (setq beg (point))))
5943 (save-excursion
5944 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5945 (setq end (1- (match-beginning 0)))
5946 (setq end (point))))
5947 (goto-line line))
5948 (if (get-buffer "*Org Edit Picture*")
5949 (kill-buffer "*Org Edit Picture*"))
5950 (switch-to-buffer (make-indirect-buffer (current-buffer)
5951 "*Org Edit Picture*"))
5952 (narrow-to-region beg end)
5953 (remove-text-properties beg end '(display nil invisible nil
5954 intangible nil))
5955 (when (fboundp 'font-lock-unfontify-region)
5956 (font-lock-unfontify-region (point-min) (point-max)))
5957 (cond
5958 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5959 (fundamental-mode)
5960 (artist-mode 1))
5961 (t (funcall org-edit-fixed-width-region-mode)))
5962 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5963 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5964 (set (make-local-variable 'org-edit-src-picture) t)
5965 (goto-char (point-min))
5966 (while (re-search-forward "^[ \t]*: ?" nil t)
5967 (replace-match ""))
5968 (goto-line line)
5969 (org-exit-edit-mode)
5970 (org-set-local 'header-line-format msg)
5971 (message "%s" msg)
5972 t)))
5975 (defun org-edit-src-find-region-and-lang ()
5976 "Find the region and language for a local edit.
5977 Return a list with beginning and end of the region, a string representing
5978 the language, a switch telling of the content should be in a single line."
5979 (let ((re-list
5980 (append
5981 org-edit-src-region-extra
5983 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5984 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5985 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5986 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5987 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5988 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5989 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5990 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5991 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5992 ("^#\\+html:" "\n" "html" single-line)
5993 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5994 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5995 ("^#\\+latex:" "\n" "latex" single-line)
5996 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5997 ("^#\\+ascii:" "\n" "ascii" single-line)
5999 (pos (point))
6000 re1 re2 single beg end lang lfmt match-re1)
6001 (catch 'exit
6002 (while (setq entry (pop re-list))
6003 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6004 single (nth 3 entry))
6005 (save-excursion
6006 (if (or (looking-at re1)
6007 (re-search-backward re1 nil t))
6008 (progn
6009 (setq match-re1 (match-string 0))
6010 (setq beg (match-end 0)
6011 lang (org-edit-src-get-lang lang)
6012 lfmt (org-edit-src-get-label-format match-re1))
6013 (if (and (re-search-forward re2 nil t)
6014 (>= (match-end 0) pos))
6015 (throw 'exit (list beg (match-beginning 0)
6016 lang single lfmt))))
6017 (if (or (looking-at re2)
6018 (re-search-forward re2 nil t))
6019 (progn
6020 (setq end (match-beginning 0))
6021 (if (and (re-search-backward re1 nil t)
6022 (<= (match-beginning 0) pos))
6023 (progn
6024 (setq lfmt (org-edit-src-get-label-format
6025 (match-string 0)))
6026 (throw 'exit
6027 (list (match-end 0) end
6028 (org-edit-src-get-lang lang)
6029 single lfmt))))))))))))
6031 (defun org-edit-src-get-lang (lang)
6032 "Extract the src language."
6033 (let ((m (match-string 0)))
6034 (cond
6035 ((stringp lang) lang)
6036 ((integerp lang) (match-string lang))
6037 ((and (eq lang 'lang)
6038 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6039 (match-string 1 m))
6040 ((and (eq lang 'style)
6041 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6042 (match-string 1 m))
6043 (t "fundamental"))))
6045 (defun org-edit-src-get-label-format (s)
6046 "Extract the label format."
6047 (save-match-data
6048 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6049 (match-string 1 s))))
6051 (defun org-edit-src-exit ()
6052 "Exit special edit and protect problematic lines."
6053 (interactive)
6054 (unless (buffer-base-buffer (current-buffer))
6055 (error "This is not an indirect buffer, something is wrong..."))
6056 (unless (> (point-min) 1)
6057 (error "This buffer is not narrowed, something is wrong..."))
6058 (goto-char (point-min))
6059 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6060 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6061 (when (org-bound-and-true-p org-edit-src-force-single-line)
6062 (goto-char (point-min))
6063 (while (re-search-forward "\n" nil t)
6064 (replace-match " "))
6065 (goto-char (point-min))
6066 (if (looking-at "\\s-*") (replace-match " "))
6067 (if (re-search-forward "\\s-+\\'" nil t)
6068 (replace-match "")))
6069 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6070 (goto-char (point-min))
6071 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6072 (replace-match ",\\1"))
6073 (when font-lock-mode
6074 (font-lock-unfontify-region (point-min) (point-max)))
6075 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6076 (when (org-bound-and-true-p org-edit-src-picture)
6077 (untabify (point-min) (point-max))
6078 (goto-char (point-min))
6079 (while (re-search-forward "^" nil t)
6080 (replace-match ": "))
6081 (when font-lock-mode
6082 (font-lock-unfontify-region (point-min) (point-max)))
6083 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6084 (kill-buffer (current-buffer))
6085 (and (org-mode-p) (org-restart-font-lock)))
6088 ;;; The orgstruct minor mode
6090 ;; Define a minor mode which can be used in other modes in order to
6091 ;; integrate the org-mode structure editing commands.
6093 ;; This is really a hack, because the org-mode structure commands use
6094 ;; keys which normally belong to the major mode. Here is how it
6095 ;; works: The minor mode defines all the keys necessary to operate the
6096 ;; structure commands, but wraps the commands into a function which
6097 ;; tests if the cursor is currently at a headline or a plain list
6098 ;; item. If that is the case, the structure command is used,
6099 ;; temporarily setting many Org-mode variables like regular
6100 ;; expressions for filling etc. However, when any of those keys is
6101 ;; used at a different location, function uses `key-binding' to look
6102 ;; up if the key has an associated command in another currently active
6103 ;; keymap (minor modes, major mode, global), and executes that
6104 ;; command. There might be problems if any of the keys is otherwise
6105 ;; used as a prefix key.
6107 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6108 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6109 ;; addresses this by checking explicitly for both bindings.
6111 (defvar orgstruct-mode-map (make-sparse-keymap)
6112 "Keymap for the minor `orgstruct-mode'.")
6114 (defvar org-local-vars nil
6115 "List of local variables, for use by `orgstruct-mode'")
6117 ;;;###autoload
6118 (define-minor-mode orgstruct-mode
6119 "Toggle the minor more `orgstruct-mode'.
6120 This mode is for using Org-mode structure commands in other modes.
6121 The following key behave as if Org-mode was active, if the cursor
6122 is on a headline, or on a plain list item (both in the definition
6123 of Org-mode).
6125 M-up Move entry/item up
6126 M-down Move entry/item down
6127 M-left Promote
6128 M-right Demote
6129 M-S-up Move entry/item up
6130 M-S-down Move entry/item down
6131 M-S-left Promote subtree
6132 M-S-right Demote subtree
6133 M-q Fill paragraph and items like in Org-mode
6134 C-c ^ Sort entries
6135 C-c - Cycle list bullet
6136 TAB Cycle item visibility
6137 M-RET Insert new heading/item
6138 S-M-RET Insert new TODO heading / Checkbox item
6139 C-c C-c Set tags / toggle checkbox"
6140 nil " OrgStruct" nil
6141 (org-load-modules-maybe)
6142 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6144 ;;;###autoload
6145 (defun turn-on-orgstruct ()
6146 "Unconditionally turn on `orgstruct-mode'."
6147 (orgstruct-mode 1))
6149 ;;;###autoload
6150 (defun turn-on-orgstruct++ ()
6151 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6152 In addition to setting orgstruct-mode, this also exports all indentation and
6153 autofilling variables from org-mode into the buffer. Note that turning
6154 off orgstruct-mode will *not* remove these additional settings."
6155 (orgstruct-mode 1)
6156 (let (var val)
6157 (mapc
6158 (lambda (x)
6159 (when (string-match
6160 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6161 (symbol-name (car x)))
6162 (setq var (car x) val (nth 1 x))
6163 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6164 org-local-vars)))
6166 (defun orgstruct-error ()
6167 "Error when there is no default binding for a structure key."
6168 (interactive)
6169 (error "This key has no function outside structure elements"))
6171 (defun orgstruct-setup ()
6172 "Setup orgstruct keymaps."
6173 (let ((nfunc 0)
6174 (bindings
6175 (list
6176 '([(meta up)] org-metaup)
6177 '([(meta down)] org-metadown)
6178 '([(meta left)] org-metaleft)
6179 '([(meta right)] org-metaright)
6180 '([(meta shift up)] org-shiftmetaup)
6181 '([(meta shift down)] org-shiftmetadown)
6182 '([(meta shift left)] org-shiftmetaleft)
6183 '([(meta shift right)] org-shiftmetaright)
6184 '([(shift up)] org-shiftup)
6185 '([(shift down)] org-shiftdown)
6186 '([(shift left)] org-shiftleft)
6187 '([(shift right)] org-shiftright)
6188 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6189 '("\M-q" fill-paragraph)
6190 '("\C-c^" org-sort)
6191 '("\C-c-" org-cycle-list-bullet)))
6192 elt key fun cmd)
6193 (while (setq elt (pop bindings))
6194 (setq nfunc (1+ nfunc))
6195 (setq key (org-key (car elt))
6196 fun (nth 1 elt)
6197 cmd (orgstruct-make-binding fun nfunc key))
6198 (org-defkey orgstruct-mode-map key cmd))
6200 ;; Special treatment needed for TAB and RET
6201 (org-defkey orgstruct-mode-map [(tab)]
6202 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6203 (org-defkey orgstruct-mode-map "\C-i"
6204 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6206 (org-defkey orgstruct-mode-map "\M-\C-m"
6207 (orgstruct-make-binding 'org-insert-heading 105
6208 "\M-\C-m" [(meta return)]))
6209 (org-defkey orgstruct-mode-map [(meta return)]
6210 (orgstruct-make-binding 'org-insert-heading 106
6211 [(meta return)] "\M-\C-m"))
6213 (org-defkey orgstruct-mode-map [(shift meta return)]
6214 (orgstruct-make-binding 'org-insert-todo-heading 107
6215 [(meta return)] "\M-\C-m"))
6217 (unless org-local-vars
6218 (setq org-local-vars (org-get-local-variables)))
6222 (defun orgstruct-make-binding (fun n &rest keys)
6223 "Create a function for binding in the structure minor mode.
6224 FUN is the command to call inside a table. N is used to create a unique
6225 command name. KEYS are keys that should be checked in for a command
6226 to execute outside of tables."
6227 (eval
6228 (list 'defun
6229 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6230 '(arg)
6231 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6232 "Outside of structure, run the binding of `"
6233 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6234 "'.")
6235 '(interactive "p")
6236 (list 'if
6237 '(org-context-p 'headline 'item)
6238 (list 'org-run-like-in-org-mode (list 'quote fun))
6239 (list 'let '(orgstruct-mode)
6240 (list 'call-interactively
6241 (append '(or)
6242 (mapcar (lambda (k)
6243 (list 'key-binding k))
6244 keys)
6245 '('orgstruct-error))))))))
6247 (defun org-context-p (&rest contexts)
6248 "Check if local context is any of CONTEXTS.
6249 Possible values in the list of contexts are `table', `headline', and `item'."
6250 (let ((pos (point)))
6251 (goto-char (point-at-bol))
6252 (prog1 (or (and (memq 'table contexts)
6253 (looking-at "[ \t]*|"))
6254 (and (memq 'headline contexts)
6255 ;;????????? (looking-at "\\*+"))
6256 (looking-at outline-regexp))
6257 (and (memq 'item contexts)
6258 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6259 (goto-char pos))))
6261 (defun org-get-local-variables ()
6262 "Return a list of all local variables in an org-mode buffer."
6263 (let (varlist)
6264 (with-current-buffer (get-buffer-create "*Org tmp*")
6265 (erase-buffer)
6266 (org-mode)
6267 (setq varlist (buffer-local-variables)))
6268 (kill-buffer "*Org tmp*")
6269 (delq nil
6270 (mapcar
6271 (lambda (x)
6272 (setq x
6273 (if (symbolp x)
6274 (list x)
6275 (list (car x) (list 'quote (cdr x)))))
6276 (if (string-match
6277 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6278 (symbol-name (car x)))
6279 x nil))
6280 varlist))))
6282 ;;;###autoload
6283 (defun org-run-like-in-org-mode (cmd)
6284 (org-load-modules-maybe)
6285 (unless org-local-vars
6286 (setq org-local-vars (org-get-local-variables)))
6287 (eval (list 'let org-local-vars
6288 (list 'call-interactively (list 'quote cmd)))))
6290 ;;;; Archiving
6292 (defun org-get-category (&optional pos)
6293 "Get the category applying to position POS."
6294 (get-text-property (or pos (point)) 'org-category))
6296 (defun org-refresh-category-properties ()
6297 "Refresh category text properties in the buffer."
6298 (let ((def-cat (cond
6299 ((null org-category)
6300 (if buffer-file-name
6301 (file-name-sans-extension
6302 (file-name-nondirectory buffer-file-name))
6303 "???"))
6304 ((symbolp org-category) (symbol-name org-category))
6305 (t org-category)))
6306 beg end cat pos optionp)
6307 (org-unmodified
6308 (save-excursion
6309 (save-restriction
6310 (widen)
6311 (goto-char (point-min))
6312 (put-text-property (point) (point-max) 'org-category def-cat)
6313 (while (re-search-forward
6314 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6315 (setq pos (match-end 0)
6316 optionp (equal (char-after (match-beginning 0)) ?#)
6317 cat (org-trim (match-string 2)))
6318 (if optionp
6319 (setq beg (point-at-bol) end (point-max))
6320 (org-back-to-heading t)
6321 (setq beg (point) end (org-end-of-subtree t t)))
6322 (put-text-property beg end 'org-category cat)
6323 (goto-char pos)))))))
6326 ;;;; Link Stuff
6328 ;;; Link abbreviations
6330 (defun org-link-expand-abbrev (link)
6331 "Apply replacements as defined in `org-link-abbrev-alist."
6332 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6333 (let* ((key (match-string 1 link))
6334 (as (or (assoc key org-link-abbrev-alist-local)
6335 (assoc key org-link-abbrev-alist)))
6336 (tag (and (match-end 2) (match-string 3 link)))
6337 rpl)
6338 (if (not as)
6339 link
6340 (setq rpl (cdr as))
6341 (cond
6342 ((symbolp rpl) (funcall rpl tag))
6343 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6344 ((string-match "%h" rpl)
6345 (replace-match (url-hexify-string (or tag "")) t t rpl))
6346 (t (concat rpl tag)))))
6347 link))
6349 ;;; Storing and inserting links
6351 (defvar org-insert-link-history nil
6352 "Minibuffer history for links inserted with `org-insert-link'.")
6354 (defvar org-stored-links nil
6355 "Contains the links stored with `org-store-link'.")
6357 (defvar org-store-link-plist nil
6358 "Plist with info about the most recently link created with `org-store-link'.")
6360 (defvar org-link-protocols nil
6361 "Link protocols added to Org-mode using `org-add-link-type'.")
6363 (defvar org-store-link-functions nil
6364 "List of functions that are called to create and store a link.
6365 Each function will be called in turn until one returns a non-nil
6366 value. Each function should check if it is responsible for creating
6367 this link (for example by looking at the major mode).
6368 If not, it must exit and return nil.
6369 If yes, it should return a non-nil value after a calling
6370 `org-store-link-props' with a list of properties and values.
6371 Special properties are:
6373 :type The link prefix. like \"http\". This must be given.
6374 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6375 This is obligatory as well.
6376 :description Optional default description for the second pair
6377 of brackets in an Org-mode link. The user can still change
6378 this when inserting this link into an Org-mode buffer.
6380 In addition to these, any additional properties can be specified
6381 and then used in remember templates.")
6383 (defun org-add-link-type (type &optional follow export)
6384 "Add TYPE to the list of `org-link-types'.
6385 Re-compute all regular expressions depending on `org-link-types'
6387 FOLLOW and EXPORT are two functions.
6389 FOLLOW should take the link path as the single argument and do whatever
6390 is necessary to follow the link, for example find a file or display
6391 a mail message.
6393 EXPORT should format the link path for export to one of the export formats.
6394 It should be a function accepting three arguments:
6396 path the path of the link, the text after the prefix (like \"http:\")
6397 desc the description of the link, if any, nil if there was no description
6398 format the export format, a symbol like `html' or `latex'.
6400 The function may use the FORMAT information to return different values
6401 depending on the format. The return value will be put literally into
6402 the exported file.
6403 Org-mode has a built-in default for exporting links. If you are happy with
6404 this default, there is no need to define an export function for the link
6405 type. For a simple example of an export function, see `org-bbdb.el'."
6406 (add-to-list 'org-link-types type t)
6407 (org-make-link-regexps)
6408 (if (assoc type org-link-protocols)
6409 (setcdr (assoc type org-link-protocols) (list follow export))
6410 (push (list type follow export) org-link-protocols)))
6412 ;;;###autoload
6413 (defun org-store-link (arg)
6414 "\\<org-mode-map>Store an org-link to the current location.
6415 This link is added to `org-stored-links' and can later be inserted
6416 into an org-buffer with \\[org-insert-link].
6418 For some link types, a prefix arg is interpreted:
6419 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6420 For file links, arg negates `org-context-in-file-links'."
6421 (interactive "P")
6422 (org-load-modules-maybe)
6423 (setq org-store-link-plist nil) ; reset
6424 (let (link cpltxt desc description search txt)
6425 (cond
6427 ((run-hook-with-args-until-success 'org-store-link-functions)
6428 (setq link (plist-get org-store-link-plist :link)
6429 desc (or (plist-get org-store-link-plist :description) link)))
6431 ((equal (buffer-name) "*Org Edit Src Example*")
6432 (let (label gc)
6433 (while (or (not label)
6434 (save-excursion
6435 (save-restriction
6436 (widen)
6437 (goto-char (point-min))
6438 (re-search-forward
6439 (regexp-quote (format org-coderef-label-format label))
6440 nil t))))
6441 (when label (message "Label exists already") (sit-for 2))
6442 (setq label (read-string "Code line label: " label)))
6443 (end-of-line 1)
6444 (setq link (format org-coderef-label-format label))
6445 (setq gc (- 79 (length link)))
6446 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6447 (insert link)
6448 (setq link (concat "(" label ")") desc nil)))
6450 ((eq major-mode 'calendar-mode)
6451 (let ((cd (calendar-cursor-to-date)))
6452 (setq link
6453 (format-time-string
6454 (car org-time-stamp-formats)
6455 (apply 'encode-time
6456 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6457 nil nil nil))))
6458 (org-store-link-props :type "calendar" :date cd)))
6460 ((eq major-mode 'w3-mode)
6461 (setq cpltxt (url-view-url t)
6462 link (org-make-link cpltxt))
6463 (org-store-link-props :type "w3" :url (url-view-url t)))
6465 ((eq major-mode 'w3m-mode)
6466 (setq cpltxt (or w3m-current-title w3m-current-url)
6467 link (org-make-link w3m-current-url))
6468 (org-store-link-props :type "w3m" :url (url-view-url t)))
6470 ((setq search (run-hook-with-args-until-success
6471 'org-create-file-search-functions))
6472 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6473 "::" search))
6474 (setq cpltxt (or description link)))
6476 ((eq major-mode 'image-mode)
6477 (setq cpltxt (concat "file:"
6478 (abbreviate-file-name buffer-file-name))
6479 link (org-make-link cpltxt))
6480 (org-store-link-props :type "image" :file buffer-file-name))
6482 ((eq major-mode 'dired-mode)
6483 ;; link to the file in the current line
6484 (setq cpltxt (concat "file:"
6485 (abbreviate-file-name
6486 (expand-file-name
6487 (dired-get-filename nil t))))
6488 link (org-make-link cpltxt)))
6490 ((and buffer-file-name (org-mode-p))
6491 (cond
6492 ((org-in-regexp "<<\\(.*?\\)>>")
6493 (setq cpltxt
6494 (concat "file:"
6495 (abbreviate-file-name buffer-file-name)
6496 "::" (match-string 1))
6497 link (org-make-link cpltxt)))
6498 ((and (featurep 'org-id)
6499 (or (eq org-link-to-org-use-id t)
6500 (and (eq org-link-to-org-use-id 'create-if-interactive)
6501 (interactive-p))
6502 (and org-link-to-org-use-id
6503 (condition-case nil
6504 (org-entry-get nil "ID")
6505 (error nil)))))
6506 ;; We can make a link using the ID.
6507 (setq link (condition-case nil
6508 (prog1 (org-id-store-link)
6509 (setq desc (plist-get org-store-link-plist
6510 :description)))
6511 (error
6512 ;; probably before first headline, link to file only
6513 (concat "file:"
6514 (abbreviate-file-name buffer-file-name))))))
6516 ;; Just link to current headline
6517 (setq cpltxt (concat "file:"
6518 (abbreviate-file-name buffer-file-name)))
6519 ;; Add a context search string
6520 (when (org-xor org-context-in-file-links arg)
6521 (setq txt (cond
6522 ((org-on-heading-p) nil)
6523 ((org-region-active-p)
6524 (buffer-substring (region-beginning) (region-end)))
6525 (t nil)))
6526 (when (or (null txt) (string-match "\\S-" txt))
6527 (setq cpltxt
6528 (concat cpltxt "::"
6529 (condition-case nil
6530 (org-make-org-heading-search-string txt)
6531 (error "")))
6532 desc "NONE")))
6533 (if (string-match "::\\'" cpltxt)
6534 (setq cpltxt (substring cpltxt 0 -2)))
6535 (setq link (org-make-link cpltxt)))))
6537 ((buffer-file-name (buffer-base-buffer))
6538 ;; Just link to this file here.
6539 (setq cpltxt (concat "file:"
6540 (abbreviate-file-name
6541 (buffer-file-name (buffer-base-buffer)))))
6542 ;; Add a context string
6543 (when (org-xor org-context-in-file-links arg)
6544 (setq txt (if (org-region-active-p)
6545 (buffer-substring (region-beginning) (region-end))
6546 (buffer-substring (point-at-bol) (point-at-eol))))
6547 ;; Only use search option if there is some text.
6548 (when (string-match "\\S-" txt)
6549 (setq cpltxt
6550 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6551 desc "NONE")))
6552 (setq link (org-make-link cpltxt)))
6554 ((interactive-p)
6555 (error "Cannot link to a buffer which is not visiting a file"))
6557 (t (setq link nil)))
6559 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6560 (setq link (or link cpltxt)
6561 desc (or desc cpltxt))
6562 (if (equal desc "NONE") (setq desc nil))
6564 (if (and (interactive-p) link)
6565 (progn
6566 (setq org-stored-links
6567 (cons (list link desc) org-stored-links))
6568 (message "Stored: %s" (or desc link)))
6569 (and link (org-make-link-string link desc)))))
6571 (defun org-store-link-props (&rest plist)
6572 "Store link properties, extract names and addresses."
6573 (let (x adr)
6574 (when (setq x (plist-get plist :from))
6575 (setq adr (mail-extract-address-components x))
6576 (setq plist (plist-put plist :fromname (car adr)))
6577 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6578 (when (setq x (plist-get plist :to))
6579 (setq adr (mail-extract-address-components x))
6580 (setq plist (plist-put plist :toname (car adr)))
6581 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6582 (let ((from (plist-get plist :from))
6583 (to (plist-get plist :to)))
6584 (when (and from to org-from-is-user-regexp)
6585 (setq plist
6586 (plist-put plist :fromto
6587 (if (string-match org-from-is-user-regexp from)
6588 (concat "to %t")
6589 (concat "from %f"))))))
6590 (setq org-store-link-plist plist))
6592 (defun org-add-link-props (&rest plist)
6593 "Add these properties to the link property list."
6594 (let (key value)
6595 (while plist
6596 (setq key (pop plist) value (pop plist))
6597 (setq org-store-link-plist
6598 (plist-put org-store-link-plist key value)))))
6600 (defun org-email-link-description (&optional fmt)
6601 "Return the description part of an email link.
6602 This takes information from `org-store-link-plist' and formats it
6603 according to FMT (default from `org-email-link-description-format')."
6604 (setq fmt (or fmt org-email-link-description-format))
6605 (let* ((p org-store-link-plist)
6606 (to (plist-get p :toaddress))
6607 (from (plist-get p :fromaddress))
6608 (table
6609 (list
6610 (cons "%c" (plist-get p :fromto))
6611 (cons "%F" (plist-get p :from))
6612 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6613 (cons "%T" (plist-get p :to))
6614 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6615 (cons "%s" (plist-get p :subject))
6616 (cons "%m" (plist-get p :message-id)))))
6617 (when (string-match "%c" fmt)
6618 ;; Check if the user wrote this message
6619 (if (and org-from-is-user-regexp from to
6620 (save-match-data (string-match org-from-is-user-regexp from)))
6621 (setq fmt (replace-match "to %t" t t fmt))
6622 (setq fmt (replace-match "from %f" t t fmt))))
6623 (org-replace-escapes fmt table)))
6625 (defun org-make-org-heading-search-string (&optional string heading)
6626 "Make search string for STRING or current headline."
6627 (interactive)
6628 (let ((s (or string (org-get-heading))))
6629 (unless (and string (not heading))
6630 ;; We are using a headline, clean up garbage in there.
6631 (if (string-match org-todo-regexp s)
6632 (setq s (replace-match "" t t s)))
6633 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6634 (setq s (replace-match "" t t s)))
6635 (setq s (org-trim s))
6636 (if (string-match (concat "^\\(" org-quote-string "\\|"
6637 org-comment-string "\\)") s)
6638 (setq s (replace-match "" t t s)))
6639 (while (string-match org-ts-regexp s)
6640 (setq s (replace-match "" t t s))))
6641 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6642 (setq s (replace-match " " t t s)))
6643 (or string (setq s (concat "*" s))) ; Add * for headlines
6644 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6646 (defun org-make-link (&rest strings)
6647 "Concatenate STRINGS."
6648 (apply 'concat strings))
6650 (defun org-make-link-string (link &optional description)
6651 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6652 (unless (string-match "\\S-" link)
6653 (error "Empty link"))
6654 (when (stringp description)
6655 ;; Remove brackets from the description, they are fatal.
6656 (while (string-match "\\[" description)
6657 (setq description (replace-match "{" t t description)))
6658 (while (string-match "\\]" description)
6659 (setq description (replace-match "}" t t description))))
6660 (when (equal (org-link-escape link) description)
6661 ;; No description needed, it is identical
6662 (setq description nil))
6663 (when (and (not description)
6664 (not (equal link (org-link-escape link))))
6665 (setq description (org-extract-attributes link)))
6666 (concat "[[" (org-link-escape link) "]"
6667 (if description (concat "[" description "]") "")
6668 "]"))
6670 (defconst org-link-escape-chars
6671 '((?\ . "%20")
6672 (?\[ . "%5B")
6673 (?\] . "%5D")
6674 (?\340 . "%E0") ; `a
6675 (?\342 . "%E2") ; ^a
6676 (?\347 . "%E7") ; ,c
6677 (?\350 . "%E8") ; `e
6678 (?\351 . "%E9") ; 'e
6679 (?\352 . "%EA") ; ^e
6680 (?\356 . "%EE") ; ^i
6681 (?\364 . "%F4") ; ^o
6682 (?\371 . "%F9") ; `u
6683 (?\373 . "%FB") ; ^u
6684 (?\; . "%3B")
6685 (?? . "%3F")
6686 (?= . "%3D")
6687 (?+ . "%2B")
6689 "Association list of escapes for some characters problematic in links.
6690 This is the list that is used for internal purposes.")
6692 (defconst org-link-escape-chars-browser
6693 '((?\ . "%20")) ; 32 for the SPC char
6694 "Association list of escapes for some characters problematic in links.
6695 This is the list that is used before handing over to the browser.")
6697 (defun org-link-escape (text &optional table)
6698 "Escape characters in TEXT that are problematic for links."
6699 (setq table (or table org-link-escape-chars))
6700 (when text
6701 (let ((re (mapconcat (lambda (x) (regexp-quote
6702 (char-to-string (car x))))
6703 table "\\|")))
6704 (while (string-match re text)
6705 (setq text
6706 (replace-match
6707 (cdr (assoc (string-to-char (match-string 0 text))
6708 table))
6709 t t text)))
6710 text)))
6712 (defun org-link-unescape (text &optional table)
6713 "Reverse the action of `org-link-escape'."
6714 (setq table (or table org-link-escape-chars))
6715 (when text
6716 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6717 table "\\|")))
6718 (while (string-match re text)
6719 (setq text
6720 (replace-match
6721 (char-to-string (car (rassoc (match-string 0 text) table)))
6722 t t text)))
6723 text)))
6725 (defun org-xor (a b)
6726 "Exclusive or."
6727 (if a (not b) b))
6729 (defun org-fixup-message-id-for-http (s)
6730 "Replace special characters in a message id, so it can be used in an http query."
6731 (while (string-match "<" s)
6732 (setq s (replace-match "%3C" t t s)))
6733 (while (string-match ">" s)
6734 (setq s (replace-match "%3E" t t s)))
6735 (while (string-match "@" s)
6736 (setq s (replace-match "%40" t t s)))
6739 ;;;###autoload
6740 (defun org-insert-link-global ()
6741 "Insert a link like Org-mode does.
6742 This command can be called in any mode to insert a link in Org-mode syntax."
6743 (interactive)
6744 (org-load-modules-maybe)
6745 (org-run-like-in-org-mode 'org-insert-link))
6747 (defun org-insert-link (&optional complete-file link-location)
6748 "Insert a link. At the prompt, enter the link.
6750 Completion can be used to insert any of the link protocol prefixes like
6751 http or ftp in use.
6753 The history can be used to select a link previously stored with
6754 `org-store-link'. When the empty string is entered (i.e. if you just
6755 press RET at the prompt), the link defaults to the most recently
6756 stored link. As SPC triggers completion in the minibuffer, you need to
6757 use M-SPC or C-q SPC to force the insertion of a space character.
6759 You will also be prompted for a description, and if one is given, it will
6760 be displayed in the buffer instead of the link.
6762 If there is already a link at point, this command will allow you to edit link
6763 and description parts.
6765 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6766 be selected using completion. The path to the file will be relative to the
6767 current directory if the file is in the current directory or a subdirectory.
6768 Otherwise, the link will be the absolute path as completed in the minibuffer
6769 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6770 option `org-link-file-path-type'.
6772 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6773 the current directory or below.
6775 With three \\[universal-argument] prefixes, negate the meaning of
6776 `org-keep-stored-link-after-insertion'.
6778 If `org-make-link-description-function' is non-nil, this function will be
6779 called with the link target, and the result will be the default
6780 link description.
6782 If the LINK-LOCATION parameter is non-nil, this value will be
6783 used as the link location instead of reading one interactively."
6784 (interactive "P")
6785 (let* ((wcf (current-window-configuration))
6786 (region (if (org-region-active-p)
6787 (buffer-substring (region-beginning) (region-end))))
6788 (remove (and region (list (region-beginning) (region-end))))
6789 (desc region)
6790 tmphist ; byte-compile incorrectly complains about this
6791 (link link-location)
6792 entry file)
6793 (cond
6794 (link-location) ; specified by arg, just use it.
6795 ((org-in-regexp org-bracket-link-regexp 1)
6796 ;; We do have a link at point, and we are going to edit it.
6797 (setq remove (list (match-beginning 0) (match-end 0)))
6798 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6799 (setq link (read-string "Link: "
6800 (org-link-unescape
6801 (org-match-string-no-properties 1)))))
6802 ((or (org-in-regexp org-angle-link-re)
6803 (org-in-regexp org-plain-link-re))
6804 ;; Convert to bracket link
6805 (setq remove (list (match-beginning 0) (match-end 0))
6806 link (read-string "Link: "
6807 (org-remove-angle-brackets (match-string 0)))))
6808 ((member complete-file '((4) (16)))
6809 ;; Completing read for file names.
6810 (setq file (read-file-name "File: "))
6811 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6812 (pwd1 (file-name-as-directory (abbreviate-file-name
6813 (expand-file-name ".")))))
6814 (cond
6815 ((equal complete-file '(16))
6816 (setq link (org-make-link
6817 "file:"
6818 (abbreviate-file-name (expand-file-name file)))))
6819 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6820 (setq link (org-make-link "file:" (match-string 1 file))))
6821 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6822 (expand-file-name file))
6823 (setq link (org-make-link
6824 "file:" (match-string 1 (expand-file-name file)))))
6825 (t (setq link (org-make-link "file:" file))))))
6827 ;; Read link, with completion for stored links.
6828 (with-output-to-temp-buffer "*Org Links*"
6829 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6830 (when org-stored-links
6831 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6832 (princ (mapconcat
6833 (lambda (x)
6834 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6835 (reverse org-stored-links) "\n"))))
6836 (let ((cw (selected-window)))
6837 (select-window (get-buffer-window "*Org Links*"))
6838 (setq truncate-lines t)
6839 (org-fit-window-to-buffer)
6840 (select-window cw))
6841 ;; Fake a link history, containing the stored links.
6842 (setq tmphist (append (mapcar 'car org-stored-links)
6843 org-insert-link-history))
6844 (unwind-protect
6845 (setq link
6846 (let ((org-completion-use-ido nil))
6847 (org-completing-read
6848 "Link: "
6849 (append
6850 (mapcar (lambda (x) (list (concat (car x) ":")))
6851 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6852 (mapcar (lambda (x) (list (concat x ":")))
6853 org-link-types))
6854 nil nil nil
6855 'tmphist
6856 (or (car (car org-stored-links))))))
6857 (set-window-configuration wcf)
6858 (kill-buffer "*Org Links*"))
6859 (setq entry (assoc link org-stored-links))
6860 (or entry (push link org-insert-link-history))
6861 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6862 (not org-keep-stored-link-after-insertion))
6863 (setq org-stored-links (delq (assoc link org-stored-links)
6864 org-stored-links)))
6865 (setq desc (or desc (nth 1 entry)))))
6867 (if (string-match org-plain-link-re link)
6868 ;; URL-like link, normalize the use of angular brackets.
6869 (setq link (org-make-link (org-remove-angle-brackets link))))
6871 ;; Check if we are linking to the current file with a search option
6872 ;; If yes, simplify the link by using only the search option.
6873 (when (and buffer-file-name
6874 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6875 (let* ((path (match-string 1 link))
6876 (case-fold-search nil)
6877 (search (match-string 2 link)))
6878 (save-match-data
6879 (if (equal (file-truename buffer-file-name) (file-truename path))
6880 ;; We are linking to this same file, with a search option
6881 (setq link search)))))
6883 ;; Check if we can/should use a relative path. If yes, simplify the link
6884 (when (string-match "^file:\\(.*\\)" link)
6885 (let* ((path (match-string 1 link))
6886 (origpath path)
6887 (case-fold-search nil))
6888 (cond
6889 ((or (eq org-link-file-path-type 'absolute)
6890 (equal complete-file '(16)))
6891 (setq path (abbreviate-file-name (expand-file-name path))))
6892 ((eq org-link-file-path-type 'noabbrev)
6893 (setq path (expand-file-name path)))
6894 ((eq org-link-file-path-type 'relative)
6895 (setq path (file-relative-name path)))
6897 (save-match-data
6898 (if (string-match (concat "^" (regexp-quote
6899 (file-name-as-directory
6900 (expand-file-name "."))))
6901 (expand-file-name path))
6902 ;; We are linking a file with relative path name.
6903 (setq path (substring (expand-file-name path)
6904 (match-end 0)))
6905 (setq path (abbreviate-file-name (expand-file-name path)))))))
6906 (setq link (concat "file:" path))
6907 (if (equal desc origpath)
6908 (setq desc path))))
6910 (if org-make-link-description-function
6911 (setq desc (funcall org-make-link-description-function link desc)))
6913 (setq desc (read-string "Description: " desc))
6914 (unless (string-match "\\S-" desc) (setq desc nil))
6915 (if remove (apply 'delete-region remove))
6916 (insert (org-make-link-string link desc))))
6918 (defun org-completing-read (&rest args)
6919 "Completing-read with SPACE being a normal character."
6920 (let ((minibuffer-local-completion-map
6921 (copy-keymap minibuffer-local-completion-map)))
6922 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6923 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6924 (apply 'org-ido-completing-read args)))
6926 (defun org-ido-completing-read (&rest args)
6927 "Completing-read using `ido-mode' speedups if available"
6928 (if (and org-completion-use-ido
6929 (fboundp 'ido-completing-read)
6930 (boundp 'ido-mode) ido-mode
6931 (listp (second args)))
6932 (apply 'ido-completing-read (concat (car args)) (cdr args))
6933 (apply 'completing-read args)))
6935 (defun org-extract-attributes (s)
6936 "Extract the attributes cookie from a string and set as text property."
6937 (let (a attr (start 0) key value)
6938 (save-match-data
6939 (when (string-match "{{\\([^}]+\\)}}$" s)
6940 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6941 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6942 (setq key (match-string 1 a) value (match-string 2 a)
6943 start (match-end 0)
6944 attr (plist-put attr (intern key) value))))
6945 (org-add-props s nil 'org-attr attr))
6948 (defun org-attributes-to-string (plist)
6949 "Format a property list into an HTML attribute list."
6950 (let ((s "") key value)
6951 (while plist
6952 (setq key (pop plist) value (pop plist))
6953 (and value
6954 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6957 ;;; Opening/following a link
6959 (defvar org-link-search-failed nil)
6961 (defun org-next-link ()
6962 "Move forward to the next link.
6963 If the link is in hidden text, expose it."
6964 (interactive)
6965 (when (and org-link-search-failed (eq this-command last-command))
6966 (goto-char (point-min))
6967 (message "Link search wrapped back to beginning of buffer"))
6968 (setq org-link-search-failed nil)
6969 (let* ((pos (point))
6970 (ct (org-context))
6971 (a (assoc :link ct)))
6972 (if a (goto-char (nth 2 a)))
6973 (if (re-search-forward org-any-link-re nil t)
6974 (progn
6975 (goto-char (match-beginning 0))
6976 (if (org-invisible-p) (org-show-context)))
6977 (goto-char pos)
6978 (setq org-link-search-failed t)
6979 (error "No further link found"))))
6981 (defun org-previous-link ()
6982 "Move backward to the previous link.
6983 If the link is in hidden text, expose it."
6984 (interactive)
6985 (when (and org-link-search-failed (eq this-command last-command))
6986 (goto-char (point-max))
6987 (message "Link search wrapped back to end of buffer"))
6988 (setq org-link-search-failed nil)
6989 (let* ((pos (point))
6990 (ct (org-context))
6991 (a (assoc :link ct)))
6992 (if a (goto-char (nth 1 a)))
6993 (if (re-search-backward org-any-link-re nil t)
6994 (progn
6995 (goto-char (match-beginning 0))
6996 (if (org-invisible-p) (org-show-context)))
6997 (goto-char pos)
6998 (setq org-link-search-failed t)
6999 (error "No further link found"))))
7001 (defun org-translate-link (s)
7002 "Translate a link string if a translation function has been defined."
7003 (if (and org-link-translation-function
7004 (fboundp org-link-translation-function)
7005 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7006 (progn
7007 (setq s (funcall org-link-translation-function
7008 (match-string 1) (match-string 2)))
7009 (concat (car s) ":" (cdr s)))
7012 (defun org-translate-link-from-planner (type path)
7013 "Translate a link from Emacs Planner syntax so that Org can follow it.
7014 This is still an experimental function, your mileage may vary."
7015 (cond
7016 ((member type '("http" "https" "news" "ftp"))
7017 ;; standard Internet links are the same.
7018 nil)
7019 ((and (equal type "irc") (string-match "^//" path))
7020 ;; Planner has two / at the beginning of an irc link, we have 1.
7021 ;; We should have zero, actually....
7022 (setq path (substring path 1)))
7023 ((and (equal type "lisp") (string-match "^/" path))
7024 ;; Planner has a slash, we do not.
7025 (setq type "elisp" path (substring path 1)))
7026 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7027 ;; A typical message link. Planner has the id after the fina slash,
7028 ;; we separate it with a hash mark
7029 (setq path (concat (match-string 1 path) "#"
7030 (org-remove-angle-brackets (match-string 2 path)))))
7032 (cons type path))
7034 (defun org-find-file-at-mouse (ev)
7035 "Open file link or URL at mouse."
7036 (interactive "e")
7037 (mouse-set-point ev)
7038 (org-open-at-point 'in-emacs))
7040 (defun org-open-at-mouse (ev)
7041 "Open file link or URL at mouse."
7042 (interactive "e")
7043 (mouse-set-point ev)
7044 (if (eq major-mode 'org-agenda-mode)
7045 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7046 (org-open-at-point))
7048 (defvar org-window-config-before-follow-link nil
7049 "The window configuration before following a link.
7050 This is saved in case the need arises to restore it.")
7052 (defvar org-open-link-marker (make-marker)
7053 "Marker pointing to the location where `org-open-at-point; was called.")
7055 ;;;###autoload
7056 (defun org-open-at-point-global ()
7057 "Follow a link like Org-mode does.
7058 This command can be called in any mode to follow a link that has
7059 Org-mode syntax."
7060 (interactive)
7061 (org-run-like-in-org-mode 'org-open-at-point))
7063 ;;;###autoload
7064 (defun org-open-link-from-string (s &optional arg)
7065 "Open a link in the string S, as if it was in Org-mode."
7066 (interactive "sLink: \nP")
7067 (with-temp-buffer
7068 (let ((org-inhibit-startup t))
7069 (org-mode)
7070 (insert s)
7071 (goto-char (point-min))
7072 (org-open-at-point arg))))
7074 (defun org-open-at-point (&optional in-emacs)
7075 "Open link at or after point.
7076 If there is no link at point, this function will search forward up to
7077 the end of the current subtree.
7078 Normally, files will be opened by an appropriate application. If the
7079 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7080 With a double prefix argument, try to open outside of Emacs, in the
7081 application the system uses for this file type."
7082 (interactive "P")
7083 (org-load-modules-maybe)
7084 (move-marker org-open-link-marker (point))
7085 (setq org-window-config-before-follow-link (current-window-configuration))
7086 (org-remove-occur-highlights nil nil t)
7087 (cond
7088 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7089 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7090 (org-footnote-action))
7092 (let (type path link line search (pos (point)))
7093 (catch 'match
7094 (save-excursion
7095 (skip-chars-forward "^]\n\r")
7096 (when (org-in-regexp org-bracket-link-regexp)
7097 (setq link (org-extract-attributes
7098 (org-link-unescape (org-match-string-no-properties 1))))
7099 (while (string-match " *\n *" link)
7100 (setq link (replace-match " " t t link)))
7101 (setq link (org-link-expand-abbrev link))
7102 (cond
7103 ((or (file-name-absolute-p link)
7104 (string-match "^\\.\\.?/" link))
7105 (setq type "file" path link))
7106 ((string-match org-link-re-with-space3 link)
7107 (setq type (match-string 1 link) path (match-string 2 link)))
7108 (t (setq type "thisfile" path link)))
7109 (throw 'match t)))
7111 (when (get-text-property (point) 'org-linked-text)
7112 (setq type "thisfile"
7113 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7114 (1+ (point)) (point))
7115 path (buffer-substring
7116 (previous-single-property-change pos 'org-linked-text)
7117 (next-single-property-change pos 'org-linked-text)))
7118 (throw 'match t))
7120 (save-excursion
7121 (when (or (org-in-regexp org-angle-link-re)
7122 (org-in-regexp org-plain-link-re))
7123 (setq type (match-string 1) path (match-string 2))
7124 (throw 'match t)))
7125 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7126 (setq type "tree-match"
7127 path (match-string 1))
7128 (throw 'match t))
7129 (save-excursion
7130 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7131 (setq type "tags"
7132 path (match-string 1))
7133 (while (string-match ":" path)
7134 (setq path (replace-match "+" t t path)))
7135 (throw 'match t))))
7136 (unless path
7137 (error "No link found"))
7138 ;; Remove any trailing spaces in path
7139 (if (string-match " +\\'" path)
7140 (setq path (replace-match "" t t path)))
7141 (if (and org-link-translation-function
7142 (fboundp org-link-translation-function))
7143 ;; Check if we need to translate the link
7144 (let ((tmp (funcall org-link-translation-function type path)))
7145 (setq type (car tmp) path (cdr tmp))))
7147 (cond
7149 ((assoc type org-link-protocols)
7150 (funcall (nth 1 (assoc type org-link-protocols)) path))
7152 ((equal type "mailto")
7153 (let ((cmd (car org-link-mailto-program))
7154 (args (cdr org-link-mailto-program)) args1
7155 (address path) (subject "") a)
7156 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7157 (setq address (match-string 1 path)
7158 subject (org-link-escape (match-string 2 path))))
7159 (while args
7160 (cond
7161 ((not (stringp (car args))) (push (pop args) args1))
7162 (t (setq a (pop args))
7163 (if (string-match "%a" a)
7164 (setq a (replace-match address t t a)))
7165 (if (string-match "%s" a)
7166 (setq a (replace-match subject t t a)))
7167 (push a args1))))
7168 (apply cmd (nreverse args1))))
7170 ((member type '("http" "https" "ftp" "news"))
7171 (browse-url (concat type ":" (org-link-escape
7172 path org-link-escape-chars-browser))))
7174 ((member type '("message"))
7175 (browse-url (concat type ":" path)))
7177 ((string= type "tags")
7178 (org-tags-view in-emacs path))
7179 ((string= type "thisfile")
7180 (if in-emacs
7181 (switch-to-buffer-other-window
7182 (org-get-buffer-for-internal-link (current-buffer)))
7183 (org-mark-ring-push))
7184 (let ((cmd `(org-link-search
7185 ,path
7186 ,(cond ((equal in-emacs '(4)) 'occur)
7187 ((equal in-emacs '(16)) 'org-occur)
7188 (t nil))
7189 ,pos)))
7190 (condition-case nil (eval cmd)
7191 (error (progn (widen) (eval cmd))))))
7193 ((string= type "tree-match")
7194 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7196 ((string= type "file")
7197 (if (string-match "::\\([0-9]+\\)\\'" path)
7198 (setq line (string-to-number (match-string 1 path))
7199 path (substring path 0 (match-beginning 0)))
7200 (if (string-match "::\\(.+\\)\\'" path)
7201 (setq search (match-string 1 path)
7202 path (substring path 0 (match-beginning 0)))))
7203 (if (string-match "[*?{]" (file-name-nondirectory path))
7204 (dired path)
7205 (org-open-file path in-emacs line search)))
7207 ((string= type "news")
7208 (require 'org-gnus)
7209 (org-gnus-follow-link path))
7211 ((string= type "shell")
7212 (let ((cmd path))
7213 (if (or (not org-confirm-shell-link-function)
7214 (funcall org-confirm-shell-link-function
7215 (format "Execute \"%s\" in shell? "
7216 (org-add-props cmd nil
7217 'face 'org-warning))))
7218 (progn
7219 (message "Executing %s" cmd)
7220 (shell-command cmd))
7221 (error "Abort"))))
7223 ((string= type "elisp")
7224 (let ((cmd path))
7225 (if (or (not org-confirm-elisp-link-function)
7226 (funcall org-confirm-elisp-link-function
7227 (format "Execute \"%s\" as elisp? "
7228 (org-add-props cmd nil
7229 'face 'org-warning))))
7230 (message "%s => %s" cmd
7231 (if (equal (string-to-char cmd) ?\()
7232 (eval (read cmd))
7233 (call-interactively (read cmd))))
7234 (error "Abort"))))
7237 (browse-url-at-point))))))
7238 (move-marker org-open-link-marker nil)
7239 (run-hook-with-args 'org-follow-link-hook))
7241 ;;;; Time estimates
7243 (defun org-get-effort (&optional pom)
7244 "Get the effort estimate for the current entry."
7245 (org-entry-get pom org-effort-property))
7247 ;;; File search
7249 (defvar org-create-file-search-functions nil
7250 "List of functions to construct the right search string for a file link.
7251 These functions are called in turn with point at the location to
7252 which the link should point.
7254 A function in the hook should first test if it would like to
7255 handle this file type, for example by checking the major-mode or
7256 the file extension. If it decides not to handle this file, it
7257 should just return nil to give other functions a chance. If it
7258 does handle the file, it must return the search string to be used
7259 when following the link. The search string will be part of the
7260 file link, given after a double colon, and `org-open-at-point'
7261 will automatically search for it. If special measures must be
7262 taken to make the search successful, another function should be
7263 added to the companion hook `org-execute-file-search-functions',
7264 which see.
7266 A function in this hook may also use `setq' to set the variable
7267 `description' to provide a suggestion for the descriptive text to
7268 be used for this link when it gets inserted into an Org-mode
7269 buffer with \\[org-insert-link].")
7271 (defvar org-execute-file-search-functions nil
7272 "List of functions to execute a file search triggered by a link.
7274 Functions added to this hook must accept a single argument, the
7275 search string that was part of the file link, the part after the
7276 double colon. The function must first check if it would like to
7277 handle this search, for example by checking the major-mode or the
7278 file extension. If it decides not to handle this search, it
7279 should just return nil to give other functions a chance. If it
7280 does handle the search, it must return a non-nil value to keep
7281 other functions from trying.
7283 Each function can access the current prefix argument through the
7284 variable `current-prefix-argument'. Note that a single prefix is
7285 used to force opening a link in Emacs, so it may be good to only
7286 use a numeric or double prefix to guide the search function.
7288 In case this is needed, a function in this hook can also restore
7289 the window configuration before `org-open-at-point' was called using:
7291 (set-window-configuration org-window-config-before-follow-link)")
7293 (defun org-link-search (s &optional type avoid-pos)
7294 "Search for a link search option.
7295 If S is surrounded by forward slashes, it is interpreted as a
7296 regular expression. In org-mode files, this will create an `org-occur'
7297 sparse tree. In ordinary files, `occur' will be used to list matches.
7298 If the current buffer is in `dired-mode', grep will be used to search
7299 in all files. If AVOID-POS is given, ignore matches near that position."
7300 (let ((case-fold-search t)
7301 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7302 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7303 (append '(("") (" ") ("\t") ("\n"))
7304 org-emphasis-alist)
7305 "\\|") "\\)"))
7306 (pos (point))
7307 (pre nil) (post nil)
7308 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7309 (cond
7310 ;; First check if there are any special
7311 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7312 ;; Now try the builtin stuff
7313 ((save-excursion
7314 (goto-char (point-min))
7315 (and
7316 (re-search-forward
7317 (concat "<<" (regexp-quote s0) ">>") nil t)
7318 (setq type 'dedicated
7319 pos (match-beginning 0))))
7320 ;; There is an exact target for this
7321 (goto-char pos))
7322 ((and (string-match "^(\\(.*\\))$" s0)
7323 (save-excursion
7324 (goto-char (point-min))
7325 (and
7326 (re-search-forward
7327 (concat "[^[]" (regexp-quote
7328 (format org-coderef-label-format
7329 (match-string 1 s0))))
7330 nil t)
7331 (setq type 'dedicated
7332 pos (1+ (match-beginning 0))))))
7333 ;; There is a coderef target for this
7334 (goto-char pos))
7335 ((string-match "^/\\(.*\\)/$" s)
7336 ;; A regular expression
7337 (cond
7338 ((org-mode-p)
7339 (org-occur (match-string 1 s)))
7340 ;;((eq major-mode 'dired-mode)
7341 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7342 (t (org-do-occur (match-string 1 s)))))
7344 ;; A normal search strings
7345 (when (equal (string-to-char s) ?*)
7346 ;; Anchor on headlines, post may include tags.
7347 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7348 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7349 s (substring s 1)))
7350 (remove-text-properties
7351 0 (length s)
7352 '(face nil mouse-face nil keymap nil fontified nil) s)
7353 ;; Make a series of regular expressions to find a match
7354 (setq words (org-split-string s "[ \n\r\t]+")
7356 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7357 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7358 "\\)" markers)
7359 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7360 re2a (concat "[ \t\r\n]" re2a_)
7361 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7362 re4 (concat "[^a-zA-Z_]" re4_)
7364 re1 (concat pre re2 post)
7365 re3 (concat pre (if pre re4_ re4) post)
7366 re5 (concat pre ".*" re4)
7367 re2 (concat pre re2)
7368 re2a (concat pre (if pre re2a_ re2a))
7369 re4 (concat pre (if pre re4_ re4))
7370 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7371 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7372 re5 "\\)"
7374 (cond
7375 ((eq type 'org-occur) (org-occur reall))
7376 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7377 (t (goto-char (point-min))
7378 (setq type 'fuzzy)
7379 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7380 (org-search-not-self 1 re1 nil t)
7381 (org-search-not-self 1 re2 nil t)
7382 (org-search-not-self 1 re2a nil t)
7383 (org-search-not-self 1 re3 nil t)
7384 (org-search-not-self 1 re4 nil t)
7385 (org-search-not-self 1 re5 nil t)
7387 (goto-char (match-beginning 1))
7388 (goto-char pos)
7389 (error "No match")))))
7391 ;; Normal string-search
7392 (goto-char (point-min))
7393 (if (search-forward s nil t)
7394 (goto-char (match-beginning 0))
7395 (error "No match"))))
7396 (and (org-mode-p) (org-show-context 'link-search))
7397 type))
7399 (defun org-search-not-self (group &rest args)
7400 "Execute `re-search-forward', but only accept matches that do not
7401 enclose the position of `org-open-link-marker'."
7402 (let ((m org-open-link-marker))
7403 (catch 'exit
7404 (while (apply 're-search-forward args)
7405 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7406 (goto-char (match-end group))
7407 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7408 (> (match-beginning 0) (marker-position m))
7409 (< (match-end 0) (marker-position m)))
7410 (save-match-data
7411 (or (not (org-in-regexp
7412 org-bracket-link-analytic-regexp 1))
7413 (not (match-end 4)) ; no description
7414 (and (<= (match-beginning 4) (point))
7415 (>= (match-end 4) (point))))))
7416 (throw 'exit (point))))))))
7418 (defun org-get-buffer-for-internal-link (buffer)
7419 "Return a buffer to be used for displaying the link target of internal links."
7420 (cond
7421 ((not org-display-internal-link-with-indirect-buffer)
7422 buffer)
7423 ((string-match "(Clone)$" (buffer-name buffer))
7424 (message "Buffer is already a clone, not making another one")
7425 ;; we also do not modify visibility in this case
7426 buffer)
7427 (t ; make a new indirect buffer for displaying the link
7428 (let* ((bn (buffer-name buffer))
7429 (ibn (concat bn "(Clone)"))
7430 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7431 (with-current-buffer ib (org-overview))
7432 ib))))
7434 (defun org-do-occur (regexp &optional cleanup)
7435 "Call the Emacs command `occur'.
7436 If CLEANUP is non-nil, remove the printout of the regular expression
7437 in the *Occur* buffer. This is useful if the regex is long and not useful
7438 to read."
7439 (occur regexp)
7440 (when cleanup
7441 (let ((cwin (selected-window)) win beg end)
7442 (when (setq win (get-buffer-window "*Occur*"))
7443 (select-window win))
7444 (goto-char (point-min))
7445 (when (re-search-forward "match[a-z]+" nil t)
7446 (setq beg (match-end 0))
7447 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7448 (setq end (1- (match-beginning 0)))))
7449 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7450 (goto-char (point-min))
7451 (select-window cwin))))
7453 ;;; The mark ring for links jumps
7455 (defvar org-mark-ring nil
7456 "Mark ring for positions before jumps in Org-mode.")
7457 (defvar org-mark-ring-last-goto nil
7458 "Last position in the mark ring used to go back.")
7459 ;; Fill and close the ring
7460 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7461 (loop for i from 1 to org-mark-ring-length do
7462 (push (make-marker) org-mark-ring))
7463 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7464 org-mark-ring)
7466 (defun org-mark-ring-push (&optional pos buffer)
7467 "Put the current position or POS into the mark ring and rotate it."
7468 (interactive)
7469 (setq pos (or pos (point)))
7470 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7471 (move-marker (car org-mark-ring)
7472 (or pos (point))
7473 (or buffer (current-buffer)))
7474 (message "%s"
7475 (substitute-command-keys
7476 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7478 (defun org-mark-ring-goto (&optional n)
7479 "Jump to the previous position in the mark ring.
7480 With prefix arg N, jump back that many stored positions. When
7481 called several times in succession, walk through the entire ring.
7482 Org-mode commands jumping to a different position in the current file,
7483 or to another Org-mode file, automatically push the old position
7484 onto the ring."
7485 (interactive "p")
7486 (let (p m)
7487 (if (eq last-command this-command)
7488 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7489 (setq p org-mark-ring))
7490 (setq org-mark-ring-last-goto p)
7491 (setq m (car p))
7492 (switch-to-buffer (marker-buffer m))
7493 (goto-char m)
7494 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7496 (defun org-remove-angle-brackets (s)
7497 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7498 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7500 (defun org-add-angle-brackets (s)
7501 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7502 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7504 (defun org-remove-double-quotes (s)
7505 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7506 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7509 ;;; Following specific links
7511 (defun org-follow-timestamp-link ()
7512 (cond
7513 ((org-at-date-range-p t)
7514 (let ((org-agenda-start-on-weekday)
7515 (t1 (match-string 1))
7516 (t2 (match-string 2)))
7517 (setq t1 (time-to-days (org-time-string-to-time t1))
7518 t2 (time-to-days (org-time-string-to-time t2)))
7519 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7520 ((org-at-timestamp-p t)
7521 (org-agenda-list nil (time-to-days (org-time-string-to-time
7522 (substring (match-string 1) 0 10)))
7524 (t (error "This should not happen"))))
7527 ;;; Following file links
7528 (defvar org-wait nil)
7529 (defun org-open-file (path &optional in-emacs line search)
7530 "Open the file at PATH.
7531 First, this expands any special file name abbreviations. Then the
7532 configuration variable `org-file-apps' is checked if it contains an
7533 entry for this file type, and if yes, the corresponding command is launched.
7535 If no application is found, Emacs simply visits the file.
7537 With optional prefix argument IN-EMACS, Emacs will visit the file.
7538 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7539 and o use an external application to visit the file.
7541 Optional LINE specifies a line to go to, optional SEARCH a string to
7542 search for. If LINE or SEARCH is given, the file will always be
7543 opened in Emacs.
7544 If the file does not exist, an error is thrown."
7545 (setq in-emacs (or in-emacs line search))
7546 (let* ((file (if (equal path "")
7547 buffer-file-name
7548 (substitute-in-file-name (expand-file-name path))))
7549 (apps (append org-file-apps (org-default-apps)))
7550 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7551 (dirp (if remp nil (file-directory-p file)))
7552 (file (if (and dirp org-open-directory-means-index-dot-org)
7553 (concat (file-name-as-directory file) "index.org")
7554 file))
7555 (a-m-a-p (assq 'auto-mode apps))
7556 (dfile (downcase file))
7557 (old-buffer (current-buffer))
7558 (old-pos (point))
7559 (old-mode major-mode)
7560 ext cmd)
7561 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7562 (setq ext (match-string 1 dfile))
7563 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7564 (setq ext (match-string 1 dfile))))
7565 (cond
7566 ((equal in-emacs '(16))
7567 (setq cmd (cdr (assoc 'system apps))))
7568 (in-emacs (setq cmd 'emacs))
7570 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7571 (and dirp (cdr (assoc 'directory apps)))
7572 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7573 'string-match)
7574 (cdr (assoc ext apps))
7575 (cdr (assoc t apps))))))
7576 (when (eq cmd 'system)
7577 (setq cmd (cdr (assoc 'system apps))))
7578 (when (eq cmd 'default)
7579 (setq cmd (cdr (assoc t apps))))
7580 (when (eq cmd 'mailcap)
7581 (require 'mailcap)
7582 (mailcap-parse-mailcaps)
7583 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7584 (command (mailcap-mime-info mime-type)))
7585 (if (stringp command)
7586 (setq cmd command)
7587 (setq cmd 'emacs))))
7588 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7589 (not (file-exists-p file))
7590 (not org-open-non-existing-files))
7591 (error "No such file: %s" file))
7592 (cond
7593 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7594 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7595 (while (string-match "['\"]%s['\"]" cmd)
7596 (setq cmd (replace-match "%s" t t cmd)))
7597 (while (string-match "%s" cmd)
7598 (setq cmd (replace-match
7599 (save-match-data
7600 (shell-quote-argument
7601 (convert-standard-filename file)))
7602 t t cmd)))
7603 (save-window-excursion
7604 (start-process-shell-command cmd nil cmd)
7605 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7607 ((or (stringp cmd)
7608 (eq cmd 'emacs))
7609 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7610 (widen)
7611 (if line (goto-line line)
7612 (if search (org-link-search search))))
7613 ((consp cmd)
7614 (let ((file (convert-standard-filename file)))
7615 (eval cmd)))
7616 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7617 (and (org-mode-p) (eq old-mode 'org-mode)
7618 (or (not (equal old-buffer (current-buffer)))
7619 (not (equal old-pos (point))))
7620 (org-mark-ring-push old-pos old-buffer))))
7622 (defun org-default-apps ()
7623 "Return the default applications for this operating system."
7624 (cond
7625 ((eq system-type 'darwin)
7626 org-file-apps-defaults-macosx)
7627 ((eq system-type 'windows-nt)
7628 org-file-apps-defaults-windowsnt)
7629 (t org-file-apps-defaults-gnu)))
7631 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7632 "Convert extensions to regular expressions in the cars of LIST.
7633 Also, weed out any non-string entries, because the return value is used
7634 only for regexp matching.
7635 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7636 point to the symbol `emacs', indicating that the file should
7637 be opened in Emacs."
7638 (append
7639 (delq nil
7640 (mapcar (lambda (x)
7641 (if (not (stringp (car x)))
7643 (if (string-match "\\W" (car x))
7645 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7646 list))
7647 (if add-auto-mode
7648 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7650 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7651 (defun org-file-remote-p (file)
7652 "Test whether FILE specifies a location on a remote system.
7653 Return non-nil if the location is indeed remote.
7655 For example, the filename \"/user@host:/foo\" specifies a location
7656 on the system \"/user@host:\"."
7657 (cond ((fboundp 'file-remote-p)
7658 (file-remote-p file))
7659 ((fboundp 'tramp-handle-file-remote-p)
7660 (tramp-handle-file-remote-p file))
7661 ((and (boundp 'ange-ftp-name-format)
7662 (string-match (car ange-ftp-name-format) file))
7664 (t nil)))
7667 ;;;; Refiling
7669 (defun org-get-org-file ()
7670 "Read a filename, with default directory `org-directory'."
7671 (let ((default (or org-default-notes-file remember-data-file)))
7672 (read-file-name (format "File name [%s]: " default)
7673 (file-name-as-directory org-directory)
7674 default)))
7676 (defun org-notes-order-reversed-p ()
7677 "Check if the current file should receive notes in reversed order."
7678 (cond
7679 ((not org-reverse-note-order) nil)
7680 ((eq t org-reverse-note-order) t)
7681 ((not (listp org-reverse-note-order)) nil)
7682 (t (catch 'exit
7683 (let ((all org-reverse-note-order)
7684 entry)
7685 (while (setq entry (pop all))
7686 (if (string-match (car entry) buffer-file-name)
7687 (throw 'exit (cdr entry))))
7688 nil)))))
7690 (defvar org-refile-target-table nil
7691 "The list of refile targets, created by `org-refile'.")
7693 (defvar org-agenda-new-buffers nil
7694 "Buffers created to visit agenda files.")
7696 (defun org-get-refile-targets (&optional default-buffer)
7697 "Produce a table with refile targets."
7698 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7699 targets txt re files f desc descre fast-path-p level)
7700 (message "Getting targets...")
7701 (with-current-buffer (or default-buffer (current-buffer))
7702 (while (setq entry (pop entries))
7703 (setq files (car entry) desc (cdr entry))
7704 (setq fast-path-p nil)
7705 (cond
7706 ((null files) (setq files (list (current-buffer))))
7707 ((eq files 'org-agenda-files)
7708 (setq files (org-agenda-files 'unrestricted)))
7709 ((and (symbolp files) (fboundp files))
7710 (setq files (funcall files)))
7711 ((and (symbolp files) (boundp files))
7712 (setq files (symbol-value files))))
7713 (if (stringp files) (setq files (list files)))
7714 (cond
7715 ((eq (car desc) :tag)
7716 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7717 ((eq (car desc) :todo)
7718 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7719 ((eq (car desc) :regexp)
7720 (setq descre (cdr desc)))
7721 ((eq (car desc) :level)
7722 (setq descre (concat "^\\*\\{" (number-to-string
7723 (if org-odd-levels-only
7724 (1- (* 2 (cdr desc)))
7725 (cdr desc)))
7726 "\\}[ \t]")))
7727 ((eq (car desc) :maxlevel)
7728 (setq fast-path-p t)
7729 (setq descre (concat "^\\*\\{1," (number-to-string
7730 (if org-odd-levels-only
7731 (1- (* 2 (cdr desc)))
7732 (cdr desc)))
7733 "\\}[ \t]")))
7734 (t (error "Bad refiling target description %s" desc)))
7735 (while (setq f (pop files))
7736 (save-excursion
7737 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7738 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7739 (setq f (expand-file-name f))
7740 (save-excursion
7741 (save-restriction
7742 (widen)
7743 (goto-char (point-min))
7744 (while (re-search-forward descre nil t)
7745 (goto-char (point-at-bol))
7746 (when (looking-at org-complex-heading-regexp)
7747 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7748 txt (org-link-display-format (match-string 4))
7749 re (concat "^" (regexp-quote
7750 (buffer-substring (match-beginning 1)
7751 (match-end 4)))))
7752 (if (match-end 5) (setq re (concat re "[ \t]+"
7753 (regexp-quote
7754 (match-string 5)))))
7755 (setq re (concat re "[ \t]*$"))
7756 (when org-refile-use-outline-path
7757 (setq txt (mapconcat 'org-protect-slash
7758 (append
7759 (if (eq org-refile-use-outline-path 'file)
7760 (list (file-name-nondirectory
7761 (buffer-file-name (buffer-base-buffer))))
7762 (if (eq org-refile-use-outline-path 'full-file-path)
7763 (list (buffer-file-name (buffer-base-buffer)))))
7764 (org-get-outline-path fast-path-p level txt)
7765 (list txt))
7766 "/")))
7767 (push (list txt f re (point)) targets))
7768 (goto-char (point-at-eol))))))))
7769 (message "Getting targets...done")
7770 (nreverse targets))))
7772 (defun org-protect-slash (s)
7773 (while (string-match "/" s)
7774 (setq s (replace-match "\\" t t s)))
7777 (defvar org-olpa (make-vector 20 nil))
7779 (defun org-get-outline-path (&optional fastp level heading)
7780 "Return the outline path to the current entry, as a list."
7781 (if fastp
7782 (progn
7783 (if (> level 19)
7784 (error "Outline path failure, more than 19 levels."))
7785 (loop for i from level upto 19 do
7786 (aset org-olpa i nil))
7787 (prog1
7788 (delq nil (append org-olpa nil))
7789 (aset org-olpa level heading)))
7790 (let (rtn)
7791 (save-excursion
7792 (while (org-up-heading-safe)
7793 (when (looking-at org-complex-heading-regexp)
7794 (push (org-match-string-no-properties 4) rtn)))
7795 rtn))))
7797 (defvar org-refile-history nil
7798 "History for refiling operations.")
7800 (defun org-refile (&optional goto default-buffer)
7801 "Move the entry at point to another heading.
7802 The list of target headings is compiled using the information in
7803 `org-refile-targets', which see. This list is created before each use
7804 and will therefore always be up-to-date.
7806 At the target location, the entry is filed as a subitem of the target heading.
7807 Depending on `org-reverse-note-order', the new subitem will either be the
7808 first or the last subitem.
7810 If there is an active region, all entries in that region will be moved.
7811 However, the region must fulfil the requirement that the first heading
7812 is the first one sets the top-level of the moved text - at most siblings
7813 below it are allowed.
7815 With prefix arg GOTO, the command will only visit the target location,
7816 not actually move anything.
7817 With a double prefix `C-u C-u', go to the location where the last refiling
7818 operation has put the subtree."
7819 (interactive "P")
7820 (let* ((cbuf (current-buffer))
7821 (regionp (org-region-active-p))
7822 (region-start (and regionp (region-beginning)))
7823 (region-end (and regionp (region-end)))
7824 (region-length (and regionp (- region-end region-start)))
7825 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7826 pos it nbuf file re level reversed)
7827 (when regionp (goto-char region-start)
7828 (unless (org-kill-is-subtree-p
7829 (buffer-substring region-start region-end))
7830 (error "The region is not a (sequence of) subtree(s)")))
7831 (if (equal goto '(16))
7832 (org-refile-goto-last-stored)
7833 (when (setq it (org-refile-get-location
7834 (if goto "Goto: " "Refile to: ") default-buffer))
7835 (setq file (nth 1 it)
7836 re (nth 2 it)
7837 pos (nth 3 it))
7838 (if (and (equal (buffer-file-name) file)
7839 (if regionp
7840 (and (>= pos region-start)
7841 (<= pos region-end))
7842 (and (>= pos (point))
7843 (< pos (save-excursion
7844 (org-end-of-subtree t t))))))
7845 (error "Cannot refile to position inside the tree or region"))
7847 (setq nbuf (or (find-buffer-visiting file)
7848 (find-file-noselect file)))
7849 (if goto
7850 (progn
7851 (switch-to-buffer nbuf)
7852 (goto-char pos)
7853 (org-show-context 'org-goto))
7854 (if regionp
7855 (progn
7856 (kill-new (buffer-substring region-start region-end))
7857 (org-save-markers-in-region region-start region-end))
7858 (org-copy-subtree 1 nil t))
7859 (save-excursion
7860 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7861 (find-file-noselect file))))
7862 (setq reversed (org-notes-order-reversed-p))
7863 (save-excursion
7864 (save-restriction
7865 (widen)
7866 (goto-char pos)
7867 (looking-at outline-regexp)
7868 (setq level (org-get-valid-level (funcall outline-level) 1))
7869 (goto-char
7870 (if reversed
7871 (or (outline-next-heading) (point-max))
7872 (or (save-excursion (outline-get-next-sibling))
7873 (org-end-of-subtree t t)
7874 (point-max))))
7875 (if (not (bolp)) (newline))
7876 (bookmark-set "org-refile-last-stored")
7877 (org-paste-subtree level))))
7878 (if regionp
7879 (delete-region (point) (+ (point) region-length))
7880 (org-cut-subtree))
7881 (setq org-markers-to-move nil)
7882 (message "Refiled to \"%s\"" (car it)))))))
7884 (defun org-refile-goto-last-stored ()
7885 "Go to the location where the last refile was stored."
7886 (interactive)
7887 (bookmark-jump "org-refile-last-stored")
7888 (message "This is the location of the last refile"))
7890 (defun org-refile-get-location (&optional prompt default-buffer)
7891 "Prompt the user for a refile location, using PROMPT."
7892 (let ((org-refile-targets org-refile-targets)
7893 (org-refile-use-outline-path org-refile-use-outline-path))
7894 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7895 (unless org-refile-target-table
7896 (error "No refile targets"))
7897 (let* ((cbuf (current-buffer))
7898 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7899 (cfunc (if (and org-refile-use-outline-path
7900 org-outline-path-complete-in-steps)
7901 'org-olpath-completing-read
7902 'org-ido-completing-read))
7903 (extra (if org-refile-use-outline-path "/" ""))
7904 (filename (and cfn (expand-file-name cfn)))
7905 (tbl (mapcar
7906 (lambda (x)
7907 (if (not (equal filename (nth 1 x)))
7908 (cons (concat (car x) extra " ("
7909 (file-name-nondirectory (nth 1 x)) ")")
7910 (cdr x))
7911 (cons (concat (car x) extra) (cdr x))))
7912 org-refile-target-table))
7913 (completion-ignore-case t))
7914 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7915 tbl)))
7917 (defun org-olpath-completing-read (prompt collection &rest args)
7918 "Read an outline path like a file name."
7919 (let ((thetable collection))
7920 (apply
7921 'org-ido-completing-read prompt
7922 (lambda (string predicate &optional flag)
7923 (let (rtn r f (l (length string)))
7924 (cond
7925 ((eq flag nil)
7926 ;; try completion
7927 (try-completion string thetable))
7928 ((eq flag t)
7929 ;; all-completions
7930 (setq rtn (all-completions string thetable predicate))
7931 (mapcar
7932 (lambda (x)
7933 (setq r (substring x l))
7934 (if (string-match " ([^)]*)$" x)
7935 (setq f (match-string 0 x))
7936 (setq f ""))
7937 (if (string-match "/" r)
7938 (concat string (substring r 0 (match-end 0)) f)
7940 rtn))
7941 ((eq flag 'lambda)
7942 ;; exact match?
7943 (assoc string thetable)))
7945 args)))
7947 ;;;; Dynamic blocks
7949 (defun org-find-dblock (name)
7950 "Find the first dynamic block with name NAME in the buffer.
7951 If not found, stay at current position and return nil."
7952 (let (pos)
7953 (save-excursion
7954 (goto-char (point-min))
7955 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7956 nil t)
7957 (match-beginning 0))))
7958 (if pos (goto-char pos))
7959 pos))
7961 (defconst org-dblock-start-re
7962 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7963 "Matches the startline of a dynamic block, with parameters.")
7965 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7966 "Matches the end of a dynamic block.")
7968 (defun org-create-dblock (plist)
7969 "Create a dynamic block section, with parameters taken from PLIST.
7970 PLIST must contain a :name entry which is used as name of the block."
7971 (unless (bolp) (newline))
7972 (let ((name (plist-get plist :name)))
7973 (insert "#+BEGIN: " name)
7974 (while plist
7975 (if (eq (car plist) :name)
7976 (setq plist (cddr plist))
7977 (insert " " (prin1-to-string (pop plist)))))
7978 (insert "\n\n#+END:\n")
7979 (beginning-of-line -2)))
7981 (defun org-prepare-dblock ()
7982 "Prepare dynamic block for refresh.
7983 This empties the block, puts the cursor at the insert position and returns
7984 the property list including an extra property :name with the block name."
7985 (unless (looking-at org-dblock-start-re)
7986 (error "Not at a dynamic block"))
7987 (let* ((begdel (1+ (match-end 0)))
7988 (name (org-no-properties (match-string 1)))
7989 (params (append (list :name name)
7990 (read (concat "(" (match-string 3) ")")))))
7991 (unless (re-search-forward org-dblock-end-re nil t)
7992 (error "Dynamic block not terminated"))
7993 (setq params
7994 (append params
7995 (list :content (buffer-substring
7996 begdel (match-beginning 0)))))
7997 (delete-region begdel (match-beginning 0))
7998 (goto-char begdel)
7999 (open-line 1)
8000 params))
8002 (defun org-map-dblocks (&optional command)
8003 "Apply COMMAND to all dynamic blocks in the current buffer.
8004 If COMMAND is not given, use `org-update-dblock'."
8005 (let ((cmd (or command 'org-update-dblock))
8006 pos)
8007 (save-excursion
8008 (goto-char (point-min))
8009 (while (re-search-forward org-dblock-start-re nil t)
8010 (goto-char (setq pos (match-beginning 0)))
8011 (condition-case nil
8012 (funcall cmd)
8013 (error (message "Error during update of dynamic block")))
8014 (goto-char pos)
8015 (unless (re-search-forward org-dblock-end-re nil t)
8016 (error "Dynamic block not terminated"))))))
8018 (defun org-dblock-update (&optional arg)
8019 "User command for updating dynamic blocks.
8020 Update the dynamic block at point. With prefix ARG, update all dynamic
8021 blocks in the buffer."
8022 (interactive "P")
8023 (if arg
8024 (org-update-all-dblocks)
8025 (or (looking-at org-dblock-start-re)
8026 (org-beginning-of-dblock))
8027 (org-update-dblock)))
8029 (defun org-update-dblock ()
8030 "Update the dynamic block at point
8031 This means to empty the block, parse for parameters and then call
8032 the correct writing function."
8033 (save-window-excursion
8034 (let* ((pos (point))
8035 (line (org-current-line))
8036 (params (org-prepare-dblock))
8037 (name (plist-get params :name))
8038 (cmd (intern (concat "org-dblock-write:" name))))
8039 (message "Updating dynamic block `%s' at line %d..." name line)
8040 (funcall cmd params)
8041 (message "Updating dynamic block `%s' at line %d...done" name line)
8042 (goto-char pos))))
8044 (defun org-beginning-of-dblock ()
8045 "Find the beginning of the dynamic block at point.
8046 Error if there is no such block at point."
8047 (let ((pos (point))
8048 beg)
8049 (end-of-line 1)
8050 (if (and (re-search-backward org-dblock-start-re nil t)
8051 (setq beg (match-beginning 0))
8052 (re-search-forward org-dblock-end-re nil t)
8053 (> (match-end 0) pos))
8054 (goto-char beg)
8055 (goto-char pos)
8056 (error "Not in a dynamic block"))))
8058 (defun org-update-all-dblocks ()
8059 "Update all dynamic blocks in the buffer.
8060 This function can be used in a hook."
8061 (when (org-mode-p)
8062 (org-map-dblocks 'org-update-dblock)))
8065 ;;;; Completion
8067 (defconst org-additional-option-like-keywords
8068 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8069 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8070 "BEGIN_EXAMPLE" "END_EXAMPLE"
8071 "BEGIN_QUOTE" "END_QUOTE"
8072 "BEGIN_VERSE" "END_VERSE"
8073 "BEGIN_SRC" "END_SRC"
8074 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8076 (defcustom org-structure-template-alist
8078 ("s" "#+begin_src ?\n\n#+end_src"
8079 "<src lang=\"?\">\n\n</src>")
8080 ("e" "#+begin_example\n?\n#+end_example"
8081 "<example>\n?\n</example>")
8082 ("q" "#+begin_quote\n?\n#+end_quote"
8083 "<quote>\n?\n</quote>")
8084 ("v" "#+begin_verse\n?\n#+end_verse"
8085 "<verse>\n?\n/verse>")
8086 ("l" "#+begin_latex\n?\n#+end_latex"
8087 "<literal style=\"latex\">\n?\n</literal>")
8088 ("L" "#+latex: "
8089 "<literal style=\"latex\">?</literal>")
8090 ("h" "#+begin_html\n?\n#+end_html"
8091 "<literal style=\"html\">\n?\n</literal>")
8092 ("H" "#+html: "
8093 "<literal style=\"html\">?</literal>")
8094 ("a" "#+begin_ascii\n?\n#+end_ascii")
8095 ("A" "#+ascii: ")
8096 ("i" "#+include %file ?"
8097 "<include file=%file markup=\"?\">")
8099 "Structure completion elements.
8100 This is a list of abbreviation keys and values. The value gets inserted
8101 it you type @samp{.} followed by the key and then the completion key,
8102 usually `M-TAB'. %file will be replaced by a file name after prompting
8103 for the file using completion.
8104 There are two templates for each key, the first uses the original Org syntax,
8105 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8106 the default when the /org-mtags.el/ module has been loaded. See also the
8107 variable `org-mtags-prefer-muse-templates'.
8108 This is an experimental feature, it is undecided if it is going to stay in."
8109 :group 'org-completion
8110 :type '(repeat
8111 (string :tag "Key")
8112 (string :tag "Template")
8113 (string :tag "Muse Template")))
8115 (defun org-try-structure-completion ()
8116 "Try to complete a structure template before point.
8117 This looks for strings like \"<e\" on an otherwise empty line and
8118 expands them."
8119 (let ((l (buffer-substring (point-at-bol) (point)))
8121 (when (and (looking-at "[ \t]*$")
8122 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8123 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8124 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8125 (match-beginning 1)) a)
8126 t)))
8128 (defun org-complete-expand-structure-template (start cell)
8129 "Expand a structure template."
8130 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8131 (rpl (nth (if musep 2 1) cell)))
8132 (delete-region start (point))
8133 (when (string-match "\\`#\\+" rpl)
8134 (cond
8135 ((bolp))
8136 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8137 (delete-region (point-at-bol) (point)))
8138 (t (newline))))
8139 (setq start (point))
8140 (if (string-match "%file" rpl)
8141 (setq rpl (replace-match
8142 (concat
8143 "\""
8144 (save-match-data
8145 (abbreviate-file-name (read-file-name "Include file: ")))
8146 "\"")
8147 t t rpl)))
8148 (insert rpl)
8149 (if (re-search-backward "\\?" start t) (delete-char 1))))
8152 (defun org-complete (&optional arg)
8153 "Perform completion on word at point.
8154 At the beginning of a headline, this completes TODO keywords as given in
8155 `org-todo-keywords'.
8156 If the current word is preceded by a backslash, completes the TeX symbols
8157 that are supported for HTML support.
8158 If the current word is preceded by \"#+\", completes special words for
8159 setting file options.
8160 In the line after \"#+STARTUP:, complete valid keywords.\"
8161 At all other locations, this simply calls the value of
8162 `org-completion-fallback-command'."
8163 (interactive "P")
8164 (org-without-partial-completion
8165 (catch 'exit
8166 (let* ((a nil)
8167 (end (point))
8168 (beg1 (save-excursion
8169 (skip-chars-backward (org-re "[:alnum:]_@"))
8170 (point)))
8171 (beg (save-excursion
8172 (skip-chars-backward "a-zA-Z0-9_:$")
8173 (point)))
8174 (confirm (lambda (x) (stringp (car x))))
8175 (searchhead (equal (char-before beg) ?*))
8176 (struct
8177 (when (and (member (char-before beg1) '(?. ?<))
8178 (setq a (assoc (buffer-substring beg1 (point))
8179 org-structure-template-alist)))
8180 (org-complete-expand-structure-template (1- beg1) a)
8181 (throw 'exit t)))
8182 (tag (and (equal (char-before beg1) ?:)
8183 (equal (char-after (point-at-bol)) ?*)))
8184 (prop (and (equal (char-before beg1) ?:)
8185 (not (equal (char-after (point-at-bol)) ?*))))
8186 (texp (equal (char-before beg) ?\\))
8187 (link (equal (char-before beg) ?\[))
8188 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8189 beg)
8190 "#+"))
8191 (startup (string-match "^#\\+STARTUP:.*"
8192 (buffer-substring (point-at-bol) (point))))
8193 (completion-ignore-case opt)
8194 (type nil)
8195 (tbl nil)
8196 (table (cond
8197 (opt
8198 (setq type :opt)
8199 (require 'org-exp)
8200 (append
8201 (mapcar
8202 (lambda (x)
8203 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8204 (cons (match-string 2 x) (match-string 1 x)))
8205 (org-split-string (org-get-current-options) "\n"))
8206 (mapcar 'list org-additional-option-like-keywords)))
8207 (startup
8208 (setq type :startup)
8209 org-startup-options)
8210 (link (append org-link-abbrev-alist-local
8211 org-link-abbrev-alist))
8212 (texp
8213 (setq type :tex)
8214 org-html-entities)
8215 ((string-match "\\`\\*+[ \t]+\\'"
8216 (buffer-substring (point-at-bol) beg))
8217 (setq type :todo)
8218 (mapcar 'list org-todo-keywords-1))
8219 (searchhead
8220 (setq type :searchhead)
8221 (save-excursion
8222 (goto-char (point-min))
8223 (while (re-search-forward org-todo-line-regexp nil t)
8224 (push (list
8225 (org-make-org-heading-search-string
8226 (match-string 3) t))
8227 tbl)))
8228 tbl)
8229 (tag (setq type :tag beg beg1)
8230 (or org-tag-alist (org-get-buffer-tags)))
8231 (prop (setq type :prop beg beg1)
8232 (mapcar 'list (org-buffer-property-keys nil t t)))
8233 (t (progn
8234 (call-interactively org-completion-fallback-command)
8235 (throw 'exit nil)))))
8236 (pattern (buffer-substring-no-properties beg end))
8237 (completion (try-completion pattern table confirm)))
8238 (cond ((eq completion t)
8239 (if (not (assoc (upcase pattern) table))
8240 (message "Already complete")
8241 (if (and (equal type :opt)
8242 (not (member (car (assoc (upcase pattern) table))
8243 org-additional-option-like-keywords)))
8244 (insert (substring (cdr (assoc (upcase pattern) table))
8245 (length pattern)))
8246 (if (memq type '(:tag :prop)) (insert ":")))))
8247 ((null completion)
8248 (message "Can't find completion for \"%s\"" pattern)
8249 (ding))
8250 ((not (string= pattern completion))
8251 (delete-region beg end)
8252 (if (string-match " +$" completion)
8253 (setq completion (replace-match "" t t completion)))
8254 (insert completion)
8255 (if (get-buffer-window "*Completions*")
8256 (delete-window (get-buffer-window "*Completions*")))
8257 (if (assoc completion table)
8258 (if (eq type :todo) (insert " ")
8259 (if (memq type '(:tag :prop)) (insert ":"))))
8260 (if (and (equal type :opt) (assoc completion table))
8261 (message "%s" (substitute-command-keys
8262 "Press \\[org-complete] again to insert example settings"))))
8264 (message "Making completion list...")
8265 (let ((list (sort (all-completions pattern table confirm)
8266 'string<)))
8267 (with-output-to-temp-buffer "*Completions*"
8268 (condition-case nil
8269 ;; Protection needed for XEmacs and emacs 21
8270 (display-completion-list list pattern)
8271 (error (display-completion-list list)))))
8272 (message "Making completion list...%s" "done")))))))
8274 ;;;; TODO, DEADLINE, Comments
8276 (defun org-toggle-comment ()
8277 "Change the COMMENT state of an entry."
8278 (interactive)
8279 (save-excursion
8280 (org-back-to-heading)
8281 (let (case-fold-search)
8282 (if (looking-at (concat outline-regexp
8283 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8284 (replace-match "" t t nil 1)
8285 (if (looking-at outline-regexp)
8286 (progn
8287 (goto-char (match-end 0))
8288 (insert org-comment-string " ")))))))
8290 (defvar org-last-todo-state-is-todo nil
8291 "This is non-nil when the last TODO state change led to a TODO state.
8292 If the last change removed the TODO tag or switched to DONE, then
8293 this is nil.")
8295 (defvar org-setting-tags nil) ; dynamically skipped
8297 (defun org-parse-local-options (string var)
8298 "Parse STRING for startup setting relevant for variable VAR."
8299 (let ((rtn (symbol-value var))
8300 e opts)
8301 (save-match-data
8302 (if (or (not string) (not (string-match "\\S-" string)))
8304 (setq opts (delq nil (mapcar (lambda (x)
8305 (setq e (assoc x org-startup-options))
8306 (if (eq (nth 1 e) var) e nil))
8307 (org-split-string string "[ \t]+"))))
8308 (if (not opts)
8310 (setq rtn nil)
8311 (while (setq e (pop opts))
8312 (if (not (nth 3 e))
8313 (setq rtn (nth 2 e))
8314 (if (not (listp rtn)) (setq rtn nil))
8315 (push (nth 2 e) rtn)))
8316 rtn)))))
8318 (defvar org-agenda-headline-snapshot-before-repeat)
8319 (defun org-todo (&optional arg)
8320 "Change the TODO state of an item.
8321 The state of an item is given by a keyword at the start of the heading,
8322 like
8323 *** TODO Write paper
8324 *** DONE Call mom
8326 The different keywords are specified in the variable `org-todo-keywords'.
8327 By default the available states are \"TODO\" and \"DONE\".
8328 So for this example: when the item starts with TODO, it is changed to DONE.
8329 When it starts with DONE, the DONE is removed. And when neither TODO nor
8330 DONE are present, add TODO at the beginning of the heading.
8332 With C-u prefix arg, use completion to determine the new state.
8333 With numeric prefix arg, switch to that state.
8334 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8336 For calling through lisp, arg is also interpreted in the following way:
8337 'none -> empty state
8338 \"\"(empty string) -> switch to empty state
8339 'done -> switch to DONE
8340 'nextset -> switch to the next set of keywords
8341 'previousset -> switch to the previous set of keywords
8342 \"WAITING\" -> switch to the specified keyword, but only if it
8343 really is a member of `org-todo-keywords'."
8344 (interactive "P")
8345 (if (equal arg '(16)) (setq arg 'nextset))
8346 (save-excursion
8347 (catch 'exit
8348 (org-back-to-heading)
8349 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8350 (or (looking-at (concat " +" org-todo-regexp " *"))
8351 (looking-at " *"))
8352 (let* ((match-data (match-data))
8353 (startpos (point-at-bol))
8354 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8355 (org-log-done org-log-done)
8356 (org-log-repeat org-log-repeat)
8357 (org-todo-log-states org-todo-log-states)
8358 (this (match-string 1))
8359 (hl-pos (match-beginning 0))
8360 (head (org-get-todo-sequence-head this))
8361 (ass (assoc head org-todo-kwd-alist))
8362 (interpret (nth 1 ass))
8363 (done-word (nth 3 ass))
8364 (final-done-word (nth 4 ass))
8365 (last-state (or this ""))
8366 (completion-ignore-case t)
8367 (member (member this org-todo-keywords-1))
8368 (tail (cdr member))
8369 (state (cond
8370 ((and org-todo-key-trigger
8371 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8372 (and (not arg) org-use-fast-todo-selection
8373 (not (eq org-use-fast-todo-selection 'prefix)))))
8374 ;; Use fast selection
8375 (org-fast-todo-selection))
8376 ((and (equal arg '(4))
8377 (or (not org-use-fast-todo-selection)
8378 (not org-todo-key-trigger)))
8379 ;; Read a state with completion
8380 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8381 org-todo-keywords-1)
8382 nil t))
8383 ((eq arg 'right)
8384 (if this
8385 (if tail (car tail) nil)
8386 (car org-todo-keywords-1)))
8387 ((eq arg 'left)
8388 (if (equal member org-todo-keywords-1)
8390 (if this
8391 (nth (- (length org-todo-keywords-1) (length tail) 2)
8392 org-todo-keywords-1)
8393 (org-last org-todo-keywords-1))))
8394 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8395 (setq arg nil))) ; hack to fall back to cycling
8396 (arg
8397 ;; user or caller requests a specific state
8398 (cond
8399 ((equal arg "") nil)
8400 ((eq arg 'none) nil)
8401 ((eq arg 'done) (or done-word (car org-done-keywords)))
8402 ((eq arg 'nextset)
8403 (or (car (cdr (member head org-todo-heads)))
8404 (car org-todo-heads)))
8405 ((eq arg 'previousset)
8406 (let ((org-todo-heads (reverse org-todo-heads)))
8407 (or (car (cdr (member head org-todo-heads)))
8408 (car org-todo-heads))))
8409 ((car (member arg org-todo-keywords-1)))
8410 ((nth (1- (prefix-numeric-value arg))
8411 org-todo-keywords-1))))
8412 ((null member) (or head (car org-todo-keywords-1)))
8413 ((equal this final-done-word) nil) ;; -> make empty
8414 ((null tail) nil) ;; -> first entry
8415 ((eq interpret 'sequence)
8416 (car tail))
8417 ((memq interpret '(type priority))
8418 (if (eq this-command last-command)
8419 (car tail)
8420 (if (> (length tail) 0)
8421 (or done-word (car org-done-keywords))
8422 nil)))
8423 (t nil)))
8424 (next (if state (concat " " state " ") " "))
8425 (change-plist (list :type 'todo-state-change :from this :to state
8426 :position startpos))
8427 dolog now-done-p)
8428 (when org-blocker-hook
8429 (setq org-last-todo-state-is-todo
8430 (not (member this org-done-keywords)))
8431 (unless (save-excursion
8432 (save-match-data
8433 (run-hook-with-args-until-failure
8434 'org-blocker-hook change-plist)))
8435 (if (interactive-p)
8436 (error "TODO state change from %s to %s blocked" this state)
8437 ;; fail silently
8438 (message "TODO state change from %s to %s blocked" this state)
8439 (throw 'exit nil))))
8440 (store-match-data match-data)
8441 (replace-match next t t)
8442 (unless (pos-visible-in-window-p hl-pos)
8443 (message "TODO state changed to %s" (org-trim next)))
8444 (unless head
8445 (setq head (org-get-todo-sequence-head state)
8446 ass (assoc head org-todo-kwd-alist)
8447 interpret (nth 1 ass)
8448 done-word (nth 3 ass)
8449 final-done-word (nth 4 ass)))
8450 (when (memq arg '(nextset previousset))
8451 (message "Keyword-Set %d/%d: %s"
8452 (- (length org-todo-sets) -1
8453 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8454 (length org-todo-sets)
8455 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8456 (setq org-last-todo-state-is-todo
8457 (not (member state org-done-keywords)))
8458 (setq now-done-p (and (member state org-done-keywords)
8459 (not (member this org-done-keywords))))
8460 (and logging (org-local-logging logging))
8461 (when (and (or org-todo-log-states org-log-done)
8462 (not (memq arg '(nextset previousset))))
8463 ;; we need to look at recording a time and note
8464 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8465 (nth 2 (assoc this org-todo-log-states))))
8466 (when (and state
8467 (member state org-not-done-keywords)
8468 (not (member this org-not-done-keywords)))
8469 ;; This is now a todo state and was not one before
8470 ;; If there was a CLOSED time stamp, get rid of it.
8471 (org-add-planning-info nil nil 'closed))
8472 (when (and now-done-p org-log-done)
8473 ;; It is now done, and it was not done before
8474 (org-add-planning-info 'closed (org-current-time))
8475 (if (and (not dolog) (eq 'note org-log-done))
8476 (org-add-log-setup 'done state 'findpos 'note)))
8477 (when (and state dolog)
8478 ;; This is a non-nil state, and we need to log it
8479 (org-add-log-setup 'state state 'findpos dolog)))
8480 ;; Fixup tag positioning
8481 (org-todo-trigger-tag-changes state)
8482 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8483 (when org-provide-todo-statistics
8484 (org-update-parent-todo-statistics))
8485 (run-hooks 'org-after-todo-state-change-hook)
8486 (if (and arg (not (member state org-done-keywords)))
8487 (setq head (org-get-todo-sequence-head state)))
8488 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8489 ;; Do we need to trigger a repeat?
8490 (when now-done-p
8491 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8492 ;; This is for the agenda, take a snapshot of the headline.
8493 (save-match-data
8494 (setq org-agenda-headline-snapshot-before-repeat
8495 (org-get-heading))))
8496 (org-auto-repeat-maybe state))
8497 ;; Fixup cursor location if close to the keyword
8498 (if (and (outline-on-heading-p)
8499 (not (bolp))
8500 (save-excursion (beginning-of-line 1)
8501 (looking-at org-todo-line-regexp))
8502 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8503 (progn
8504 (goto-char (or (match-end 2) (match-end 1)))
8505 (just-one-space)))
8506 (when org-trigger-hook
8507 (save-excursion
8508 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8510 (defun org-block-todo-from-children-or-siblings (change-plist)
8511 "Block turning an entry into a TODO, using the hierarchy.
8512 This checks whether the current task should be blocked from state
8513 changes. Such blocking occurs when:
8515 1. The task has children which are not all in a completed state.
8517 2. A task has a parent with the property :ORDERED:, and there
8518 are siblings prior to the current task with incomplete
8519 status."
8520 (catch 'dont-block
8521 ;; If this is not a todo state change, or if this entry is already DONE,
8522 ;; do not block
8523 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8524 (member (plist-get change-plist :from)
8525 (cons 'done org-done-keywords)))
8526 (throw 'dont-block t))
8527 ;; If this task has children, and any are undone, it's blocked
8528 (save-excursion
8529 (org-back-to-heading t)
8530 (let ((this-level (funcall outline-level)))
8531 (outline-next-heading)
8532 (let ((child-level (funcall outline-level)))
8533 (while (and (not (eobp))
8534 (> child-level this-level))
8535 ;; this todo has children, check whether they are all
8536 ;; completed
8537 (if (and (not (org-entry-is-done-p))
8538 (org-entry-is-todo-p))
8539 (throw 'dont-block nil))
8540 (outline-next-heading)
8541 (setq child-level (funcall outline-level))))))
8542 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8543 ;; any previous siblings are undone, it's blocked
8544 (save-excursion
8545 (org-back-to-heading t)
8546 (when (save-excursion
8547 (ignore-errors
8548 (outline-up-heading 1)
8549 (org-entry-get (point) "ORDERED")))
8550 (let* ((this-level (funcall outline-level))
8551 (current-level this-level))
8552 (while (and (not (bobp))
8553 (= current-level this-level))
8554 (outline-previous-heading)
8555 (setq current-level (funcall outline-level))
8556 (if (= current-level this-level)
8557 ;; this todo has children, check whether they are all
8558 ;; completed
8559 (if (and (not (org-entry-is-done-p))
8560 (org-entry-is-todo-p))
8561 (throw 'dont-block nil)))))))
8562 t)) ; don't block
8564 (defun org-toggle-ordered-property ()
8565 "Toggle the ORDERED property of the current entry."
8566 (interactive)
8567 (save-excursion
8568 (org-back-to-heading)
8569 (if (org-entry-get nil "ORDERED")
8570 (progn
8571 (org-delete-property "ORDERED")
8572 (message "Subtasks can be completed in arbitrary order or parallel"))
8573 (org-entry-put nil "ORDERED" "t")
8574 (message "Subtasks must be completed in sequence"))))
8576 (defun org-update-parent-todo-statistics ()
8577 "Update any statistics cookie in the parent of the current headline."
8578 (interactive)
8579 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8580 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8581 (catch 'exit
8582 (save-excursion
8583 (setq level (org-up-heading-safe))
8584 (unless level
8585 (throw 'exit nil))
8586 (while (re-search-forward box-re (point-at-eol) t)
8587 (setq is-percent (match-end 2))
8588 (save-match-data
8589 (unless (outline-next-heading) (throw 'exit nil))
8590 (while (looking-at org-todo-line-regexp)
8591 (setq kwd (match-string 2))
8592 (and kwd (setq cnt-all (1+ cnt-all)))
8593 (and (member kwd org-done-keywords)
8594 (setq cnt-done (1+ cnt-done)))
8595 (condition-case nil
8596 (org-forward-same-level 1)
8597 (error (end-of-line 1)))))
8598 (replace-match
8599 (if is-percent
8600 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8601 (format "[%d/%d]" cnt-done cnt-all))))
8602 (run-hook-with-args 'org-after-todo-statistics-hook
8603 cnt-done (- cnt-all cnt-done))))))
8605 (defvar org-after-todo-statistics-hook nil
8606 "Hook that is called after a TODO statistics cookie has been updated.
8607 Each function is called with two arguments: the number of not-done entries
8608 and the number of done entries.
8610 For example, the following function, when added to this hook, will switch
8611 an entry to DONE when all children are done, and back to TODO when new
8612 entries are set to a TODO status. Note that this hook is only called
8613 when there is a statistics cookie in the headline!
8615 (defun org-summary-todo (n-done n-not-done)
8616 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8617 (let (org-log-done org-log-states) ; turn off logging
8618 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8621 (defun org-todo-trigger-tag-changes (state)
8622 "Apply the changes defined in `org-todo-state-tags-triggers'."
8623 (let ((l org-todo-state-tags-triggers)
8624 changes)
8625 (when (or (not state) (equal state ""))
8626 (setq changes (append changes (cdr (assoc "" l)))))
8627 (when (and (stringp state) (> (length state) 0))
8628 (setq changes (append changes (cdr (assoc state l)))))
8629 (when (member state org-not-done-keywords)
8630 (setq changes (append changes (cdr (assoc 'todo l)))))
8631 (when (member state org-done-keywords)
8632 (setq changes (append changes (cdr (assoc 'done l)))))
8633 (dolist (c changes)
8634 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8636 (defun org-local-logging (value)
8637 "Get logging settings from a property VALUE."
8638 (let* (words w a)
8639 ;; directly set the variables, they are already local.
8640 (setq org-log-done nil
8641 org-log-repeat nil
8642 org-todo-log-states nil)
8643 (setq words (org-split-string value))
8644 (while (setq w (pop words))
8645 (cond
8646 ((setq a (assoc w org-startup-options))
8647 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8648 (set (nth 1 a) (nth 2 a))))
8649 ((setq a (org-extract-log-state-settings w))
8650 (and (member (car a) org-todo-keywords-1)
8651 (push a org-todo-log-states)))))))
8653 (defun org-get-todo-sequence-head (kwd)
8654 "Return the head of the TODO sequence to which KWD belongs.
8655 If KWD is not set, check if there is a text property remembering the
8656 right sequence."
8657 (let (p)
8658 (cond
8659 ((not kwd)
8660 (or (get-text-property (point-at-bol) 'org-todo-head)
8661 (progn
8662 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8663 nil (point-at-eol)))
8664 (get-text-property p 'org-todo-head))))
8665 ((not (member kwd org-todo-keywords-1))
8666 (car org-todo-keywords-1))
8667 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8669 (defun org-fast-todo-selection ()
8670 "Fast TODO keyword selection with single keys.
8671 Returns the new TODO keyword, or nil if no state change should occur."
8672 (let* ((fulltable org-todo-key-alist)
8673 (done-keywords org-done-keywords) ;; needed for the faces.
8674 (maxlen (apply 'max (mapcar
8675 (lambda (x)
8676 (if (stringp (car x)) (string-width (car x)) 0))
8677 fulltable)))
8678 (expert nil)
8679 (fwidth (+ maxlen 3 1 3))
8680 (ncol (/ (- (window-width) 4) fwidth))
8681 tg cnt e c tbl
8682 groups ingroup)
8683 (save-excursion
8684 (save-window-excursion
8685 (if expert
8686 (set-buffer (get-buffer-create " *Org todo*"))
8687 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8688 (erase-buffer)
8689 (org-set-local 'org-done-keywords done-keywords)
8690 (setq tbl fulltable cnt 0)
8691 (while (setq e (pop tbl))
8692 (cond
8693 ((equal e '(:startgroup))
8694 (push '() groups) (setq ingroup t)
8695 (when (not (= cnt 0))
8696 (setq cnt 0)
8697 (insert "\n"))
8698 (insert "{ "))
8699 ((equal e '(:endgroup))
8700 (setq ingroup nil cnt 0)
8701 (insert "}\n"))
8703 (setq tg (car e) c (cdr e))
8704 (if ingroup (push tg (car groups)))
8705 (setq tg (org-add-props tg nil 'face
8706 (org-get-todo-face tg)))
8707 (if (and (= cnt 0) (not ingroup)) (insert " "))
8708 (insert "[" c "] " tg (make-string
8709 (- fwidth 4 (length tg)) ?\ ))
8710 (when (= (setq cnt (1+ cnt)) ncol)
8711 (insert "\n")
8712 (if ingroup (insert " "))
8713 (setq cnt 0)))))
8714 (insert "\n")
8715 (goto-char (point-min))
8716 (if (not expert) (org-fit-window-to-buffer))
8717 (message "[a-z..]:Set [SPC]:clear")
8718 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8719 (cond
8720 ((or (= c ?\C-g)
8721 (and (= c ?q) (not (rassoc c fulltable))))
8722 (setq quit-flag t))
8723 ((= c ?\ ) nil)
8724 ((setq e (rassoc c fulltable) tg (car e))
8726 (t (setq quit-flag t)))))))
8728 (defun org-entry-is-todo-p ()
8729 (member (org-get-todo-state) org-not-done-keywords))
8731 (defun org-entry-is-done-p ()
8732 (member (org-get-todo-state) org-done-keywords))
8734 (defun org-get-todo-state ()
8735 (save-excursion
8736 (org-back-to-heading t)
8737 (and (looking-at org-todo-line-regexp)
8738 (match-end 2)
8739 (match-string 2))))
8741 (defun org-at-date-range-p (&optional inactive-ok)
8742 "Is the cursor inside a date range?"
8743 (interactive)
8744 (save-excursion
8745 (catch 'exit
8746 (let ((pos (point)))
8747 (skip-chars-backward "^[<\r\n")
8748 (skip-chars-backward "<[")
8749 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8750 (>= (match-end 0) pos)
8751 (throw 'exit t))
8752 (skip-chars-backward "^<[\r\n")
8753 (skip-chars-backward "<[")
8754 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8755 (>= (match-end 0) pos)
8756 (throw 'exit t)))
8757 nil)))
8759 (defun org-get-repeat ()
8760 "Check if there is a deadline/schedule with repeater in this entry."
8761 (save-match-data
8762 (save-excursion
8763 (org-back-to-heading t)
8764 (if (re-search-forward
8765 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8766 (match-string 1)))))
8768 (defvar org-last-changed-timestamp)
8769 (defvar org-last-inserted-timestamp)
8770 (defvar org-log-post-message)
8771 (defvar org-log-note-purpose)
8772 (defvar org-log-note-how)
8773 (defvar org-log-note-extra)
8774 (defun org-auto-repeat-maybe (done-word)
8775 "Check if the current headline contains a repeated deadline/schedule.
8776 If yes, set TODO state back to what it was and change the base date
8777 of repeating deadline/scheduled time stamps to new date.
8778 This function is run automatically after each state change to a DONE state."
8779 ;; last-state is dynamically scoped into this function
8780 (let* ((repeat (org-get-repeat))
8781 (aa (assoc last-state org-todo-kwd-alist))
8782 (interpret (nth 1 aa))
8783 (head (nth 2 aa))
8784 (whata '(("d" . day) ("m" . month) ("y" . year)))
8785 (msg "Entry repeats: ")
8786 (org-log-done nil)
8787 (org-todo-log-states nil)
8788 (nshiftmax 10) (nshift 0)
8789 re type n what ts time)
8790 (when repeat
8791 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8792 (org-todo (if (eq interpret 'type) last-state head))
8793 (when org-log-repeat
8794 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8795 (memq 'org-add-log-note post-command-hook))
8796 ;; OK, we are already setup for some record
8797 (if (eq org-log-repeat 'note)
8798 ;; make sure we take a note, not only a time stamp
8799 (setq org-log-note-how 'note))
8800 ;; Set up for taking a record
8801 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8802 'findpos org-log-repeat)))
8803 (org-back-to-heading t)
8804 (org-add-planning-info nil nil 'closed)
8805 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8806 org-deadline-time-regexp "\\)\\|\\("
8807 org-ts-regexp "\\)"))
8808 (while (re-search-forward
8809 re (save-excursion (outline-next-heading) (point)) t)
8810 (setq type (if (match-end 1) org-scheduled-string
8811 (if (match-end 3) org-deadline-string "Plain:"))
8812 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8813 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8814 (setq n (string-to-number (match-string 2 ts))
8815 what (match-string 3 ts))
8816 (if (equal what "w") (setq n (* n 7) what "d"))
8817 ;; Preparation, see if we need to modify the start date for the change
8818 (when (match-end 1)
8819 (setq time (save-match-data (org-time-string-to-time ts)))
8820 (cond
8821 ((equal (match-string 1 ts) ".")
8822 ;; Shift starting date to today
8823 (org-timestamp-change
8824 (- (time-to-days (current-time)) (time-to-days time))
8825 'day))
8826 ((equal (match-string 1 ts) "+")
8827 (while (or (= nshift 0)
8828 (<= (time-to-days time) (time-to-days (current-time))))
8829 (when (= (incf nshift) nshiftmax)
8830 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8831 (error "Abort")))
8832 (org-timestamp-change n (cdr (assoc what whata)))
8833 (org-at-timestamp-p t)
8834 (setq ts (match-string 1))
8835 (setq time (save-match-data (org-time-string-to-time ts))))
8836 (org-timestamp-change (- n) (cdr (assoc what whata)))
8837 ;; rematch, so that we have everything in place for the real shift
8838 (org-at-timestamp-p t)
8839 (setq ts (match-string 1))
8840 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8841 (org-timestamp-change n (cdr (assoc what whata)))
8842 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8843 (setq org-log-post-message msg)
8844 (message "%s" msg))))
8846 (defun org-show-todo-tree (arg)
8847 "Make a compact tree which shows all headlines marked with TODO.
8848 The tree will show the lines where the regexp matches, and all higher
8849 headlines above the match.
8850 With a \\[universal-argument] prefix, also show the DONE entries.
8851 With a numeric prefix N, construct a sparse tree for the Nth element
8852 of `org-todo-keywords-1'."
8853 (interactive "P")
8854 (let ((case-fold-search nil)
8855 (kwd-re
8856 (cond ((null arg) org-not-done-regexp)
8857 ((equal arg '(4))
8858 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8859 (mapcar 'list org-todo-keywords-1))))
8860 (concat "\\("
8861 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8862 "\\)\\>")))
8863 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8864 (regexp-quote (nth (1- (prefix-numeric-value arg))
8865 org-todo-keywords-1)))
8866 (t (error "Invalid prefix argument: %s" arg)))))
8867 (message "%d TODO entries found"
8868 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8870 (defun org-deadline (&optional remove time)
8871 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8872 With argument REMOVE, remove any deadline from the item.
8873 When TIME is set, it should be an internal time specification, and the
8874 scheduling will use the corresponding date."
8875 (interactive "P")
8876 (if remove
8877 (progn
8878 (org-remove-timestamp-with-keyword org-deadline-string)
8879 (message "Item no longer has a deadline."))
8880 (if (org-get-repeat)
8881 (error "Cannot change deadline on task with repeater, please do that by hand")
8882 (org-add-planning-info 'deadline time 'closed)
8883 (message "Deadline on %s" org-last-inserted-timestamp))))
8885 (defun org-schedule (&optional remove time)
8886 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8887 With argument REMOVE, remove any scheduling date from the item.
8888 When TIME is set, it should be an internal time specification, and the
8889 scheduling will use the corresponding date."
8890 (interactive "P")
8891 (if remove
8892 (progn
8893 (org-remove-timestamp-with-keyword org-scheduled-string)
8894 (message "Item is no longer scheduled."))
8895 (if (org-get-repeat)
8896 (error "Cannot reschedule task with repeater, please do that by hand")
8897 (org-add-planning-info 'scheduled time 'closed)
8898 (message "Scheduled to %s" org-last-inserted-timestamp))))
8900 (defun org-remove-timestamp-with-keyword (keyword)
8901 "Remove all time stamps with KEYWORD in the current entry."
8902 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8903 beg)
8904 (save-excursion
8905 (org-back-to-heading t)
8906 (setq beg (point))
8907 (org-end-of-subtree t t)
8908 (while (re-search-backward re beg t)
8909 (replace-match "")
8910 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8911 (equal (char-before) ?\ ))
8912 (backward-delete-char 1)
8913 (if (string-match "^[ \t]*$" (buffer-substring
8914 (point-at-bol) (point-at-eol)))
8915 (delete-region (point-at-bol)
8916 (min (point-max) (1+ (point-at-eol))))))))))
8918 (defun org-add-planning-info (what &optional time &rest remove)
8919 "Insert new timestamp with keyword in the line directly after the headline.
8920 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8921 If non is given, the user is prompted for a date.
8922 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8923 be removed."
8924 (interactive)
8925 (let (org-time-was-given org-end-time-was-given ts
8926 end default-time default-input)
8928 (when (and (not time) (memq what '(scheduled deadline)))
8929 ;; Try to get a default date/time from existing timestamp
8930 (save-excursion
8931 (org-back-to-heading t)
8932 (setq end (save-excursion (outline-next-heading) (point)))
8933 (when (re-search-forward (if (eq what 'scheduled)
8934 org-scheduled-time-regexp
8935 org-deadline-time-regexp)
8936 end t)
8937 (setq ts (match-string 1)
8938 default-time
8939 (apply 'encode-time (org-parse-time-string ts))
8940 default-input (and ts (org-get-compact-tod ts))))))
8941 (when what
8942 ;; If necessary, get the time from the user
8943 (setq time (or time (org-read-date nil 'to-time nil nil
8944 default-time default-input))))
8946 (when (and org-insert-labeled-timestamps-at-point
8947 (member what '(scheduled deadline)))
8948 (insert
8949 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8950 (org-insert-time-stamp time org-time-was-given
8951 nil nil nil (list org-end-time-was-given))
8952 (setq what nil))
8953 (save-excursion
8954 (save-restriction
8955 (let (col list elt ts buffer-invisibility-spec)
8956 (org-back-to-heading t)
8957 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8958 (goto-char (match-end 1))
8959 (setq col (current-column))
8960 (goto-char (match-end 0))
8961 (if (eobp) (insert "\n") (forward-char 1))
8962 (if (and (not (looking-at outline-regexp))
8963 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8964 "[^\r\n]*"))
8965 (not (equal (match-string 1) org-clock-string)))
8966 (narrow-to-region (match-beginning 0) (match-end 0))
8967 (insert-before-markers "\n")
8968 (backward-char 1)
8969 (narrow-to-region (point) (point))
8970 (and org-adapt-indentation (org-indent-to-column col)))
8971 ;; Check if we have to remove something.
8972 (setq list (cons what remove))
8973 (while list
8974 (setq elt (pop list))
8975 (goto-char (point-min))
8976 (when (or (and (eq elt 'scheduled)
8977 (re-search-forward org-scheduled-time-regexp nil t))
8978 (and (eq elt 'deadline)
8979 (re-search-forward org-deadline-time-regexp nil t))
8980 (and (eq elt 'closed)
8981 (re-search-forward org-closed-time-regexp nil t)))
8982 (replace-match "")
8983 (if (looking-at "--+<[^>]+>") (replace-match ""))
8984 (if (looking-at " +") (replace-match ""))))
8985 (goto-char (point-max))
8986 (when what
8987 (insert
8988 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8989 (cond ((eq what 'scheduled) org-scheduled-string)
8990 ((eq what 'deadline) org-deadline-string)
8991 ((eq what 'closed) org-closed-string))
8992 " ")
8993 (setq ts (org-insert-time-stamp
8994 time
8995 (or org-time-was-given
8996 (and (eq what 'closed) org-log-done-with-time))
8997 (eq what 'closed)
8998 nil nil (list org-end-time-was-given)))
8999 (end-of-line 1))
9000 (goto-char (point-min))
9001 (widen)
9002 (if (and (looking-at "[ \t]+\n")
9003 (equal (char-before) ?\n))
9004 (delete-region (1- (point)) (point-at-eol)))
9005 ts)))))
9007 (defvar org-log-note-marker (make-marker))
9008 (defvar org-log-note-purpose nil)
9009 (defvar org-log-note-state nil)
9010 (defvar org-log-note-how nil)
9011 (defvar org-log-note-extra nil)
9012 (defvar org-log-note-window-configuration nil)
9013 (defvar org-log-note-return-to (make-marker))
9014 (defvar org-log-post-message nil
9015 "Message to be displayed after a log note has been stored.
9016 The auto-repeater uses this.")
9018 (defun org-add-note ()
9019 "Add a note to the current entry.
9020 This is done in the same way as adding a state change note."
9021 (interactive)
9022 (org-add-log-setup 'note nil 'findpos nil))
9024 (defvar org-property-end-re)
9025 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
9026 "Set up the post command hook to take a note.
9027 If this is about to TODO state change, the new state is expected in STATE.
9028 When FINDPOS is non-nil, find the correct position for the note in
9029 the current entry. If not, assume that it can be inserted at point.
9030 HOW is an indicator what kind of note should be created.
9031 EXTRA is additional text that will be inserted into the notes buffer."
9032 (save-restriction
9033 (save-excursion
9034 (when findpos
9035 (org-back-to-heading t)
9036 (narrow-to-region (point) (save-excursion
9037 (outline-next-heading) (point)))
9038 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9039 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9040 "[^\r\n]*\\)?"))
9041 (goto-char (match-end 0))
9042 (when (and org-log-state-notes-insert-after-drawers
9043 (save-excursion
9044 (forward-line) (looking-at org-drawer-regexp)))
9045 (progn (forward-line)
9046 (while (looking-at org-drawer-regexp)
9047 (goto-char (match-end 0))
9048 (re-search-forward org-property-end-re (point-max) t)
9049 (forward-line))
9050 (forward-line -1)))
9051 (unless org-log-states-order-reversed
9052 (and (= (char-after) ?\n) (forward-char 1))
9053 (org-skip-over-state-notes)
9054 (skip-chars-backward " \t\n\r")))
9055 (move-marker org-log-note-marker (point))
9056 (setq org-log-note-purpose purpose
9057 org-log-note-state state
9058 org-log-note-how how
9059 org-log-note-extra extra)
9060 (add-hook 'post-command-hook 'org-add-log-note 'append))))
9062 (defun org-skip-over-state-notes ()
9063 "Skip past the list of State notes in an entry."
9064 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9065 (while (looking-at "[ \t]*- State")
9066 (condition-case nil
9067 (org-next-item)
9068 (error (org-end-of-item)))))
9070 (defun org-add-log-note (&optional purpose)
9071 "Pop up a window for taking a note, and add this note later at point."
9072 (remove-hook 'post-command-hook 'org-add-log-note)
9073 (setq org-log-note-window-configuration (current-window-configuration))
9074 (delete-other-windows)
9075 (move-marker org-log-note-return-to (point))
9076 (switch-to-buffer (marker-buffer org-log-note-marker))
9077 (goto-char org-log-note-marker)
9078 (org-switch-to-buffer-other-window "*Org Note*")
9079 (erase-buffer)
9080 (if (memq org-log-note-how '(time state))
9081 (let (current-prefix-arg) (org-store-log-note))
9082 (let ((org-inhibit-startup t)) (org-mode))
9083 (insert (format "# Insert note for %s.
9084 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9085 (cond
9086 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9087 ((eq org-log-note-purpose 'done) "closed todo item")
9088 ((eq org-log-note-purpose 'state)
9089 (format "state change to \"%s\"" org-log-note-state))
9090 ((eq org-log-note-purpose 'note)
9091 "this entry")
9092 (t (error "This should not happen")))))
9093 (if org-log-note-extra (insert org-log-note-extra))
9094 (org-set-local 'org-finish-function 'org-store-log-note)))
9096 (defvar org-note-abort nil) ; dynamically scoped
9097 (defun org-store-log-note ()
9098 "Finish taking a log note, and insert it to where it belongs."
9099 (let ((txt (buffer-string))
9100 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9101 lines ind)
9102 (kill-buffer (current-buffer))
9103 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9104 (setq txt (replace-match "" t t txt)))
9105 (if (string-match "\\s-+\\'" txt)
9106 (setq txt (replace-match "" t t txt)))
9107 (setq lines (org-split-string txt "\n"))
9108 (when (and note (string-match "\\S-" note))
9109 (setq note
9110 (org-replace-escapes
9111 note
9112 (list (cons "%u" (user-login-name))
9113 (cons "%U" user-full-name)
9114 (cons "%t" (format-time-string
9115 (org-time-stamp-format 'long 'inactive)
9116 (current-time)))
9117 (cons "%s" (if org-log-note-state
9118 (concat "\"" org-log-note-state "\"")
9119 "")))))
9120 (if lines (setq note (concat note " \\\\")))
9121 (push note lines))
9122 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9123 (when lines
9124 (save-excursion
9125 (set-buffer (marker-buffer org-log-note-marker))
9126 (save-excursion
9127 (goto-char org-log-note-marker)
9128 (move-marker org-log-note-marker nil)
9129 (end-of-line 1)
9130 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9131 (indent-relative nil)
9132 (insert "- " (pop lines))
9133 (org-indent-line-function)
9134 (beginning-of-line 1)
9135 (looking-at "[ \t]*")
9136 (setq ind (concat (match-string 0) " "))
9137 (end-of-line 1)
9138 (while lines (insert "\n" ind (pop lines)))))))
9139 (set-window-configuration org-log-note-window-configuration)
9140 (with-current-buffer (marker-buffer org-log-note-return-to)
9141 (goto-char org-log-note-return-to))
9142 (move-marker org-log-note-return-to nil)
9143 (and org-log-post-message (message "%s" org-log-post-message)))
9145 (defun org-sparse-tree (&optional arg)
9146 "Create a sparse tree, prompt for the details.
9147 This command can create sparse trees. You first need to select the type
9148 of match used to create the tree:
9150 t Show entries with a specific TODO keyword.
9151 T Show entries selected by a tags match.
9152 p Enter a property name and its value (both with completion on existing
9153 names/values) and show entries with that property.
9154 r Show entries matching a regular expression
9155 d Show deadlines due within `org-deadline-warning-days'."
9156 (interactive "P")
9157 (let (ans kwd value)
9158 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9159 (setq ans (read-char-exclusive))
9160 (cond
9161 ((equal ans ?d)
9162 (call-interactively 'org-check-deadlines))
9163 ((equal ans ?b)
9164 (call-interactively 'org-check-before-date))
9165 ((equal ans ?t)
9166 (org-show-todo-tree '(4)))
9167 ((equal ans ?T)
9168 (call-interactively 'org-tags-sparse-tree))
9169 ((member ans '(?p ?P))
9170 (setq kwd (org-ido-completing-read "Property: "
9171 (mapcar 'list (org-buffer-property-keys))))
9172 (setq value (org-ido-completing-read "Value: "
9173 (mapcar 'list (org-property-values kwd))))
9174 (unless (string-match "\\`{.*}\\'" value)
9175 (setq value (concat "\"" value "\"")))
9176 (org-tags-sparse-tree arg (concat kwd "=" value)))
9177 ((member ans '(?r ?R ?/))
9178 (call-interactively 'org-occur))
9179 (t (error "No such sparse tree command \"%c\"" ans)))))
9181 (defvar org-occur-highlights nil
9182 "List of overlays used for occur matches.")
9183 (make-variable-buffer-local 'org-occur-highlights)
9184 (defvar org-occur-parameters nil
9185 "Parameters of the active org-occur calls.
9186 This is a list, each call to org-occur pushes as cons cell,
9187 containing the regular expression and the callback, onto the list.
9188 The list can contain several entries if `org-occur' has been called
9189 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9190 will only contain one set of parameters. When the highlights are
9191 removed (for example with `C-c C-c', or with the next edit (depending
9192 on `org-remove-highlights-with-change'), this variable is emptied
9193 as well.")
9194 (make-variable-buffer-local 'org-occur-parameters)
9196 (defun org-occur (regexp &optional keep-previous callback)
9197 "Make a compact tree which shows all matches of REGEXP.
9198 The tree will show the lines where the regexp matches, and all higher
9199 headlines above the match. It will also show the heading after the match,
9200 to make sure editing the matching entry is easy.
9201 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9202 call to `org-occur' will be kept, to allow stacking of calls to this
9203 command.
9204 If CALLBACK is non-nil, it is a function which is called to confirm
9205 that the match should indeed be shown."
9206 (interactive "sRegexp: \nP")
9207 (unless keep-previous
9208 (org-remove-occur-highlights nil nil t))
9209 (push (cons regexp callback) org-occur-parameters)
9210 (let ((cnt 0))
9211 (save-excursion
9212 (goto-char (point-min))
9213 (if (or (not keep-previous) ; do not want to keep
9214 (not org-occur-highlights)) ; no previous matches
9215 ;; hide everything
9216 (org-overview))
9217 (while (re-search-forward regexp nil t)
9218 (when (or (not callback)
9219 (save-match-data (funcall callback)))
9220 (setq cnt (1+ cnt))
9221 (when org-highlight-sparse-tree-matches
9222 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9223 (org-show-context 'occur-tree))))
9224 (when org-remove-highlights-with-change
9225 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9226 nil 'local))
9227 (unless org-sparse-tree-open-archived-trees
9228 (org-hide-archived-subtrees (point-min) (point-max)))
9229 (run-hooks 'org-occur-hook)
9230 (if (interactive-p)
9231 (message "%d match(es) for regexp %s" cnt regexp))
9232 cnt))
9234 (defun org-show-context (&optional key)
9235 "Make sure point and context and visible.
9236 How much context is shown depends upon the variables
9237 `org-show-hierarchy-above', `org-show-following-heading'. and
9238 `org-show-siblings'."
9239 (let ((heading-p (org-on-heading-p t))
9240 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9241 (following-p (org-get-alist-option org-show-following-heading key))
9242 (entry-p (org-get-alist-option org-show-entry-below key))
9243 (siblings-p (org-get-alist-option org-show-siblings key)))
9244 (catch 'exit
9245 ;; Show heading or entry text
9246 (if (and heading-p (not entry-p))
9247 (org-flag-heading nil) ; only show the heading
9248 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9249 (org-show-hidden-entry))) ; show entire entry
9250 (when following-p
9251 ;; Show next sibling, or heading below text
9252 (save-excursion
9253 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9254 (org-flag-heading nil))))
9255 (when siblings-p (org-show-siblings))
9256 (when hierarchy-p
9257 ;; show all higher headings, possibly with siblings
9258 (save-excursion
9259 (while (and (condition-case nil
9260 (progn (org-up-heading-all 1) t)
9261 (error nil))
9262 (not (bobp)))
9263 (org-flag-heading nil)
9264 (when siblings-p (org-show-siblings))))))))
9266 (defun org-reveal (&optional siblings)
9267 "Show current entry, hierarchy above it, and the following headline.
9268 This can be used to show a consistent set of context around locations
9269 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9270 not t for the search context.
9272 With optional argument SIBLINGS, on each level of the hierarchy all
9273 siblings are shown. This repairs the tree structure to what it would
9274 look like when opened with hierarchical calls to `org-cycle'."
9275 (interactive "P")
9276 (let ((org-show-hierarchy-above t)
9277 (org-show-following-heading t)
9278 (org-show-siblings (if siblings t org-show-siblings)))
9279 (org-show-context nil)))
9281 (defun org-highlight-new-match (beg end)
9282 "Highlight from BEG to END and mark the highlight is an occur headline."
9283 (let ((ov (org-make-overlay beg end)))
9284 (org-overlay-put ov 'face 'secondary-selection)
9285 (push ov org-occur-highlights)))
9287 (defun org-remove-occur-highlights (&optional beg end noremove)
9288 "Remove the occur highlights from the buffer.
9289 BEG and END are ignored. If NOREMOVE is nil, remove this function
9290 from the `before-change-functions' in the current buffer."
9291 (interactive)
9292 (unless org-inhibit-highlight-removal
9293 (mapc 'org-delete-overlay org-occur-highlights)
9294 (setq org-occur-highlights nil)
9295 (setq org-occur-parameters nil)
9296 (unless noremove
9297 (remove-hook 'before-change-functions
9298 'org-remove-occur-highlights 'local))))
9300 ;;;; Priorities
9302 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9303 "Regular expression matching the priority indicator.")
9305 (defvar org-remove-priority-next-time nil)
9307 (defun org-priority-up ()
9308 "Increase the priority of the current item."
9309 (interactive)
9310 (org-priority 'up))
9312 (defun org-priority-down ()
9313 "Decrease the priority of the current item."
9314 (interactive)
9315 (org-priority 'down))
9317 (defun org-priority (&optional action)
9318 "Change the priority of an item by ARG.
9319 ACTION can be `set', `up', `down', or a character."
9320 (interactive)
9321 (setq action (or action 'set))
9322 (let (current new news have remove)
9323 (save-excursion
9324 (org-back-to-heading)
9325 (if (looking-at org-priority-regexp)
9326 (setq current (string-to-char (match-string 2))
9327 have t)
9328 (setq current org-default-priority))
9329 (cond
9330 ((or (eq action 'set)
9331 (if (featurep 'xemacs) (characterp action) (integerp action)))
9332 (if (not (eq action 'set))
9333 (setq new action)
9334 (message "Priority %c-%c, SPC to remove: "
9335 org-highest-priority org-lowest-priority)
9336 (setq new (read-char-exclusive)))
9337 (if (and (= (upcase org-highest-priority) org-highest-priority)
9338 (= (upcase org-lowest-priority) org-lowest-priority))
9339 (setq new (upcase new)))
9340 (cond ((equal new ?\ ) (setq remove t))
9341 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9342 (error "Priority must be between `%c' and `%c'"
9343 org-highest-priority org-lowest-priority))))
9344 ((eq action 'up)
9345 (if (and (not have) (eq last-command this-command))
9346 (setq new org-lowest-priority)
9347 (setq new (if (and org-priority-start-cycle-with-default (not have))
9348 org-default-priority (1- current)))))
9349 ((eq action 'down)
9350 (if (and (not have) (eq last-command this-command))
9351 (setq new org-highest-priority)
9352 (setq new (if (and org-priority-start-cycle-with-default (not have))
9353 org-default-priority (1+ current)))))
9354 (t (error "Invalid action")))
9355 (if (or (< (upcase new) org-highest-priority)
9356 (> (upcase new) org-lowest-priority))
9357 (setq remove t))
9358 (setq news (format "%c" new))
9359 (if have
9360 (if remove
9361 (replace-match "" t t nil 1)
9362 (replace-match news t t nil 2))
9363 (if remove
9364 (error "No priority cookie found in line")
9365 (looking-at org-todo-line-regexp)
9366 (if (match-end 2)
9367 (progn
9368 (goto-char (match-end 2))
9369 (insert " [#" news "]"))
9370 (goto-char (match-beginning 3))
9371 (insert "[#" news "] ")))))
9372 (org-preserve-lc (org-set-tags nil 'align))
9373 (if remove
9374 (message "Priority removed")
9375 (message "Priority of current item set to %s" news))))
9378 (defun org-get-priority (s)
9379 "Find priority cookie and return priority."
9380 (save-match-data
9381 (if (not (string-match org-priority-regexp s))
9382 (* 1000 (- org-lowest-priority org-default-priority))
9383 (* 1000 (- org-lowest-priority
9384 (string-to-char (match-string 2 s)))))))
9386 ;;;; Tags
9388 (defvar org-agenda-archives-mode)
9389 (defun org-scan-tags (action matcher &optional todo-only)
9390 "Scan headline tags with inheritance and produce output ACTION.
9392 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9393 or `agenda' to produce an entry list for an agenda view. It can also be
9394 a Lisp form or a function that should be called at each matched headline, in
9395 this case the return value is a list of all return values from these calls.
9397 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9398 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9399 only lines with a TODO keyword are included in the output."
9400 (require 'org-agenda)
9401 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9402 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9403 (org-re
9404 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9405 (props (list 'face 'default
9406 'done-face 'org-done
9407 'undone-face 'default
9408 'mouse-face 'highlight
9409 'org-not-done-regexp org-not-done-regexp
9410 'org-todo-regexp org-todo-regexp
9411 'keymap org-agenda-keymap
9412 'help-echo
9413 (format "mouse-2 or RET jump to org file %s"
9414 (abbreviate-file-name
9415 (or (buffer-file-name (buffer-base-buffer))
9416 (buffer-name (buffer-base-buffer)))))))
9417 (case-fold-search nil)
9418 lspos tags tags-list
9419 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9420 (llast 0) rtn rtn1 level category i txt
9421 todo marker entry priority)
9422 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9423 (setq action (list 'lambda nil action)))
9424 (save-excursion
9425 (goto-char (point-min))
9426 (when (eq action 'sparse-tree)
9427 (org-overview)
9428 (org-remove-occur-highlights))
9429 (while (re-search-forward re nil t)
9430 (catch :skip
9431 (setq todo (if (match-end 1) (match-string 2))
9432 tags (if (match-end 4) (match-string 4)))
9433 (goto-char (setq lspos (1+ (match-beginning 0))))
9434 (setq level (org-reduced-level (funcall outline-level))
9435 category (org-get-category))
9436 (setq i llast llast level)
9437 ;; remove tag lists from same and sublevels
9438 (while (>= i level)
9439 (when (setq entry (assoc i tags-alist))
9440 (setq tags-alist (delete entry tags-alist)))
9441 (setq i (1- i)))
9442 ;; add the next tags
9443 (when tags
9444 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9445 tags-alist
9446 (cons (cons level tags) tags-alist)))
9447 ;; compile tags for current headline
9448 (setq tags-list
9449 (if org-use-tag-inheritance
9450 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9451 tags))
9452 (when org-use-tag-inheritance
9453 (setcdr (car tags-alist)
9454 (mapcar (lambda (x)
9455 (setq x (copy-sequence x))
9456 (org-add-prop-inherited x))
9457 (cdar tags-alist))))
9458 (when (and tags org-use-tag-inheritance
9459 (not (eq t org-use-tag-inheritance)))
9460 ;; selective inheritance, remove uninherited ones
9461 (setcdr (car tags-alist)
9462 (org-remove-uniherited-tags (cdar tags-alist))))
9463 (when (and (or (not todo-only)
9464 (and (member todo org-not-done-keywords)
9465 (or (not org-agenda-tags-todo-honor-ignore-options)
9466 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9467 (let ((case-fold-search t)) (eval matcher))
9469 (not (member org-archive-tag tags-list))
9470 ;; we have an archive tag, should we use this anyway?
9471 (or (not org-agenda-skip-archived-trees)
9472 (and (eq action 'agenda) org-agenda-archives-mode))))
9473 (unless (eq action 'sparse-tree) (org-agenda-skip))
9475 ;; select this headline
9477 (cond
9478 ((eq action 'sparse-tree)
9479 (and org-highlight-sparse-tree-matches
9480 (org-get-heading) (match-end 0)
9481 (org-highlight-new-match
9482 (match-beginning 0) (match-beginning 1)))
9483 (org-show-context 'tags-tree))
9484 ((eq action 'agenda)
9485 (setq txt (org-format-agenda-item
9487 (concat
9488 (if org-tags-match-list-sublevels
9489 (make-string (1- level) ?.) "")
9490 (org-get-heading))
9491 category (org-get-tags-at))
9492 priority (org-get-priority txt))
9493 (goto-char lspos)
9494 (setq marker (org-agenda-new-marker))
9495 (org-add-props txt props
9496 'org-marker marker 'org-hd-marker marker 'org-category category
9497 'priority priority 'type "tagsmatch")
9498 (push txt rtn))
9499 ((functionp action)
9500 (save-excursion
9501 (setq rtn1 (funcall action))
9502 (push rtn1 rtn))
9503 (goto-char (point-at-eol)))
9504 (t (error "Invalid action")))
9506 ;; if we are to skip sublevels, jump to end of subtree
9507 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9508 (when (and (eq action 'sparse-tree)
9509 (not org-sparse-tree-open-archived-trees))
9510 (org-hide-archived-subtrees (point-min) (point-max)))
9511 (nreverse rtn)))
9513 (defun org-remove-uniherited-tags (tags)
9514 "Remove all tags that are not inherited from the list TAGS."
9515 (cond
9516 ((eq org-use-tag-inheritance t)
9517 (if org-tags-exclude-from-inheritance
9518 (org-delete-all org-tags-exclude-from-inheritance tags)
9519 tags))
9520 ((not org-use-tag-inheritance) nil)
9521 ((stringp org-use-tag-inheritance)
9522 (delq nil (mapcar
9523 (lambda (x)
9524 (if (and (string-match org-use-tag-inheritance x)
9525 (not (member x org-tags-exclude-from-inheritance)))
9526 x nil))
9527 tags)))
9528 ((listp org-use-tag-inheritance)
9529 (delq nil (mapcar
9530 (lambda (x)
9531 (if (member x org-use-tag-inheritance) x nil))
9532 tags)))))
9534 (defvar todo-only) ;; dynamically scoped
9536 (defun org-tags-sparse-tree (&optional todo-only match)
9537 "Create a sparse tree according to tags string MATCH.
9538 MATCH can contain positive and negative selection of tags, like
9539 \"+WORK+URGENT-WITHBOSS\".
9540 If optional argument TODO-ONLY is non-nil, only select lines that are
9541 also TODO lines."
9542 (interactive "P")
9543 (org-prepare-agenda-buffers (list (current-buffer)))
9544 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9546 (defvar org-cached-props nil)
9547 (defun org-cached-entry-get (pom property)
9548 (if (or (eq t org-use-property-inheritance)
9549 (and (stringp org-use-property-inheritance)
9550 (string-match org-use-property-inheritance property))
9551 (and (listp org-use-property-inheritance)
9552 (member property org-use-property-inheritance)))
9553 ;; Caching is not possible, check it directly
9554 (org-entry-get pom property 'inherit)
9555 ;; Get all properties, so that we can do complicated checks easily
9556 (cdr (assoc property (or org-cached-props
9557 (setq org-cached-props
9558 (org-entry-properties pom)))))))
9560 (defun org-global-tags-completion-table (&optional files)
9561 "Return the list of all tags in all agenda buffer/files."
9562 (save-excursion
9563 (org-uniquify
9564 (delq nil
9565 (apply 'append
9566 (mapcar
9567 (lambda (file)
9568 (set-buffer (find-file-noselect file))
9569 (append (org-get-buffer-tags)
9570 (mapcar (lambda (x) (if (stringp (car-safe x))
9571 (list (car-safe x)) nil))
9572 org-tag-alist)))
9573 (if (and files (car files))
9574 files
9575 (org-agenda-files))))))))
9577 (defun org-make-tags-matcher (match)
9578 "Create the TAGS//TODO matcher form for the selection string MATCH."
9579 ;; todo-only is scoped dynamically into this function, and the function
9580 ;; may change it if the matcher asks for it.
9581 (unless match
9582 ;; Get a new match request, with completion
9583 (let ((org-last-tags-completion-table
9584 (org-global-tags-completion-table)))
9585 (setq match (org-completing-read
9586 "Match: " 'org-tags-completion-function nil nil nil
9587 'org-tags-history))))
9589 ;; Parse the string and create a lisp form
9590 (let ((match0 match)
9591 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9592 minus tag mm
9593 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9594 orterms term orlist re-p str-p level-p level-op time-p
9595 prop-p pn pv po cat-p gv rest)
9596 (if (string-match "/+" match)
9597 ;; match contains also a todo-matching request
9598 (progn
9599 (setq tagsmatch (substring match 0 (match-beginning 0))
9600 todomatch (substring match (match-end 0)))
9601 (if (string-match "^!" todomatch)
9602 (setq todo-only t todomatch (substring todomatch 1)))
9603 (if (string-match "^\\s-*$" todomatch)
9604 (setq todomatch nil)))
9605 ;; only matching tags
9606 (setq tagsmatch match todomatch nil))
9608 ;; Make the tags matcher
9609 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9610 (setq tagsmatcher t)
9611 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9612 (while (setq term (pop orterms))
9613 (while (and (equal (substring term -1) "\\") orterms)
9614 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9615 (while (string-match re term)
9616 (setq rest (substring term (match-end 0))
9617 minus (and (match-end 1)
9618 (equal (match-string 1 term) "-"))
9619 tag (match-string 2 term)
9620 re-p (equal (string-to-char tag) ?{)
9621 level-p (match-end 4)
9622 prop-p (match-end 5)
9623 mm (cond
9624 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9625 (level-p
9626 (setq level-op (org-op-to-function (match-string 3 term)))
9627 `(,level-op level ,(string-to-number
9628 (match-string 4 term))))
9629 (prop-p
9630 (setq pn (match-string 5 term)
9631 po (match-string 6 term)
9632 pv (match-string 7 term)
9633 cat-p (equal pn "CATEGORY")
9634 re-p (equal (string-to-char pv) ?{)
9635 str-p (equal (string-to-char pv) ?\")
9636 time-p (save-match-data
9637 (string-match "^\"[[<].*[]>]\"$" pv))
9638 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9639 (if time-p (setq pv (org-matcher-time pv)))
9640 (setq po (org-op-to-function po (if time-p 'time str-p)))
9641 (cond
9642 ((equal pn "CATEGORY")
9643 (setq gv '(get-text-property (point) 'org-category)))
9644 ((equal pn "TODO")
9645 (setq gv 'todo))
9647 (setq gv `(org-cached-entry-get nil ,pn))))
9648 (if re-p
9649 (if (eq po 'org<>)
9650 `(not (string-match ,pv (or ,gv "")))
9651 `(string-match ,pv (or ,gv "")))
9652 (if str-p
9653 `(,po (or ,gv "") ,pv)
9654 `(,po (string-to-number (or ,gv ""))
9655 ,(string-to-number pv) ))))
9656 (t `(member ,(downcase tag) tags-list)))
9657 mm (if minus (list 'not mm) mm)
9658 term rest)
9659 (push mm tagsmatcher))
9660 (push (if (> (length tagsmatcher) 1)
9661 (cons 'and tagsmatcher)
9662 (car tagsmatcher))
9663 orlist)
9664 (setq tagsmatcher nil))
9665 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9666 (setq tagsmatcher
9667 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9668 ;; Make the todo matcher
9669 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9670 (setq todomatcher t)
9671 (setq orterms (org-split-string todomatch "|") orlist nil)
9672 (while (setq term (pop orterms))
9673 (while (string-match re term)
9674 (setq minus (and (match-end 1)
9675 (equal (match-string 1 term) "-"))
9676 kwd (match-string 2 term)
9677 re-p (equal (string-to-char kwd) ?{)
9678 term (substring term (match-end 0))
9679 mm (if re-p
9680 `(string-match ,(substring kwd 1 -1) todo)
9681 (list 'equal 'todo kwd))
9682 mm (if minus (list 'not mm) mm))
9683 (push mm todomatcher))
9684 (push (if (> (length todomatcher) 1)
9685 (cons 'and todomatcher)
9686 (car todomatcher))
9687 orlist)
9688 (setq todomatcher nil))
9689 (setq todomatcher (if (> (length orlist) 1)
9690 (cons 'or orlist) (car orlist))))
9692 ;; Return the string and lisp forms of the matcher
9693 (setq matcher (if todomatcher
9694 (list 'and tagsmatcher todomatcher)
9695 tagsmatcher))
9696 (cons match0 matcher)))
9698 (defun org-op-to-function (op &optional stringp)
9699 "Turn an operator into the appropriate function."
9700 (setq op
9701 (cond
9702 ((equal op "<" ) '(< string< org-time<))
9703 ((equal op ">" ) '(> org-string> org-time>))
9704 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9705 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9706 ((member op '("=" "==")) '(= string= org-time=))
9707 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9708 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9710 (defun org<> (a b) (not (= a b)))
9711 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9712 (defun org-string>= (a b) (not (string< a b)))
9713 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9714 (defun org-string<> (a b) (not (string= a b)))
9715 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9716 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9717 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9718 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9719 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9720 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9721 (defun org-2ft (s)
9722 "Convert S to a floating point time.
9723 If S is already a number, just return it. If it is a string, parse
9724 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9725 (cond
9726 ((numberp s) s)
9727 ((stringp s)
9728 (condition-case nil
9729 (float-time (apply 'encode-time (org-parse-time-string s)))
9730 (error 0.)))
9731 (t 0.)))
9733 (defun org-time-today ()
9734 "Time in seconds today at 0:00.
9735 Returns the float number of seconds since the beginning of the
9736 epoch to the beginning of today (00:00)."
9737 (float-time (apply 'encode-time
9738 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9740 (defun org-matcher-time (s)
9741 "Interpret a time comparison value."
9742 (save-match-data
9743 (cond
9744 ((string= s "<now>") (float-time))
9745 ((string= s "<today>") (org-time-today))
9746 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9747 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9748 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9749 (+ (org-time-today)
9750 (* (string-to-number (match-string 1 s))
9751 (cdr (assoc (match-string 2 s)
9752 '(("d" . 86400.0) ("w" . 604800.0)
9753 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9754 (t (org-2ft s)))))
9756 (defun org-match-any-p (re list)
9757 "Does re match any element of list?"
9758 (setq list (mapcar (lambda (x) (string-match re x)) list))
9759 (delq nil list))
9761 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9762 (defvar org-tags-overlay (org-make-overlay 1 1))
9763 (org-detach-overlay org-tags-overlay)
9765 (defun org-get-local-tags-at (&optional pos)
9766 "Get a list of tags defined in the current headline."
9767 (org-get-tags-at pos 'local))
9769 (defun org-get-local-tags ()
9770 "Get a list of tags defined in the current headline."
9771 (org-get-tags-at nil 'local))
9773 (defun org-get-tags-at (&optional pos local)
9774 "Get a list of all headline tags applicable at POS.
9775 POS defaults to point. If tags are inherited, the list contains
9776 the targets in the same sequence as the headlines appear, i.e.
9777 the tags of the current headline come last.
9778 When LOCAL is non-nil, only return tags from the current headline,
9779 ignore inherited ones."
9780 (interactive)
9781 (let (tags ltags lastpos parent)
9782 (save-excursion
9783 (save-restriction
9784 (widen)
9785 (goto-char (or pos (point)))
9786 (save-match-data
9787 (catch 'done
9788 (condition-case nil
9789 (progn
9790 (org-back-to-heading t)
9791 (while (not (equal lastpos (point)))
9792 (setq lastpos (point))
9793 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9794 (setq ltags (org-split-string
9795 (org-match-string-no-properties 1) ":"))
9796 (when parent
9797 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9798 (setq tags (append
9799 (if parent
9800 (org-remove-uniherited-tags ltags)
9801 ltags)
9802 tags)))
9803 (or org-use-tag-inheritance (throw 'done t))
9804 (if local (throw 'done t))
9805 (org-up-heading-all 1)
9806 (setq parent t)))
9807 (error nil)))))
9808 (append (org-remove-uniherited-tags org-file-tags) tags))))
9810 (defun org-add-prop-inherited (s)
9811 (add-text-properties 0 (length s) '(inherited t) s)
9814 (defun org-toggle-tag (tag &optional onoff)
9815 "Toggle the tag TAG for the current line.
9816 If ONOFF is `on' or `off', don't toggle but set to this state."
9817 (let (res current)
9818 (save-excursion
9819 (org-back-to-heading t)
9820 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9821 (point-at-eol) t)
9822 (progn
9823 (setq current (match-string 1))
9824 (replace-match ""))
9825 (setq current ""))
9826 (setq current (nreverse (org-split-string current ":")))
9827 (cond
9828 ((eq onoff 'on)
9829 (setq res t)
9830 (or (member tag current) (push tag current)))
9831 ((eq onoff 'off)
9832 (or (not (member tag current)) (setq current (delete tag current))))
9833 (t (if (member tag current)
9834 (setq current (delete tag current))
9835 (setq res t)
9836 (push tag current))))
9837 (end-of-line 1)
9838 (if current
9839 (progn
9840 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9841 (org-set-tags nil t))
9842 (delete-horizontal-space))
9843 (run-hooks 'org-after-tags-change-hook))
9844 res))
9846 (defun org-align-tags-here (to-col)
9847 ;; Assumes that this is a headline
9848 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9849 (beginning-of-line 1)
9850 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9851 (< pos (match-beginning 2)))
9852 (progn
9853 (setq tags-l (- (match-end 2) (match-beginning 2)))
9854 (goto-char (match-beginning 1))
9855 (insert " ")
9856 (delete-region (point) (1+ (match-beginning 2)))
9857 (setq ncol (max (1+ (current-column))
9858 (1+ col)
9859 (if (> to-col 0)
9860 to-col
9861 (- (abs to-col) tags-l))))
9862 (setq p (point))
9863 (insert (make-string (- ncol (current-column)) ?\ ))
9864 (setq ncol (current-column))
9865 (when indent-tabs-mode (tabify p (point-at-eol)))
9866 (org-move-to-column (min ncol col) t))
9867 (goto-char pos))))
9869 (defun org-set-tags-command (&optional arg just-align)
9870 "Call the set-tags command for the current entry."
9871 (interactive "P")
9872 (if (org-on-heading-p)
9873 (org-set-tags arg just-align)
9874 (save-excursion
9875 (org-back-to-heading t)
9876 (org-set-tags arg just-align))))
9878 (defun org-set-tags (&optional arg just-align)
9879 "Set the tags for the current headline.
9880 With prefix ARG, realign all tags in headings in the current buffer."
9881 (interactive "P")
9882 (let* ((re (concat "^" outline-regexp))
9883 (current (org-get-tags-string))
9884 (col (current-column))
9885 (org-setting-tags t)
9886 table current-tags inherited-tags ; computed below when needed
9887 tags p0 c0 c1 rpl)
9888 (if arg
9889 (save-excursion
9890 (goto-char (point-min))
9891 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9892 (while (re-search-forward re nil t)
9893 (org-set-tags nil t)
9894 (end-of-line 1)))
9895 (message "All tags realigned to column %d" org-tags-column))
9896 (if just-align
9897 (setq tags current)
9898 ;; Get a new set of tags from the user
9899 (save-excursion
9900 (setq table (or org-tag-alist (org-get-buffer-tags))
9901 org-last-tags-completion-table table
9902 current-tags (org-split-string current ":")
9903 inherited-tags (nreverse
9904 (nthcdr (length current-tags)
9905 (nreverse (org-get-tags-at))))
9906 tags
9907 (if (or (eq t org-use-fast-tag-selection)
9908 (and org-use-fast-tag-selection
9909 (delq nil (mapcar 'cdr table))))
9910 (org-fast-tag-selection
9911 current-tags inherited-tags table
9912 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9913 (let ((org-add-colon-after-tag-completion t))
9914 (org-trim
9915 (org-without-partial-completion
9916 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9917 nil nil current 'org-tags-history)))))))
9918 (while (string-match "[-+&]+" tags)
9919 ;; No boolean logic, just a list
9920 (setq tags (replace-match ":" t t tags))))
9922 (if (string-match "\\`[\t ]*\\'" tags)
9923 (setq tags "")
9924 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9925 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9927 ;; Insert new tags at the correct column
9928 (beginning-of-line 1)
9929 (cond
9930 ((and (equal current "") (equal tags "")))
9931 ((re-search-forward
9932 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9933 (point-at-eol) t)
9934 (if (equal tags "")
9935 (setq rpl "")
9936 (goto-char (match-beginning 0))
9937 (setq c0 (current-column) p0 (point)
9938 c1 (max (1+ c0) (if (> org-tags-column 0)
9939 org-tags-column
9940 (- (- org-tags-column) (length tags))))
9941 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9942 (replace-match rpl t t)
9943 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9944 tags)
9945 (t (error "Tags alignment failed")))
9946 (org-move-to-column col)
9947 (unless just-align
9948 (run-hooks 'org-after-tags-change-hook)))))
9950 (defun org-change-tag-in-region (beg end tag off)
9951 "Add or remove TAG for each entry in the region.
9952 This works in the agenda, and also in an org-mode buffer."
9953 (interactive
9954 (list (region-beginning) (region-end)
9955 (let ((org-last-tags-completion-table
9956 (if (org-mode-p)
9957 (org-get-buffer-tags)
9958 (org-global-tags-completion-table))))
9959 (org-ido-completing-read
9960 "Tag: " 'org-tags-completion-function nil nil nil
9961 'org-tags-history))
9962 (progn
9963 (message "[s]et or [r]emove? ")
9964 (equal (read-char-exclusive) ?r))))
9965 (if (fboundp 'deactivate-mark) (deactivate-mark))
9966 (let ((agendap (equal major-mode 'org-agenda-mode))
9967 l1 l2 m buf pos newhead (cnt 0))
9968 (goto-char end)
9969 (setq l2 (1- (org-current-line)))
9970 (goto-char beg)
9971 (setq l1 (org-current-line))
9972 (loop for l from l1 to l2 do
9973 (goto-line l)
9974 (setq m (get-text-property (point) 'org-hd-marker))
9975 (when (or (and (org-mode-p) (org-on-heading-p))
9976 (and agendap m))
9977 (setq buf (if agendap (marker-buffer m) (current-buffer))
9978 pos (if agendap m (point)))
9979 (with-current-buffer buf
9980 (save-excursion
9981 (save-restriction
9982 (goto-char pos)
9983 (setq cnt (1+ cnt))
9984 (org-toggle-tag tag (if off 'off 'on))
9985 (setq newhead (org-get-heading)))))
9986 (and agendap (org-agenda-change-all-lines newhead m))))
9987 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9989 (defun org-tags-completion-function (string predicate &optional flag)
9990 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9991 (confirm (lambda (x) (stringp (car x)))))
9992 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9993 (setq s1 (match-string 1 string)
9994 s2 (match-string 2 string))
9995 (setq s1 "" s2 string))
9996 (cond
9997 ((eq flag nil)
9998 ;; try completion
9999 (setq rtn (try-completion s2 ctable confirm))
10000 (if (stringp rtn)
10001 (setq rtn
10002 (concat s1 s2 (substring rtn (length s2))
10003 (if (and org-add-colon-after-tag-completion
10004 (assoc rtn ctable))
10005 ":" ""))))
10006 rtn)
10007 ((eq flag t)
10008 ;; all-completions
10009 (all-completions s2 ctable confirm)
10011 ((eq flag 'lambda)
10012 ;; exact match?
10013 (assoc s2 ctable)))
10016 (defun org-fast-tag-insert (kwd tags face &optional end)
10017 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10018 (insert (format "%-12s" (concat kwd ":"))
10019 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10020 (or end "")))
10022 (defun org-fast-tag-show-exit (flag)
10023 (save-excursion
10024 (goto-line 3)
10025 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10026 (replace-match ""))
10027 (when flag
10028 (end-of-line 1)
10029 (org-move-to-column (- (window-width) 19) t)
10030 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10032 (defun org-set-current-tags-overlay (current prefix)
10033 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10034 (if (featurep 'xemacs)
10035 (org-overlay-display org-tags-overlay (concat prefix s)
10036 'secondary-selection)
10037 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10038 (org-overlay-display org-tags-overlay (concat prefix s)))))
10040 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10041 "Fast tag selection with single keys.
10042 CURRENT is the current list of tags in the headline, INHERITED is the
10043 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10044 possibly with grouping information. TODO-TABLE is a similar table with
10045 TODO keywords, should these have keys assigned to them.
10046 If the keys are nil, a-z are automatically assigned.
10047 Returns the new tags string, or nil to not change the current settings."
10048 (let* ((fulltable (append table todo-table))
10049 (maxlen (apply 'max (mapcar
10050 (lambda (x)
10051 (if (stringp (car x)) (string-width (car x)) 0))
10052 fulltable)))
10053 (buf (current-buffer))
10054 (expert (eq org-fast-tag-selection-single-key 'expert))
10055 (buffer-tags nil)
10056 (fwidth (+ maxlen 3 1 3))
10057 (ncol (/ (- (window-width) 4) fwidth))
10058 (i-face 'org-done)
10059 (c-face 'org-todo)
10060 tg cnt e c char c1 c2 ntable tbl rtn
10061 ov-start ov-end ov-prefix
10062 (exit-after-next org-fast-tag-selection-single-key)
10063 (done-keywords org-done-keywords)
10064 groups ingroup)
10065 (save-excursion
10066 (beginning-of-line 1)
10067 (if (looking-at
10068 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10069 (setq ov-start (match-beginning 1)
10070 ov-end (match-end 1)
10071 ov-prefix "")
10072 (setq ov-start (1- (point-at-eol))
10073 ov-end (1+ ov-start))
10074 (skip-chars-forward "^\n\r")
10075 (setq ov-prefix
10076 (concat
10077 (buffer-substring (1- (point)) (point))
10078 (if (> (current-column) org-tags-column)
10080 (make-string (- org-tags-column (current-column)) ?\ ))))))
10081 (org-move-overlay org-tags-overlay ov-start ov-end)
10082 (save-window-excursion
10083 (if expert
10084 (set-buffer (get-buffer-create " *Org tags*"))
10085 (delete-other-windows)
10086 (split-window-vertically)
10087 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10088 (erase-buffer)
10089 (org-set-local 'org-done-keywords done-keywords)
10090 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10091 (org-fast-tag-insert "Current" current c-face "\n\n")
10092 (org-fast-tag-show-exit exit-after-next)
10093 (org-set-current-tags-overlay current ov-prefix)
10094 (setq tbl fulltable char ?a cnt 0)
10095 (while (setq e (pop tbl))
10096 (cond
10097 ((equal e '(:startgroup))
10098 (push '() groups) (setq ingroup t)
10099 (when (not (= cnt 0))
10100 (setq cnt 0)
10101 (insert "\n"))
10102 (insert "{ "))
10103 ((equal e '(:endgroup))
10104 (setq ingroup nil cnt 0)
10105 (insert "}\n"))
10107 (setq tg (car e) c2 nil)
10108 (if (cdr e)
10109 (setq c (cdr e))
10110 ;; automatically assign a character.
10111 (setq c1 (string-to-char
10112 (downcase (substring
10113 tg (if (= (string-to-char tg) ?@) 1 0)))))
10114 (if (or (rassoc c1 ntable) (rassoc c1 table))
10115 (while (or (rassoc char ntable) (rassoc char table))
10116 (setq char (1+ char)))
10117 (setq c2 c1))
10118 (setq c (or c2 char)))
10119 (if ingroup (push tg (car groups)))
10120 (setq tg (org-add-props tg nil 'face
10121 (cond
10122 ((not (assoc tg table))
10123 (org-get-todo-face tg))
10124 ((member tg current) c-face)
10125 ((member tg inherited) i-face)
10126 (t nil))))
10127 (if (and (= cnt 0) (not ingroup)) (insert " "))
10128 (insert "[" c "] " tg (make-string
10129 (- fwidth 4 (length tg)) ?\ ))
10130 (push (cons tg c) ntable)
10131 (when (= (setq cnt (1+ cnt)) ncol)
10132 (insert "\n")
10133 (if ingroup (insert " "))
10134 (setq cnt 0)))))
10135 (setq ntable (nreverse ntable))
10136 (insert "\n")
10137 (goto-char (point-min))
10138 (if (not expert) (org-fit-window-to-buffer))
10139 (setq rtn
10140 (catch 'exit
10141 (while t
10142 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10143 (if groups " [!] no groups" " [!]groups")
10144 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10145 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10146 (cond
10147 ((= c ?\r) (throw 'exit t))
10148 ((= c ?!)
10149 (setq groups (not groups))
10150 (goto-char (point-min))
10151 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10152 ((= c ?\C-c)
10153 (if (not expert)
10154 (org-fast-tag-show-exit
10155 (setq exit-after-next (not exit-after-next)))
10156 (setq expert nil)
10157 (delete-other-windows)
10158 (split-window-vertically)
10159 (org-switch-to-buffer-other-window " *Org tags*")
10160 (org-fit-window-to-buffer)))
10161 ((or (= c ?\C-g)
10162 (and (= c ?q) (not (rassoc c ntable))))
10163 (org-detach-overlay org-tags-overlay)
10164 (setq quit-flag t))
10165 ((= c ?\ )
10166 (setq current nil)
10167 (if exit-after-next (setq exit-after-next 'now)))
10168 ((= c ?\t)
10169 (condition-case nil
10170 (setq tg (org-ido-completing-read
10171 "Tag: "
10172 (or buffer-tags
10173 (with-current-buffer buf
10174 (org-get-buffer-tags)))))
10175 (quit (setq tg "")))
10176 (when (string-match "\\S-" tg)
10177 (add-to-list 'buffer-tags (list tg))
10178 (if (member tg current)
10179 (setq current (delete tg current))
10180 (push tg current)))
10181 (if exit-after-next (setq exit-after-next 'now)))
10182 ((setq e (rassoc c todo-table) tg (car e))
10183 (with-current-buffer buf
10184 (save-excursion (org-todo tg)))
10185 (if exit-after-next (setq exit-after-next 'now)))
10186 ((setq e (rassoc c ntable) tg (car e))
10187 (if (member tg current)
10188 (setq current (delete tg current))
10189 (loop for g in groups do
10190 (if (member tg g)
10191 (mapc (lambda (x)
10192 (setq current (delete x current)))
10193 g)))
10194 (push tg current))
10195 (if exit-after-next (setq exit-after-next 'now))))
10197 ;; Create a sorted list
10198 (setq current
10199 (sort current
10200 (lambda (a b)
10201 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10202 (if (eq exit-after-next 'now) (throw 'exit t))
10203 (goto-char (point-min))
10204 (beginning-of-line 2)
10205 (delete-region (point) (point-at-eol))
10206 (org-fast-tag-insert "Current" current c-face)
10207 (org-set-current-tags-overlay current ov-prefix)
10208 (while (re-search-forward
10209 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10210 (setq tg (match-string 1))
10211 (add-text-properties
10212 (match-beginning 1) (match-end 1)
10213 (list 'face
10214 (cond
10215 ((member tg current) c-face)
10216 ((member tg inherited) i-face)
10217 (t (get-text-property (match-beginning 1) 'face))))))
10218 (goto-char (point-min)))))
10219 (org-detach-overlay org-tags-overlay)
10220 (if rtn
10221 (mapconcat 'identity current ":")
10222 nil))))
10224 (defun org-get-tags-string ()
10225 "Get the TAGS string in the current headline."
10226 (unless (org-on-heading-p t)
10227 (error "Not on a heading"))
10228 (save-excursion
10229 (beginning-of-line 1)
10230 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10231 (org-match-string-no-properties 1)
10232 "")))
10234 (defun org-get-tags ()
10235 "Get the list of tags specified in the current headline."
10236 (org-split-string (org-get-tags-string) ":"))
10238 (defun org-get-buffer-tags ()
10239 "Get a table of all tags used in the buffer, for completion."
10240 (let (tags)
10241 (save-excursion
10242 (goto-char (point-min))
10243 (while (re-search-forward
10244 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10245 (when (equal (char-after (point-at-bol 0)) ?*)
10246 (mapc (lambda (x) (add-to-list 'tags x))
10247 (org-split-string (org-match-string-no-properties 1) ":")))))
10248 (mapcar 'list tags)))
10250 ;;;; The mapping API
10252 ;;;###autoload
10253 (defun org-map-entries (func &optional match scope &rest skip)
10254 "Call FUNC at each headline selected by MATCH in SCOPE.
10256 FUNC is a function or a lisp form. The function will be called without
10257 arguments, with the cursor positioned at the beginning of the headline.
10258 The return values of all calls to the function will be collected and
10259 returned as a list.
10261 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10262 Only headlines that are matched by this query will be considered during
10263 the iteration. When MATCH is nil or t, all headlines will be
10264 visited by the iteration.
10266 SCOPE determines the scope of this command. It can be any of:
10268 nil The current buffer, respecting the restriction if any
10269 tree The subtree started with the entry at point
10270 file The current buffer, without restriction
10271 file-with-archives
10272 The current buffer, and any archives associated with it
10273 agenda All agenda files
10274 agenda-with-archives
10275 All agenda files with any archive files associated with them
10276 \(file1 file2 ...)
10277 If this is a list, all files in the list will be scanned
10279 The remaining args are treated as settings for the skipping facilities of
10280 the scanner. The following items can be given here:
10282 archive skip trees with the archive tag.
10283 comment skip trees with the COMMENT keyword
10284 function or Emacs Lisp form:
10285 will be used as value for `org-agenda-skip-function', so whenever
10286 the the function returns t, FUNC will not be called for that
10287 entry and search will continue from the point where the
10288 function leaves it."
10289 (let* ((org-agenda-archives-mode nil) ; just to make sure
10290 (org-agenda-skip-archived-trees (memq 'archive skip))
10291 (org-agenda-skip-comment-trees (memq 'comment skip))
10292 (org-agenda-skip-function
10293 (car (org-delete-all '(comment archive) skip)))
10294 (org-tags-match-list-sublevels t)
10295 matcher file res
10296 org-todo-keywords-for-agenda
10297 org-done-keywords-for-agenda
10298 org-todo-keyword-alist-for-agenda
10299 org-tag-alist-for-agenda)
10301 (cond
10302 ((eq match t) (setq matcher t))
10303 ((eq match nil) (setq matcher t))
10304 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10306 (save-excursion
10307 (save-restriction
10308 (when (eq scope 'tree)
10309 (org-back-to-heading t)
10310 (org-narrow-to-subtree)
10311 (setq scope nil))
10313 (if (not scope)
10314 (progn
10315 (org-prepare-agenda-buffers
10316 (list (buffer-file-name (current-buffer))))
10317 (setq res (org-scan-tags func matcher)))
10318 ;; Get the right scope
10319 (cond
10320 ((and scope (listp scope) (symbolp (car scope)))
10321 (setq scope (eval scope)))
10322 ((eq scope 'agenda)
10323 (setq scope (org-agenda-files t)))
10324 ((eq scope 'agenda-with-archives)
10325 (setq scope (org-agenda-files t))
10326 (setq scope (org-add-archive-files scope)))
10327 ((eq scope 'file)
10328 (setq scope (list (buffer-file-name))))
10329 ((eq scope 'file-with-archives)
10330 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10331 (org-prepare-agenda-buffers scope)
10332 (while (setq file (pop scope))
10333 (with-current-buffer (org-find-base-buffer-visiting file)
10334 (save-excursion
10335 (save-restriction
10336 (widen)
10337 (goto-char (point-min))
10338 (setq res (append res (org-scan-tags func matcher))))))))))
10339 res))
10341 ;;;; Properties
10343 ;;; Setting and retrieving properties
10345 (defconst org-special-properties
10346 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10347 "TIMESTAMP" "TIMESTAMP_IA")
10348 "The special properties valid in Org-mode.
10350 These are properties that are not defined in the property drawer,
10351 but in some other way.")
10353 (defconst org-default-properties
10354 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10355 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10356 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10357 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10358 "Some properties that are used by Org-mode for various purposes.
10359 Being in this list makes sure that they are offered for completion.")
10361 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10362 "Regular expression matching the first line of a property drawer.")
10364 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10365 "Regular expression matching the first line of a property drawer.")
10367 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10368 "Regular expression matching the first line of a property drawer.")
10370 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10371 "Regular expression matching the first line of a property drawer.")
10373 (defconst org-property-drawer-re
10374 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10375 org-property-end-re "\\)\n?")
10376 "Matches an entire property drawer.")
10378 (defconst org-clock-drawer-re
10379 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10380 org-property-end-re "\\)\n?")
10381 "Matches an entire clock drawer.")
10383 (defun org-property-action ()
10384 "Do an action on properties."
10385 (interactive)
10386 (let (c)
10387 (org-at-property-p)
10388 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10389 (setq c (read-char-exclusive))
10390 (cond
10391 ((equal c ?s)
10392 (call-interactively 'org-set-property))
10393 ((equal c ?d)
10394 (call-interactively 'org-delete-property))
10395 ((equal c ?D)
10396 (call-interactively 'org-delete-property-globally))
10397 ((equal c ?c)
10398 (call-interactively 'org-compute-property-at-point))
10399 (t (error "No such property action %c" c)))))
10401 (defun org-at-property-p ()
10402 "Is the cursor in a property line?"
10403 ;; FIXME: Does not check if we are actually in the drawer.
10404 ;; FIXME: also returns true on any drawers.....
10405 ;; This is used by C-c C-c for property action.
10406 (save-excursion
10407 (beginning-of-line 1)
10408 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10410 (defun org-get-property-block (&optional beg end force)
10411 "Return the (beg . end) range of the body of the property drawer.
10412 BEG and END can be beginning and end of subtree, if not given
10413 they will be found.
10414 If the drawer does not exist and FORCE is non-nil, create the drawer."
10415 (catch 'exit
10416 (save-excursion
10417 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10418 (end (or end (progn (outline-next-heading) (point)))))
10419 (goto-char beg)
10420 (if (re-search-forward org-property-start-re end t)
10421 (setq beg (1+ (match-end 0)))
10422 (if force
10423 (save-excursion
10424 (org-insert-property-drawer)
10425 (setq end (progn (outline-next-heading) (point))))
10426 (throw 'exit nil))
10427 (goto-char beg)
10428 (if (re-search-forward org-property-start-re end t)
10429 (setq beg (1+ (match-end 0)))))
10430 (if (re-search-forward org-property-end-re end t)
10431 (setq end (match-beginning 0))
10432 (or force (throw 'exit nil))
10433 (goto-char beg)
10434 (setq end beg)
10435 (org-indent-line-function)
10436 (insert ":END:\n"))
10437 (cons beg end)))))
10439 (defun org-entry-properties (&optional pom which)
10440 "Get all properties of the entry at point-or-marker POM.
10441 This includes the TODO keyword, the tags, time strings for deadline,
10442 scheduled, and clocking, and any additional properties defined in the
10443 entry. The return value is an alist, keys may occur multiple times
10444 if the property key was used several times.
10445 POM may also be nil, in which case the current entry is used.
10446 If WHICH is nil or `all', get all properties. If WHICH is
10447 `special' or `standard', only get that subclass."
10448 (setq which (or which 'all))
10449 (org-with-point-at pom
10450 (let ((clockstr (substring org-clock-string 0 -1))
10451 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10452 beg end range props sum-props key value string clocksum)
10453 (save-excursion
10454 (when (condition-case nil
10455 (and (org-mode-p) (org-back-to-heading t))
10456 (error nil))
10457 (setq beg (point))
10458 (setq sum-props (get-text-property (point) 'org-summaries))
10459 (setq clocksum (get-text-property (point) :org-clock-minutes))
10460 (outline-next-heading)
10461 (setq end (point))
10462 (when (memq which '(all special))
10463 ;; Get the special properties, like TODO and tags
10464 (goto-char beg)
10465 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10466 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10467 (when (looking-at org-priority-regexp)
10468 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10469 (when (and (setq value (org-get-tags-string))
10470 (string-match "\\S-" value))
10471 (push (cons "TAGS" value) props))
10472 (when (setq value (org-get-tags-at))
10473 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10474 props))
10475 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10476 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10477 string (if (equal key clockstr)
10478 (org-no-properties
10479 (org-trim
10480 (buffer-substring
10481 (match-beginning 3) (goto-char (point-at-eol)))))
10482 (substring (org-match-string-no-properties 3) 1 -1)))
10483 (unless key
10484 (if (= (char-after (match-beginning 3)) ?\[)
10485 (setq key "TIMESTAMP_IA")
10486 (setq key "TIMESTAMP")))
10487 (when (or (equal key clockstr) (not (assoc key props)))
10488 (push (cons key string) props)))
10492 (when (memq which '(all standard))
10493 ;; Get the standard properties, like :PORP: ...
10494 (setq range (org-get-property-block beg end))
10495 (when range
10496 (goto-char (car range))
10497 (while (re-search-forward
10498 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10499 (cdr range) t)
10500 (setq key (org-match-string-no-properties 1)
10501 value (org-trim (or (org-match-string-no-properties 2) "")))
10502 (unless (member key excluded)
10503 (push (cons key (or value "")) props)))))
10504 (if clocksum
10505 (push (cons "CLOCKSUM"
10506 (org-columns-number-to-string (/ (float clocksum) 60.)
10507 'add_times))
10508 props))
10509 (unless (assoc "CATEGORY" props)
10510 (setq value (or (org-get-category)
10511 (progn (org-refresh-category-properties)
10512 (org-get-category))))
10513 (push (cons "CATEGORY" value) props))
10514 (append sum-props (nreverse props)))))))
10516 (defun org-entry-get (pom property &optional inherit)
10517 "Get value of PROPERTY for entry at point-or-marker POM.
10518 If INHERIT is non-nil and the entry does not have the property,
10519 then also check higher levels of the hierarchy.
10520 If INHERIT is the symbol `selective', use inheritance only if the setting
10521 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10522 If the property is present but empty, the return value is the empty string.
10523 If the property is not present at all, nil is returned."
10524 (org-with-point-at pom
10525 (if (and inherit (if (eq inherit 'selective)
10526 (org-property-inherit-p property)
10528 (org-entry-get-with-inheritance property)
10529 (if (member property org-special-properties)
10530 ;; We need a special property. Use brute force, get all properties.
10531 (cdr (assoc property (org-entry-properties nil 'special)))
10532 (let ((range (org-get-property-block)))
10533 (if (and range
10534 (goto-char (car range))
10535 (re-search-forward
10536 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10537 (cdr range) t))
10538 ;; Found the property, return it.
10539 (if (match-end 1)
10540 (org-match-string-no-properties 1)
10541 "")))))))
10543 (defun org-property-or-variable-value (var &optional inherit)
10544 "Check if there is a property fixing the value of VAR.
10545 If yes, return this value. If not, return the current value of the variable."
10546 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10547 (if (and prop (stringp prop) (string-match "\\S-" prop))
10548 (read prop)
10549 (symbol-value var))))
10551 (defun org-entry-delete (pom property)
10552 "Delete the property PROPERTY from entry at point-or-marker POM."
10553 (org-with-point-at pom
10554 (if (member property org-special-properties)
10555 nil ; cannot delete these properties.
10556 (let ((range (org-get-property-block)))
10557 (if (and range
10558 (goto-char (car range))
10559 (re-search-forward
10560 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10561 (cdr range) t))
10562 (progn
10563 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10565 nil)))))
10567 ;; Multi-values properties are properties that contain multiple values
10568 ;; These values are assumed to be single words, separated by whitespace.
10569 (defun org-entry-add-to-multivalued-property (pom property value)
10570 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10571 (let* ((old (org-entry-get pom property))
10572 (values (and old (org-split-string old "[ \t]"))))
10573 (setq value (org-entry-protect-space value))
10574 (unless (member value values)
10575 (setq values (cons value values))
10576 (org-entry-put pom property
10577 (mapconcat 'identity values " ")))))
10579 (defun org-entry-remove-from-multivalued-property (pom property value)
10580 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10581 (let* ((old (org-entry-get pom property))
10582 (values (and old (org-split-string old "[ \t]"))))
10583 (setq value (org-entry-protect-space value))
10584 (when (member value values)
10585 (setq values (delete value values))
10586 (org-entry-put pom property
10587 (mapconcat 'identity values " ")))))
10589 (defun org-entry-member-in-multivalued-property (pom property value)
10590 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10591 (let* ((old (org-entry-get pom property))
10592 (values (and old (org-split-string old "[ \t]"))))
10593 (setq value (org-entry-protect-space value))
10594 (member value values)))
10596 (defun org-entry-get-multivalued-property (pom property)
10597 "Return a list of values in a multivalued property."
10598 (let* ((value (org-entry-get pom property))
10599 (values (and value (org-split-string value "[ \t]"))))
10600 (mapcar 'org-entry-restore-space values)))
10602 (defun org-entry-put-multivalued-property (pom property &rest values)
10603 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10604 VALUES should be a list of strings. Spaces will be protected."
10605 (org-entry-put pom property
10606 (mapconcat 'org-entry-protect-space values " "))
10607 (let* ((value (org-entry-get pom property))
10608 (values (and value (org-split-string value "[ \t]"))))
10609 (mapcar 'org-entry-restore-space values)))
10611 (defun org-entry-protect-space (s)
10612 "Protect spaces and newline in string S."
10613 (while (string-match " " s)
10614 (setq s (replace-match "%20" t t s)))
10615 (while (string-match "\n" s)
10616 (setq s (replace-match "%0A" t t s)))
10619 (defun org-entry-restore-space (s)
10620 "Restore spaces and newline in string S."
10621 (while (string-match "%20" s)
10622 (setq s (replace-match " " t t s)))
10623 (while (string-match "%0A" s)
10624 (setq s (replace-match "\n" t t s)))
10627 (defvar org-entry-property-inherited-from (make-marker)
10628 "Marker pointing to the entry from where a property was inherited.
10629 Each call to `org-entry-get-with-inheritance' will set this marker to the
10630 location of the entry where the inheritance search matched. If there was
10631 no match, the marker will point nowhere.
10632 Note that also `org-entry-get' calls this function, if the INHERIT flag
10633 is set.")
10635 (defun org-entry-get-with-inheritance (property)
10636 "Get entry property, and search higher levels if not present."
10637 (move-marker org-entry-property-inherited-from nil)
10638 (let (tmp)
10639 (save-excursion
10640 (save-restriction
10641 (widen)
10642 (catch 'ex
10643 (while t
10644 (when (setq tmp (org-entry-get nil property))
10645 (org-back-to-heading t)
10646 (move-marker org-entry-property-inherited-from (point))
10647 (throw 'ex tmp))
10648 (or (org-up-heading-safe) (throw 'ex nil)))))
10649 (or tmp
10650 (cdr (assoc property org-file-properties))
10651 (cdr (assoc property org-global-properties))
10652 (cdr (assoc property org-global-properties-fixed))))))
10654 (defun org-entry-put (pom property value)
10655 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10656 (org-with-point-at pom
10657 (org-back-to-heading t)
10658 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10659 range)
10660 (cond
10661 ((equal property "TODO")
10662 (when (and (stringp value) (string-match "\\S-" value)
10663 (not (member value org-todo-keywords-1)))
10664 (error "\"%s\" is not a valid TODO state" value))
10665 (if (or (not value)
10666 (not (string-match "\\S-" value)))
10667 (setq value 'none))
10668 (org-todo value)
10669 (org-set-tags nil 'align))
10670 ((equal property "PRIORITY")
10671 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10672 (string-to-char value) ?\ ))
10673 (org-set-tags nil 'align))
10674 ((equal property "SCHEDULED")
10675 (if (re-search-forward org-scheduled-time-regexp end t)
10676 (cond
10677 ((eq value 'earlier) (org-timestamp-change -1 'day))
10678 ((eq value 'later) (org-timestamp-change 1 'day))
10679 (t (call-interactively 'org-schedule)))
10680 (call-interactively 'org-schedule)))
10681 ((equal property "DEADLINE")
10682 (if (re-search-forward org-deadline-time-regexp end t)
10683 (cond
10684 ((eq value 'earlier) (org-timestamp-change -1 'day))
10685 ((eq value 'later) (org-timestamp-change 1 'day))
10686 (t (call-interactively 'org-deadline)))
10687 (call-interactively 'org-deadline)))
10688 ((member property org-special-properties)
10689 (error "The %s property can not yet be set with `org-entry-put'"
10690 property))
10691 (t ; a non-special property
10692 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10693 (setq range (org-get-property-block beg end 'force))
10694 (goto-char (car range))
10695 (if (re-search-forward
10696 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10697 (progn
10698 (delete-region (match-beginning 1) (match-end 1))
10699 (goto-char (match-beginning 1)))
10700 (goto-char (cdr range))
10701 (insert "\n")
10702 (backward-char 1)
10703 (org-indent-line-function)
10704 (insert ":" property ":"))
10705 (and value (insert " " value))
10706 (org-indent-line-function)))))))
10708 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10709 "Get all property keys in the current buffer.
10710 With INCLUDE-SPECIALS, also list the special properties that reflect things
10711 like tags and TODO state.
10712 With INCLUDE-DEFAULTS, also include properties that has special meaning
10713 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10714 With INCLUDE-COLUMNS, also include property names given in COLUMN
10715 formats in the current buffer."
10716 (let (rtn range cfmt s p)
10717 (save-excursion
10718 (save-restriction
10719 (widen)
10720 (goto-char (point-min))
10721 (while (re-search-forward org-property-start-re nil t)
10722 (setq range (org-get-property-block))
10723 (goto-char (car range))
10724 (while (re-search-forward
10725 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10726 (cdr range) t)
10727 (add-to-list 'rtn (org-match-string-no-properties 1)))
10728 (outline-next-heading))))
10730 (when include-specials
10731 (setq rtn (append org-special-properties rtn)))
10733 (when include-defaults
10734 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10736 (when include-columns
10737 (save-excursion
10738 (save-restriction
10739 (widen)
10740 (goto-char (point-min))
10741 (while (re-search-forward
10742 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10743 nil t)
10744 (setq cfmt (match-string 2) s 0)
10745 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10746 cfmt s)
10747 (setq s (match-end 0)
10748 p (match-string 1 cfmt))
10749 (unless (or (equal p "ITEM")
10750 (member p org-special-properties))
10751 (add-to-list 'rtn (match-string 1 cfmt))))))))
10753 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10755 (defun org-property-values (key)
10756 "Return a list of all values of property KEY."
10757 (save-excursion
10758 (save-restriction
10759 (widen)
10760 (goto-char (point-min))
10761 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10762 values)
10763 (while (re-search-forward re nil t)
10764 (add-to-list 'values (org-trim (match-string 1))))
10765 (delete "" values)))))
10767 (defun org-insert-property-drawer ()
10768 "Insert a property drawer into the current entry."
10769 (interactive)
10770 (org-back-to-heading t)
10771 (looking-at outline-regexp)
10772 (let ((indent (- (match-end 0)(match-beginning 0)))
10773 (beg (point))
10774 (re (concat "^[ \t]*" org-keyword-time-regexp))
10775 end hiddenp)
10776 (outline-next-heading)
10777 (setq end (point))
10778 (goto-char beg)
10779 (while (re-search-forward re end t))
10780 (setq hiddenp (org-invisible-p))
10781 (end-of-line 1)
10782 (and (equal (char-after) ?\n) (forward-char 1))
10783 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10784 (beginning-of-line 2))
10785 (org-skip-over-state-notes)
10786 (skip-chars-backward " \t\n\r")
10787 (if (eq (char-before) ?*) (forward-char 1))
10788 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10789 (beginning-of-line 0)
10790 (org-indent-to-column indent)
10791 (beginning-of-line 2)
10792 (org-indent-to-column indent)
10793 (beginning-of-line 0)
10794 (if hiddenp
10795 (save-excursion
10796 (org-back-to-heading t)
10797 (hide-entry))
10798 (org-flag-drawer t))))
10800 (defun org-set-property (property value)
10801 "In the current entry, set PROPERTY to VALUE.
10802 When called interactively, this will prompt for a property name, offering
10803 completion on existing and default properties. And then it will prompt
10804 for a value, offering completion either on allowed values (via an inherited
10805 xxx_ALL property) or on existing values in other instances of this property
10806 in the current file."
10807 (interactive
10808 (let* ((completion-ignore-case t)
10809 (keys (org-buffer-property-keys nil t t))
10810 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10811 (prop (if (member prop0 keys)
10812 prop0
10813 (or (cdr (assoc (downcase prop0)
10814 (mapcar (lambda (x) (cons (downcase x) x))
10815 keys)))
10816 prop0)))
10817 (cur (org-entry-get nil prop))
10818 (allowed (org-property-get-allowed-values nil prop 'table))
10819 (existing (mapcar 'list (org-property-values prop)))
10820 (val (if allowed
10821 (org-completing-read "Value: " allowed nil 'req-match)
10822 (org-completing-read
10823 (concat "Value" (if (and cur (string-match "\\S-" cur))
10824 (concat "[" cur "]") "")
10825 ": ")
10826 existing nil nil "" nil cur))))
10827 (list prop (if (equal val "") cur val))))
10828 (unless (equal (org-entry-get nil property) value)
10829 (org-entry-put nil property value)))
10831 (defun org-delete-property (property)
10832 "In the current entry, delete PROPERTY."
10833 (interactive
10834 (let* ((completion-ignore-case t)
10835 (prop (org-ido-completing-read
10836 "Property: " (org-entry-properties nil 'standard))))
10837 (list prop)))
10838 (message "Property %s %s" property
10839 (if (org-entry-delete nil property)
10840 "deleted"
10841 "was not present in the entry")))
10843 (defun org-delete-property-globally (property)
10844 "Remove PROPERTY globally, from all entries."
10845 (interactive
10846 (let* ((completion-ignore-case t)
10847 (prop (org-ido-completing-read
10848 "Globally remove property: "
10849 (mapcar 'list (org-buffer-property-keys)))))
10850 (list prop)))
10851 (save-excursion
10852 (save-restriction
10853 (widen)
10854 (goto-char (point-min))
10855 (let ((cnt 0))
10856 (while (re-search-forward
10857 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10858 nil t)
10859 (setq cnt (1+ cnt))
10860 (replace-match ""))
10861 (message "Property \"%s\" removed from %d entries" property cnt)))))
10863 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10865 (defun org-compute-property-at-point ()
10866 "Compute the property at point.
10867 This looks for an enclosing column format, extracts the operator and
10868 then applies it to the property in the column format's scope."
10869 (interactive)
10870 (unless (org-at-property-p)
10871 (error "Not at a property"))
10872 (let ((prop (org-match-string-no-properties 2)))
10873 (org-columns-get-format-and-top-level)
10874 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10875 (error "No operator defined for property %s" prop))
10876 (org-columns-compute prop)))
10878 (defun org-property-get-allowed-values (pom property &optional table)
10879 "Get allowed values for the property PROPERTY.
10880 When TABLE is non-nil, return an alist that can directly be used for
10881 completion."
10882 (let (vals)
10883 (cond
10884 ((equal property "TODO")
10885 (setq vals (org-with-point-at pom
10886 (append org-todo-keywords-1 '("")))))
10887 ((equal property "PRIORITY")
10888 (let ((n org-lowest-priority))
10889 (while (>= n org-highest-priority)
10890 (push (char-to-string n) vals)
10891 (setq n (1- n)))))
10892 ((member property org-special-properties))
10894 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10896 (when (and vals (string-match "\\S-" vals))
10897 (setq vals (car (read-from-string (concat "(" vals ")"))))
10898 (setq vals (mapcar (lambda (x)
10899 (cond ((stringp x) x)
10900 ((numberp x) (number-to-string x))
10901 ((symbolp x) (symbol-name x))
10902 (t "???")))
10903 vals)))))
10904 (if table (mapcar 'list vals) vals)))
10906 (defun org-property-previous-allowed-value (&optional previous)
10907 "Switch to the next allowed value for this property."
10908 (interactive)
10909 (org-property-next-allowed-value t))
10911 (defun org-property-next-allowed-value (&optional previous)
10912 "Switch to the next allowed value for this property."
10913 (interactive)
10914 (unless (org-at-property-p)
10915 (error "Not at a property"))
10916 (let* ((key (match-string 2))
10917 (value (match-string 3))
10918 (allowed (or (org-property-get-allowed-values (point) key)
10919 (and (member value '("[ ]" "[-]" "[X]"))
10920 '("[ ]" "[X]"))))
10921 nval)
10922 (unless allowed
10923 (error "Allowed values for this property have not been defined"))
10924 (if previous (setq allowed (reverse allowed)))
10925 (if (member value allowed)
10926 (setq nval (car (cdr (member value allowed)))))
10927 (setq nval (or nval (car allowed)))
10928 (if (equal nval value)
10929 (error "Only one allowed value for this property"))
10930 (org-at-property-p)
10931 (replace-match (concat " :" key ": " nval) t t)
10932 (org-indent-line-function)
10933 (beginning-of-line 1)
10934 (skip-chars-forward " \t")))
10936 (defun org-find-entry-with-id (ident)
10937 "Locate the entry that contains the ID property with exact value IDENT.
10938 IDENT can be a string, a symbol or a number, this function will search for
10939 the string representation of it.
10940 Return the position where this entry starts, or nil if there is no such entry."
10941 (interactive "sID: ")
10942 (let ((id (cond
10943 ((stringp ident) ident)
10944 ((symbol-name ident) (symbol-name ident))
10945 ((numberp ident) (number-to-string ident))
10946 (t (error "IDENT %s must be a string, symbol or number" ident))))
10947 (case-fold-search nil))
10948 (save-excursion
10949 (save-restriction
10950 (widen)
10951 (goto-char (point-min))
10952 (when (re-search-forward
10953 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10954 nil t)
10955 (org-back-to-heading)
10956 (point))))))
10958 ;;;; Timestamps
10960 (defvar org-last-changed-timestamp nil)
10961 (defvar org-last-inserted-timestamp nil
10962 "The last time stamp inserted with `org-insert-time-stamp'.")
10963 (defvar org-time-was-given) ; dynamically scoped parameter
10964 (defvar org-end-time-was-given) ; dynamically scoped parameter
10965 (defvar org-ts-what) ; dynamically scoped parameter
10967 (defun org-time-stamp (arg &optional inactive)
10968 "Prompt for a date/time and insert a time stamp.
10969 If the user specifies a time like HH:MM, or if this command is called
10970 with a prefix argument, the time stamp will contain date and time.
10971 Otherwise, only the date will be included. All parts of a date not
10972 specified by the user will be filled in from the current date/time.
10973 So if you press just return without typing anything, the time stamp
10974 will represent the current date/time. If there is already a timestamp
10975 at the cursor, it will be modified."
10976 (interactive "P")
10977 (let* ((ts nil)
10978 (default-time
10979 ;; Default time is either today, or, when entering a range,
10980 ;; the range start.
10981 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10982 (save-excursion
10983 (re-search-backward
10984 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10985 (- (point) 20) t)))
10986 (apply 'encode-time (org-parse-time-string (match-string 1)))
10987 (current-time)))
10988 (default-input (and ts (org-get-compact-tod ts)))
10989 org-time-was-given org-end-time-was-given time)
10990 (cond
10991 ((and (org-at-timestamp-p t)
10992 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10993 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10994 (insert "--")
10995 (setq time (let ((this-command this-command))
10996 (org-read-date arg 'totime nil nil
10997 default-time default-input)))
10998 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10999 ((org-at-timestamp-p t)
11000 (setq time (let ((this-command this-command))
11001 (org-read-date arg 'totime nil nil default-time default-input)))
11002 (when (org-at-timestamp-p t) ; just to get the match data
11003 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11004 (replace-match "")
11005 (setq org-last-changed-timestamp
11006 (org-insert-time-stamp
11007 time (or org-time-was-given arg)
11008 inactive nil nil (list org-end-time-was-given))))
11009 (message "Timestamp updated"))
11011 (setq time (let ((this-command this-command))
11012 (org-read-date arg 'totime nil nil default-time default-input)))
11013 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11014 nil nil (list org-end-time-was-given))))))
11016 ;; FIXME: can we use this for something else, like computing time differences?
11017 (defun org-get-compact-tod (s)
11018 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11019 (let* ((t1 (match-string 1 s))
11020 (h1 (string-to-number (match-string 2 s)))
11021 (m1 (string-to-number (match-string 3 s)))
11022 (t2 (and (match-end 4) (match-string 5 s)))
11023 (h2 (and t2 (string-to-number (match-string 6 s))))
11024 (m2 (and t2 (string-to-number (match-string 7 s))))
11025 dh dm)
11026 (if (not t2)
11028 (setq dh (- h2 h1) dm (- m2 m1))
11029 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11030 (concat t1 "+" (number-to-string dh)
11031 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11033 (defun org-time-stamp-inactive (&optional arg)
11034 "Insert an inactive time stamp.
11035 An inactive time stamp is enclosed in square brackets instead of angle
11036 brackets. It is inactive in the sense that it does not trigger agenda entries,
11037 does not link to the calendar and cannot be changed with the S-cursor keys.
11038 So these are more for recording a certain time/date."
11039 (interactive "P")
11040 (org-time-stamp arg 'inactive))
11042 (defvar org-date-ovl (org-make-overlay 1 1))
11043 (org-overlay-put org-date-ovl 'face 'org-warning)
11044 (org-detach-overlay org-date-ovl)
11046 (defvar org-ans1) ; dynamically scoped parameter
11047 (defvar org-ans2) ; dynamically scoped parameter
11049 (defvar org-plain-time-of-day-regexp) ; defined below
11051 (defvar org-overriding-default-time nil) ; dynamically scoped
11052 (defvar org-read-date-overlay nil)
11053 (defvar org-dcst nil) ; dynamically scoped
11055 (defun org-read-date (&optional with-time to-time from-string prompt
11056 default-time default-input)
11057 "Read a date, possibly a time, and make things smooth for the user.
11058 The prompt will suggest to enter an ISO date, but you can also enter anything
11059 which will at least partially be understood by `parse-time-string'.
11060 Unrecognized parts of the date will default to the current day, month, year,
11061 hour and minute. If this command is called to replace a timestamp at point,
11062 of to enter the second timestamp of a range, the default time is taken from the
11063 existing stamp. For example,
11064 3-2-5 --> 2003-02-05
11065 feb 15 --> currentyear-02-15
11066 sep 12 9 --> 2009-09-12
11067 12:45 --> today 12:45
11068 22 sept 0:34 --> currentyear-09-22 0:34
11069 12 --> currentyear-currentmonth-12
11070 Fri --> nearest Friday (today or later)
11071 etc.
11073 Furthermore you can specify a relative date by giving, as the *first* thing
11074 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11075 change in days weeks, months, years.
11076 With a single plus or minus, the date is relative to today. With a double
11077 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11078 +4d --> four days from today
11079 +4 --> same as above
11080 +2w --> two weeks from today
11081 ++5 --> five days from default date
11083 The function understands only English month and weekday abbreviations,
11084 but this can be configured with the variables `parse-time-months' and
11085 `parse-time-weekdays'.
11087 While prompting, a calendar is popped up - you can also select the
11088 date with the mouse (button 1). The calendar shows a period of three
11089 months. To scroll it to other months, use the keys `>' and `<'.
11090 If you don't like the calendar, turn it off with
11091 \(setq org-read-date-popup-calendar nil)
11093 With optional argument TO-TIME, the date will immediately be converted
11094 to an internal time.
11095 With an optional argument WITH-TIME, the prompt will suggest to also
11096 insert a time. Note that when WITH-TIME is not set, you can still
11097 enter a time, and this function will inform the calling routine about
11098 this change. The calling routine may then choose to change the format
11099 used to insert the time stamp into the buffer to include the time.
11100 With optional argument FROM-STRING, read from this string instead from
11101 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11102 the time/date that is used for everything that is not specified by the
11103 user."
11104 (require 'parse-time)
11105 (let* ((org-time-stamp-rounding-minutes
11106 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11107 (org-dcst org-display-custom-times)
11108 (ct (org-current-time))
11109 (def (or org-overriding-default-time default-time ct))
11110 (defdecode (decode-time def))
11111 (dummy (progn
11112 (when (< (nth 2 defdecode) org-extend-today-until)
11113 (setcar (nthcdr 2 defdecode) -1)
11114 (setcar (nthcdr 1 defdecode) 59)
11115 (setq def (apply 'encode-time defdecode)
11116 defdecode (decode-time def)))))
11117 (calendar-move-hook nil)
11118 (calendar-view-diary-initially-flag nil)
11119 (view-diary-entries-initially nil)
11120 (calendar-view-holidays-initially-flag nil)
11121 (view-calendar-holidays-initially nil)
11122 (timestr (format-time-string
11123 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11124 (prompt (concat (if prompt (concat prompt " ") "")
11125 (format "Date+time [%s]: " timestr)))
11126 ans (org-ans0 "") org-ans1 org-ans2 final)
11128 (cond
11129 (from-string (setq ans from-string))
11130 (org-read-date-popup-calendar
11131 (save-excursion
11132 (save-window-excursion
11133 (calendar)
11134 (calendar-forward-day (- (time-to-days def)
11135 (calendar-absolute-from-gregorian
11136 (calendar-current-date))))
11137 (org-eval-in-calendar nil t)
11138 (let* ((old-map (current-local-map))
11139 (map (copy-keymap calendar-mode-map))
11140 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11141 (org-defkey map (kbd "RET") 'org-calendar-select)
11142 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11143 'org-calendar-select-mouse)
11144 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11145 'org-calendar-select-mouse)
11146 (org-defkey minibuffer-local-map [(meta shift left)]
11147 (lambda () (interactive)
11148 (org-eval-in-calendar '(calendar-backward-month 1))))
11149 (org-defkey minibuffer-local-map [(meta shift right)]
11150 (lambda () (interactive)
11151 (org-eval-in-calendar '(calendar-forward-month 1))))
11152 (org-defkey minibuffer-local-map [(meta shift up)]
11153 (lambda () (interactive)
11154 (org-eval-in-calendar '(calendar-backward-year 1))))
11155 (org-defkey minibuffer-local-map [(meta shift down)]
11156 (lambda () (interactive)
11157 (org-eval-in-calendar '(calendar-forward-year 1))))
11158 (org-defkey minibuffer-local-map [(shift up)]
11159 (lambda () (interactive)
11160 (org-eval-in-calendar '(calendar-backward-week 1))))
11161 (org-defkey minibuffer-local-map [(shift down)]
11162 (lambda () (interactive)
11163 (org-eval-in-calendar '(calendar-forward-week 1))))
11164 (org-defkey minibuffer-local-map [(shift left)]
11165 (lambda () (interactive)
11166 (org-eval-in-calendar '(calendar-backward-day 1))))
11167 (org-defkey minibuffer-local-map [(shift right)]
11168 (lambda () (interactive)
11169 (org-eval-in-calendar '(calendar-forward-day 1))))
11170 (org-defkey minibuffer-local-map ">"
11171 (lambda () (interactive)
11172 (org-eval-in-calendar '(scroll-calendar-left 1))))
11173 (org-defkey minibuffer-local-map "<"
11174 (lambda () (interactive)
11175 (org-eval-in-calendar '(scroll-calendar-right 1))))
11176 (unwind-protect
11177 (progn
11178 (use-local-map map)
11179 (add-hook 'post-command-hook 'org-read-date-display)
11180 (setq org-ans0 (read-string prompt default-input nil nil))
11181 ;; org-ans0: from prompt
11182 ;; org-ans1: from mouse click
11183 ;; org-ans2: from calendar motion
11184 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11185 (remove-hook 'post-command-hook 'org-read-date-display)
11186 (use-local-map old-map)
11187 (when org-read-date-overlay
11188 (org-delete-overlay org-read-date-overlay)
11189 (setq org-read-date-overlay nil)))))))
11191 (t ; Naked prompt only
11192 (unwind-protect
11193 (setq ans (read-string prompt default-input nil timestr))
11194 (when org-read-date-overlay
11195 (org-delete-overlay org-read-date-overlay)
11196 (setq org-read-date-overlay nil)))))
11198 (setq final (org-read-date-analyze ans def defdecode))
11200 (if to-time
11201 (apply 'encode-time final)
11202 (if (and (boundp 'org-time-was-given) org-time-was-given)
11203 (format "%04d-%02d-%02d %02d:%02d"
11204 (nth 5 final) (nth 4 final) (nth 3 final)
11205 (nth 2 final) (nth 1 final))
11206 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11207 (defvar def)
11208 (defvar defdecode)
11209 (defvar with-time)
11210 (defun org-read-date-display ()
11211 "Display the current date prompt interpretation in the minibuffer."
11212 (when org-read-date-display-live
11213 (when org-read-date-overlay
11214 (org-delete-overlay org-read-date-overlay))
11215 (let ((p (point)))
11216 (end-of-line 1)
11217 (while (not (equal (buffer-substring
11218 (max (point-min) (- (point) 4)) (point))
11219 " "))
11220 (insert " "))
11221 (goto-char p))
11222 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11223 " " (or org-ans1 org-ans2)))
11224 (org-end-time-was-given nil)
11225 (f (org-read-date-analyze ans def defdecode))
11226 (fmts (if org-dcst
11227 org-time-stamp-custom-formats
11228 org-time-stamp-formats))
11229 (fmt (if (or with-time
11230 (and (boundp 'org-time-was-given) org-time-was-given))
11231 (cdr fmts)
11232 (car fmts)))
11233 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11234 (when (and org-end-time-was-given
11235 (string-match org-plain-time-of-day-regexp txt))
11236 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11237 org-end-time-was-given
11238 (substring txt (match-end 0)))))
11239 (setq org-read-date-overlay
11240 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11241 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11243 (defun org-read-date-analyze (ans def defdecode)
11244 "Analyse the combined answer of the date prompt."
11245 ;; FIXME: cleanup and comment
11246 (let (delta deltan deltaw deltadef year month day
11247 hour minute second wday pm h2 m2 tl wday1
11248 iso-year iso-weekday iso-week iso-year iso-date)
11250 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11251 (setq ans "+0"))
11253 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11254 (setq ans (replace-match "" t t ans)
11255 deltan (car delta)
11256 deltaw (nth 1 delta)
11257 deltadef (nth 2 delta)))
11259 ;; Check if there is an iso week date in there
11260 ;; If yes, sore the info and postpone interpreting it until the rest
11261 ;; of the parsing is done
11262 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11263 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11264 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11265 iso-week (string-to-number (match-string 2 ans)))
11266 (setq ans (replace-match "" t t ans)))
11268 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11269 (when (string-match
11270 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11271 (setq year (if (match-end 2)
11272 (string-to-number (match-string 2 ans))
11273 (string-to-number (format-time-string "%Y")))
11274 month (string-to-number (match-string 3 ans))
11275 day (string-to-number (match-string 4 ans)))
11276 (if (< year 100) (setq year (+ 2000 year)))
11277 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11278 t nil ans)))
11279 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11280 ;; If there is a time with am/pm, and *no* time without it, we convert
11281 ;; so that matching will be successful.
11282 (loop for i from 1 to 2 do ; twice, for end time as well
11283 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11284 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11285 (setq hour (string-to-number (match-string 1 ans))
11286 minute (if (match-end 3)
11287 (string-to-number (match-string 3 ans))
11289 pm (equal ?p
11290 (string-to-char (downcase (match-string 4 ans)))))
11291 (if (and (= hour 12) (not pm))
11292 (setq hour 0)
11293 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11294 (setq ans (replace-match (format "%02d:%02d" hour minute)
11295 t t ans))))
11297 ;; Check if a time range is given as a duration
11298 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11299 (setq hour (string-to-number (match-string 1 ans))
11300 h2 (+ hour (string-to-number (match-string 3 ans)))
11301 minute (string-to-number (match-string 2 ans))
11302 m2 (+ minute (if (match-end 5) (string-to-number
11303 (match-string 5 ans))0)))
11304 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11305 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11306 t t ans)))
11308 ;; Check if there is a time range
11309 (when (boundp 'org-end-time-was-given)
11310 (setq org-time-was-given nil)
11311 (when (and (string-match org-plain-time-of-day-regexp ans)
11312 (match-end 8))
11313 (setq org-end-time-was-given (match-string 8 ans))
11314 (setq ans (concat (substring ans 0 (match-beginning 7))
11315 (substring ans (match-end 7))))))
11317 (setq tl (parse-time-string ans)
11318 day (or (nth 3 tl) (nth 3 defdecode))
11319 month (or (nth 4 tl)
11320 (if (and org-read-date-prefer-future
11321 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11322 (1+ (nth 4 defdecode))
11323 (nth 4 defdecode)))
11324 year (or (nth 5 tl)
11325 (if (and org-read-date-prefer-future
11326 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11327 (1+ (nth 5 defdecode))
11328 (nth 5 defdecode)))
11329 hour (or (nth 2 tl) (nth 2 defdecode))
11330 minute (or (nth 1 tl) (nth 1 defdecode))
11331 second (or (nth 0 tl) 0)
11332 wday (nth 6 tl))
11334 ;; Special date definitions below
11335 (cond
11336 (iso-week
11337 ;; There was an iso week
11338 (setq year (or iso-year year)
11339 day (or iso-weekday wday 1)
11340 wday nil ; to make sure that the trigger below does not match
11341 iso-date (calendar-gregorian-from-absolute
11342 (calendar-absolute-from-iso
11343 (list iso-week day year))))
11344 ; FIXME: Should we also push ISO weeks into the future?
11345 ; (when (and org-read-date-prefer-future
11346 ; (not iso-year)
11347 ; (< (calendar-absolute-from-gregorian iso-date)
11348 ; (time-to-days (current-time))))
11349 ; (setq year (1+ year)
11350 ; iso-date (calendar-gregorian-from-absolute
11351 ; (calendar-absolute-from-iso
11352 ; (list iso-week day year)))))
11353 (setq month (car iso-date)
11354 year (nth 2 iso-date)
11355 day (nth 1 iso-date)))
11356 (deltan
11357 (unless deltadef
11358 (let ((now (decode-time (current-time))))
11359 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11360 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11361 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11362 ((equal deltaw "m") (setq month (+ month deltan)))
11363 ((equal deltaw "y") (setq year (+ year deltan)))))
11364 ((and wday (not (nth 3 tl)))
11365 ;; Weekday was given, but no day, so pick that day in the week
11366 ;; on or after the derived date.
11367 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11368 (unless (equal wday wday1)
11369 (setq day (+ day (% (- wday wday1 -7) 7))))))
11370 (if (and (boundp 'org-time-was-given)
11371 (nth 2 tl))
11372 (setq org-time-was-given t))
11373 (if (< year 100) (setq year (+ 2000 year)))
11374 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11375 (list second minute hour day month year)))
11377 (defvar parse-time-weekdays)
11379 (defun org-read-date-get-relative (s today default)
11380 "Check string S for special relative date string.
11381 TODAY and DEFAULT are internal times, for today and for a default.
11382 Return shift list (N what def-flag)
11383 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11384 N is the number of WHATs to shift.
11385 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11386 the DEFAULT date rather than TODAY."
11387 (when (and
11388 (string-match
11389 (concat
11390 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11391 "\\([0-9]+\\)?"
11392 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11393 "\\([ \t]\\|$\\)") s)
11394 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11395 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11396 (string-to-char (substring (match-string 1 s) -1))
11397 ?+))
11398 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11399 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11400 (what (if (match-end 3) (match-string 3 s) "d"))
11401 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11402 (date (if rel default today))
11403 (wday (nth 6 (decode-time date)))
11404 delta)
11405 (if wday1
11406 (progn
11407 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11408 (if (= dir ?-) (setq delta (- delta 7)))
11409 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11410 (list delta "d" rel))
11411 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11413 (defun org-eval-in-calendar (form &optional keepdate)
11414 "Eval FORM in the calendar window and return to current window.
11415 Also, store the cursor date in variable org-ans2."
11416 (let ((sw (selected-window)))
11417 (select-window (get-buffer-window "*Calendar*"))
11418 (eval form)
11419 (when (and (not keepdate) (calendar-cursor-to-date))
11420 (let* ((date (calendar-cursor-to-date))
11421 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11422 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11423 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11424 (select-window sw)))
11426 (defun org-calendar-select ()
11427 "Return to `org-read-date' with the date currently selected.
11428 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11429 (interactive)
11430 (when (calendar-cursor-to-date)
11431 (let* ((date (calendar-cursor-to-date))
11432 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11433 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11434 (if (active-minibuffer-window) (exit-minibuffer))))
11436 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11437 "Insert a date stamp for the date given by the internal TIME.
11438 WITH-HM means, use the stamp format that includes the time of the day.
11439 INACTIVE means use square brackets instead of angular ones, so that the
11440 stamp will not contribute to the agenda.
11441 PRE and POST are optional strings to be inserted before and after the
11442 stamp.
11443 The command returns the inserted time stamp."
11444 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11445 stamp)
11446 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11447 (insert-before-markers (or pre ""))
11448 (insert-before-markers (setq stamp (format-time-string fmt time)))
11449 (when (listp extra)
11450 (setq extra (car extra))
11451 (if (and (stringp extra)
11452 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11453 (setq extra (format "-%02d:%02d"
11454 (string-to-number (match-string 1 extra))
11455 (string-to-number (match-string 2 extra))))
11456 (setq extra nil)))
11457 (when extra
11458 (backward-char 1)
11459 (insert-before-markers extra)
11460 (forward-char 1))
11461 (insert-before-markers (or post ""))
11462 (setq org-last-inserted-timestamp stamp)))
11464 (defun org-toggle-time-stamp-overlays ()
11465 "Toggle the use of custom time stamp formats."
11466 (interactive)
11467 (setq org-display-custom-times (not org-display-custom-times))
11468 (unless org-display-custom-times
11469 (let ((p (point-min)) (bmp (buffer-modified-p)))
11470 (while (setq p (next-single-property-change p 'display))
11471 (if (and (get-text-property p 'display)
11472 (eq (get-text-property p 'face) 'org-date))
11473 (remove-text-properties
11474 p (setq p (next-single-property-change p 'display))
11475 '(display t))))
11476 (set-buffer-modified-p bmp)))
11477 (if (featurep 'xemacs)
11478 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11479 (org-restart-font-lock)
11480 (setq org-table-may-need-update t)
11481 (if org-display-custom-times
11482 (message "Time stamps are overlayed with custom format")
11483 (message "Time stamp overlays removed")))
11485 (defun org-display-custom-time (beg end)
11486 "Overlay modified time stamp format over timestamp between BEG and END."
11487 (let* ((ts (buffer-substring beg end))
11488 t1 w1 with-hm tf time str w2 (off 0))
11489 (save-match-data
11490 (setq t1 (org-parse-time-string ts t))
11491 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11492 (setq off (- (match-end 0) (match-beginning 0)))))
11493 (setq end (- end off))
11494 (setq w1 (- end beg)
11495 with-hm (and (nth 1 t1) (nth 2 t1))
11496 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11497 time (org-fix-decoded-time t1)
11498 str (org-add-props
11499 (format-time-string
11500 (substring tf 1 -1) (apply 'encode-time time))
11501 nil 'mouse-face 'highlight)
11502 w2 (length str))
11503 (if (not (= w2 w1))
11504 (add-text-properties (1+ beg) (+ 2 beg)
11505 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11506 (if (featurep 'xemacs)
11507 (progn
11508 (put-text-property beg end 'invisible t)
11509 (put-text-property beg end 'end-glyph (make-glyph str)))
11510 (put-text-property beg end 'display str))))
11512 (defun org-translate-time (string)
11513 "Translate all timestamps in STRING to custom format.
11514 But do this only if the variable `org-display-custom-times' is set."
11515 (when org-display-custom-times
11516 (save-match-data
11517 (let* ((start 0)
11518 (re org-ts-regexp-both)
11519 t1 with-hm inactive tf time str beg end)
11520 (while (setq start (string-match re string start))
11521 (setq beg (match-beginning 0)
11522 end (match-end 0)
11523 t1 (save-match-data
11524 (org-parse-time-string (substring string beg end) t))
11525 with-hm (and (nth 1 t1) (nth 2 t1))
11526 inactive (equal (substring string beg (1+ beg)) "[")
11527 tf (funcall (if with-hm 'cdr 'car)
11528 org-time-stamp-custom-formats)
11529 time (org-fix-decoded-time t1)
11530 str (format-time-string
11531 (concat
11532 (if inactive "[" "<") (substring tf 1 -1)
11533 (if inactive "]" ">"))
11534 (apply 'encode-time time))
11535 string (replace-match str t t string)
11536 start (+ start (length str)))))))
11537 string)
11539 (defun org-fix-decoded-time (time)
11540 "Set 0 instead of nil for the first 6 elements of time.
11541 Don't touch the rest."
11542 (let ((n 0))
11543 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11545 (defun org-days-to-time (timestamp-string)
11546 "Difference between TIMESTAMP-STRING and now in days."
11547 (- (time-to-days (org-time-string-to-time timestamp-string))
11548 (time-to-days (current-time))))
11550 (defun org-deadline-close (timestamp-string &optional ndays)
11551 "Is the time in TIMESTAMP-STRING close to the current date?"
11552 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11553 (and (< (org-days-to-time timestamp-string) ndays)
11554 (not (org-entry-is-done-p))))
11556 (defun org-get-wdays (ts)
11557 "Get the deadline lead time appropriate for timestring TS."
11558 (cond
11559 ((<= org-deadline-warning-days 0)
11560 ;; 0 or negative, enforce this value no matter what
11561 (- org-deadline-warning-days))
11562 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11563 ;; lead time is specified.
11564 (floor (* (string-to-number (match-string 1 ts))
11565 (cdr (assoc (match-string 2 ts)
11566 '(("d" . 1) ("w" . 7)
11567 ("m" . 30.4) ("y" . 365.25)))))))
11568 ;; go for the default.
11569 (t org-deadline-warning-days)))
11571 (defun org-calendar-select-mouse (ev)
11572 "Return to `org-read-date' with the date currently selected.
11573 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11574 (interactive "e")
11575 (mouse-set-point ev)
11576 (when (calendar-cursor-to-date)
11577 (let* ((date (calendar-cursor-to-date))
11578 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11579 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11580 (if (active-minibuffer-window) (exit-minibuffer))))
11582 (defun org-check-deadlines (ndays)
11583 "Check if there are any deadlines due or past due.
11584 A deadline is considered due if it happens within `org-deadline-warning-days'
11585 days from today's date. If the deadline appears in an entry marked DONE,
11586 it is not shown. The prefix arg NDAYS can be used to test that many
11587 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11588 (interactive "P")
11589 (let* ((org-warn-days
11590 (cond
11591 ((equal ndays '(4)) 100000)
11592 (ndays (prefix-numeric-value ndays))
11593 (t (abs org-deadline-warning-days))))
11594 (case-fold-search nil)
11595 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11596 (callback
11597 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11599 (message "%d deadlines past-due or due within %d days"
11600 (org-occur regexp nil callback)
11601 org-warn-days)))
11603 (defun org-check-before-date (date)
11604 "Check if there are deadlines or scheduled entries before DATE."
11605 (interactive (list (org-read-date)))
11606 (let ((case-fold-search nil)
11607 (regexp (concat "\\<\\(" org-deadline-string
11608 "\\|" org-scheduled-string
11609 "\\) *<\\([^>]+\\)>"))
11610 (callback
11611 (lambda () (time-less-p
11612 (org-time-string-to-time (match-string 2))
11613 (org-time-string-to-time date)))))
11614 (message "%d entries before %s"
11615 (org-occur regexp nil callback) date)))
11617 (defun org-evaluate-time-range (&optional to-buffer)
11618 "Evaluate a time range by computing the difference between start and end.
11619 Normally the result is just printed in the echo area, but with prefix arg
11620 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11621 If the time range is actually in a table, the result is inserted into the
11622 next column.
11623 For time difference computation, a year is assumed to be exactly 365
11624 days in order to avoid rounding problems."
11625 (interactive "P")
11627 (org-clock-update-time-maybe)
11628 (save-excursion
11629 (unless (org-at-date-range-p t)
11630 (goto-char (point-at-bol))
11631 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11632 (if (not (org-at-date-range-p t))
11633 (error "Not at a time-stamp range, and none found in current line")))
11634 (let* ((ts1 (match-string 1))
11635 (ts2 (match-string 2))
11636 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11637 (match-end (match-end 0))
11638 (time1 (org-time-string-to-time ts1))
11639 (time2 (org-time-string-to-time ts2))
11640 (t1 (time-to-seconds time1))
11641 (t2 (time-to-seconds time2))
11642 (diff (abs (- t2 t1)))
11643 (negative (< (- t2 t1) 0))
11644 ;; (ys (floor (* 365 24 60 60)))
11645 (ds (* 24 60 60))
11646 (hs (* 60 60))
11647 (fy "%dy %dd %02d:%02d")
11648 (fy1 "%dy %dd")
11649 (fd "%dd %02d:%02d")
11650 (fd1 "%dd")
11651 (fh "%02d:%02d")
11652 y d h m align)
11653 (if havetime
11654 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11656 d (floor (/ diff ds)) diff (mod diff ds)
11657 h (floor (/ diff hs)) diff (mod diff hs)
11658 m (floor (/ diff 60)))
11659 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11661 d (floor (+ (/ diff ds) 0.5))
11662 h 0 m 0))
11663 (if (not to-buffer)
11664 (message "%s" (org-make-tdiff-string y d h m))
11665 (if (org-at-table-p)
11666 (progn
11667 (goto-char match-end)
11668 (setq align t)
11669 (and (looking-at " *|") (goto-char (match-end 0))))
11670 (goto-char match-end))
11671 (if (looking-at
11672 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11673 (replace-match ""))
11674 (if negative (insert " -"))
11675 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11676 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11677 (insert " " (format fh h m))))
11678 (if align (org-table-align))
11679 (message "Time difference inserted")))))
11681 (defun org-make-tdiff-string (y d h m)
11682 (let ((fmt "")
11683 (l nil))
11684 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11685 l (push y l)))
11686 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11687 l (push d l)))
11688 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11689 l (push h l)))
11690 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11691 l (push m l)))
11692 (apply 'format fmt (nreverse l))))
11694 (defun org-time-string-to-time (s)
11695 (apply 'encode-time (org-parse-time-string s)))
11697 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11698 "Convert a time stamp to an absolute day number.
11699 If there is a specifyer for a cyclic time stamp, get the closest date to
11700 DAYNR.
11701 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11702 (cond
11703 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11704 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11705 daynr
11706 (+ daynr 1000)))
11707 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11708 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11709 (time-to-days (current-time))) (match-string 0 s)
11710 prefer show-all))
11711 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11713 (defun org-days-to-iso-week (days)
11714 "Return the iso week number."
11715 (require 'cal-iso)
11716 (car (calendar-iso-from-absolute days)))
11718 (defun org-small-year-to-year (year)
11719 "Convert 2-digit years into 4-digit years.
11720 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11721 The year 2000 cannot be abbreviated. Any year larger than 99
11722 is returned unchanged."
11723 (if (< year 38)
11724 (setq year (+ 2000 year))
11725 (if (< year 100)
11726 (setq year (+ 1900 year))))
11727 year)
11729 (defun org-time-from-absolute (d)
11730 "Return the time corresponding to date D.
11731 D may be an absolute day number, or a calendar-type list (month day year)."
11732 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11733 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11735 (defun org-calendar-holiday ()
11736 "List of holidays, for Diary display in Org-mode."
11737 (require 'holidays)
11738 (let ((hl (funcall
11739 (if (fboundp 'calendar-check-holidays)
11740 'calendar-check-holidays 'check-calendar-holidays) date)))
11741 (if hl (mapconcat 'identity hl "; "))))
11743 (defun org-diary-sexp-entry (sexp entry date)
11744 "Process a SEXP diary ENTRY for DATE."
11745 (require 'diary-lib)
11746 (let ((result (if calendar-debug-sexp
11747 (let ((stack-trace-on-error t))
11748 (eval (car (read-from-string sexp))))
11749 (condition-case nil
11750 (eval (car (read-from-string sexp)))
11751 (error
11752 (beep)
11753 (message "Bad sexp at line %d in %s: %s"
11754 (org-current-line)
11755 (buffer-file-name) sexp)
11756 (sleep-for 2))))))
11757 (cond ((stringp result) result)
11758 ((and (consp result)
11759 (stringp (cdr result))) (cdr result))
11760 (result entry)
11761 (t nil))))
11763 (defun org-diary-to-ical-string (frombuf)
11764 "Get iCalendar entries from diary entries in buffer FROMBUF.
11765 This uses the icalendar.el library."
11766 (let* ((tmpdir (if (featurep 'xemacs)
11767 (temp-directory)
11768 temporary-file-directory))
11769 (tmpfile (make-temp-name
11770 (expand-file-name "orgics" tmpdir)))
11771 buf rtn b e)
11772 (save-excursion
11773 (set-buffer frombuf)
11774 (icalendar-export-region (point-min) (point-max) tmpfile)
11775 (setq buf (find-buffer-visiting tmpfile))
11776 (set-buffer buf)
11777 (goto-char (point-min))
11778 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11779 (setq b (match-beginning 0)))
11780 (goto-char (point-max))
11781 (if (re-search-backward "^END:VEVENT" nil t)
11782 (setq e (match-end 0)))
11783 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11784 (kill-buffer buf)
11785 (delete-file tmpfile)
11786 rtn))
11788 (defun org-closest-date (start current change prefer show-all)
11789 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11790 When PREFER is `past' return a date that is either CURRENT or past.
11791 When PREFER is `future', return a date that is either CURRENT or future.
11792 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11793 ;; Make the proper lists from the dates
11794 (catch 'exit
11795 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11796 dn dw sday cday n1 n2 n0
11797 d m y y1 y2 date1 date2 nmonths nm ny m2)
11799 (setq start (org-date-to-gregorian start)
11800 current (org-date-to-gregorian
11801 (if show-all
11802 current
11803 (time-to-days (current-time))))
11804 sday (calendar-absolute-from-gregorian start)
11805 cday (calendar-absolute-from-gregorian current))
11807 (if (<= cday sday) (throw 'exit sday))
11809 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11810 (setq dn (string-to-number (match-string 1 change))
11811 dw (cdr (assoc (match-string 2 change) a1)))
11812 (error "Invalid change specifyer: %s" change))
11813 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11814 (cond
11815 ((eq dw 'day)
11816 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11817 n2 (+ n1 dn)))
11818 ((eq dw 'year)
11819 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11820 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11821 (setq date1 (list m d y1)
11822 n1 (calendar-absolute-from-gregorian date1)
11823 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11824 n2 (calendar-absolute-from-gregorian date2)))
11825 ((eq dw 'month)
11826 ;; approx number of month between the two dates
11827 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11828 ;; How often does dn fit in there?
11829 (setq d (nth 1 start) m (car start) y (nth 2 start)
11830 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11831 m (+ m nm)
11832 ny (floor (/ m 12))
11833 y (+ y ny)
11834 m (- m (* ny 12)))
11835 (while (> m 12) (setq m (- m 12) y (1+ y)))
11836 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11837 (setq m2 (+ m dn) y2 y)
11838 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11839 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11840 (while (<= n2 cday)
11841 (setq n1 n2 m m2 y y2)
11842 (setq m2 (+ m dn) y2 y)
11843 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11844 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11845 ;; Make sure n1 is the earlier date
11846 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11847 (if show-all
11848 (cond
11849 ((eq prefer 'past) n1)
11850 ((eq prefer 'future) (if (= cday n1) n1 n2))
11851 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11852 (cond
11853 ((eq prefer 'past) n1)
11854 ((eq prefer 'future) (if (= cday n1) n1 n2))
11855 (t (if (= cday n1) n1 n2)))))))
11857 (defun org-date-to-gregorian (date)
11858 "Turn any specification of DATE into a gregorian date for the calendar."
11859 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11860 ((and (listp date) (= (length date) 3)) date)
11861 ((stringp date)
11862 (setq date (org-parse-time-string date))
11863 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11864 ((listp date)
11865 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11867 (defun org-parse-time-string (s &optional nodefault)
11868 "Parse the standard Org-mode time string.
11869 This should be a lot faster than the normal `parse-time-string'.
11870 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11871 hour and minute fields will be nil if not given."
11872 (if (string-match org-ts-regexp0 s)
11873 (list 0
11874 (if (or (match-beginning 8) (not nodefault))
11875 (string-to-number (or (match-string 8 s) "0")))
11876 (if (or (match-beginning 7) (not nodefault))
11877 (string-to-number (or (match-string 7 s) "0")))
11878 (string-to-number (match-string 4 s))
11879 (string-to-number (match-string 3 s))
11880 (string-to-number (match-string 2 s))
11881 nil nil nil)
11882 (make-list 9 0)))
11884 (defun org-timestamp-up (&optional arg)
11885 "Increase the date item at the cursor by one.
11886 If the cursor is on the year, change the year. If it is on the month or
11887 the day, change that.
11888 With prefix ARG, change by that many units."
11889 (interactive "p")
11890 (org-timestamp-change (prefix-numeric-value arg)))
11892 (defun org-timestamp-down (&optional arg)
11893 "Decrease the date item at the cursor by one.
11894 If the cursor is on the year, change the year. If it is on the month or
11895 the day, change that.
11896 With prefix ARG, change by that many units."
11897 (interactive "p")
11898 (org-timestamp-change (- (prefix-numeric-value arg))))
11900 (defun org-timestamp-up-day (&optional arg)
11901 "Increase the date in the time stamp by one day.
11902 With prefix ARG, change that many days."
11903 (interactive "p")
11904 (if (and (not (org-at-timestamp-p t))
11905 (org-on-heading-p))
11906 (org-todo 'up)
11907 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11909 (defun org-timestamp-down-day (&optional arg)
11910 "Decrease the date in the time stamp by one day.
11911 With prefix ARG, change that many days."
11912 (interactive "p")
11913 (if (and (not (org-at-timestamp-p t))
11914 (org-on-heading-p))
11915 (org-todo 'down)
11916 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11918 (defun org-at-timestamp-p (&optional inactive-ok)
11919 "Determine if the cursor is in or at a timestamp."
11920 (interactive)
11921 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11922 (pos (point))
11923 (ans (or (looking-at tsr)
11924 (save-excursion
11925 (skip-chars-backward "^[<\n\r\t")
11926 (if (> (point) (point-min)) (backward-char 1))
11927 (and (looking-at tsr)
11928 (> (- (match-end 0) pos) -1))))))
11929 (and ans
11930 (boundp 'org-ts-what)
11931 (setq org-ts-what
11932 (cond
11933 ((= pos (match-beginning 0)) 'bracket)
11934 ((= pos (1- (match-end 0))) 'bracket)
11935 ((org-pos-in-match-range pos 2) 'year)
11936 ((org-pos-in-match-range pos 3) 'month)
11937 ((org-pos-in-match-range pos 7) 'hour)
11938 ((org-pos-in-match-range pos 8) 'minute)
11939 ((or (org-pos-in-match-range pos 4)
11940 (org-pos-in-match-range pos 5)) 'day)
11941 ((and (> pos (or (match-end 8) (match-end 5)))
11942 (< pos (match-end 0)))
11943 (- pos (or (match-end 8) (match-end 5))))
11944 (t 'day))))
11945 ans))
11947 (defun org-toggle-timestamp-type ()
11948 "Toggle the type (<active> or [inactive]) of a time stamp."
11949 (interactive)
11950 (when (org-at-timestamp-p t)
11951 (let ((beg (match-beginning 0)) (end (match-end 0))
11952 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11953 (save-excursion
11954 (goto-char beg)
11955 (while (re-search-forward "[][<>]" end t)
11956 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11957 t t)))
11958 (message "Timestamp is now %sactive"
11959 (if (equal (char-after beg) ?<) "" "in")))))
11961 (defun org-timestamp-change (n &optional what)
11962 "Change the date in the time stamp at point.
11963 The date will be changed by N times WHAT. WHAT can be `day', `month',
11964 `year', `minute', `second'. If WHAT is not given, the cursor position
11965 in the timestamp determines what will be changed."
11966 (let ((pos (point))
11967 with-hm inactive
11968 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11969 org-ts-what
11970 extra rem
11971 ts time time0)
11972 (if (not (org-at-timestamp-p t))
11973 (error "Not at a timestamp"))
11974 (if (and (not what) (eq org-ts-what 'bracket))
11975 (org-toggle-timestamp-type)
11976 (if (and (not what) (not (eq org-ts-what 'day))
11977 org-display-custom-times
11978 (get-text-property (point) 'display)
11979 (not (get-text-property (1- (point)) 'display)))
11980 (setq org-ts-what 'day))
11981 (setq org-ts-what (or what org-ts-what)
11982 inactive (= (char-after (match-beginning 0)) ?\[)
11983 ts (match-string 0))
11984 (replace-match "")
11985 (if (string-match
11986 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11988 (setq extra (match-string 1 ts)))
11989 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11990 (setq with-hm t))
11991 (setq time0 (org-parse-time-string ts))
11992 (when (and (eq org-ts-what 'minute)
11993 (eq current-prefix-arg nil))
11994 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11995 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11996 (setcar (cdr time0) (+ (nth 1 time0)
11997 (if (> n 0) (- rem) (- dm rem))))))
11998 (setq time
11999 (encode-time (or (car time0) 0)
12000 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12001 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12002 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12003 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12004 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12005 (nthcdr 6 time0)))
12006 (when (integerp org-ts-what)
12007 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12008 (if (eq what 'calendar)
12009 (let ((cal-date (org-get-date-from-calendar)))
12010 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12011 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12012 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12013 (setcar time0 (or (car time0) 0))
12014 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12015 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12016 (setq time (apply 'encode-time time0))))
12017 (setq org-last-changed-timestamp
12018 (org-insert-time-stamp time with-hm inactive nil nil extra))
12019 (org-clock-update-time-maybe)
12020 (goto-char pos)
12021 ;; Try to recenter the calendar window, if any
12022 (if (and org-calendar-follow-timestamp-change
12023 (get-buffer-window "*Calendar*" t)
12024 (memq org-ts-what '(day month year)))
12025 (org-recenter-calendar (time-to-days time))))))
12027 (defun org-modify-ts-extra (s pos n dm)
12028 "Change the different parts of the lead-time and repeat fields in timestamp."
12029 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12030 ng h m new rem)
12031 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12032 (cond
12033 ((or (org-pos-in-match-range pos 2)
12034 (org-pos-in-match-range pos 3))
12035 (setq m (string-to-number (match-string 3 s))
12036 h (string-to-number (match-string 2 s)))
12037 (if (org-pos-in-match-range pos 2)
12038 (setq h (+ h n))
12039 (setq n (* dm (org-no-warnings (signum n))))
12040 (when (not (= 0 (setq rem (% m dm))))
12041 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12042 (setq m (+ m n)))
12043 (if (< m 0) (setq m (+ m 60) h (1- h)))
12044 (if (> m 59) (setq m (- m 60) h (1+ h)))
12045 (setq h (min 24 (max 0 h)))
12046 (setq ng 1 new (format "-%02d:%02d" h m)))
12047 ((org-pos-in-match-range pos 6)
12048 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12049 ((org-pos-in-match-range pos 5)
12050 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12052 ((org-pos-in-match-range pos 9)
12053 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12054 ((org-pos-in-match-range pos 8)
12055 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12057 (when ng
12058 (setq s (concat
12059 (substring s 0 (match-beginning ng))
12061 (substring s (match-end ng))))))
12064 (defun org-recenter-calendar (date)
12065 "If the calendar is visible, recenter it to DATE."
12066 (let* ((win (selected-window))
12067 (cwin (get-buffer-window "*Calendar*" t))
12068 (calendar-move-hook nil))
12069 (when cwin
12070 (select-window cwin)
12071 (calendar-goto-date (if (listp date) date
12072 (calendar-gregorian-from-absolute date)))
12073 (select-window win))))
12075 (defun org-goto-calendar (&optional arg)
12076 "Go to the Emacs calendar at the current date.
12077 If there is a time stamp in the current line, go to that date.
12078 A prefix ARG can be used to force the current date."
12079 (interactive "P")
12080 (let ((tsr org-ts-regexp) diff
12081 (calendar-move-hook nil)
12082 (calendar-view-holidays-initially-flag nil)
12083 (view-calendar-holidays-initially nil)
12084 (calendar-view-diary-initially-flag nil)
12085 (view-diary-entries-initially nil))
12086 (if (or (org-at-timestamp-p)
12087 (save-excursion
12088 (beginning-of-line 1)
12089 (looking-at (concat ".*" tsr))))
12090 (let ((d1 (time-to-days (current-time)))
12091 (d2 (time-to-days
12092 (org-time-string-to-time (match-string 1)))))
12093 (setq diff (- d2 d1))))
12094 (calendar)
12095 (calendar-goto-today)
12096 (if (and diff (not arg)) (calendar-forward-day diff))))
12098 (defun org-get-date-from-calendar ()
12099 "Return a list (month day year) of date at point in calendar."
12100 (with-current-buffer "*Calendar*"
12101 (save-match-data
12102 (calendar-cursor-to-date))))
12104 (defun org-date-from-calendar ()
12105 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12106 If there is already a time stamp at the cursor position, update it."
12107 (interactive)
12108 (if (org-at-timestamp-p t)
12109 (org-timestamp-change 0 'calendar)
12110 (let ((cal-date (org-get-date-from-calendar)))
12111 (org-insert-time-stamp
12112 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12114 (defun org-minutes-to-hh:mm-string (m)
12115 "Compute H:MM from a number of minutes."
12116 (let ((h (/ m 60)))
12117 (setq m (- m (* 60 h)))
12118 (format org-time-clocksum-format h m)))
12120 (defun org-hh:mm-string-to-minutes (s)
12121 "Convert a string H:MM to a number of minutes."
12122 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12123 (+ (* (string-to-number (match-string 1 s)) 60)
12124 (string-to-number (match-string 2 s)))
12127 ;;;; Agenda files
12129 ;;;###autoload
12130 (defun org-iswitchb (&optional arg)
12131 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12132 With a prefix argument, restrict available to files.
12133 With two prefix arguments, restrict available buffers to agenda files.
12135 Due to some yet unresolved reason, the global function
12136 `iswitchb-mode' needs to be active for this function to work."
12137 (interactive "P")
12138 (require 'iswitchb)
12139 (let ((enabled iswitchb-mode) blist)
12140 (or enabled (iswitchb-mode 1))
12141 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12142 ((equal arg '(16)) (org-buffer-list 'agenda))
12143 (t (org-buffer-list))))
12144 (unwind-protect
12145 (let ((iswitchb-make-buflist-hook
12146 (lambda ()
12147 (setq iswitchb-temp-buflist
12148 (mapcar 'buffer-name blist)))))
12149 (switch-to-buffer
12150 (iswitchb-read-buffer
12151 "Switch-to: " nil t))
12152 (or enabled (iswitchb-mode -1))))))
12154 ;;;###autoload
12155 (defun org-ido-switchb (&optional arg)
12156 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12157 With a prefix argument, restrict available to files.
12158 With two prefix arguments, restrict available buffers to agenda files."
12159 (interactive "P")
12160 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12161 ((equal arg '(16)) (org-buffer-list 'agenda))
12162 (t (org-buffer-list)))))
12163 (switch-to-buffer
12164 (org-ido-completing-read "Org buffer: "
12165 (mapcar 'buffer-name blist)
12166 nil t))))
12168 (defun org-buffer-list (&optional predicate exclude-tmp)
12169 "Return a list of Org buffers.
12170 PREDICATE can be `export', `files' or `agenda'.
12172 export restrict the list to Export buffers.
12173 files restrict the list to buffers visiting Org files.
12174 agenda restrict the list to buffers visiting agenda files.
12176 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12177 (let* ((bfn nil)
12178 (agenda-files (and (eq predicate 'agenda)
12179 (mapcar 'file-truename (org-agenda-files t))))
12180 (filter
12181 (cond
12182 ((eq predicate 'files)
12183 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12184 ((eq predicate 'export)
12185 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12186 ((eq predicate 'agenda)
12187 (lambda (b)
12188 (with-current-buffer b
12189 (and (eq major-mode 'org-mode)
12190 (setq bfn (buffer-file-name b))
12191 (member (file-truename bfn) agenda-files)))))
12192 (t (lambda (b) (with-current-buffer b
12193 (or (eq major-mode 'org-mode)
12194 (string-match "\*Org .*Export"
12195 (buffer-name b)))))))))
12196 (delq nil
12197 (mapcar
12198 (lambda(b)
12199 (if (and (funcall filter b)
12200 (or (not exclude-tmp)
12201 (not (string-match "tmp" (buffer-name b)))))
12203 nil))
12204 (buffer-list)))))
12206 (defun org-agenda-files (&optional unrestricted archives)
12207 "Get the list of agenda files.
12208 Optional UNRESTRICTED means return the full list even if a restriction
12209 is currently in place.
12210 When ARCHIVES is t, include all archive files hat are really being
12211 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12212 `org-agenda-archives-mode' is t."
12213 (let ((files
12214 (cond
12215 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12216 ((stringp org-agenda-files) (org-read-agenda-file-list))
12217 ((listp org-agenda-files) org-agenda-files)
12218 (t (error "Invalid value of `org-agenda-files'")))))
12219 (setq files (apply 'append
12220 (mapcar (lambda (f)
12221 (if (file-directory-p f)
12222 (directory-files
12223 f t org-agenda-file-regexp)
12224 (list f)))
12225 files)))
12226 (when org-agenda-skip-unavailable-files
12227 (setq files (delq nil
12228 (mapcar (function
12229 (lambda (file)
12230 (and (file-readable-p file) file)))
12231 files))))
12232 (when (or (eq archives t)
12233 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12234 (setq files (org-add-archive-files files)))
12235 files))
12237 (defun org-edit-agenda-file-list ()
12238 "Edit the list of agenda files.
12239 Depending on setup, this either uses customize to edit the variable
12240 `org-agenda-files', or it visits the file that is holding the list. In the
12241 latter case, the buffer is set up in a way that saving it automatically kills
12242 the buffer and restores the previous window configuration."
12243 (interactive)
12244 (if (stringp org-agenda-files)
12245 (let ((cw (current-window-configuration)))
12246 (find-file org-agenda-files)
12247 (org-set-local 'org-window-configuration cw)
12248 (org-add-hook 'after-save-hook
12249 (lambda ()
12250 (set-window-configuration
12251 (prog1 org-window-configuration
12252 (kill-buffer (current-buffer))))
12253 (org-install-agenda-files-menu)
12254 (message "New agenda file list installed"))
12255 nil 'local)
12256 (message "%s" (substitute-command-keys
12257 "Edit list and finish with \\[save-buffer]")))
12258 (customize-variable 'org-agenda-files)))
12260 (defun org-store-new-agenda-file-list (list)
12261 "Set new value for the agenda file list and save it correctly."
12262 (if (stringp org-agenda-files)
12263 (let ((f org-agenda-files) b)
12264 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12265 (with-temp-file f
12266 (insert (mapconcat 'identity list "\n") "\n")))
12267 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12268 (setq org-agenda-files list)
12269 (customize-save-variable 'org-agenda-files org-agenda-files))))
12271 (defun org-read-agenda-file-list ()
12272 "Read the list of agenda files from a file."
12273 (when (file-directory-p org-agenda-files)
12274 (error "`org-agenda-files' cannot be a single directory"))
12275 (when (stringp org-agenda-files)
12276 (with-temp-buffer
12277 (insert-file-contents org-agenda-files)
12278 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12281 ;;;###autoload
12282 (defun org-cycle-agenda-files ()
12283 "Cycle through the files in `org-agenda-files'.
12284 If the current buffer visits an agenda file, find the next one in the list.
12285 If the current buffer does not, find the first agenda file."
12286 (interactive)
12287 (let* ((fs (org-agenda-files t))
12288 (files (append fs (list (car fs))))
12289 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12290 file)
12291 (unless files (error "No agenda files"))
12292 (catch 'exit
12293 (while (setq file (pop files))
12294 (if (equal (file-truename file) tcf)
12295 (when (car files)
12296 (find-file (car files))
12297 (throw 'exit t))))
12298 (find-file (car fs)))
12299 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12301 (defun org-agenda-file-to-front (&optional to-end)
12302 "Move/add the current file to the top of the agenda file list.
12303 If the file is not present in the list, it is added to the front. If it is
12304 present, it is moved there. With optional argument TO-END, add/move to the
12305 end of the list."
12306 (interactive "P")
12307 (let ((org-agenda-skip-unavailable-files nil)
12308 (file-alist (mapcar (lambda (x)
12309 (cons (file-truename x) x))
12310 (org-agenda-files t)))
12311 (ctf (file-truename buffer-file-name))
12312 x had)
12313 (setq x (assoc ctf file-alist) had x)
12315 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12316 (if to-end
12317 (setq file-alist (append (delq x file-alist) (list x)))
12318 (setq file-alist (cons x (delq x file-alist))))
12319 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12320 (org-install-agenda-files-menu)
12321 (message "File %s to %s of agenda file list"
12322 (if had "moved" "added") (if to-end "end" "front"))))
12324 (defun org-remove-file (&optional file)
12325 "Remove current file from the list of files in variable `org-agenda-files'.
12326 These are the files which are being checked for agenda entries.
12327 Optional argument FILE means, use this file instead of the current."
12328 (interactive)
12329 (let* ((org-agenda-skip-unavailable-files nil)
12330 (file (or file buffer-file-name))
12331 (true-file (file-truename file))
12332 (afile (abbreviate-file-name file))
12333 (files (delq nil (mapcar
12334 (lambda (x)
12335 (if (equal true-file
12336 (file-truename x))
12337 nil x))
12338 (org-agenda-files t)))))
12339 (if (not (= (length files) (length (org-agenda-files t))))
12340 (progn
12341 (org-store-new-agenda-file-list files)
12342 (org-install-agenda-files-menu)
12343 (message "Removed file: %s" afile))
12344 (message "File was not in list: %s (not removed)" afile))))
12346 (defun org-file-menu-entry (file)
12347 (vector file (list 'find-file file) t))
12349 (defun org-check-agenda-file (file)
12350 "Make sure FILE exists. If not, ask user what to do."
12351 (when (not (file-exists-p file))
12352 (message "non-existent file %s. [R]emove from list or [A]bort?"
12353 (abbreviate-file-name file))
12354 (let ((r (downcase (read-char-exclusive))))
12355 (cond
12356 ((equal r ?r)
12357 (org-remove-file file)
12358 (throw 'nextfile t))
12359 (t (error "Abort"))))))
12361 (defun org-get-agenda-file-buffer (file)
12362 "Get a buffer visiting FILE. If the buffer needs to be created, add
12363 it to the list of buffers which might be released later."
12364 (let ((buf (org-find-base-buffer-visiting file)))
12365 (if buf
12366 buf ; just return it
12367 ;; Make a new buffer and remember it
12368 (setq buf (find-file-noselect file))
12369 (if buf (push buf org-agenda-new-buffers))
12370 buf)))
12372 (defun org-release-buffers (blist)
12373 "Release all buffers in list, asking the user for confirmation when needed.
12374 When a buffer is unmodified, it is just killed. When modified, it is saved
12375 \(if the user agrees) and then killed."
12376 (let (buf file)
12377 (while (setq buf (pop blist))
12378 (setq file (buffer-file-name buf))
12379 (when (and (buffer-modified-p buf)
12380 file
12381 (y-or-n-p (format "Save file %s? " file)))
12382 (with-current-buffer buf (save-buffer)))
12383 (kill-buffer buf))))
12385 (defun org-prepare-agenda-buffers (files)
12386 "Create buffers for all agenda files, protect archived trees and comments."
12387 (interactive)
12388 (let ((pa '(:org-archived t))
12389 (pc '(:org-comment t))
12390 (pall '(:org-archived t :org-comment t))
12391 (inhibit-read-only t)
12392 (rea (concat ":" org-archive-tag ":"))
12393 bmp file re)
12394 (save-excursion
12395 (save-restriction
12396 (while (setq file (pop files))
12397 (if (bufferp file)
12398 (set-buffer file)
12399 (org-check-agenda-file file)
12400 (set-buffer (org-get-agenda-file-buffer file)))
12401 (widen)
12402 (setq bmp (buffer-modified-p))
12403 (org-refresh-category-properties)
12404 (setq org-todo-keywords-for-agenda
12405 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12406 (setq org-done-keywords-for-agenda
12407 (append org-done-keywords-for-agenda org-done-keywords))
12408 (setq org-todo-keyword-alist-for-agenda
12409 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12410 (setq org-tag-alist-for-agenda
12411 (append org-tag-alist-for-agenda org-tag-alist))
12413 (save-excursion
12414 (remove-text-properties (point-min) (point-max) pall)
12415 (when org-agenda-skip-archived-trees
12416 (goto-char (point-min))
12417 (while (re-search-forward rea nil t)
12418 (if (org-on-heading-p t)
12419 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12420 (goto-char (point-min))
12421 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12422 (while (re-search-forward re nil t)
12423 (add-text-properties
12424 (match-beginning 0) (org-end-of-subtree t) pc)))
12425 (set-buffer-modified-p bmp))))
12426 (setq org-todo-keyword-alist-for-agenda
12427 (org-uniquify org-todo-keyword-alist-for-agenda)
12428 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12430 ;;;; Embedded LaTeX
12432 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12433 "Keymap for the minor `org-cdlatex-mode'.")
12435 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12436 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12437 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12438 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12439 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12441 (defvar org-cdlatex-texmathp-advice-is-done nil
12442 "Flag remembering if we have applied the advice to texmathp already.")
12444 (define-minor-mode org-cdlatex-mode
12445 "Toggle the minor `org-cdlatex-mode'.
12446 This mode supports entering LaTeX environment and math in LaTeX fragments
12447 in Org-mode.
12448 \\{org-cdlatex-mode-map}"
12449 nil " OCDL" nil
12450 (when org-cdlatex-mode (require 'cdlatex))
12451 (unless org-cdlatex-texmathp-advice-is-done
12452 (setq org-cdlatex-texmathp-advice-is-done t)
12453 (defadvice texmathp (around org-math-always-on activate)
12454 "Always return t in org-mode buffers.
12455 This is because we want to insert math symbols without dollars even outside
12456 the LaTeX math segments. If Orgmode thinks that point is actually inside
12457 an embedded LaTeX fragment, let texmathp do its job.
12458 \\[org-cdlatex-mode-map]"
12459 (interactive)
12460 (let (p)
12461 (cond
12462 ((not (org-mode-p)) ad-do-it)
12463 ((eq this-command 'cdlatex-math-symbol)
12464 (setq ad-return-value t
12465 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12467 (let ((p (org-inside-LaTeX-fragment-p)))
12468 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12469 (setq ad-return-value t
12470 texmathp-why '("Org-mode embedded math" . 0))
12471 (if p ad-do-it)))))))))
12473 (defun turn-on-org-cdlatex ()
12474 "Unconditionally turn on `org-cdlatex-mode'."
12475 (org-cdlatex-mode 1))
12477 (defun org-inside-LaTeX-fragment-p ()
12478 "Test if point is inside a LaTeX fragment.
12479 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12480 sequence appearing also before point.
12481 Even though the matchers for math are configurable, this function assumes
12482 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12483 delimiters are skipped when they have been removed by customization.
12484 The return value is nil, or a cons cell with the delimiter and
12485 and the position of this delimiter.
12487 This function does a reasonably good job, but can locally be fooled by
12488 for example currency specifications. For example it will assume being in
12489 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12490 fragments that are properly closed, but during editing, we have to live
12491 with the uncertainty caused by missing closing delimiters. This function
12492 looks only before point, not after."
12493 (catch 'exit
12494 (let ((pos (point))
12495 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12496 (lim (progn
12497 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12498 (point)))
12499 dd-on str (start 0) m re)
12500 (goto-char pos)
12501 (when dodollar
12502 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12503 re (nth 1 (assoc "$" org-latex-regexps)))
12504 (while (string-match re str start)
12505 (cond
12506 ((= (match-end 0) (length str))
12507 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12508 ((= (match-end 0) (- (length str) 5))
12509 (throw 'exit nil))
12510 (t (setq start (match-end 0))))))
12511 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12512 (goto-char pos)
12513 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12514 (and (match-beginning 2) (throw 'exit nil))
12515 ;; count $$
12516 (while (re-search-backward "\\$\\$" lim t)
12517 (setq dd-on (not dd-on)))
12518 (goto-char pos)
12519 (if dd-on (cons "$$" m))))))
12522 (defun org-try-cdlatex-tab ()
12523 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12524 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12525 - inside a LaTeX fragment, or
12526 - after the first word in a line, where an abbreviation expansion could
12527 insert a LaTeX environment."
12528 (when org-cdlatex-mode
12529 (cond
12530 ((save-excursion
12531 (skip-chars-backward "a-zA-Z0-9*")
12532 (skip-chars-backward " \t")
12533 (bolp))
12534 (cdlatex-tab) t)
12535 ((org-inside-LaTeX-fragment-p)
12536 (cdlatex-tab) t)
12537 (t nil))))
12539 (defun org-cdlatex-underscore-caret (&optional arg)
12540 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12541 Revert to the normal definition outside of these fragments."
12542 (interactive "P")
12543 (if (org-inside-LaTeX-fragment-p)
12544 (call-interactively 'cdlatex-sub-superscript)
12545 (let (org-cdlatex-mode)
12546 (call-interactively (key-binding (vector last-input-event))))))
12548 (defun org-cdlatex-math-modify (&optional arg)
12549 "Execute `cdlatex-math-modify' in LaTeX fragments.
12550 Revert to the normal definition outside of these fragments."
12551 (interactive "P")
12552 (if (org-inside-LaTeX-fragment-p)
12553 (call-interactively 'cdlatex-math-modify)
12554 (let (org-cdlatex-mode)
12555 (call-interactively (key-binding (vector last-input-event))))))
12557 (defvar org-latex-fragment-image-overlays nil
12558 "List of overlays carrying the images of latex fragments.")
12559 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12561 (defun org-remove-latex-fragment-image-overlays ()
12562 "Remove all overlays with LaTeX fragment images in current buffer."
12563 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12564 (setq org-latex-fragment-image-overlays nil))
12566 (defun org-preview-latex-fragment (&optional subtree)
12567 "Preview the LaTeX fragment at point, or all locally or globally.
12568 If the cursor is in a LaTeX fragment, create the image and overlay
12569 it over the source code. If there is no fragment at point, display
12570 all fragments in the current text, from one headline to the next. With
12571 prefix SUBTREE, display all fragments in the current subtree. With a
12572 double prefix `C-u C-u', or when the cursor is before the first headline,
12573 display all fragments in the buffer.
12574 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12575 (interactive "P")
12576 (org-remove-latex-fragment-image-overlays)
12577 (save-excursion
12578 (save-restriction
12579 (let (beg end at msg)
12580 (cond
12581 ((or (equal subtree '(16))
12582 (not (save-excursion
12583 (re-search-backward (concat "^" outline-regexp) nil t))))
12584 (setq beg (point-min) end (point-max)
12585 msg "Creating images for buffer...%s"))
12586 ((equal subtree '(4))
12587 (org-back-to-heading)
12588 (setq beg (point) end (org-end-of-subtree t)
12589 msg "Creating images for subtree...%s"))
12591 (if (setq at (org-inside-LaTeX-fragment-p))
12592 (goto-char (max (point-min) (- (cdr at) 2)))
12593 (org-back-to-heading))
12594 (setq beg (point) end (progn (outline-next-heading) (point))
12595 msg (if at "Creating image...%s"
12596 "Creating images for entry...%s"))))
12597 (message msg "")
12598 (narrow-to-region beg end)
12599 (goto-char beg)
12600 (org-format-latex
12601 (concat "ltxpng/" (file-name-sans-extension
12602 (file-name-nondirectory
12603 buffer-file-name)))
12604 default-directory 'overlays msg at 'forbuffer)
12605 (message msg "done. Use `C-c C-c' to remove images.")))))
12607 (defvar org-latex-regexps
12608 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12609 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12610 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12611 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12612 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12613 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12614 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12615 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12616 "Regular expressions for matching embedded LaTeX.")
12618 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12619 "Replace LaTeX fragments with links to an image, and produce images."
12620 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12621 (let* ((prefixnodir (file-name-nondirectory prefix))
12622 (absprefix (expand-file-name prefix dir))
12623 (todir (file-name-directory absprefix))
12624 (opt org-format-latex-options)
12625 (matchers (plist-get opt :matchers))
12626 (re-list org-latex-regexps)
12627 (cnt 0) txt link beg end re e checkdir
12628 m n block linkfile movefile ov)
12629 ;; Check if there are old images files with this prefix, and remove them
12630 (when (file-directory-p todir)
12631 (mapc 'delete-file
12632 (directory-files
12633 todir 'full
12634 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12635 ;; Check the different regular expressions
12636 (while (setq e (pop re-list))
12637 (setq m (car e) re (nth 1 e) n (nth 2 e)
12638 block (if (nth 3 e) "\n\n" ""))
12639 (when (member m matchers)
12640 (goto-char (point-min))
12641 (while (re-search-forward re nil t)
12642 (when (or (not at) (equal (cdr at) (match-beginning n)))
12643 (setq txt (match-string n)
12644 beg (match-beginning n) end (match-end n)
12645 cnt (1+ cnt)
12646 linkfile (format "%s_%04d.png" prefix cnt)
12647 movefile (format "%s_%04d.png" absprefix cnt)
12648 link (concat block "[[file:" linkfile "]]" block))
12649 (if msg (message msg cnt))
12650 (goto-char beg)
12651 (unless checkdir ; make sure the directory exists
12652 (setq checkdir t)
12653 (or (file-directory-p todir) (make-directory todir)))
12654 (org-create-formula-image
12655 txt movefile opt forbuffer)
12656 (if overlays
12657 (progn
12658 (setq ov (org-make-overlay beg end))
12659 (if (featurep 'xemacs)
12660 (progn
12661 (org-overlay-put ov 'invisible t)
12662 (org-overlay-put
12663 ov 'end-glyph
12664 (make-glyph (vector 'png :file movefile))))
12665 (org-overlay-put
12666 ov 'display
12667 (list 'image :type 'png :file movefile :ascent 'center)))
12668 (push ov org-latex-fragment-image-overlays)
12669 (goto-char end))
12670 (delete-region beg end)
12671 (insert link))))))))
12673 ;; This function borrows from Ganesh Swami's latex2png.el
12674 (defun org-create-formula-image (string tofile options buffer)
12675 (let* ((tmpdir (if (featurep 'xemacs)
12676 (temp-directory)
12677 temporary-file-directory))
12678 (texfilebase (make-temp-name
12679 (expand-file-name "orgtex" tmpdir)))
12680 (texfile (concat texfilebase ".tex"))
12681 (dvifile (concat texfilebase ".dvi"))
12682 (pngfile (concat texfilebase ".png"))
12683 (fnh (if (featurep 'xemacs)
12684 (font-height (get-face-font 'default))
12685 (face-attribute 'default :height nil)))
12686 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12687 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12688 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12689 "Black"))
12690 (bg (or (plist-get options (if buffer :background :html-background))
12691 "Transparent")))
12692 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12693 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12694 (with-temp-file texfile
12695 (insert org-format-latex-header
12696 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12697 (let ((dir default-directory))
12698 (condition-case nil
12699 (progn
12700 (cd tmpdir)
12701 (call-process "latex" nil nil nil texfile))
12702 (error nil))
12703 (cd dir))
12704 (if (not (file-exists-p dvifile))
12705 (progn (message "Failed to create dvi file from %s" texfile) nil)
12706 (condition-case nil
12707 (call-process "dvipng" nil nil nil
12708 "-E" "-fg" fg "-bg" bg
12709 "-D" dpi
12710 ;;"-x" scale "-y" scale
12711 "-T" "tight"
12712 "-o" pngfile
12713 dvifile)
12714 (error nil))
12715 (if (not (file-exists-p pngfile))
12716 (progn (message "Failed to create png file from %s" texfile) nil)
12717 ;; Use the requested file name and clean up
12718 (copy-file pngfile tofile 'replace)
12719 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12720 (delete-file (concat texfilebase e)))
12721 pngfile))))
12723 (defun org-dvipng-color (attr)
12724 "Return an rgb color specification for dvipng."
12725 (apply 'format "rgb %s %s %s"
12726 (mapcar 'org-normalize-color
12727 (color-values (face-attribute 'default attr nil)))))
12729 (defun org-normalize-color (value)
12730 "Return string to be used as color value for an RGB component."
12731 (format "%g" (/ value 65535.0)))
12733 ;;;; Key bindings
12735 ;; Make `C-c C-x' a prefix key
12736 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12738 ;; TAB key with modifiers
12739 (org-defkey org-mode-map "\C-i" 'org-cycle)
12740 (org-defkey org-mode-map [(tab)] 'org-cycle)
12741 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12742 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12743 (org-defkey org-mode-map "\M-\t" 'org-complete)
12744 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12745 ;; The following line is necessary under Suse GNU/Linux
12746 (unless (featurep 'xemacs)
12747 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12748 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12749 (define-key org-mode-map [backtab] 'org-shifttab)
12751 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12752 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12753 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12755 ;; Cursor keys with modifiers
12756 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12757 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12758 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12759 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12761 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12762 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12763 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12764 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12766 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12767 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12768 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12769 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12771 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12772 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12774 ;;; Extra keys for tty access.
12775 ;; We only set them when really needed because otherwise the
12776 ;; menus don't show the simple keys
12778 (when (or org-use-extra-keys
12779 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12780 (not window-system))
12781 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12782 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12783 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12784 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12785 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12786 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12787 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12788 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12789 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12790 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12791 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12792 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12793 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12794 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12795 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12796 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12797 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12798 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12799 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12800 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12801 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12802 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12804 ;; All the other keys
12806 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12807 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12808 (if (boundp 'narrow-map)
12809 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12810 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12811 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12812 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12813 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12814 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12815 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12816 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12817 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12818 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12819 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12820 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12821 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12822 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12823 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12824 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12825 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12826 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12827 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12828 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12829 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12830 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12831 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12832 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12833 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12834 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12835 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12836 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12837 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12838 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12839 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12840 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12841 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12842 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12843 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12844 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12845 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12846 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12847 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12848 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12849 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12850 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12851 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12852 (org-defkey org-mode-map "\C-c^" 'org-sort)
12853 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12854 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12855 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12856 (org-defkey org-mode-map "\C-m" 'org-return)
12857 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12858 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12859 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12860 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12861 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12862 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12863 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12864 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12865 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12866 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12867 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12868 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12869 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12870 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12871 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12872 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12873 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12875 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12876 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12877 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12878 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12880 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12881 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12882 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12883 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12884 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12885 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12886 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12887 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12888 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12889 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12890 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12891 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
12892 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12894 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12895 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12896 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12897 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12899 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12901 (when (featurep 'xemacs)
12902 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12904 (defvar org-table-auto-blank-field) ; defined in org-table.el
12905 (defun org-self-insert-command (N)
12906 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12907 If the cursor is in a table looking at whitespace, the whitespace is
12908 overwritten, and the table is not marked as requiring realignment."
12909 (interactive "p")
12910 (if (and (org-table-p)
12911 (progn
12912 ;; check if we blank the field, and if that triggers align
12913 (and (featurep 'org-table) org-table-auto-blank-field
12914 (member last-command
12915 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12916 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12917 ;; got extra space, this field does not determine column width
12918 (let (org-table-may-need-update) (org-table-blank-field))
12919 ;; no extra space, this field may determine column width
12920 (org-table-blank-field)))
12922 (eq N 1)
12923 (looking-at "[^|\n]* |"))
12924 (let (org-table-may-need-update)
12925 (goto-char (1- (match-end 0)))
12926 (delete-backward-char 1)
12927 (goto-char (match-beginning 0))
12928 (self-insert-command N))
12929 (setq org-table-may-need-update t)
12930 (self-insert-command N)
12931 (org-fix-tags-on-the-fly)))
12933 (defun org-fix-tags-on-the-fly ()
12934 (when (and (equal (char-after (point-at-bol)) ?*)
12935 (org-on-heading-p))
12936 (org-align-tags-here org-tags-column)))
12938 (defun org-delete-backward-char (N)
12939 "Like `delete-backward-char', insert whitespace at field end in tables.
12940 When deleting backwards, in tables this function will insert whitespace in
12941 front of the next \"|\" separator, to keep the table aligned. The table will
12942 still be marked for re-alignment if the field did fill the entire column,
12943 because, in this case the deletion might narrow the column."
12944 (interactive "p")
12945 (if (and (org-table-p)
12946 (eq N 1)
12947 (string-match "|" (buffer-substring (point-at-bol) (point)))
12948 (looking-at ".*?|"))
12949 (let ((pos (point))
12950 (noalign (looking-at "[^|\n\r]* |"))
12951 (c org-table-may-need-update))
12952 (backward-delete-char N)
12953 (skip-chars-forward "^|")
12954 (insert " ")
12955 (goto-char (1- pos))
12956 ;; noalign: if there were two spaces at the end, this field
12957 ;; does not determine the width of the column.
12958 (if noalign (setq org-table-may-need-update c)))
12959 (backward-delete-char N)
12960 (org-fix-tags-on-the-fly)))
12962 (defun org-delete-char (N)
12963 "Like `delete-char', but insert whitespace at field end in tables.
12964 When deleting characters, in tables this function will insert whitespace in
12965 front of the next \"|\" separator, to keep the table aligned. The table will
12966 still be marked for re-alignment if the field did fill the entire column,
12967 because, in this case the deletion might narrow the column."
12968 (interactive "p")
12969 (if (and (org-table-p)
12970 (not (bolp))
12971 (not (= (char-after) ?|))
12972 (eq N 1))
12973 (if (looking-at ".*?|")
12974 (let ((pos (point))
12975 (noalign (looking-at "[^|\n\r]* |"))
12976 (c org-table-may-need-update))
12977 (replace-match (concat
12978 (substring (match-string 0) 1 -1)
12979 " |"))
12980 (goto-char pos)
12981 ;; noalign: if there were two spaces at the end, this field
12982 ;; does not determine the width of the column.
12983 (if noalign (setq org-table-may-need-update c)))
12984 (delete-char N))
12985 (delete-char N)
12986 (org-fix-tags-on-the-fly)))
12988 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12989 (put 'org-self-insert-command 'delete-selection t)
12990 (put 'orgtbl-self-insert-command 'delete-selection t)
12991 (put 'org-delete-char 'delete-selection 'supersede)
12992 (put 'org-delete-backward-char 'delete-selection 'supersede)
12993 (put 'org-yank 'delete-selection 'yank)
12995 ;; Make `flyspell-mode' delay after some commands
12996 (put 'org-self-insert-command 'flyspell-delayed t)
12997 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12998 (put 'org-delete-char 'flyspell-delayed t)
12999 (put 'org-delete-backward-char 'flyspell-delayed t)
13001 ;; Make pabbrev-mode expand after org-mode commands
13002 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13003 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13005 ;; How to do this: Measure non-white length of current string
13006 ;; If equal to column width, we should realign.
13008 (defun org-remap (map &rest commands)
13009 "In MAP, remap the functions given in COMMANDS.
13010 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13011 (let (new old)
13012 (while commands
13013 (setq old (pop commands) new (pop commands))
13014 (if (fboundp 'command-remapping)
13015 (org-defkey map (vector 'remap old) new)
13016 (substitute-key-definition old new map global-map)))))
13018 (when (eq org-enable-table-editor 'optimized)
13019 ;; If the user wants maximum table support, we need to hijack
13020 ;; some standard editing functions
13021 (org-remap org-mode-map
13022 'self-insert-command 'org-self-insert-command
13023 'delete-char 'org-delete-char
13024 'delete-backward-char 'org-delete-backward-char)
13025 (org-defkey org-mode-map "|" 'org-force-self-insert))
13027 (defun org-modifier-cursor-error ()
13028 "Throw an error, a modified cursor command was applied in wrong context."
13029 (error "This command is active in special context like tables, headlines or items"))
13031 (defun org-shiftselect-error ()
13032 "Throw an error because Shift-Cursor command was applied in wrong context."
13033 (if (and (boundp 'shift-select-mode) shift-select-mode)
13034 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13035 (error "This command works only in special context like headlines or timestamps.")))
13037 (defun org-call-for-shift-select (cmd)
13038 (let ((this-command-keys-shift-translated t))
13039 (call-interactively cmd)))
13041 (defun org-shifttab (&optional arg)
13042 "Global visibility cycling or move to previous table field.
13043 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13044 on context.
13045 See the individual commands for more information."
13046 (interactive "P")
13047 (cond
13048 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13049 ((integerp arg)
13050 (message "Content view to level: %d" arg)
13051 (org-content (prefix-numeric-value arg))
13052 (setq org-cycle-global-status 'overview))
13053 (t (call-interactively 'org-global-cycle))))
13055 (defun org-shiftmetaleft ()
13056 "Promote subtree or delete table column.
13057 Calls `org-promote-subtree', `org-outdent-item',
13058 or `org-table-delete-column', depending on context.
13059 See the individual commands for more information."
13060 (interactive)
13061 (cond
13062 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13063 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13064 ((org-at-item-p) (call-interactively 'org-outdent-item))
13065 (t (org-modifier-cursor-error))))
13067 (defun org-shiftmetaright ()
13068 "Demote subtree or insert table column.
13069 Calls `org-demote-subtree', `org-indent-item',
13070 or `org-table-insert-column', depending on context.
13071 See the individual commands for more information."
13072 (interactive)
13073 (cond
13074 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13075 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13076 ((org-at-item-p) (call-interactively 'org-indent-item))
13077 (t (org-modifier-cursor-error))))
13079 (defun org-shiftmetaup (&optional arg)
13080 "Move subtree up or kill table row.
13081 Calls `org-move-subtree-up' or `org-table-kill-row' or
13082 `org-move-item-up' depending on context. See the individual commands
13083 for more information."
13084 (interactive "P")
13085 (cond
13086 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13087 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13088 ((org-at-item-p) (call-interactively 'org-move-item-up))
13089 (t (org-modifier-cursor-error))))
13090 (defun org-shiftmetadown (&optional arg)
13091 "Move subtree down or insert table row.
13092 Calls `org-move-subtree-down' or `org-table-insert-row' or
13093 `org-move-item-down', depending on context. See the individual
13094 commands for more information."
13095 (interactive "P")
13096 (cond
13097 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13098 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13099 ((org-at-item-p) (call-interactively 'org-move-item-down))
13100 (t (org-modifier-cursor-error))))
13102 (defun org-metaleft (&optional arg)
13103 "Promote heading or move table column to left.
13104 Calls `org-do-promote' or `org-table-move-column', depending on context.
13105 With no specific context, calls the Emacs default `backward-word'.
13106 See the individual commands for more information."
13107 (interactive "P")
13108 (cond
13109 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13110 ((or (org-on-heading-p) (org-region-active-p))
13111 (call-interactively 'org-do-promote))
13112 ((org-at-item-p) (call-interactively 'org-outdent-item))
13113 (t (call-interactively 'backward-word))))
13115 (defun org-metaright (&optional arg)
13116 "Demote subtree or move table column to right.
13117 Calls `org-do-demote' or `org-table-move-column', depending on context.
13118 With no specific context, calls the Emacs default `forward-word'.
13119 See the individual commands for more information."
13120 (interactive "P")
13121 (cond
13122 ((org-at-table-p) (call-interactively 'org-table-move-column))
13123 ((or (org-on-heading-p) (org-region-active-p))
13124 (call-interactively 'org-do-demote))
13125 ((org-at-item-p) (call-interactively 'org-indent-item))
13126 (t (call-interactively 'forward-word))))
13128 (defun org-metaup (&optional arg)
13129 "Move subtree up or move table row up.
13130 Calls `org-move-subtree-up' or `org-table-move-row' or
13131 `org-move-item-up', depending on context. See the individual commands
13132 for more information."
13133 (interactive "P")
13134 (cond
13135 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13136 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13137 ((org-at-item-p) (call-interactively 'org-move-item-up))
13138 (t (transpose-lines 1) (beginning-of-line -1))))
13140 (defun org-metadown (&optional arg)
13141 "Move subtree down or move table row down.
13142 Calls `org-move-subtree-down' or `org-table-move-row' or
13143 `org-move-item-down', depending on context. See the individual
13144 commands for more information."
13145 (interactive "P")
13146 (cond
13147 ((org-at-table-p) (call-interactively 'org-table-move-row))
13148 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13149 ((org-at-item-p) (call-interactively 'org-move-item-down))
13150 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13152 (defun org-shiftup (&optional arg)
13153 "Increase item in timestamp or increase priority of current headline.
13154 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13155 depending on context. See the individual commands for more information."
13156 (interactive "P")
13157 (cond
13158 ((and org-support-shift-select (org-region-active-p))
13159 (org-call-for-shift-select 'previous-line))
13160 ((org-at-timestamp-p t)
13161 (call-interactively (if org-edit-timestamp-down-means-later
13162 'org-timestamp-down 'org-timestamp-up)))
13163 ((and (not (eq org-support-shift-select 'always))
13164 (org-on-heading-p))
13165 (call-interactively 'org-priority-up))
13166 ((and (not org-support-shift-select) (org-at-item-p))
13167 (call-interactively 'org-previous-item))
13168 ((org-clocktable-try-shift 'up arg))
13169 (org-support-shift-select
13170 (org-call-for-shift-select 'previous-line))
13171 (t (org-shiftselect-error))))
13173 (defun org-shiftdown (&optional arg)
13174 "Decrease item in timestamp or decrease priority of current headline.
13175 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13176 depending on context. See the individual commands for more information."
13177 (interactive "P")
13178 (cond
13179 ((and org-support-shift-select (org-region-active-p))
13180 (org-call-for-shift-select 'next-line))
13181 ((org-at-timestamp-p t)
13182 (call-interactively (if org-edit-timestamp-down-means-later
13183 'org-timestamp-up 'org-timestamp-down)))
13184 ((and (not (eq org-support-shift-select 'always))
13185 (org-on-heading-p))
13186 (call-interactively 'org-priority-down))
13187 ((and (not org-support-shift-select) (org-at-item-p))
13188 (call-interactively 'org-next-item))
13189 ((org-clocktable-try-shift 'down arg))
13190 (org-support-shift-select
13191 (org-call-for-shift-select 'next-line))
13192 (t (org-shiftselect-error))))
13194 (defun org-shiftright (&optional arg)
13195 "Cycle the thing at point or in the current line, depending on context.
13196 Depending on context, this does one of the following:
13198 - switch a timestamp at point one day into the future
13199 - on a headline, switch to the next TODO keyword.
13200 - on an item, switch entire list to the next bullet type
13201 - on a property line, switch to the next allowed value
13202 - on a clocktable definition line, move time block into the future"
13203 (interactive "P")
13204 (cond
13205 ((and org-support-shift-select (org-region-active-p))
13206 (org-call-for-shift-select 'forward-char))
13207 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13208 ((and (not (eq org-support-shift-select 'always))
13209 (org-on-heading-p))
13210 (org-call-with-arg 'org-todo 'right))
13211 ((or (and org-support-shift-select
13212 (not (eq org-support-shift-select 'always))
13213 (org-at-item-bullet-p))
13214 (and (not org-support-shift-select) (org-at-item-p)))
13215 (org-call-with-arg 'org-cycle-list-bullet nil))
13216 ((and (not (eq org-support-shift-select 'always))
13217 (org-at-property-p))
13218 (call-interactively 'org-property-next-allowed-value))
13219 ((org-clocktable-try-shift 'right arg))
13220 (org-support-shift-select
13221 (org-call-for-shift-select 'forward-char))
13222 (t (org-shiftselect-error))))
13224 (defun org-shiftleft (&optional arg)
13225 "Cycle the thing at point or in the current line, depending on context.
13226 Depending on context, this does one of the following:
13228 - switch a timestamp at point one day into the past
13229 - on a headline, switch to the previous TODO keyword.
13230 - on an item, switch entire list to the previous bullet type
13231 - on a property line, switch to the previous allowed value
13232 - on a clocktable definition line, move time block into the past"
13233 (interactive "P")
13234 (cond
13235 ((and org-support-shift-select (org-region-active-p))
13236 (org-call-for-shift-select 'backward-char))
13237 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13238 ((and (not (eq org-support-shift-select 'always))
13239 (org-on-heading-p))
13240 (org-call-with-arg 'org-todo 'left))
13241 ((or (and org-support-shift-select
13242 (not (eq org-support-shift-select 'always))
13243 (org-at-item-bullet-p))
13244 (and (not org-support-shift-select) (org-at-item-p)))
13245 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13246 ((and (not (eq org-support-shift-select 'always))
13247 (org-at-property-p))
13248 (call-interactively 'org-property-previous-allowed-value))
13249 ((org-clocktable-try-shift 'left arg))
13250 (org-support-shift-select
13251 (org-call-for-shift-select 'backward-char))
13252 (t (org-shiftselect-error))))
13254 (defun org-shiftcontrolright ()
13255 "Switch to next TODO set."
13256 (interactive)
13257 (cond
13258 ((and org-support-shift-select (org-region-active-p))
13259 (org-call-for-shift-select 'forward-word))
13260 ((and (not (eq org-support-shift-select 'always))
13261 (org-on-heading-p))
13262 (org-call-with-arg 'org-todo 'nextset))
13263 (org-support-shift-select
13264 (org-call-for-shift-select 'forward-word))
13265 (t (org-shiftselect-error))))
13267 (defun org-shiftcontrolleft ()
13268 "Switch to previous TODO set."
13269 (interactive)
13270 (cond
13271 ((and org-support-shift-select (org-region-active-p))
13272 (org-call-for-shift-select 'backward-word))
13273 ((and (not (eq org-support-shift-select 'always))
13274 (org-on-heading-p))
13275 (org-call-with-arg 'org-todo 'previousset))
13276 (org-support-shift-select
13277 (org-call-for-shift-select 'backward-word))
13278 (t (org-shiftselect-error))))
13280 (defun org-ctrl-c-ret ()
13281 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13282 (interactive)
13283 (cond
13284 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13285 (t (call-interactively 'org-insert-heading))))
13287 (defun org-copy-special ()
13288 "Copy region in table or copy current subtree.
13289 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13290 See the individual commands for more information."
13291 (interactive)
13292 (call-interactively
13293 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13295 (defun org-cut-special ()
13296 "Cut region in table or cut current subtree.
13297 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13298 See the individual commands for more information."
13299 (interactive)
13300 (call-interactively
13301 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13303 (defun org-paste-special (arg)
13304 "Paste rectangular region into table, or past subtree relative to level.
13305 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13306 See the individual commands for more information."
13307 (interactive "P")
13308 (if (org-at-table-p)
13309 (org-table-paste-rectangle)
13310 (org-paste-subtree arg)))
13312 (defun org-edit-special ()
13313 "Call a special editor for the stuff at point.
13314 When at a table, call the formula editor with `org-table-edit-formulas'.
13315 When at the first line of an src example, call `org-edit-src-code'.
13316 When in an #+include line, visit the include file. Otherwise call
13317 `ffap' to visit the file at point."
13318 (interactive)
13319 (cond
13320 ((org-at-table-p)
13321 (call-interactively 'org-table-edit-formulas))
13322 ((save-excursion
13323 (beginning-of-line 1)
13324 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13325 (find-file (org-trim (match-string 1))))
13326 ((org-edit-src-code))
13327 ((org-edit-fixed-width-region))
13328 (t (call-interactively 'ffap))))
13330 (defun org-ctrl-c-ctrl-c (&optional arg)
13331 "Set tags in headline, or update according to changed information at point.
13333 This command does many different things, depending on context:
13335 - If the cursor is in a headline, prompt for tags and insert them
13336 into the current line, aligned to `org-tags-column'. When called
13337 with prefix arg, realign all tags in the current buffer.
13339 - If the cursor is in one of the special #+KEYWORD lines, this
13340 triggers scanning the buffer for these lines and updating the
13341 information.
13343 - If the cursor is inside a table, realign the table. This command
13344 works even if the automatic table editor has been turned off.
13346 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13347 the entire table.
13349 - If the cursor is at a footnote reference or definition, jump to
13350 the corresponding definition or references, respectively.
13352 - If the cursor is a the beginning of a dynamic block, update it.
13354 - If the cursor is inside a table created by the table.el package,
13355 activate that table.
13357 - If the current buffer is a remember buffer, close note and file
13358 it. A prefix argument of 1 files to the default location
13359 without further interaction. A prefix argument of 2 files to
13360 the currently clocking task.
13362 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13363 links in this buffer.
13365 - If the cursor is on a numbered item in a plain list, renumber the
13366 ordered list.
13368 - If the cursor is on a checkbox, toggle it."
13369 (interactive "P")
13370 (let ((org-enable-table-editor t))
13371 (cond
13372 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13373 org-occur-highlights
13374 org-latex-fragment-image-overlays)
13375 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13376 (org-remove-occur-highlights)
13377 (org-remove-latex-fragment-image-overlays)
13378 (message "Temporary highlights/overlays removed from current buffer"))
13379 ((and (local-variable-p 'org-finish-function (current-buffer))
13380 (fboundp org-finish-function))
13381 (funcall org-finish-function))
13382 ((org-at-property-p)
13383 (call-interactively 'org-property-action))
13384 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13385 ((org-on-heading-p) (call-interactively 'org-set-tags))
13386 ((org-at-table.el-p)
13387 (require 'table)
13388 (beginning-of-line 1)
13389 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13390 (call-interactively 'table-recognize-table))
13391 ((org-at-table-p)
13392 (org-table-maybe-eval-formula)
13393 (if arg
13394 (call-interactively 'org-table-recalculate)
13395 (org-table-maybe-recalculate-line))
13396 (call-interactively 'org-table-align))
13397 ((or (org-footnote-at-reference-p)
13398 (org-footnote-at-definition-p))
13399 (call-interactively 'org-footnote-action))
13400 ((org-at-item-checkbox-p)
13401 (call-interactively 'org-toggle-checkbox))
13402 ((org-at-item-p)
13403 (call-interactively 'org-maybe-renumber-ordered-list))
13404 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13405 ;; Dynamic block
13406 (beginning-of-line 1)
13407 (save-excursion (org-update-dblock)))
13408 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13409 (cond
13410 ((equal (match-string 1) "TBLFM")
13411 ;; Recalculate the table before this line
13412 (save-excursion
13413 (beginning-of-line 1)
13414 (skip-chars-backward " \r\n\t")
13415 (if (org-at-table-p)
13416 (org-call-with-arg 'org-table-recalculate t))))
13418 ; (org-set-regexps-and-options)
13419 ; (org-restart-font-lock)
13420 (let ((org-inhibit-startup t)) (org-mode-restart))
13421 (message "Local setup has been refreshed"))))
13422 (t (error "C-c C-c can do nothing useful at this location.")))))
13424 (defun org-mode-restart ()
13425 "Restart Org-mode, to scan again for special lines.
13426 Also updates the keyword regular expressions."
13427 (interactive)
13428 (org-mode)
13429 (message "Org-mode restarted"))
13431 (defun org-kill-note-or-show-branches ()
13432 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13433 (interactive)
13434 (if (not org-finish-function)
13435 (call-interactively 'show-branches)
13436 (let ((org-note-abort t))
13437 (funcall org-finish-function))))
13439 (defun org-return (&optional indent)
13440 "Goto next table row or insert a newline.
13441 Calls `org-table-next-row' or `newline', depending on context.
13442 See the individual commands for more information."
13443 (interactive)
13444 (cond
13445 ((bobp) (if indent (newline-and-indent) (newline)))
13446 ((and (org-at-heading-p)
13447 (looking-at
13448 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13449 (org-show-entry)
13450 (end-of-line 1)
13451 (newline))
13452 ((org-at-table-p)
13453 (org-table-justify-field-maybe)
13454 (call-interactively 'org-table-next-row))
13455 (t (if indent (newline-and-indent) (newline)))))
13457 (defun org-return-indent ()
13458 "Goto next table row or insert a newline and indent.
13459 Calls `org-table-next-row' or `newline-and-indent', depending on
13460 context. See the individual commands for more information."
13461 (interactive)
13462 (org-return t))
13464 (defun org-ctrl-c-star ()
13465 "Compute table, or change heading status of lines.
13466 Calls `org-table-recalculate' or `org-toggle-heading',
13467 depending on context."
13468 (interactive)
13469 (cond
13470 ((org-at-table-p)
13471 (call-interactively 'org-table-recalculate))
13473 ;; Convert all lines in region to list items
13474 (call-interactively 'org-toggle-heading))))
13476 (defun org-ctrl-c-minus ()
13477 "Insert separator line in table or modify bullet status of line.
13478 Also turns a plain line or a region of lines into list items.
13479 Calls `org-table-insert-hline', `org-toggle-item', or
13480 `org-cycle-list-bullet', depending on context."
13481 (interactive)
13482 (cond
13483 ((org-at-table-p)
13484 (call-interactively 'org-table-insert-hline))
13485 ((org-region-active-p)
13486 (call-interactively 'org-toggle-item))
13487 ((org-in-item-p)
13488 (call-interactively 'org-cycle-list-bullet))
13490 (call-interactively 'org-toggle-item))))
13492 (defun org-toggle-item ()
13493 "Convert headings or normal lines to items, items to normal lines.
13494 If there is no active region, only the current line is considered.
13496 If the first line in the region is a headline, convert all headlines to items.
13498 If the first line in the region is an item, convert all items to normal lines.
13500 If the first line is normal text, add an item bullet to each line."
13501 (interactive)
13502 (let (l2 l beg end)
13503 (if (org-region-active-p)
13504 (setq beg (region-beginning) end (region-end))
13505 (setq beg (point-at-bol)
13506 end (min (1+ (point-at-eol)) (point-max))))
13507 (save-excursion
13508 (goto-char end)
13509 (setq l2 (org-current-line))
13510 (goto-char beg)
13511 (beginning-of-line 1)
13512 (setq l (1- (org-current-line)))
13513 (if (org-at-item-p)
13514 ;; We already have items, de-itemize
13515 (while (< (setq l (1+ l)) l2)
13516 (when (org-at-item-p)
13517 (goto-char (match-beginning 2))
13518 (delete-region (match-beginning 2) (match-end 2))
13519 (and (looking-at "[ \t]+") (replace-match "")))
13520 (beginning-of-line 2))
13521 (if (org-on-heading-p)
13522 ;; Headings, convert to items
13523 (while (< (setq l (1+ l)) l2)
13524 (if (looking-at org-outline-regexp)
13525 (replace-match "- " t t))
13526 (beginning-of-line 2))
13527 ;; normal lines, turn them into items
13528 (while (< (setq l (1+ l)) l2)
13529 (unless (org-at-item-p)
13530 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13531 (replace-match "\\1- \\2")))
13532 (beginning-of-line 2)))))))
13534 (defun org-toggle-heading (&optional nstars)
13535 "Convert headings to normal text, or items or text to headings.
13536 If there is no active region, only the current line is considered.
13538 If the first line is a heading, remove the stars from all headlines
13539 in the region.
13541 If the first line is a plain list item, turn all plain list items into
13542 headings.
13544 If the first line is a normal line, turn each and every line in the region
13545 into a heading.
13547 When converting a line into a heading, the number of stars is chosen
13548 such that the lines become children of the current entry. However, when
13549 a prefix argument is given, its value determines the number of stars to add."
13550 (interactive "P")
13551 (let (l2 l itemp beg end)
13552 (if (org-region-active-p)
13553 (setq beg (region-beginning) end (region-end))
13554 (setq beg (point-at-bol)
13555 end (min (1+ (point-at-eol)) (point-max))))
13556 (save-excursion
13557 (goto-char end)
13558 (setq l2 (org-current-line))
13559 (goto-char beg)
13560 (beginning-of-line 1)
13561 (setq l (1- (org-current-line)))
13562 (if (org-on-heading-p)
13563 ;; We already have headlines, de-star them
13564 (while (< (setq l (1+ l)) l2)
13565 (when (org-on-heading-p t)
13566 (and (looking-at outline-regexp) (replace-match "")))
13567 (beginning-of-line 2))
13568 (setq itemp (org-at-item-p))
13569 (let* ((stars
13570 (if nstars
13571 (make-string (prefix-numeric-value current-prefix-arg)
13573 (save-excursion
13574 (re-search-backward org-complex-heading-regexp nil t)
13575 (or (match-string 1) "*"))))
13576 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13577 (rpl (concat stars add-stars " ")))
13578 (while (< (setq l (1+ l)) l2)
13579 (if itemp
13580 (and (org-at-item-p) (replace-match rpl t t))
13581 (unless (org-on-heading-p)
13582 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13583 (replace-match (concat rpl (match-string 2))))))
13584 (beginning-of-line 2)))))))
13586 (defun org-meta-return (&optional arg)
13587 "Insert a new heading or wrap a region in a table.
13588 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13589 See the individual commands for more information."
13590 (interactive "P")
13591 (cond
13592 ((org-at-table-p)
13593 (call-interactively 'org-table-wrap-region))
13594 (t (call-interactively 'org-insert-heading))))
13596 ;;; Menu entries
13598 ;; Define the Org-mode menus
13599 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13600 '("Tbl"
13601 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13602 ["Next Field" org-cycle (org-at-table-p)]
13603 ["Previous Field" org-shifttab (org-at-table-p)]
13604 ["Next Row" org-return (org-at-table-p)]
13605 "--"
13606 ["Blank Field" org-table-blank-field (org-at-table-p)]
13607 ["Edit Field" org-table-edit-field (org-at-table-p)]
13608 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13609 "--"
13610 ("Column"
13611 ["Move Column Left" org-metaleft (org-at-table-p)]
13612 ["Move Column Right" org-metaright (org-at-table-p)]
13613 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13614 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13615 ("Row"
13616 ["Move Row Up" org-metaup (org-at-table-p)]
13617 ["Move Row Down" org-metadown (org-at-table-p)]
13618 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13619 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13620 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13621 "--"
13622 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13623 ("Rectangle"
13624 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13625 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13626 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13627 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13628 "--"
13629 ("Calculate"
13630 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13631 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13632 ["Edit Formulas" org-edit-special (org-at-table-p)]
13633 "--"
13634 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13635 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13636 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13637 "--"
13638 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13639 "--"
13640 ["Sum Column/Rectangle" org-table-sum
13641 (or (org-at-table-p) (org-region-active-p))]
13642 ["Which Column?" org-table-current-column (org-at-table-p)])
13643 ["Debug Formulas"
13644 org-table-toggle-formula-debugger
13645 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13646 ["Show Col/Row Numbers"
13647 org-table-toggle-coordinate-overlays
13648 :style toggle
13649 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13650 "--"
13651 ["Create" org-table-create (and (not (org-at-table-p))
13652 org-enable-table-editor)]
13653 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13654 ["Import from File" org-table-import (not (org-at-table-p))]
13655 ["Export to File" org-table-export (org-at-table-p)]
13656 "--"
13657 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13659 (easy-menu-define org-org-menu org-mode-map "Org menu"
13660 '("Org"
13661 ("Show/Hide"
13662 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13663 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13664 ["Sparse Tree..." org-sparse-tree t]
13665 ["Reveal Context" org-reveal t]
13666 ["Show All" show-all t]
13667 "--"
13668 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13669 "--"
13670 ["New Heading" org-insert-heading t]
13671 ("Navigate Headings"
13672 ["Up" outline-up-heading t]
13673 ["Next" outline-next-visible-heading t]
13674 ["Previous" outline-previous-visible-heading t]
13675 ["Next Same Level" outline-forward-same-level t]
13676 ["Previous Same Level" outline-backward-same-level t]
13677 "--"
13678 ["Jump" org-goto t])
13679 ("Edit Structure"
13680 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13681 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13682 "--"
13683 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13684 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13685 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13686 "--"
13687 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13688 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13689 ["Demote Heading" org-metaright (not (org-at-table-p))]
13690 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13691 "--"
13692 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13693 "--"
13694 ["Convert to odd levels" org-convert-to-odd-levels t]
13695 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13696 ("Editing"
13697 ["Emphasis..." org-emphasize t]
13698 ["Edit Source Example" org-edit-special t]
13699 "--"
13700 ["Footnote new/jump" org-footnote-action t]
13701 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13702 ("Archive"
13703 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13704 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13705 ; :active t :keys "C-u C-c C-x C-a"]
13706 ["Sparse trees open ARCHIVE trees"
13707 (setq org-sparse-tree-open-archived-trees
13708 (not org-sparse-tree-open-archived-trees))
13709 :style toggle :selected org-sparse-tree-open-archived-trees]
13710 ["Cycling opens ARCHIVE trees"
13711 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13712 :style toggle :selected org-cycle-open-archived-trees]
13713 "--"
13714 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13715 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13716 ; ["Check and Move Children" (org-archive-subtree '(4))
13717 ; :active t :keys "C-u C-c C-x C-s"]
13719 "--"
13720 ("TODO Lists"
13721 ["TODO/DONE/-" org-todo t]
13722 ("Select keyword"
13723 ["Next keyword" org-shiftright (org-on-heading-p)]
13724 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13725 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13726 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13727 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13728 ["Show TODO Tree" org-show-todo-tree t]
13729 ["Global TODO list" org-todo-list t]
13730 "--"
13731 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
13732 :selected org-enforce-todo-dependencies :style toggle :active t]
13733 "Settings for tree at point"
13734 ["Do Children sequentially" org-toggle-ordered-property :style radio
13735 :selected (ignore-errors (org-entry-get nil "ORDERED"))
13736 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13737 ["Do Children parallel" org-toggle-ordered-property :style radio
13738 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
13739 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13740 "--"
13741 ["Set Priority" org-priority t]
13742 ["Priority Up" org-shiftup t]
13743 ["Priority Down" org-shiftdown t])
13744 ("TAGS and Properties"
13745 ["Set Tags" org-set-tags-command t]
13746 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13747 "--"
13748 ["Set property" org-set-property t]
13749 ["Column view of properties" org-columns t]
13750 ["Insert Column View DBlock" org-insert-columns-dblock t])
13751 ("Dates and Scheduling"
13752 ["Timestamp" org-time-stamp t]
13753 ["Timestamp (inactive)" org-time-stamp-inactive t]
13754 ("Change Date"
13755 ["1 Day Later" org-shiftright t]
13756 ["1 Day Earlier" org-shiftleft t]
13757 ["1 ... Later" org-shiftup t]
13758 ["1 ... Earlier" org-shiftdown t])
13759 ["Compute Time Range" org-evaluate-time-range t]
13760 ["Schedule Item" org-schedule t]
13761 ["Deadline" org-deadline t]
13762 "--"
13763 ["Custom time format" org-toggle-time-stamp-overlays
13764 :style radio :selected org-display-custom-times]
13765 "--"
13766 ["Goto Calendar" org-goto-calendar t]
13767 ["Date from Calendar" org-date-from-calendar t]
13768 "--"
13769 ["Start/Restart Timer" org-timer-start t]
13770 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13771 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13772 ["Insert Timer String" org-timer t]
13773 ["Insert Timer Item" org-timer-item t])
13774 ("Logging work"
13775 ["Clock in" org-clock-in t]
13776 ["Clock out" org-clock-out t]
13777 ["Clock cancel" org-clock-cancel t]
13778 ["Goto running clock" org-clock-goto t]
13779 ["Display times" org-clock-display t]
13780 ["Create clock table" org-clock-report t]
13781 "--"
13782 ["Record DONE time"
13783 (progn (setq org-log-done (not org-log-done))
13784 (message "Switching to %s will %s record a timestamp"
13785 (car org-done-keywords)
13786 (if org-log-done "automatically" "not")))
13787 :style toggle :selected org-log-done])
13788 "--"
13789 ["Agenda Command..." org-agenda t]
13790 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13791 ("File List for Agenda")
13792 ("Special views current file"
13793 ["TODO Tree" org-show-todo-tree t]
13794 ["Check Deadlines" org-check-deadlines t]
13795 ["Timeline" org-timeline t]
13796 ["Tags Tree" org-tags-sparse-tree t])
13797 "--"
13798 ("Hyperlinks"
13799 ["Store Link (Global)" org-store-link t]
13800 ["Insert Link" org-insert-link t]
13801 ["Follow Link" org-open-at-point t]
13802 "--"
13803 ["Next link" org-next-link t]
13804 ["Previous link" org-previous-link t]
13805 "--"
13806 ["Descriptive Links"
13807 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13808 :style radio
13809 :selected (member '(org-link) buffer-invisibility-spec)]
13810 ["Literal Links"
13811 (progn
13812 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13813 :style radio
13814 :selected (not (member '(org-link) buffer-invisibility-spec))])
13815 "--"
13816 ["Export/Publish..." org-export t]
13817 ("LaTeX"
13818 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13819 :selected org-cdlatex-mode]
13820 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13821 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13822 ["Modify math symbol" org-cdlatex-math-modify
13823 (org-inside-LaTeX-fragment-p)]
13824 ["Export LaTeX fragments as images"
13825 (if (featurep 'org-exp)
13826 (setq org-export-with-LaTeX-fragments
13827 (not org-export-with-LaTeX-fragments))
13828 (require 'org-exp))
13829 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13830 org-export-with-LaTeX-fragments)])
13831 "--"
13832 ("Documentation"
13833 ["Show Version" org-version t]
13834 ["Info Documentation" org-info t])
13835 ("Customize"
13836 ["Browse Org Group" org-customize t]
13837 "--"
13838 ["Expand This Menu" org-create-customize-menu
13839 (fboundp 'customize-menu-create)])
13840 "--"
13841 ["Refresh setup" org-mode-restart t]
13844 (defun org-info (&optional node)
13845 "Read documentation for Org-mode in the info system.
13846 With optional NODE, go directly to that node."
13847 (interactive)
13848 (info (format "(org)%s" (or node ""))))
13850 (defun org-install-agenda-files-menu ()
13851 (let ((bl (buffer-list)))
13852 (save-excursion
13853 (while bl
13854 (set-buffer (pop bl))
13855 (if (org-mode-p) (setq bl nil)))
13856 (when (org-mode-p)
13857 (easy-menu-change
13858 '("Org") "File List for Agenda"
13859 (append
13860 (list
13861 ["Edit File List" (org-edit-agenda-file-list) t]
13862 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13863 ["Remove Current File from List" org-remove-file t]
13864 ["Cycle through agenda files" org-cycle-agenda-files t]
13865 ["Occur in all agenda files" org-occur-in-agenda-files t]
13866 "--")
13867 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13869 ;;;; Documentation
13871 ;;;###autoload
13872 (defun org-require-autoloaded-modules ()
13873 (interactive)
13874 (mapc 'require
13875 '(org-agenda org-archive org-attach org-clock org-colview
13876 org-exp org-id org-export-latex org-publish
13877 org-remember org-table org-timer)))
13879 ;;;###autoload
13880 (defun org-customize ()
13881 "Call the customize function with org as argument."
13882 (interactive)
13883 (org-load-modules-maybe)
13884 (org-require-autoloaded-modules)
13885 (customize-browse 'org))
13887 (defun org-create-customize-menu ()
13888 "Create a full customization menu for Org-mode, insert it into the menu."
13889 (interactive)
13890 (org-load-modules-maybe)
13891 (org-require-autoloaded-modules)
13892 (if (fboundp 'customize-menu-create)
13893 (progn
13894 (easy-menu-change
13895 '("Org") "Customize"
13896 `(["Browse Org group" org-customize t]
13897 "--"
13898 ,(customize-menu-create 'org)
13899 ["Set" Custom-set t]
13900 ["Save" Custom-save t]
13901 ["Reset to Current" Custom-reset-current t]
13902 ["Reset to Saved" Custom-reset-saved t]
13903 ["Reset to Standard Settings" Custom-reset-standard t]))
13904 (message "\"Org\"-menu now contains full customization menu"))
13905 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13907 ;;;; Miscellaneous stuff
13909 ;;; Generally useful functions
13911 (defun org-find-text-property-in-string (prop s)
13912 "Return the first non-nil value of property PROP in string S."
13913 (or (get-text-property 0 prop s)
13914 (get-text-property (or (next-single-property-change 0 prop s) 0)
13915 prop s)))
13917 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13918 "Display the given MESSAGE as a warning."
13919 (if (fboundp 'display-warning)
13920 (display-warning 'org message
13921 (if (featurep 'xemacs)
13922 'warning
13923 :warning))
13924 (let ((buf (get-buffer-create "*Org warnings*")))
13925 (with-current-buffer buf
13926 (goto-char (point-max))
13927 (insert "Warning (Org): " message)
13928 (unless (bolp)
13929 (newline)))
13930 (display-buffer buf)
13931 (sit-for 0))))
13933 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13934 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13935 (if (and marker (marker-buffer marker)
13936 (buffer-live-p (marker-buffer marker)))
13937 (progn
13938 (switch-to-buffer (marker-buffer marker))
13939 (if (or (> marker (point-max)) (< marker (point-min)))
13940 (widen))
13941 (goto-char marker)
13942 (org-show-context 'org-goto))
13943 (if bookmark
13944 (bookmark-jump bookmark)
13945 (error "Cannot find location"))))
13947 (defun org-quote-csv-field (s)
13948 "Quote field for inclusion in CSV material."
13949 (if (string-match "[\",]" s)
13950 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13953 (defun org-plist-delete (plist property)
13954 "Delete PROPERTY from PLIST.
13955 This is in contrast to merely setting it to 0."
13956 (let (p)
13957 (while plist
13958 (if (not (eq property (car plist)))
13959 (setq p (plist-put p (car plist) (nth 1 plist))))
13960 (setq plist (cddr plist)))
13963 (defun org-force-self-insert (N)
13964 "Needed to enforce self-insert under remapping."
13965 (interactive "p")
13966 (self-insert-command N))
13968 (defun org-string-width (s)
13969 "Compute width of string, ignoring invisible characters.
13970 This ignores character with invisibility property `org-link', and also
13971 characters with property `org-cwidth', because these will become invisible
13972 upon the next fontification round."
13973 (let (b l)
13974 (when (or (eq t buffer-invisibility-spec)
13975 (assq 'org-link buffer-invisibility-spec))
13976 (while (setq b (text-property-any 0 (length s)
13977 'invisible 'org-link s))
13978 (setq s (concat (substring s 0 b)
13979 (substring s (or (next-single-property-change
13980 b 'invisible s) (length s)))))))
13981 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13982 (setq s (concat (substring s 0 b)
13983 (substring s (or (next-single-property-change
13984 b 'org-cwidth s) (length s))))))
13985 (setq l (string-width s) b -1)
13986 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13987 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13990 (defun org-get-indentation (&optional line)
13991 "Get the indentation of the current line, interpreting tabs.
13992 When LINE is given, assume it represents a line and compute its indentation."
13993 (if line
13994 (if (string-match "^ *" (org-remove-tabs line))
13995 (match-end 0))
13996 (save-excursion
13997 (beginning-of-line 1)
13998 (skip-chars-forward " \t")
13999 (current-column))))
14001 (defun org-remove-tabs (s &optional width)
14002 "Replace tabulators in S with spaces.
14003 Assumes that s is a single line, starting in column 0."
14004 (setq width (or width tab-width))
14005 (while (string-match "\t" s)
14006 (setq s (replace-match
14007 (make-string
14008 (- (* width (/ (+ (match-beginning 0) width) width))
14009 (match-beginning 0)) ?\ )
14010 t t s)))
14013 (defun org-fix-indentation (line ind)
14014 "Fix indentation in LINE.
14015 IND is a cons cell with target and minimum indentation.
14016 If the current indentation in LINE is smaller than the minimum,
14017 leave it alone. If it is larger than ind, set it to the target."
14018 (let* ((l (org-remove-tabs line))
14019 (i (org-get-indentation l))
14020 (i1 (car ind)) (i2 (cdr ind)))
14021 (if (>= i i2) (setq l (substring line i2)))
14022 (if (> i1 0)
14023 (concat (make-string i1 ?\ ) l)
14024 l)))
14026 (defun org-base-buffer (buffer)
14027 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14028 (if (not buffer)
14029 buffer
14030 (or (buffer-base-buffer buffer)
14031 buffer)))
14033 (defun org-trim (s)
14034 "Remove whitespace at beginning and end of string."
14035 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14036 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14039 (defun org-wrap (string &optional width lines)
14040 "Wrap string to either a number of lines, or a width in characters.
14041 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14042 that costs. If there is a word longer than WIDTH, the text is actually
14043 wrapped to the length of that word.
14044 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14045 many lines, whatever width that takes.
14046 The return value is a list of lines, without newlines at the end."
14047 (let* ((words (org-split-string string "[ \t\n]+"))
14048 (maxword (apply 'max (mapcar 'org-string-width words)))
14049 w ll)
14050 (cond (width
14051 (org-do-wrap words (max maxword width)))
14052 (lines
14053 (setq w maxword)
14054 (setq ll (org-do-wrap words maxword))
14055 (if (<= (length ll) lines)
14057 (setq ll words)
14058 (while (> (length ll) lines)
14059 (setq w (1+ w))
14060 (setq ll (org-do-wrap words w)))
14061 ll))
14062 (t (error "Cannot wrap this")))))
14064 (defun org-do-wrap (words width)
14065 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14066 (let (lines line)
14067 (while words
14068 (setq line (pop words))
14069 (while (and words (< (+ (length line) (length (car words))) width))
14070 (setq line (concat line " " (pop words))))
14071 (setq lines (push line lines)))
14072 (nreverse lines)))
14074 (defun org-split-string (string &optional separators)
14075 "Splits STRING into substrings at SEPARATORS.
14076 No empty strings are returned if there are matches at the beginning
14077 and end of string."
14078 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14079 (start 0)
14080 notfirst
14081 (list nil))
14082 (while (and (string-match rexp string
14083 (if (and notfirst
14084 (= start (match-beginning 0))
14085 (< start (length string)))
14086 (1+ start) start))
14087 (< (match-beginning 0) (length string)))
14088 (setq notfirst t)
14089 (or (eq (match-beginning 0) 0)
14090 (and (eq (match-beginning 0) (match-end 0))
14091 (eq (match-beginning 0) start))
14092 (setq list
14093 (cons (substring string start (match-beginning 0))
14094 list)))
14095 (setq start (match-end 0)))
14096 (or (eq start (length string))
14097 (setq list
14098 (cons (substring string start)
14099 list)))
14100 (nreverse list)))
14102 (defun org-context ()
14103 "Return a list of contexts of the current cursor position.
14104 If several contexts apply, all are returned.
14105 Each context entry is a list with a symbol naming the context, and
14106 two positions indicating start and end of the context. Possible
14107 contexts are:
14109 :headline anywhere in a headline
14110 :headline-stars on the leading stars in a headline
14111 :todo-keyword on a TODO keyword (including DONE) in a headline
14112 :tags on the TAGS in a headline
14113 :priority on the priority cookie in a headline
14114 :item on the first line of a plain list item
14115 :item-bullet on the bullet/number of a plain list item
14116 :checkbox on the checkbox in a plain list item
14117 :table in an org-mode table
14118 :table-special on a special filed in a table
14119 :table-table in a table.el table
14120 :link on a hyperlink
14121 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14122 :target on a <<target>>
14123 :radio-target on a <<<radio-target>>>
14124 :latex-fragment on a LaTeX fragment
14125 :latex-preview on a LaTeX fragment with overlayed preview image
14127 This function expects the position to be visible because it uses font-lock
14128 faces as a help to recognize the following contexts: :table-special, :link,
14129 and :keyword."
14130 (let* ((f (get-text-property (point) 'face))
14131 (faces (if (listp f) f (list f)))
14132 (p (point)) clist o)
14133 ;; First the large context
14134 (cond
14135 ((org-on-heading-p t)
14136 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14137 (when (progn
14138 (beginning-of-line 1)
14139 (looking-at org-todo-line-tags-regexp))
14140 (push (org-point-in-group p 1 :headline-stars) clist)
14141 (push (org-point-in-group p 2 :todo-keyword) clist)
14142 (push (org-point-in-group p 4 :tags) clist))
14143 (goto-char p)
14144 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14145 (if (looking-at "\\[#[A-Z0-9]\\]")
14146 (push (org-point-in-group p 0 :priority) clist)))
14148 ((org-at-item-p)
14149 (push (org-point-in-group p 2 :item-bullet) clist)
14150 (push (list :item (point-at-bol)
14151 (save-excursion (org-end-of-item) (point)))
14152 clist)
14153 (and (org-at-item-checkbox-p)
14154 (push (org-point-in-group p 0 :checkbox) clist)))
14156 ((org-at-table-p)
14157 (push (list :table (org-table-begin) (org-table-end)) clist)
14158 (if (memq 'org-formula faces)
14159 (push (list :table-special
14160 (previous-single-property-change p 'face)
14161 (next-single-property-change p 'face)) clist)))
14162 ((org-at-table-p 'any)
14163 (push (list :table-table) clist)))
14164 (goto-char p)
14166 ;; Now the small context
14167 (cond
14168 ((org-at-timestamp-p)
14169 (push (org-point-in-group p 0 :timestamp) clist))
14170 ((memq 'org-link faces)
14171 (push (list :link
14172 (previous-single-property-change p 'face)
14173 (next-single-property-change p 'face)) clist))
14174 ((memq 'org-special-keyword faces)
14175 (push (list :keyword
14176 (previous-single-property-change p 'face)
14177 (next-single-property-change p 'face)) clist))
14178 ((org-on-target-p)
14179 (push (org-point-in-group p 0 :target) clist)
14180 (goto-char (1- (match-beginning 0)))
14181 (if (looking-at org-radio-target-regexp)
14182 (push (org-point-in-group p 0 :radio-target) clist))
14183 (goto-char p))
14184 ((setq o (car (delq nil
14185 (mapcar
14186 (lambda (x)
14187 (if (memq x org-latex-fragment-image-overlays) x))
14188 (org-overlays-at (point))))))
14189 (push (list :latex-fragment
14190 (org-overlay-start o) (org-overlay-end o)) clist)
14191 (push (list :latex-preview
14192 (org-overlay-start o) (org-overlay-end o)) clist))
14193 ((org-inside-LaTeX-fragment-p)
14194 ;; FIXME: positions wrong.
14195 (push (list :latex-fragment (point) (point)) clist)))
14197 (setq clist (nreverse (delq nil clist)))
14198 clist))
14200 ;; FIXME: Compare with at-regexp-p Do we need both?
14201 (defun org-in-regexp (re &optional nlines visually)
14202 "Check if point is inside a match of regexp.
14203 Normally only the current line is checked, but you can include NLINES extra
14204 lines both before and after point into the search.
14205 If VISUALLY is set, require that the cursor is not after the match but
14206 really on, so that the block visually is on the match."
14207 (catch 'exit
14208 (let ((pos (point))
14209 (eol (point-at-eol (+ 1 (or nlines 0))))
14210 (inc (if visually 1 0)))
14211 (save-excursion
14212 (beginning-of-line (- 1 (or nlines 0)))
14213 (while (re-search-forward re eol t)
14214 (if (and (<= (match-beginning 0) pos)
14215 (>= (+ inc (match-end 0)) pos))
14216 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14218 (defun org-at-regexp-p (regexp)
14219 "Is point inside a match of REGEXP in the current line?"
14220 (catch 'exit
14221 (save-excursion
14222 (let ((pos (point)) (end (point-at-eol)))
14223 (beginning-of-line 1)
14224 (while (re-search-forward regexp end t)
14225 (if (and (<= (match-beginning 0) pos)
14226 (>= (match-end 0) pos))
14227 (throw 'exit t)))
14228 nil))))
14230 (defun org-occur-in-agenda-files (regexp &optional nlines)
14231 "Call `multi-occur' with buffers for all agenda files."
14232 (interactive "sOrg-files matching: \np")
14233 (let* ((files (org-agenda-files))
14234 (tnames (mapcar 'file-truename files))
14235 (extra org-agenda-text-search-extra-files)
14237 (when (eq (car extra) 'agenda-archives)
14238 (setq extra (cdr extra))
14239 (setq files (org-add-archive-files files)))
14240 (while (setq f (pop extra))
14241 (unless (member (file-truename f) tnames)
14242 (add-to-list 'files f 'append)
14243 (add-to-list 'tnames (file-truename f) 'append)))
14244 (multi-occur
14245 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14246 regexp)))
14248 (if (boundp 'occur-mode-find-occurrence-hook)
14249 ;; Emacs 23
14250 (add-hook 'occur-mode-find-occurrence-hook
14251 (lambda ()
14252 (when (org-mode-p)
14253 (org-reveal))))
14254 ;; Emacs 22
14255 (defadvice occur-mode-goto-occurrence
14256 (after org-occur-reveal activate)
14257 (and (org-mode-p) (org-reveal)))
14258 (defadvice occur-mode-goto-occurrence-other-window
14259 (after org-occur-reveal activate)
14260 (and (org-mode-p) (org-reveal)))
14261 (defadvice occur-mode-display-occurrence
14262 (after org-occur-reveal activate)
14263 (when (org-mode-p)
14264 (let ((pos (occur-mode-find-occurrence)))
14265 (with-current-buffer (marker-buffer pos)
14266 (save-excursion
14267 (goto-char pos)
14268 (org-reveal)))))))
14270 (defun org-uniquify (list)
14271 "Remove duplicate elements from LIST."
14272 (let (res)
14273 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14274 res))
14276 (defun org-delete-all (elts list)
14277 "Remove all elements in ELTS from LIST."
14278 (while elts
14279 (setq list (delete (pop elts) list)))
14280 list)
14282 (defun org-back-over-empty-lines ()
14283 "Move backwards over whitespace, to the beginning of the first empty line.
14284 Returns the number of empty lines passed."
14285 (let ((pos (point)))
14286 (skip-chars-backward " \t\n\r")
14287 (beginning-of-line 2)
14288 (goto-char (min (point) pos))
14289 (count-lines (point) pos)))
14291 (defun org-skip-whitespace ()
14292 (skip-chars-forward " \t\n\r"))
14294 (defun org-point-in-group (point group &optional context)
14295 "Check if POINT is in match-group GROUP.
14296 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14297 match. If the match group does ot exist or point is not inside it,
14298 return nil."
14299 (and (match-beginning group)
14300 (>= point (match-beginning group))
14301 (<= point (match-end group))
14302 (if context
14303 (list context (match-beginning group) (match-end group))
14304 t)))
14306 (defun org-switch-to-buffer-other-window (&rest args)
14307 "Switch to buffer in a second window on the current frame.
14308 In particular, do not allow pop-up frames."
14309 (let (pop-up-frames special-display-buffer-names special-display-regexps
14310 special-display-function)
14311 (apply 'switch-to-buffer-other-window args)))
14313 (defun org-combine-plists (&rest plists)
14314 "Create a single property list from all plists in PLISTS.
14315 The process starts by copying the first list, and then setting properties
14316 from the other lists. Settings in the last list are the most significant
14317 ones and overrule settings in the other lists."
14318 (let ((rtn (copy-sequence (pop plists)))
14319 p v ls)
14320 (while plists
14321 (setq ls (pop plists))
14322 (while ls
14323 (setq p (pop ls) v (pop ls))
14324 (setq rtn (plist-put rtn p v))))
14325 rtn))
14327 (defun org-move-line-down (arg)
14328 "Move the current line down. With prefix argument, move it past ARG lines."
14329 (interactive "p")
14330 (let ((col (current-column))
14331 beg end pos)
14332 (beginning-of-line 1) (setq beg (point))
14333 (beginning-of-line 2) (setq end (point))
14334 (beginning-of-line (+ 1 arg))
14335 (setq pos (move-marker (make-marker) (point)))
14336 (insert (delete-and-extract-region beg end))
14337 (goto-char pos)
14338 (org-move-to-column col)))
14340 (defun org-move-line-up (arg)
14341 "Move the current line up. With prefix argument, move it past ARG lines."
14342 (interactive "p")
14343 (let ((col (current-column))
14344 beg end pos)
14345 (beginning-of-line 1) (setq beg (point))
14346 (beginning-of-line 2) (setq end (point))
14347 (beginning-of-line (- arg))
14348 (setq pos (move-marker (make-marker) (point)))
14349 (insert (delete-and-extract-region beg end))
14350 (goto-char pos)
14351 (org-move-to-column col)))
14353 (defun org-replace-escapes (string table)
14354 "Replace %-escapes in STRING with values in TABLE.
14355 TABLE is an association list with keys like \"%a\" and string values.
14356 The sequences in STRING may contain normal field width and padding information,
14357 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14358 so values can contain further %-escapes if they are define later in TABLE."
14359 (let ((case-fold-search nil)
14360 e re rpl)
14361 (while (setq e (pop table))
14362 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14363 (while (string-match re string)
14364 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14365 (cdr e)))
14366 (setq string (replace-match rpl t t string))))
14367 string))
14370 (defun org-sublist (list start end)
14371 "Return a section of LIST, from START to END.
14372 Counting starts at 1."
14373 (let (rtn (c start))
14374 (setq list (nthcdr (1- start) list))
14375 (while (and list (<= c end))
14376 (push (pop list) rtn)
14377 (setq c (1+ c)))
14378 (nreverse rtn)))
14380 (defun org-find-base-buffer-visiting (file)
14381 "Like `find-buffer-visiting' but alway return the base buffer and
14382 not an indirect buffer."
14383 (let ((buf (find-buffer-visiting file)))
14384 (if buf
14385 (or (buffer-base-buffer buf) buf)
14386 nil)))
14388 (defun org-image-file-name-regexp (&optional extensions)
14389 "Return regexp matching the file names of images.
14390 If EXTENSIONS is given, only match these."
14391 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14392 (image-file-name-regexp)
14393 (let ((image-file-name-extensions
14394 (or extensions
14395 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14396 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14397 (concat "\\."
14398 (regexp-opt (nconc (mapcar 'upcase
14399 image-file-name-extensions)
14400 image-file-name-extensions)
14402 "\\'"))))
14404 (defun org-file-image-p (file &optional extensions)
14405 "Return non-nil if FILE is an image."
14406 (save-match-data
14407 (string-match (org-image-file-name-regexp extensions) file)))
14409 (defun org-get-cursor-date ()
14410 "Return the date at cursor in as a time.
14411 This works in the calendar and in the agenda, anywhere else it just
14412 returns the current time."
14413 (let (date day defd)
14414 (cond
14415 ((eq major-mode 'calendar-mode)
14416 (setq date (calendar-cursor-to-date)
14417 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14418 ((eq major-mode 'org-agenda-mode)
14419 (setq day (get-text-property (point) 'day))
14420 (if day
14421 (setq date (calendar-gregorian-from-absolute day)
14422 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14423 (nth 2 date))))))
14424 (or defd (current-time))))
14426 (defvar org-agenda-action-marker (make-marker)
14427 "Marker pointing to the entry for the next agenda action.")
14429 (defun org-mark-entry-for-agenda-action ()
14430 "Mark the current entry as target of an agenda action.
14431 Agenda actions are actions executed from the agenda with the key `k',
14432 which make use of the date at the cursor."
14433 (interactive)
14434 (move-marker org-agenda-action-marker
14435 (save-excursion (org-back-to-heading t) (point))
14436 (current-buffer))
14437 (message
14438 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14440 ;;; Paragraph filling stuff.
14441 ;; We want this to be just right, so use the full arsenal.
14443 (defun org-indent-line-function ()
14444 "Indent line like previous, but further if previous was headline or item."
14445 (interactive)
14446 (let* ((pos (point))
14447 (itemp (org-at-item-p))
14448 column bpos bcol tpos tcol bullet btype bullet-type)
14449 ;; Find the previous relevant line
14450 (beginning-of-line 1)
14451 (cond
14452 ((looking-at "#") (setq column 0))
14453 ((looking-at "\\*+ ") (setq column 0))
14455 (beginning-of-line 0)
14456 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14457 (beginning-of-line 0))
14458 (cond
14459 ((looking-at "\\*+[ \t]+")
14460 (if (not org-adapt-indentation)
14461 (setq column 0)
14462 (goto-char (match-end 0))
14463 (setq column (current-column))))
14464 ((org-in-item-p)
14465 (org-beginning-of-item)
14466 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14467 (setq bpos (match-beginning 1) tpos (match-end 0)
14468 bcol (progn (goto-char bpos) (current-column))
14469 tcol (progn (goto-char tpos) (current-column))
14470 bullet (match-string 1)
14471 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14472 (if (> tcol (+ bcol org-description-max-indent))
14473 (setq tcol (+ bcol 5)))
14474 (if (not itemp)
14475 (setq column tcol)
14476 (goto-char pos)
14477 (beginning-of-line 1)
14478 (if (looking-at "\\S-")
14479 (progn
14480 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14481 (setq bullet (match-string 1)
14482 btype (if (string-match "[0-9]" bullet) "n" bullet))
14483 (setq column (if (equal btype bullet-type) bcol tcol)))
14484 (setq column (org-get-indentation)))))
14485 (t (setq column (org-get-indentation))))))
14486 (goto-char pos)
14487 (if (<= (current-column) (current-indentation))
14488 (org-indent-line-to column)
14489 (save-excursion (org-indent-line-to column)))
14490 (setq column (current-column))
14491 (beginning-of-line 1)
14492 (if (looking-at
14493 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14494 (replace-match (concat "\\1" (format org-property-format
14495 (match-string 2) (match-string 3)))
14496 t nil))
14497 (org-move-to-column column)))
14499 (defun org-set-autofill-regexps ()
14500 (interactive)
14501 ;; In the paragraph separator we include headlines, because filling
14502 ;; text in a line directly attached to a headline would otherwise
14503 ;; fill the headline as well.
14504 (org-set-local 'comment-start-skip "^#+[ \t]*")
14505 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14506 ;; The paragraph starter includes hand-formatted lists.
14507 (org-set-local 'paragraph-start
14508 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14509 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14510 ;; But only if the user has not turned off tables or fixed-width regions
14511 (org-set-local
14512 'auto-fill-inhibit-regexp
14513 (concat "\\*+ \\|#\\+"
14514 "\\|[ \t]*" org-keyword-time-regexp
14515 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14516 (concat
14517 "\\|[ \t]*["
14518 (if org-enable-table-editor "|" "")
14519 (if org-enable-fixed-width-editor ":" "")
14520 "]"))))
14521 ;; We use our own fill-paragraph function, to make sure that tables
14522 ;; and fixed-width regions are not wrapped. That function will pass
14523 ;; through to `fill-paragraph' when appropriate.
14524 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14525 ; Adaptive filling: To get full control, first make sure that
14526 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14527 (org-set-local 'adaptive-fill-regexp "\000")
14528 (org-set-local 'adaptive-fill-function
14529 'org-adaptive-fill-function)
14530 (org-set-local
14531 'align-mode-rules-list
14532 '((org-in-buffer-settings
14533 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14534 (modes . '(org-mode))))))
14536 (defun org-fill-paragraph (&optional justify)
14537 "Re-align a table, pass through to fill-paragraph if no table."
14538 (let ((table-p (org-at-table-p))
14539 (table.el-p (org-at-table.el-p)))
14540 (cond ((and (equal (char-after (point-at-bol)) ?*)
14541 (save-excursion (goto-char (point-at-bol))
14542 (looking-at outline-regexp)))
14543 t) ; skip headlines
14544 (table.el-p t) ; skip table.el tables
14545 (table-p (org-table-align) t) ; align org-mode tables
14546 (t nil)))) ; call paragraph-fill
14548 ;; For reference, this is the default value of adaptive-fill-regexp
14549 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14551 (defun org-adaptive-fill-function ()
14552 "Return a fill prefix for org-mode files.
14553 In particular, this makes sure hanging paragraphs for hand-formatted lists
14554 work correctly."
14555 (cond ((looking-at "#[ \t]+")
14556 (match-string 0))
14557 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14558 (save-excursion
14559 (if (> (match-end 1) (+ (match-beginning 1)
14560 org-description-max-indent))
14561 (goto-char (+ (match-beginning 1) 5))
14562 (goto-char (match-end 0)))
14563 (make-string (current-column) ?\ )))
14564 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14565 (save-excursion
14566 (goto-char (match-end 0))
14567 (make-string (current-column) ?\ )))
14568 (t nil)))
14570 ;;; Other stuff.
14572 (defun org-toggle-fixed-width-section (arg)
14573 "Toggle the fixed-width export.
14574 If there is no active region, the QUOTE keyword at the current headline is
14575 inserted or removed. When present, it causes the text between this headline
14576 and the next to be exported as fixed-width text, and unmodified.
14577 If there is an active region, this command adds or removes a colon as the
14578 first character of this line. If the first character of a line is a colon,
14579 this line is also exported in fixed-width font."
14580 (interactive "P")
14581 (let* ((cc 0)
14582 (regionp (org-region-active-p))
14583 (beg (if regionp (region-beginning) (point)))
14584 (end (if regionp (region-end)))
14585 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14586 (case-fold-search nil)
14587 (re "[ \t]*\\(:\\)")
14588 off)
14589 (if regionp
14590 (save-excursion
14591 (goto-char beg)
14592 (setq cc (current-column))
14593 (beginning-of-line 1)
14594 (setq off (looking-at re))
14595 (while (> nlines 0)
14596 (setq nlines (1- nlines))
14597 (beginning-of-line 1)
14598 (cond
14599 (arg
14600 (org-move-to-column cc t)
14601 (insert ":\n")
14602 (forward-line -1))
14603 ((and off (looking-at re))
14604 (replace-match "" t t nil 1))
14605 ((not off) (org-move-to-column cc t) (insert ":")))
14606 (forward-line 1)))
14607 (save-excursion
14608 (org-back-to-heading)
14609 (if (looking-at (concat outline-regexp
14610 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14611 (replace-match "" t t nil 1)
14612 (if (looking-at outline-regexp)
14613 (progn
14614 (goto-char (match-end 0))
14615 (insert org-quote-string " "))))))))
14617 ;;;; Functions extending outline functionality
14619 (defun org-beginning-of-line (&optional arg)
14620 "Go to the beginning of the current line. If that is invisible, continue
14621 to a visible line beginning. This makes the function of C-a more intuitive.
14622 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14623 first attempt, and only move to after the tags when the cursor is already
14624 beyond the end of the headline."
14625 (interactive "P")
14626 (let ((pos (point)) refpos)
14627 (beginning-of-line 1)
14628 (if (bobp)
14630 (backward-char 1)
14631 (if (org-invisible-p)
14632 (while (and (not (bobp)) (org-invisible-p))
14633 (backward-char 1)
14634 (beginning-of-line 1))
14635 (forward-char 1)))
14636 (when org-special-ctrl-a/e
14637 (cond
14638 ((and (looking-at org-complex-heading-regexp)
14639 (= (char-after (match-end 1)) ?\ ))
14640 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14641 (point-at-eol)))
14642 (goto-char
14643 (if (eq org-special-ctrl-a/e t)
14644 (cond ((> pos refpos) refpos)
14645 ((= pos (point)) refpos)
14646 (t (point)))
14647 (cond ((> pos (point)) (point))
14648 ((not (eq last-command this-command)) (point))
14649 (t refpos)))))
14650 ((org-at-item-p)
14651 (goto-char
14652 (if (eq org-special-ctrl-a/e t)
14653 (cond ((> pos (match-end 4)) (match-end 4))
14654 ((= pos (point)) (match-end 4))
14655 (t (point)))
14656 (cond ((> pos (point)) (point))
14657 ((not (eq last-command this-command)) (point))
14658 (t (match-end 4))))))))
14659 (org-no-warnings
14660 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14662 (defun org-end-of-line (&optional arg)
14663 "Go to the end of the line.
14664 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14665 first attempt, and only move to after the tags when the cursor is already
14666 beyond the end of the headline."
14667 (interactive "P")
14668 (if (or (not org-special-ctrl-a/e)
14669 (not (org-on-heading-p)))
14670 (end-of-line arg)
14671 (let ((pos (point)))
14672 (beginning-of-line 1)
14673 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14674 (if (eq org-special-ctrl-a/e t)
14675 (if (or (< pos (match-beginning 1))
14676 (= pos (match-end 0)))
14677 (goto-char (match-beginning 1))
14678 (goto-char (match-end 0)))
14679 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14680 (goto-char (match-end 0))
14681 (goto-char (match-beginning 1))))
14682 (end-of-line arg))))
14683 (org-no-warnings
14684 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14687 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14688 (define-key org-mode-map "\C-e" 'org-end-of-line)
14690 (defun org-kill-line (&optional arg)
14691 "Kill line, to tags or end of line."
14692 (interactive "P")
14693 (cond
14694 ((or (not org-special-ctrl-k)
14695 (bolp)
14696 (not (org-on-heading-p)))
14697 (call-interactively 'kill-line))
14698 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14699 (kill-region (point) (match-beginning 1))
14700 (org-set-tags nil t))
14701 (t (kill-region (point) (point-at-eol)))))
14703 (define-key org-mode-map "\C-k" 'org-kill-line)
14705 (defun org-yank (&optional arg)
14706 "Yank. If the kill is a subtree, treat it specially.
14707 This command will look at the current kill and check if is a single
14708 subtree, or a series of subtrees[1]. If it passes the test, and if the
14709 cursor is at the beginning of a line or after the stars of a currently
14710 empty headline, then the yank is handled specially. How exactly depends
14711 on the value of the following variables, both set by default.
14713 org-yank-folded-subtrees
14714 When set, the subtree(s) will be folded after insertion, but only
14715 if doing so would now swallow text after the yanked text.
14717 org-yank-adjusted-subtrees
14718 When set, the subtree will be promoted or demoted in order to
14719 fit into the local outline tree structure, which means that the level
14720 will be adjusted so that it becomes the smaller one of the two
14721 *visible* surrounding headings.
14723 Any prefix to this command will cause `yank' to be called directly with
14724 no special treatment. In particular, a simple `C-u' prefix will just
14725 plainly yank the text as it is.
14727 \[1] Basically, the test checks if the first non-white line is a heading
14728 and if there are no other headings with fewer stars."
14729 (interactive "P")
14730 (setq this-command 'yank)
14731 (if arg
14732 (call-interactively 'yank)
14733 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14734 (and (org-kill-is-subtree-p)
14735 (or (bolp)
14736 (and (looking-at "[ \t]*$")
14737 (string-match
14738 "\\`\\*+\\'"
14739 (buffer-substring (point-at-bol) (point)))))))
14740 swallowp)
14741 (cond
14742 ((and subtreep org-yank-folded-subtrees)
14743 (let ((beg (point))
14744 end)
14745 (if (and subtreep org-yank-adjusted-subtrees)
14746 (org-paste-subtree nil nil 'for-yank)
14747 (call-interactively 'yank))
14748 (setq end (point))
14749 (goto-char beg)
14750 (when (and (bolp) subtreep
14751 (not (setq swallowp
14752 (org-yank-folding-would-swallow-text beg end))))
14753 (or (looking-at outline-regexp)
14754 (re-search-forward (concat "^" outline-regexp) end t))
14755 (while (and (< (point) end) (looking-at outline-regexp))
14756 (hide-subtree)
14757 (org-cycle-show-empty-lines 'folded)
14758 (condition-case nil
14759 (outline-forward-same-level 1)
14760 (error (goto-char end)))))
14761 (when swallowp
14762 (message
14763 "Yanked text not folded because that would swallow text"))
14764 (goto-char end)
14765 (skip-chars-forward " \t\n\r")
14766 (beginning-of-line 1)
14767 (push-mark beg 'nomsg)))
14768 ((and subtreep org-yank-adjusted-subtrees)
14769 (let ((beg (point-at-bol)))
14770 (org-paste-subtree nil nil 'for-yank)
14771 (push-mark beg 'nomsg)))
14773 (call-interactively 'yank))))))
14775 (defun org-yank-folding-would-swallow-text (beg end)
14776 "Would hide-subtree at BEG swallow any text after END?"
14777 (let (level)
14778 (save-excursion
14779 (goto-char beg)
14780 (when (or (looking-at outline-regexp)
14781 (re-search-forward (concat "^" outline-regexp) end t))
14782 (setq level (org-outline-level)))
14783 (goto-char end)
14784 (skip-chars-forward " \t\r\n\v\f")
14785 (if (or (eobp)
14786 (and (bolp) (looking-at org-outline-regexp)
14787 (<= (org-outline-level) level)))
14788 nil ; Nothing would be swallowed
14789 t)))) ; something would swallow
14791 (define-key org-mode-map "\C-y" 'org-yank)
14793 (defun org-invisible-p ()
14794 "Check if point is at a character currently not visible."
14795 ;; Early versions of noutline don't have `outline-invisible-p'.
14796 (if (fboundp 'outline-invisible-p)
14797 (outline-invisible-p)
14798 (get-char-property (point) 'invisible)))
14800 (defun org-invisible-p2 ()
14801 "Check if point is at a character currently not visible."
14802 (save-excursion
14803 (if (and (eolp) (not (bobp))) (backward-char 1))
14804 ;; Early versions of noutline don't have `outline-invisible-p'.
14805 (if (fboundp 'outline-invisible-p)
14806 (outline-invisible-p)
14807 (get-char-property (point) 'invisible))))
14809 (defun org-back-to-heading (&optional invisible-ok)
14810 "Call `outline-back-to-heading', but provide a better error message."
14811 (condition-case nil
14812 (outline-back-to-heading invisible-ok)
14813 (error (error "Before first headline at position %d in buffer %s"
14814 (point) (current-buffer)))))
14816 (defun org-before-first-heading-p ()
14817 "Before first heading?"
14818 (save-excursion
14819 (null (re-search-backward "^\\*+ " nil t))))
14821 (defalias 'org-on-heading-p 'outline-on-heading-p)
14822 (defalias 'org-at-heading-p 'outline-on-heading-p)
14823 (defun org-at-heading-or-item-p ()
14824 (or (org-on-heading-p) (org-at-item-p)))
14826 (defun org-on-target-p ()
14827 (or (org-in-regexp org-radio-target-regexp)
14828 (org-in-regexp org-target-regexp)))
14830 (defun org-up-heading-all (arg)
14831 "Move to the heading line of which the present line is a subheading.
14832 This function considers both visible and invisible heading lines.
14833 With argument, move up ARG levels."
14834 (if (fboundp 'outline-up-heading-all)
14835 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14836 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14838 (defun org-up-heading-safe ()
14839 "Move to the heading line of which the present line is a subheading.
14840 This version will not throw an error. It will return the level of the
14841 headline found, or nil if no higher level is found."
14842 (let (start-level re)
14843 (org-back-to-heading t)
14844 (setq start-level (funcall outline-level))
14845 (if (equal start-level 1)
14847 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14848 (if (re-search-backward re nil t)
14849 (funcall outline-level)))))
14851 (defun org-first-sibling-p ()
14852 "Is this heading the first child of its parents?"
14853 (interactive)
14854 (let ((re (concat "^" outline-regexp))
14855 level l)
14856 (unless (org-at-heading-p t)
14857 (error "Not at a heading"))
14858 (setq level (funcall outline-level))
14859 (save-excursion
14860 (if (not (re-search-backward re nil t))
14862 (setq l (funcall outline-level))
14863 (< l level)))))
14865 (defun org-goto-sibling (&optional previous)
14866 "Goto the next sibling, even if it is invisible.
14867 When PREVIOUS is set, go to the previous sibling instead. Returns t
14868 when a sibling was found. When none is found, return nil and don't
14869 move point."
14870 (let ((fun (if previous 're-search-backward 're-search-forward))
14871 (pos (point))
14872 (re (concat "^" outline-regexp))
14873 level l)
14874 (when (condition-case nil (org-back-to-heading t) (error nil))
14875 (setq level (funcall outline-level))
14876 (catch 'exit
14877 (or previous (forward-char 1))
14878 (while (funcall fun re nil t)
14879 (setq l (funcall outline-level))
14880 (when (< l level) (goto-char pos) (throw 'exit nil))
14881 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14882 (goto-char pos)
14883 nil))))
14885 (defun org-show-siblings ()
14886 "Show all siblings of the current headline."
14887 (save-excursion
14888 (while (org-goto-sibling) (org-flag-heading nil)))
14889 (save-excursion
14890 (while (org-goto-sibling 'previous)
14891 (org-flag-heading nil))))
14893 (defun org-show-hidden-entry ()
14894 "Show an entry where even the heading is hidden."
14895 (save-excursion
14896 (org-show-entry)))
14898 (defun org-flag-heading (flag &optional entry)
14899 "Flag the current heading. FLAG non-nil means make invisible.
14900 When ENTRY is non-nil, show the entire entry."
14901 (save-excursion
14902 (org-back-to-heading t)
14903 ;; Check if we should show the entire entry
14904 (if entry
14905 (progn
14906 (org-show-entry)
14907 (save-excursion
14908 (and (outline-next-heading)
14909 (org-flag-heading nil))))
14910 (outline-flag-region (max (point-min) (1- (point)))
14911 (save-excursion (outline-end-of-heading) (point))
14912 flag))))
14914 (defun org-forward-same-level (arg)
14915 "Move forward to the ARG'th subheading at same level as this one.
14916 Stop at the first and last subheadings of a superior heading.
14917 This is like outline-forward-same-level, but invisible headings are ok."
14918 (interactive "p")
14919 (org-back-to-heading t)
14920 (while (> arg 0)
14921 (let ((point-to-move-to (save-excursion
14922 (org-get-next-sibling))))
14923 (if point-to-move-to
14924 (progn
14925 (goto-char point-to-move-to)
14926 (setq arg (1- arg)))
14927 (progn
14928 (setq arg 0)
14929 (error "No following same-level heading"))))))
14931 (defun org-get-next-sibling ()
14932 "Move to next heading of the same level, and return point.
14933 If there is no such heading, return nil.
14934 This is like outline-next-sibling, but invisible headings are ok."
14935 (let ((level (funcall outline-level)))
14936 (outline-next-heading)
14937 (while (and (not (eobp)) (> (funcall outline-level) level))
14938 (outline-next-heading))
14939 (if (or (eobp) (< (funcall outline-level) level))
14941 (point))))
14943 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14944 ;; This is an exact copy of the original function, but it uses
14945 ;; `org-back-to-heading', to make it work also in invisible
14946 ;; trees. And is uses an invisible-OK argument.
14947 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14948 (org-back-to-heading invisible-OK)
14949 (let ((first t)
14950 (level (funcall outline-level)))
14951 (while (and (not (eobp))
14952 (or first (> (funcall outline-level) level)))
14953 (setq first nil)
14954 (outline-next-heading))
14955 (unless to-heading
14956 (if (memq (preceding-char) '(?\n ?\^M))
14957 (progn
14958 ;; Go to end of line before heading
14959 (forward-char -1)
14960 (if (memq (preceding-char) '(?\n ?\^M))
14961 ;; leave blank line before heading
14962 (forward-char -1))))))
14963 (point))
14965 (defun org-show-subtree ()
14966 "Show everything after this heading at deeper levels."
14967 (outline-flag-region
14968 (point)
14969 (save-excursion
14970 (outline-end-of-subtree) (outline-next-heading) (point))
14971 nil))
14973 (defun org-show-entry ()
14974 "Show the body directly following this heading.
14975 Show the heading too, if it is currently invisible."
14976 (interactive)
14977 (save-excursion
14978 (condition-case nil
14979 (progn
14980 (org-back-to-heading t)
14981 (outline-flag-region
14982 (max (point-min) (1- (point)))
14983 (save-excursion
14984 (re-search-forward
14985 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14986 (or (match-beginning 1) (point-max)))
14987 nil))
14988 (error nil))))
14990 (defun org-make-options-regexp (kwds)
14991 "Make a regular expression for keyword lines."
14992 (concat
14994 "#?[ \t]*\\+\\("
14995 (mapconcat 'regexp-quote kwds "\\|")
14996 "\\):[ \t]*"
14997 "\\(.+\\)"))
14999 ;; Make isearch reveal the necessary context
15000 (defun org-isearch-end ()
15001 "Reveal context after isearch exits."
15002 (when isearch-success ; only if search was successful
15003 (if (featurep 'xemacs)
15004 ;; Under XEmacs, the hook is run in the correct place,
15005 ;; we directly show the context.
15006 (org-show-context 'isearch)
15007 ;; In Emacs the hook runs *before* restoring the overlays.
15008 ;; So we have to use a one-time post-command-hook to do this.
15009 ;; (Emacs 22 has a special variable, see function `org-mode')
15010 (unless (and (boundp 'isearch-mode-end-hook-quit)
15011 isearch-mode-end-hook-quit)
15012 ;; Only when the isearch was not quitted.
15013 (org-add-hook 'post-command-hook 'org-isearch-post-command
15014 'append 'local)))))
15016 (defun org-isearch-post-command ()
15017 "Remove self from hook, and show context."
15018 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15019 (org-show-context 'isearch))
15022 ;;;; Integration with and fixes for other packages
15024 ;;; Imenu support
15026 (defvar org-imenu-markers nil
15027 "All markers currently used by Imenu.")
15028 (make-variable-buffer-local 'org-imenu-markers)
15030 (defun org-imenu-new-marker (&optional pos)
15031 "Return a new marker for use by Imenu, and remember the marker."
15032 (let ((m (make-marker)))
15033 (move-marker m (or pos (point)))
15034 (push m org-imenu-markers)
15037 (defun org-imenu-get-tree ()
15038 "Produce the index for Imenu."
15039 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15040 (setq org-imenu-markers nil)
15041 (let* ((n org-imenu-depth)
15042 (re (concat "^" outline-regexp))
15043 (subs (make-vector (1+ n) nil))
15044 (last-level 0)
15045 m level head)
15046 (save-excursion
15047 (save-restriction
15048 (widen)
15049 (goto-char (point-max))
15050 (while (re-search-backward re nil t)
15051 (setq level (org-reduced-level (funcall outline-level)))
15052 (when (<= level n)
15053 (looking-at org-complex-heading-regexp)
15054 (setq head (org-link-display-format
15055 (org-match-string-no-properties 4))
15056 m (org-imenu-new-marker))
15057 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15058 (if (>= level last-level)
15059 (push (cons head m) (aref subs level))
15060 (push (cons head (aref subs (1+ level))) (aref subs level))
15061 (loop for i from (1+ level) to n do (aset subs i nil)))
15062 (setq last-level level)))))
15063 (aref subs 1)))
15065 (eval-after-load "imenu"
15066 '(progn
15067 (add-hook 'imenu-after-jump-hook
15068 (lambda ()
15069 (if (eq major-mode 'org-mode)
15070 (org-show-context 'org-goto))))))
15072 (defun org-link-display-format (link)
15073 "Replace a link with either the description, or the link target
15074 if no description is present"
15075 (save-match-data
15076 (if (string-match org-bracket-link-analytic-regexp link)
15077 (replace-match (or (match-string 5 link)
15078 (concat (match-string 1 link)
15079 (match-string 3 link)))
15080 nil nil link)
15081 link)))
15083 ;; Speedbar support
15085 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15086 "Overlay marking the agenda restriction line in speedbar.")
15087 (org-overlay-put org-speedbar-restriction-lock-overlay
15088 'face 'org-agenda-restriction-lock)
15089 (org-overlay-put org-speedbar-restriction-lock-overlay
15090 'help-echo "Agendas are currently limited to this item.")
15091 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15093 (defun org-speedbar-set-agenda-restriction ()
15094 "Restrict future agenda commands to the location at point in speedbar.
15095 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15096 (interactive)
15097 (require 'org-agenda)
15098 (let (p m tp np dir txt)
15099 (cond
15100 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15101 'org-imenu t))
15102 (setq m (get-text-property p 'org-imenu-marker))
15103 (save-excursion
15104 (save-restriction
15105 (set-buffer (marker-buffer m))
15106 (goto-char m)
15107 (org-agenda-set-restriction-lock 'subtree))))
15108 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15109 'speedbar-function 'speedbar-find-file))
15110 (setq tp (previous-single-property-change
15111 (1+ p) 'speedbar-function)
15112 np (next-single-property-change
15113 tp 'speedbar-function)
15114 dir (speedbar-line-directory)
15115 txt (buffer-substring-no-properties (or tp (point-min))
15116 (or np (point-max))))
15117 (save-excursion
15118 (save-restriction
15119 (set-buffer (find-file-noselect
15120 (let ((default-directory dir))
15121 (expand-file-name txt))))
15122 (unless (org-mode-p)
15123 (error "Cannot restrict to non-Org-mode file"))
15124 (org-agenda-set-restriction-lock 'file))))
15125 (t (error "Don't know how to restrict Org-mode's agenda")))
15126 (org-move-overlay org-speedbar-restriction-lock-overlay
15127 (point-at-bol) (point-at-eol))
15128 (setq current-prefix-arg nil)
15129 (org-agenda-maybe-redo)))
15131 (eval-after-load "speedbar"
15132 '(progn
15133 (speedbar-add-supported-extension ".org")
15134 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15135 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15136 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15137 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15138 (add-hook 'speedbar-visiting-tag-hook
15139 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15142 ;;; Fixes and Hacks for problems with other packages
15144 ;; Make flyspell not check words in links, to not mess up our keymap
15145 (defun org-mode-flyspell-verify ()
15146 "Don't let flyspell put overlays at active buttons."
15147 (not (get-text-property (point) 'keymap)))
15149 ;; Make `bookmark-jump' show the jump location if it was hidden.
15150 (eval-after-load "bookmark"
15151 '(if (boundp 'bookmark-after-jump-hook)
15152 ;; We can use the hook
15153 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15154 ;; Hook not available, use advice
15155 (defadvice bookmark-jump (after org-make-visible activate)
15156 "Make the position visible."
15157 (org-bookmark-jump-unhide))))
15159 ;; Make sure saveplace show the location if it was hidden
15160 (eval-after-load "saveplace"
15161 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15162 "Make the position visible."
15163 (org-bookmark-jump-unhide)))
15165 (defun org-bookmark-jump-unhide ()
15166 "Unhide the current position, to show the bookmark location."
15167 (and (org-mode-p)
15168 (or (org-invisible-p)
15169 (save-excursion (goto-char (max (point-min) (1- (point))))
15170 (org-invisible-p)))
15171 (org-show-context 'bookmark-jump)))
15173 ;; Make session.el ignore our circular variable
15174 (eval-after-load "session"
15175 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15177 ;;;; Experimental code
15179 (defun org-closed-in-range ()
15180 "Sparse tree of items closed in a certain time range.
15181 Still experimental, may disappear in the future."
15182 (interactive)
15183 ;; Get the time interval from the user.
15184 (let* ((time1 (time-to-seconds
15185 (org-read-date nil 'to-time nil "Starting date: ")))
15186 (time2 (time-to-seconds
15187 (org-read-date nil 'to-time nil "End date:")))
15188 ;; callback function
15189 (callback (lambda ()
15190 (let ((time
15191 (time-to-seconds
15192 (apply 'encode-time
15193 (org-parse-time-string
15194 (match-string 1))))))
15195 ;; check if time in interval
15196 (and (>= time time1) (<= time time2))))))
15197 ;; make tree, check each match with the callback
15198 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15201 ;;;; Finish up
15203 (provide 'org)
15205 (run-hooks 'org-load-hook)
15207 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15209 ;;; org.el ends here