Bugfix: Avoid emphasis processing across lines and fields in tables.
[org-mode.git] / lisp / org.el
blobc33560eefd47045525bba53eec2d3b2128fde51a
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 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.17trans
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
89 (require 'org-list)
90 (require 'org-footnote)
92 ;;;; Customization variables
94 ;;; Version
96 (defconst org-version "6.17trans"
97 "The version number of the file org.el.")
99 (defun org-version (&optional here)
100 "Show the org-mode version in the echo area.
101 With prefix arg HERE, insert it at point."
102 (interactive "P")
103 (let ((version (format "Org-mode version %s" org-version)))
104 (message version)
105 (if here
106 (insert version))))
108 ;;; Compatibility constants
110 ;;; The custom variables
112 (defgroup org nil
113 "Outline-based notes management and organizer."
114 :tag "Org"
115 :group 'outlines
116 :group 'hypermedia
117 :group 'calendar)
119 (defcustom org-load-hook nil
120 "Hook that is run after org.el has been loaded."
121 :group 'org
122 :type 'hook)
124 (defvar org-modules) ; defined below
125 (defvar org-modules-loaded nil
126 "Have the modules been loaded already?")
128 (defun org-load-modules-maybe (&optional force)
129 "Load all extensions listed in `org-modules'."
130 (when (or force (not org-modules-loaded))
131 (mapc (lambda (ext)
132 (condition-case nil (require ext)
133 (error (message "Problems while trying to load feature `%s'" ext))))
134 org-modules)
135 (setq org-modules-loaded t)))
137 (defun org-set-modules (var value)
138 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
139 (set var value)
140 (when (featurep 'org)
141 (org-load-modules-maybe 'force)))
143 (when (org-bound-and-true-p org-modules)
144 (let ((a (member 'org-infojs org-modules)))
145 (and a (setcar a 'org-jsinfo))))
147 (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)
148 "Modules that should always be loaded together with org.el.
149 If a description starts with <C>, the file is not part of Emacs
150 and loading it will require that you have downloaded and properly installed
151 the org-mode distribution.
153 You can also use this system to load external packages (i.e. neither Org
154 core modules, not modules from the CONTRIB directory). Just add symbols
155 to the end of the list. If the package is called org-xyz.el, then you need
156 to add the symbol `xyz', and the package must have a call to
158 (provide 'org-xyz)"
159 :group 'org
160 :set 'org-set-modules
161 :type
162 '(set :greedy t
163 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
164 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
165 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
166 (const :tag " id: Global IDs for identifying entries" org-id)
167 (const :tag " info: Links to Info nodes" org-info)
168 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
169 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
170 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
171 (const :tag " mew Links to Mew folders/messages" org-mew)
172 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
173 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
174 (const :tag " vm: Links to VM folders/messages" org-vm)
175 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
176 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
177 (const :tag " mouse: Additional mouse support" org-mouse)
179 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
180 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
181 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
182 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
183 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
184 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
185 (const :tag "C eval: Include command output as text" org-eval)
186 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
187 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
188 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
189 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
190 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
191 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
192 (const :tag "C mtags: Support for muse-like tags" org-mtags)
193 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
194 (const :tag "C registry: A registry for Org links" org-registry)
195 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
196 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
197 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
198 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
199 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
202 (defgroup org-startup nil
203 "Options concerning startup of Org-mode."
204 :tag "Org Startup"
205 :group 'org)
207 (defcustom org-startup-folded t
208 "Non-nil means, entering Org-mode will switch to OVERVIEW.
209 This can also be configured on a per-file basis by adding one of
210 the following lines anywhere in the buffer:
212 #+STARTUP: fold
213 #+STARTUP: nofold
214 #+STARTUP: content"
215 :group 'org-startup
216 :type '(choice
217 (const :tag "nofold: show all" nil)
218 (const :tag "fold: overview" t)
219 (const :tag "content: all headlines" content)))
221 (defcustom org-startup-truncated t
222 "Non-nil means, entering Org-mode will set `truncate-lines'.
223 This is useful since some lines containing links can be very long and
224 uninteresting. Also tables look terrible when wrapped."
225 :group 'org-startup
226 :type 'boolean)
228 (defcustom org-startup-align-all-tables nil
229 "Non-nil means, align all tables when visiting a file.
230 This is useful when the column width in tables is forced with <N> cookies
231 in table fields. Such tables will look correct only after the first re-align.
232 This can also be configured on a per-file basis by adding one of
233 the following lines anywhere in the buffer:
234 #+STARTUP: align
235 #+STARTUP: noalign"
236 :group 'org-startup
237 :type 'boolean)
239 (defcustom org-insert-mode-line-in-empty-file nil
240 "Non-nil means insert the first line setting Org-mode in empty files.
241 When the function `org-mode' is called interactively in an empty file, this
242 normally means that the file name does not automatically trigger Org-mode.
243 To ensure that the file will always be in Org-mode in the future, a
244 line enforcing Org-mode will be inserted into the buffer, if this option
245 has been set."
246 :group 'org-startup
247 :type 'boolean)
249 (defcustom org-replace-disputed-keys nil
250 "Non-nil means use alternative key bindings for some keys.
251 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
252 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
253 If you want to use Org-mode together with one of these other modes,
254 or more generally if you would like to move some Org-mode commands to
255 other keys, set this variable and configure the keys with the variable
256 `org-disputed-keys'.
258 This option is only relevant at load-time of Org-mode, and must be set
259 *before* org.el is loaded. Changing it requires a restart of Emacs to
260 become effective."
261 :group 'org-startup
262 :type 'boolean)
264 (defcustom org-use-extra-keys nil
265 "Non-nil means use extra key sequence definitions for certain
266 commands. This happens automatically if you run XEmacs or if
267 window-system is nil. This variable lets you do the same
268 manually. You must set it before loading org.
270 Example: on Carbon Emacs 22 running graphically, with an external
271 keyboard on a Powerbook, the default way of setting M-left might
272 not work for either Alt or ESC. Setting this variable will make
273 it work for ESC."
274 :group 'org-startup
275 :type 'boolean)
277 (if (fboundp 'defvaralias)
278 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
280 (defcustom org-disputed-keys
281 '(([(shift up)] . [(meta p)])
282 ([(shift down)] . [(meta n)])
283 ([(shift left)] . [(meta -)])
284 ([(shift right)] . [(meta +)])
285 ([(control shift right)] . [(meta shift +)])
286 ([(control shift left)] . [(meta shift -)]))
287 "Keys for which Org-mode and other modes compete.
288 This is an alist, cars are the default keys, second element specifies
289 the alternative to use when `org-replace-disputed-keys' is t.
291 Keys can be specified in any syntax supported by `define-key'.
292 The value of this option takes effect only at Org-mode's startup,
293 therefore you'll have to restart Emacs to apply it after changing."
294 :group 'org-startup
295 :type 'alist)
297 (defun org-key (key)
298 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
299 Or return the original if not disputed."
300 (if org-replace-disputed-keys
301 (let* ((nkey (key-description key))
302 (x (org-find-if (lambda (x)
303 (equal (key-description (car x)) nkey))
304 org-disputed-keys)))
305 (if x (cdr x) key))
306 key))
308 (defun org-find-if (predicate seq)
309 (catch 'exit
310 (while seq
311 (if (funcall predicate (car seq))
312 (throw 'exit (car seq))
313 (pop seq)))))
315 (defun org-defkey (keymap key def)
316 "Define a key, possibly translated, as returned by `org-key'."
317 (define-key keymap (org-key key) def))
319 (defcustom org-ellipsis nil
320 "The ellipsis to use in the Org-mode outline.
321 When nil, just use the standard three dots. When a string, use that instead,
322 When a face, use the standard 3 dots, but with the specified face.
323 The change affects only Org-mode (which will then use its own display table).
324 Changing this requires executing `M-x org-mode' in a buffer to become
325 effective."
326 :group 'org-startup
327 :type '(choice (const :tag "Default" nil)
328 (face :tag "Face" :value org-warning)
329 (string :tag "String" :value "...#")))
331 (defvar org-display-table nil
332 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
334 (defgroup org-keywords nil
335 "Keywords in Org-mode."
336 :tag "Org Keywords"
337 :group 'org)
339 (defcustom org-deadline-string "DEADLINE:"
340 "String to mark deadline entries.
341 A deadline is this string, followed by a time stamp. Should be a word,
342 terminated by a colon. You can insert a schedule keyword and
343 a timestamp with \\[org-deadline].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
348 (defcustom org-scheduled-string "SCHEDULED:"
349 "String to mark scheduled TODO entries.
350 A schedule is this string, followed by a time stamp. Should be a word,
351 terminated by a colon. You can insert a schedule keyword and
352 a timestamp with \\[org-schedule].
353 Changes become only effective after restarting Emacs."
354 :group 'org-keywords
355 :type 'string)
357 (defcustom org-closed-string "CLOSED:"
358 "String used as the prefix for timestamps logging closing a TODO entry."
359 :group 'org-keywords
360 :type 'string)
362 (defcustom org-clock-string "CLOCK:"
363 "String used as prefix for timestamps clocking work hours on an item."
364 :group 'org-keywords
365 :type 'string)
367 (defcustom org-comment-string "COMMENT"
368 "Entries starting with this keyword will never be exported.
369 An entry can be toggled between COMMENT and normal with
370 \\[org-toggle-comment].
371 Changes become only effective after restarting Emacs."
372 :group 'org-keywords
373 :type 'string)
375 (defcustom org-quote-string "QUOTE"
376 "Entries starting with this keyword will be exported in fixed-width font.
377 Quoting applies only to the text in the entry following the headline, and does
378 not extend beyond the next headline, even if that is lower level.
379 An entry can be toggled between QUOTE and normal with
380 \\[org-toggle-fixed-width-section]."
381 :group 'org-keywords
382 :type 'string)
384 (defconst org-repeat-re
385 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
386 "Regular expression for specifying repeated events.
387 After a match, group 1 contains the repeat expression.")
389 (defgroup org-structure nil
390 "Options concerning the general structure of Org-mode files."
391 :tag "Org Structure"
392 :group 'org)
394 (defgroup org-reveal-location nil
395 "Options about how to make context of a location visible."
396 :tag "Org Reveal Location"
397 :group 'org-structure)
399 (defconst org-context-choice
400 '(choice
401 (const :tag "Always" t)
402 (const :tag "Never" nil)
403 (repeat :greedy t :tag "Individual contexts"
404 (cons
405 (choice :tag "Context"
406 (const agenda)
407 (const org-goto)
408 (const occur-tree)
409 (const tags-tree)
410 (const link-search)
411 (const mark-goto)
412 (const bookmark-jump)
413 (const isearch)
414 (const default))
415 (boolean))))
416 "Contexts for the reveal options.")
418 (defcustom org-show-hierarchy-above '((default . t))
419 "Non-nil means, show full hierarchy when revealing a location.
420 Org-mode often shows locations in an org-mode file which might have
421 been invisible before. When this is set, the hierarchy of headings
422 above the exposed location is shown.
423 Turning this off for example for sparse trees makes them very compact.
424 Instead of t, this can also be an alist specifying this option for different
425 contexts. Valid contexts are
426 agenda when exposing an entry from the agenda
427 org-goto when using the command `org-goto' on key C-c C-j
428 occur-tree when using the command `org-occur' on key C-c /
429 tags-tree when constructing a sparse tree based on tags matches
430 link-search when exposing search matches associated with a link
431 mark-goto when exposing the jump goal of a mark
432 bookmark-jump when exposing a bookmark location
433 isearch when exiting from an incremental search
434 default default for all contexts not set explicitly"
435 :group 'org-reveal-location
436 :type org-context-choice)
438 (defcustom org-show-following-heading '((default . nil))
439 "Non-nil means, show following heading when revealing a location.
440 Org-mode often shows locations in an org-mode file which might have
441 been invisible before. When this is set, the heading following the
442 match is shown.
443 Turning this off for example for sparse trees makes them very compact,
444 but makes it harder to edit the location of the match. In such a case,
445 use the command \\[org-reveal] to show more context.
446 Instead of t, this can also be an alist specifying this option for different
447 contexts. See `org-show-hierarchy-above' for valid contexts."
448 :group 'org-reveal-location
449 :type org-context-choice)
451 (defcustom org-show-siblings '((default . nil) (isearch t))
452 "Non-nil means, show all sibling heading when revealing a location.
453 Org-mode often shows locations in an org-mode file which might have
454 been invisible before. When this is set, the sibling of the current entry
455 heading are all made visible. If `org-show-hierarchy-above' is t,
456 the same happens on each level of the hierarchy above the current entry.
458 By default this is on for the isearch context, off for all other contexts.
459 Turning this off for example for sparse trees makes them very compact,
460 but makes it harder to edit the location of the match. In such a case,
461 use the command \\[org-reveal] to show more context.
462 Instead of t, this can also be an alist specifying this option for different
463 contexts. See `org-show-hierarchy-above' for valid contexts."
464 :group 'org-reveal-location
465 :type org-context-choice)
467 (defcustom org-show-entry-below '((default . nil))
468 "Non-nil means, show the entry below a headline when revealing a location.
469 Org-mode often shows locations in an org-mode file which might have
470 been invisible before. When this is set, the text below the headline that is
471 exposed is also shown.
473 By default this is off for all contexts.
474 Instead of t, this can also be an alist specifying this option for different
475 contexts. See `org-show-hierarchy-above' for valid contexts."
476 :group 'org-reveal-location
477 :type org-context-choice)
479 (defcustom org-indirect-buffer-display 'other-window
480 "How should indirect tree buffers be displayed?
481 This applies to indirect buffers created with the commands
482 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
483 Valid values are:
484 current-window Display in the current window
485 other-window Just display in another window.
486 dedicated-frame Create one new frame, and re-use it each time.
487 new-frame Make a new frame each time. Note that in this case
488 previously-made indirect buffers are kept, and you need to
489 kill these buffers yourself."
490 :group 'org-structure
491 :group 'org-agenda-windows
492 :type '(choice
493 (const :tag "In current window" current-window)
494 (const :tag "In current frame, other window" other-window)
495 (const :tag "Each time a new frame" new-frame)
496 (const :tag "One dedicated frame" dedicated-frame)))
498 (defgroup org-cycle nil
499 "Options concerning visibility cycling in Org-mode."
500 :tag "Org Cycle"
501 :group 'org-structure)
503 (defcustom org-drawers '("PROPERTIES" "CLOCK")
504 "Names of drawers. Drawers are not opened by cycling on the headline above.
505 Drawers only open with a TAB on the drawer line itself. A drawer looks like
506 this:
507 :DRAWERNAME:
508 .....
509 :END:
510 The drawer \"PROPERTIES\" is special for capturing properties through
511 the property API.
513 Drawers can be defined on the per-file basis with a line like:
515 #+DRAWERS: HIDDEN STATE PROPERTIES"
516 :group 'org-structure
517 :type '(repeat (string :tag "Drawer Name")))
519 (defcustom org-cycle-global-at-bob nil
520 "Cycle globally if cursor is at beginning of buffer and not at a headline.
521 This makes it possible to do global cycling without having to use S-TAB or
522 C-u TAB. For this special case to work, the first line of the buffer
523 must not be a headline - it may be empty ot some other text. When used in
524 this way, `org-cycle-hook' is disables temporarily, to make sure the
525 cursor stays at the beginning of the buffer.
526 When this option is nil, don't do anything special at the beginning
527 of the buffer."
528 :group 'org-cycle
529 :type 'boolean)
531 (defcustom org-cycle-emulate-tab t
532 "Where should `org-cycle' emulate TAB.
533 nil Never
534 white Only in completely white lines
535 whitestart Only at the beginning of lines, before the first non-white char
536 t Everywhere except in headlines
537 exc-hl-bol Everywhere except at the start of a headline
538 If TAB is used in a place where it does not emulate TAB, the current subtree
539 visibility is cycled."
540 :group 'org-cycle
541 :type '(choice (const :tag "Never" nil)
542 (const :tag "Only in completely white lines" white)
543 (const :tag "Before first char in a line" whitestart)
544 (const :tag "Everywhere except in headlines" t)
545 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
548 (defcustom org-cycle-separator-lines 2
549 "Number of empty lines needed to keep an empty line between collapsed trees.
550 If you leave an empty line between the end of a subtree and the following
551 headline, this empty line is hidden when the subtree is folded.
552 Org-mode will leave (exactly) one empty line visible if the number of
553 empty lines is equal or larger to the number given in this variable.
554 So the default 2 means, at least 2 empty lines after the end of a subtree
555 are needed to produce free space between a collapsed subtree and the
556 following headline.
558 Special case: when 0, never leave empty lines in collapsed view."
559 :group 'org-cycle
560 :type 'integer)
561 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
563 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
564 org-cycle-hide-drawers
565 org-cycle-show-empty-lines
566 org-optimize-window-after-visibility-change)
567 "Hook that is run after `org-cycle' has changed the buffer visibility.
568 The function(s) in this hook must accept a single argument which indicates
569 the new state that was set by the most recent `org-cycle' command. The
570 argument is a symbol. After a global state change, it can have the values
571 `overview', `content', or `all'. After a local state change, it can have
572 the values `folded', `children', or `subtree'."
573 :group 'org-cycle
574 :type 'hook)
576 (defgroup org-edit-structure nil
577 "Options concerning structure editing in Org-mode."
578 :tag "Org Edit Structure"
579 :group 'org-structure)
581 (defcustom org-odd-levels-only nil
582 "Non-nil means, skip even levels and only use odd levels for the outline.
583 This has the effect that two stars are being added/taken away in
584 promotion/demotion commands. It also influences how levels are
585 handled by the exporters.
586 Changing it requires restart of `font-lock-mode' to become effective
587 for fontification also in regions already fontified.
588 You may also set this on a per-file basis by adding one of the following
589 lines to the buffer:
591 #+STARTUP: odd
592 #+STARTUP: oddeven"
593 :group 'org-edit-structure
594 :group 'org-font-lock
595 :type 'boolean)
597 (defcustom org-adapt-indentation t
598 "Non-nil means, adapt indentation when promoting and demoting.
599 When this is set and the *entire* text in an entry is indented, the
600 indentation is increased by one space in a demotion command, and
601 decreased by one in a promotion command. If any line in the entry
602 body starts at column 0, indentation is not changed at all."
603 :group 'org-edit-structure
604 :type 'boolean)
606 (defcustom org-special-ctrl-a/e nil
607 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
608 When t, `C-a' will bring back the cursor to the beginning of the
609 headline text, i.e. after the stars and after a possible TODO keyword.
610 In an item, this will be the position after the bullet.
611 When the cursor is already at that position, another `C-a' will bring
612 it to the beginning of the line.
613 `C-e' will jump to the end of the headline, ignoring the presence of tags
614 in the headline. A second `C-e' will then jump to the true end of the
615 line, after any tags.
616 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
617 and only a directly following, identical keypress will bring the cursor
618 to the special positions."
619 :group 'org-edit-structure
620 :type '(choice
621 (const :tag "off" nil)
622 (const :tag "after bullet first" t)
623 (const :tag "border first" reversed)))
625 (if (fboundp 'defvaralias)
626 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
628 (defcustom org-special-ctrl-k nil
629 "Non-nil means `C-k' will behave specially in headlines.
630 When nil, `C-k' will call the default `kill-line' command.
631 When t, the following will happen while the cursor is in the headline:
633 - When the cursor is at the beginning of a headline, kill the entire
634 line and possible the folded subtree below the line.
635 - When in the middle of the headline text, kill the headline up to the tags.
636 - When after the headline text, kill the tags."
637 :group 'org-edit-structure
638 :type 'boolean)
640 (defcustom org-yank-folded-subtrees t
641 "Non-nil means, when yanking subtrees, fold them.
642 If the kill is a single subtree, or a sequence of subtrees, i.e. if
643 it starts with a heading and all other headings in it are either children
644 or siblings, then fold all the subtrees. However, do this only if no
645 text after the yank would be swallowed into a folded tree by this action."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defcustom org-yank-adjusted-subtrees t
650 "Non-nil means, when yanking subtrees, adjust the level.
651 With this setting, `org-paste-subtree' is used to insert the subtree, see
652 this function for details."
653 :group 'org-edit-structure
654 :type 'boolean)
656 (defcustom org-M-RET-may-split-line '((default . t))
657 "Non-nil means, M-RET will split the line at the cursor position.
658 When nil, it will go to the end of the line before making a
659 new line.
660 You may also set this option in a different way for different
661 contexts. Valid contexts are:
663 headline when creating a new headline
664 item when creating a new item
665 table in a table field
666 default the value to be used for all contexts not explicitly
667 customized"
668 :group 'org-structure
669 :group 'org-table
670 :type '(choice
671 (const :tag "Always" t)
672 (const :tag "Never" nil)
673 (repeat :greedy t :tag "Individual contexts"
674 (cons
675 (choice :tag "Context"
676 (const headline)
677 (const item)
678 (const table)
679 (const default))
680 (boolean)))))
683 (defcustom org-insert-heading-respect-content nil
684 "Non-nil means, insert new headings after the current subtree.
685 When nil, the new heading is created directly after the current line.
686 The commands \\[org-insert-heading-respect-content] and
687 \\[org-insert-todo-heading-respect-content] turn this variable on
688 for the duration of the command."
689 :group 'org-structure
690 :type 'boolean)
692 (defcustom org-blank-before-new-entry '((heading . auto)
693 (plain-list-item . auto))
694 "Should `org-insert-heading' leave a blank line before new heading/item?
695 The value is an alist, with `heading' and `plain-list-item' as car,
696 and a boolean flag as cdr."
697 :group 'org-edit-structure
698 :type '(list
699 (cons (const heading)
700 (choice (const :tag "Never" nil)
701 (const :tag "Always" t)
702 (const :tag "Auto" auto)))
703 (cons (const plain-list-item)
704 (choice (const :tag "Never" nil)
705 (const :tag "Always" t)
706 (const :tag "Auto" auto)))))
708 (defcustom org-insert-heading-hook nil
709 "Hook being run after inserting a new heading."
710 :group 'org-edit-structure
711 :type 'hook)
713 (defcustom org-enable-fixed-width-editor t
714 "Non-nil means, lines starting with \":\" are treated as fixed-width.
715 This currently only means, they are never auto-wrapped.
716 When nil, such lines will be treated like ordinary lines.
717 See also the QUOTE keyword."
718 :group 'org-edit-structure
719 :type 'boolean)
721 (defcustom org-edit-src-region-extra nil
722 "Additional regexps to identify regions for editing with `org-edit-src-code'.
723 For examples see the function `org-edit-src-find-region-and-lang'.
724 The regular expression identifying the begin marker should end with a newline,
725 and the regexp marking the end line should start with a newline, to make sure
726 there are kept outside the narrowed region."
727 :group 'org-edit-structure
728 :type '(repeat
729 (list
730 (regexp :tag "begin regexp")
731 (regexp :tag "end regexp")
732 (choice :tag "language"
733 (string :tag "specify")
734 (integer :tag "from match group")
735 (const :tag "from `lang' element")
736 (const :tag "from `style' element")))))
738 (defcustom org-coderef-label-format "(ref:%s)"
739 "The default coderef format.
740 This format string will be used to search for coderef labels in literal
741 examples (EXAMPLE and SRC blocks). The format can be overwritten
742 an individual literal example with the -f option, like
744 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
746 #+END_SRC
748 If you want to use this for HTML export, make sure that the format does
749 not introduce special font-locking, and avoid the HTML special
750 characters `<', `>', and `&'. The reason for this restriction is that
751 the labels are searched for only after htmlize has done its job."
752 :group 'org-edit-structure ; FIXME this is not in the right group
753 :type 'string)
755 (defcustom org-edit-fixed-width-region-mode 'artist-mode
756 "The mode that should be used to edit fixed-width regions.
757 These are the regions where each line starts with a colon."
758 :group 'org-edit-structure
759 :type '(choice
760 (const artist-mode)
761 (const picture-mode)
762 (const fundamental-mode)
763 (function :tag "Other (specify)")))
765 (defcustom org-goto-auto-isearch t
766 "Non-nil means, typing characters in org-goto starts incremental search."
767 :group 'org-edit-structure
768 :type 'boolean)
770 (defgroup org-sparse-trees nil
771 "Options concerning sparse trees in Org-mode."
772 :tag "Org Sparse Trees"
773 :group 'org-structure)
775 (defcustom org-highlight-sparse-tree-matches t
776 "Non-nil means, highlight all matches that define a sparse tree.
777 The highlights will automatically disappear the next time the buffer is
778 changed by an edit command."
779 :group 'org-sparse-trees
780 :type 'boolean)
782 (defcustom org-remove-highlights-with-change t
783 "Non-nil means, any change to the buffer will remove temporary highlights.
784 Such highlights are created by `org-occur' and `org-clock-display'.
785 When nil, `C-c C-c needs to be used to get rid of the highlights.
786 The highlights created by `org-preview-latex-fragment' always need
787 `C-c C-c' to be removed."
788 :group 'org-sparse-trees
789 :group 'org-time
790 :type 'boolean)
793 (defcustom org-occur-hook '(org-first-headline-recenter)
794 "Hook that is run after `org-occur' has constructed a sparse tree.
795 This can be used to recenter the window to show as much of the structure
796 as possible."
797 :group 'org-sparse-trees
798 :type 'hook)
800 (defgroup org-imenu-and-speedbar nil
801 "Options concerning imenu and speedbar in Org-mode."
802 :tag "Org Imenu and Speedbar"
803 :group 'org-structure)
805 (defcustom org-imenu-depth 2
806 "The maximum level for Imenu access to Org-mode headlines.
807 This also applied for speedbar access."
808 :group 'org-imenu-and-speedbar
809 :type 'number)
811 (defgroup org-table nil
812 "Options concerning tables in Org-mode."
813 :tag "Org Table"
814 :group 'org)
816 (defcustom org-enable-table-editor 'optimized
817 "Non-nil means, lines starting with \"|\" are handled by the table editor.
818 When nil, such lines will be treated like ordinary lines.
820 When equal to the symbol `optimized', the table editor will be optimized to
821 do the following:
822 - Automatic overwrite mode in front of whitespace in table fields.
823 This makes the structure of the table stay in tact as long as the edited
824 field does not exceed the column width.
825 - Minimize the number of realigns. Normally, the table is aligned each time
826 TAB or RET are pressed to move to another field. With optimization this
827 happens only if changes to a field might have changed the column width.
828 Optimization requires replacing the functions `self-insert-command',
829 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
830 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
831 very good at guessing when a re-align will be necessary, but you can always
832 force one with \\[org-ctrl-c-ctrl-c].
834 If you would like to use the optimized version in Org-mode, but the
835 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
837 This variable can be used to turn on and off the table editor during a session,
838 but in order to toggle optimization, a restart is required.
840 See also the variable `org-table-auto-blank-field'."
841 :group 'org-table
842 :type '(choice
843 (const :tag "off" nil)
844 (const :tag "on" t)
845 (const :tag "on, optimized" optimized)))
847 (defcustom org-table-tab-recognizes-table.el t
848 "Non-nil means, TAB will automatically notice a table.el table.
849 When it sees such a table, it moves point into it and - if necessary -
850 calls `table-recognize-table'."
851 :group 'org-table-editing
852 :type 'boolean)
854 (defgroup org-link nil
855 "Options concerning links in Org-mode."
856 :tag "Org Link"
857 :group 'org)
859 (defvar org-link-abbrev-alist-local nil
860 "Buffer-local version of `org-link-abbrev-alist', which see.
861 The value of this is taken from the #+LINK lines.")
862 (make-variable-buffer-local 'org-link-abbrev-alist-local)
864 (defcustom org-link-abbrev-alist nil
865 "Alist of link abbreviations.
866 The car of each element is a string, to be replaced at the start of a link.
867 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
868 links in Org-mode buffers can have an optional tag after a double colon, e.g.
870 [[linkkey:tag][description]]
872 If REPLACE is a string, the tag will simply be appended to create the link.
873 If the string contains \"%s\", the tag will be inserted there. Alternatively,
874 the placeholder \"%h\" will cause a url-encoded version of the tag to
875 be inserted at that point (see the function `url-hexify-string').
877 REPLACE may also be a function that will be called with the tag as the
878 only argument to create the link, which should be returned as a string.
880 See the manual for examples."
881 :group 'org-link
882 :type '(repeat
883 (cons
884 (string :tag "Protocol")
885 (choice
886 (string :tag "Format")
887 (function)))))
889 (defcustom org-descriptive-links t
890 "Non-nil means, hide link part and only show description of bracket links.
891 Bracket links are like [[link][description]]. This variable sets the initial
892 state in new org-mode buffers. The setting can then be toggled on a
893 per-buffer basis from the Org->Hyperlinks menu."
894 :group 'org-link
895 :type 'boolean)
897 (defcustom org-link-file-path-type 'adaptive
898 "How the path name in file links should be stored.
899 Valid values are:
901 relative Relative to the current directory, i.e. the directory of the file
902 into which the link is being inserted.
903 absolute Absolute path, if possible with ~ for home directory.
904 noabbrev Absolute path, no abbreviation of home directory.
905 adaptive Use relative path for files in the current directory and sub-
906 directories of it. For other files, use an absolute path."
907 :group 'org-link
908 :type '(choice
909 (const relative)
910 (const absolute)
911 (const noabbrev)
912 (const adaptive)))
914 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
915 "Types of links that should be activated in Org-mode files.
916 This is a list of symbols, each leading to the activation of a certain link
917 type. In principle, it does not hurt to turn on most link types - there may
918 be a small gain when turning off unused link types. The types are:
920 bracket The recommended [[link][description]] or [[link]] links with hiding.
921 angular Links in angular brackets that may contain whitespace like
922 <bbdb:Carsten Dominik>.
923 plain Plain links in normal text, no whitespace, like http://google.com.
924 radio Text that is matched by a radio target, see manual for details.
925 tag Tag settings in a headline (link to tag search).
926 date Time stamps (link to calendar).
927 footnote Footnote labels.
929 Changing this variable requires a restart of Emacs to become effective."
930 :group 'org-link
931 :type '(set :greedy t
932 (const :tag "Double bracket links (new style)" bracket)
933 (const :tag "Angular bracket links (old style)" angular)
934 (const :tag "Plain text links" plain)
935 (const :tag "Radio target matches" radio)
936 (const :tag "Tags" tag)
937 (const :tag "Timestamps" date)
938 (const :tag "Footnotes" footnote)))
940 (defcustom org-make-link-description-function nil
941 "Function to use to generate link descriptions from links. If
942 nil the link location will be used. This function must take two
943 parameters; the first is the link and the second the description
944 org-insert-link has generated, and should return the description
945 to use."
946 :group 'org-link
947 :type 'function)
949 (defgroup org-link-store nil
950 "Options concerning storing links in Org-mode."
951 :tag "Org Store Link"
952 :group 'org-link)
954 (defcustom org-email-link-description-format "Email %c: %.30s"
955 "Format of the description part of a link to an email or usenet message.
956 The following %-escapes will be replaced by corresponding information:
958 %F full \"From\" field
959 %f name, taken from \"From\" field, address if no name
960 %T full \"To\" field
961 %t first name in \"To\" field, address if no name
962 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
963 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
964 %s subject
965 %m message-id.
967 You may use normal field width specification between the % and the letter.
968 This is for example useful to limit the length of the subject.
970 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
971 :group 'org-link-store
972 :type 'string)
974 (defcustom org-from-is-user-regexp
975 (let (r1 r2)
976 (when (and user-mail-address (not (string= user-mail-address "")))
977 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
978 (when (and user-full-name (not (string= user-full-name "")))
979 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
980 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
981 "Regexp matched against the \"From:\" header of an email or usenet message.
982 It should match if the message is from the user him/herself."
983 :group 'org-link-store
984 :type 'regexp)
986 (defcustom org-link-to-org-use-id 'create-if-interactive
987 "Non-nil means, storing a link to an Org file will use entry IDs.
989 Note that before this variable is even considered, org-id must be loaded,
990 to please customize `org-modules' and turn it on.
992 The variable can have the following values:
994 t Create an ID if needed to make a link to the current entry.
996 create-if-interactive
997 If `org-store-link' is called directly (interactively, as a user
998 command), do create an ID to support the link. But when doing the
999 job for remember, only use the ID if it already exists. The
1000 purpose of this setting is to avoid proliferation of unwanted
1001 IDs, just because you happen to be in an Org file when you
1002 call `org-remember' that automatically and preemptively
1003 creates a link. If you do want to get an ID link in a remember
1004 template to an entry not having an ID, create it first by
1005 explicitly creating a link to it, using `C-c C-l' first.
1007 use-existing
1008 Use existing ID, do not create one.
1010 nil Never use an ID to make a link, instead link using a text search for
1011 the headline text."
1012 :group 'org-link-store
1013 :type '(choice
1014 (const :tag "Create ID to make link" t)
1015 (const :tag "Create if string link interactively"
1016 'create-if-interactive)
1017 (const :tag "Only use existing" 'use-existing)
1018 (const :tag "Do not use ID to create link" nil)))
1020 (defcustom org-context-in-file-links t
1021 "Non-nil means, file links from `org-store-link' contain context.
1022 A search string will be added to the file name with :: as separator and
1023 used to find the context when the link is activated by the command
1024 `org-open-at-point'.
1025 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1026 negates this setting for the duration of the command."
1027 :group 'org-link-store
1028 :type 'boolean)
1030 (defcustom org-keep-stored-link-after-insertion nil
1031 "Non-nil means, keep link in list for entire session.
1033 The command `org-store-link' adds a link pointing to the current
1034 location to an internal list. These links accumulate during a session.
1035 The command `org-insert-link' can be used to insert links into any
1036 Org-mode file (offering completion for all stored links). When this
1037 option is nil, every link which has been inserted once using \\[org-insert-link]
1038 will be removed from the list, to make completing the unused links
1039 more efficient."
1040 :group 'org-link-store
1041 :type 'boolean)
1043 (defgroup org-link-follow nil
1044 "Options concerning following links in Org-mode."
1045 :tag "Org Follow Link"
1046 :group 'org-link)
1048 (defcustom org-link-translation-function nil
1049 "Function to translate links with different syntax to Org syntax.
1050 This can be used to translate links created for example by the Planner
1051 or emacs-wiki packages to Org syntax.
1052 The function must accept two parameters, a TYPE containing the link
1053 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1054 which is everything after the link protocol. It should return a cons
1055 with possibly modified values of type and path.
1056 Org contains a function for this, so if you set this variable to
1057 `org-translate-link-from-planner', you should be able follow many
1058 links created by planner."
1059 :group 'org-link-follow
1060 :type 'function)
1062 (defcustom org-follow-link-hook nil
1063 "Hook that is run after a link has been followed."
1064 :group 'org-link-follow
1065 :type 'hook)
1067 (defcustom org-tab-follows-link nil
1068 "Non-nil means, on links TAB will follow the link.
1069 Needs to be set before org.el is loaded."
1070 :group 'org-link-follow
1071 :type 'boolean)
1073 (defcustom org-return-follows-link nil
1074 "Non-nil means, on links RET will follow the link.
1075 Needs to be set before org.el is loaded."
1076 :group 'org-link-follow
1077 :type 'boolean)
1079 (defcustom org-mouse-1-follows-link
1080 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1081 "Non-nil means, mouse-1 on a link will follow the link.
1082 A longer mouse click will still set point. Does not work on XEmacs.
1083 Needs to be set before org.el is loaded."
1084 :group 'org-link-follow
1085 :type 'boolean)
1087 (defcustom org-mark-ring-length 4
1088 "Number of different positions to be recorded in the ring
1089 Changing this requires a restart of Emacs to work correctly."
1090 :group 'org-link-follow
1091 :type 'integer)
1093 (defcustom org-link-frame-setup
1094 '((vm . vm-visit-folder-other-frame)
1095 (gnus . gnus-other-frame)
1096 (file . find-file-other-window))
1097 "Setup the frame configuration for following links.
1098 When following a link with Emacs, it may often be useful to display
1099 this link in another window or frame. This variable can be used to
1100 set this up for the different types of links.
1101 For VM, use any of
1102 `vm-visit-folder'
1103 `vm-visit-folder-other-frame'
1104 For Gnus, use any of
1105 `gnus'
1106 `gnus-other-frame'
1107 `org-gnus-no-new-news'
1108 For FILE, use any of
1109 `find-file'
1110 `find-file-other-window'
1111 `find-file-other-frame'
1112 For the calendar, use the variable `calendar-setup'.
1113 For BBDB, it is currently only possible to display the matches in
1114 another window."
1115 :group 'org-link-follow
1116 :type '(list
1117 (cons (const vm)
1118 (choice
1119 (const vm-visit-folder)
1120 (const vm-visit-folder-other-window)
1121 (const vm-visit-folder-other-frame)))
1122 (cons (const gnus)
1123 (choice
1124 (const gnus)
1125 (const gnus-other-frame)
1126 (const org-gnus-no-new-news)))
1127 (cons (const file)
1128 (choice
1129 (const find-file)
1130 (const find-file-other-window)
1131 (const find-file-other-frame)))))
1133 (defcustom org-display-internal-link-with-indirect-buffer nil
1134 "Non-nil means, use indirect buffer to display infile links.
1135 Activating internal links (from one location in a file to another location
1136 in the same file) normally just jumps to the location. When the link is
1137 activated with a C-u prefix (or with mouse-3), the link is displayed in
1138 another window. When this option is set, the other window actually displays
1139 an indirect buffer clone of the current buffer, to avoid any visibility
1140 changes to the current buffer."
1141 :group 'org-link-follow
1142 :type 'boolean)
1144 (defcustom org-open-non-existing-files nil
1145 "Non-nil means, `org-open-file' will open non-existing files.
1146 When nil, an error will be generated."
1147 :group 'org-link-follow
1148 :type 'boolean)
1150 (defcustom org-open-directory-means-index-dot-org nil
1151 "Non-nil means, a link to a directory really means to index.org.
1152 When nil, following a directory link will run dired or open a finder/explorer
1153 window on that directory."
1154 :group 'org-link-follow
1155 :type 'boolean)
1157 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1158 "Function and arguments to call for following mailto links.
1159 This is a list with the first element being a lisp function, and the
1160 remaining elements being arguments to the function. In string arguments,
1161 %a will be replaced by the address, and %s will be replaced by the subject
1162 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1163 :group 'org-link-follow
1164 :type '(choice
1165 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1166 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1167 (const :tag "message-mail" (message-mail "%a" "%s"))
1168 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1170 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1171 "Non-nil means, ask for confirmation before executing shell links.
1172 Shell links can be dangerous: just think about a link
1174 [[shell:rm -rf ~/*][Google Search]]
1176 This link would show up in your Org-mode document as \"Google Search\",
1177 but really it would remove your entire home directory.
1178 Therefore we advise against setting this variable to nil.
1179 Just change it to `y-or-n-p' of you want to confirm with a
1180 single keystroke rather than having to type \"yes\"."
1181 :group 'org-link-follow
1182 :type '(choice
1183 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1184 (const :tag "with y-or-n (faster)" y-or-n-p)
1185 (const :tag "no confirmation (dangerous)" nil)))
1187 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1188 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1189 Elisp links can be dangerous: just think about a link
1191 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1193 This link would show up in your Org-mode document as \"Google Search\",
1194 but really it would remove your entire home directory.
1195 Therefore we advise against setting this variable to nil.
1196 Just change it to `y-or-n-p' of you want to confirm with a
1197 single keystroke rather than having to type \"yes\"."
1198 :group 'org-link-follow
1199 :type '(choice
1200 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1201 (const :tag "with y-or-n (faster)" y-or-n-p)
1202 (const :tag "no confirmation (dangerous)" nil)))
1204 (defconst org-file-apps-defaults-gnu
1205 '((remote . emacs)
1206 (system . mailcap)
1207 (t . mailcap))
1208 "Default file applications on a UNIX or GNU/Linux system.
1209 See `org-file-apps'.")
1211 (defconst org-file-apps-defaults-macosx
1212 '((remote . emacs)
1213 (t . "open %s")
1214 (system . "open %s")
1215 ("ps.gz" . "gv %s")
1216 ("eps.gz" . "gv %s")
1217 ("dvi" . "xdvi %s")
1218 ("fig" . "xfig %s"))
1219 "Default file applications on a MacOS X system.
1220 The system \"open\" is known as a default, but we use X11 applications
1221 for some files for which the OS does not have a good default.
1222 See `org-file-apps'.")
1224 (defconst org-file-apps-defaults-windowsnt
1225 (list
1226 '(remote . emacs)
1227 (cons t
1228 (list (if (featurep 'xemacs)
1229 'mswindows-shell-execute
1230 'w32-shell-execute)
1231 "open" 'file))
1232 (cons 'system
1233 (list (if (featurep 'xemacs)
1234 'mswindows-shell-execute
1235 'w32-shell-execute)
1236 "open" 'file)))
1237 "Default file applications on a Windows NT system.
1238 The system \"open\" is used for most files.
1239 See `org-file-apps'.")
1241 (defcustom org-file-apps
1243 (auto-mode . emacs)
1244 ("\\.x?html?\\'" . default)
1245 ("\\.pdf\\'" . default)
1247 "External applications for opening `file:path' items in a document.
1248 Org-mode uses system defaults for different file types, but
1249 you can use this variable to set the application for a given file
1250 extension. The entries in this list are cons cells where the car identifies
1251 files and the cdr the corresponding command. Possible values for the
1252 file identifier are
1253 \"regex\" Regular expression matched against the file name. For backward
1254 compatibility, this can also be a string with only alphanumeric
1255 characters, which is then interpreted as an extension.
1256 `directory' Matches a directory
1257 `remote' Matches a remote file, accessible through tramp or efs.
1258 Remote files most likely should be visited through Emacs
1259 because external applications cannot handle such paths.
1260 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1261 so all files Emacs knows how to handle. Using this with
1262 command `emacs' will open most files in Emacs. Beware that this
1263 will also open html files inside Emacs, unless you add
1264 (\"html\" . default) to the list as well.
1265 t Default for files not matched by any of the other options.
1266 `system' The system command to open files, like `open' on Windows
1267 and Mac OS X, and mailcap under GNU/Linux. This is the command
1268 that will be selected if you call `C-c C-o' with a double
1269 `C-u C-u' prefix.
1271 Possible values for the command are:
1272 `emacs' The file will be visited by the current Emacs process.
1273 `default' Use the default application for this file type, which is the
1274 association for t in the list, most likely in the system-specific
1275 part.
1276 This can be used to overrule an unwanted setting in the
1277 system-specific variable.
1278 `system' Use the system command for opening files, like \"open\".
1279 This command is specified by the entry whose car is `system'.
1280 Most likely, the system-specific version of this variable
1281 does define this command, but you can overrule/replace it
1282 here.
1283 string A command to be executed by a shell; %s will be replaced
1284 by the path to the file.
1285 sexp A Lisp form which will be evaluated. The file path will
1286 be available in the Lisp variable `file'.
1287 For more examples, see the system specific constants
1288 `org-file-apps-defaults-macosx'
1289 `org-file-apps-defaults-windowsnt'
1290 `org-file-apps-defaults-gnu'."
1291 :group 'org-link-follow
1292 :type '(repeat
1293 (cons (choice :value ""
1294 (string :tag "Extension")
1295 (const :tag "System command to open files" system)
1296 (const :tag "Default for unrecognized files" t)
1297 (const :tag "Remote file" remote)
1298 (const :tag "Links to a directory" directory)
1299 (const :tag "Any files that have Emacs modes"
1300 auto-mode))
1301 (choice :value ""
1302 (const :tag "Visit with Emacs" emacs)
1303 (const :tag "Use default" default)
1304 (const :tag "Use the system command" system)
1305 (string :tag "Command")
1306 (sexp :tag "Lisp form")))))
1308 (defgroup org-refile nil
1309 "Options concerning refiling entries in Org-mode."
1310 :tag "Org Refile"
1311 :group 'org)
1313 (defcustom org-directory "~/org"
1314 "Directory with org files.
1315 This directory will be used as default to prompt for org files.
1316 Used by the hooks for remember.el."
1317 :group 'org-refile
1318 :group 'org-remember
1319 :type 'directory)
1321 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1322 "Default target for storing notes.
1323 Used by the hooks for remember.el. This can be a string, or nil to mean
1324 the value of `remember-data-file'.
1325 You can set this on a per-template basis with the variable
1326 `org-remember-templates'."
1327 :group 'org-refile
1328 :group 'org-remember
1329 :type '(choice
1330 (const :tag "Default from remember-data-file" nil)
1331 file))
1333 (defcustom org-goto-interface 'outline
1334 "The default interface to be used for `org-goto'.
1335 Allowed values are:
1336 outline The interface shows an outline of the relevant file
1337 and the correct heading is found by moving through
1338 the outline or by searching with incremental search.
1339 outline-path-completion Headlines in the current buffer are offered via
1340 completion. This is the interface also used by
1341 the refile command."
1342 :group 'org-refile
1343 :type '(choice
1344 (const :tag "Outline" outline)
1345 (const :tag "Outline-path-completion" outline-path-completion)))
1347 (defcustom org-goto-max-level 5
1348 "Maximum level to be considered when running org-goto with refile interface."
1349 :group 'org-refile
1350 :type 'number)
1352 (defcustom org-reverse-note-order nil
1353 "Non-nil means, store new notes at the beginning of a file or entry.
1354 When nil, new notes will be filed to the end of a file or entry.
1355 This can also be a list with cons cells of regular expressions that
1356 are matched against file names, and values."
1357 :group 'org-remember
1358 :group 'org-refile
1359 :type '(choice
1360 (const :tag "Reverse always" t)
1361 (const :tag "Reverse never" nil)
1362 (repeat :tag "By file name regexp"
1363 (cons regexp boolean))))
1365 (defcustom org-refile-targets nil
1366 "Targets for refiling entries with \\[org-refile].
1367 This is list of cons cells. Each cell contains:
1368 - a specification of the files to be considered, either a list of files,
1369 or a symbol whose function or variable value will be used to retrieve
1370 a file name or a list of file names. If you use `org-agenda-files' for
1371 that, all agenda files will be scanned for targets. Nil means, consider
1372 headings in the current buffer.
1373 - A specification of how to select find candidate refile targets. This
1374 may be any of
1375 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1376 This tag has to be present in all target headlines, inheritance will
1377 not be considered.
1378 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1379 todo keyword.
1380 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1381 headlines that are refiling targets.
1382 - a cons cell (:level . N). Any headline of level N is considered a target.
1383 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1385 When this variable is nil, all top-level headlines in the current buffer
1386 are used, equivalent to the value `((nil . (:level . 1))'."
1387 :group 'org-refile
1388 :type '(repeat
1389 (cons
1390 (choice :value org-agenda-files
1391 (const :tag "All agenda files" org-agenda-files)
1392 (const :tag "Current buffer" nil)
1393 (function) (variable) (file))
1394 (choice :tag "Identify target headline by"
1395 (cons :tag "Specific tag" (const :value :tag) (string))
1396 (cons :tag "TODO keyword" (const :value :todo) (string))
1397 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1398 (cons :tag "Level number" (const :value :level) (integer))
1399 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1401 (defcustom org-refile-use-outline-path nil
1402 "Non-nil means, provide refile targets as paths.
1403 So a level 3 headline will be available as level1/level2/level3.
1404 When the value is `file', also include the file name (without directory)
1405 into the path. When `full-file-path', include the full file path."
1406 :group 'org-refile
1407 :type '(choice
1408 (const :tag "Not" nil)
1409 (const :tag "Yes" t)
1410 (const :tag "Start with file name" file)
1411 (const :tag "Start with full file path" full-file-path)))
1413 (defcustom org-outline-path-complete-in-steps t
1414 "Non-nil means, complete the outline path in hierarchical steps.
1415 When Org-mode uses the refile interface to select an outline path
1416 \(see variable `org-refile-use-outline-path'), the completion of
1417 the path can be done is a single go, or if can be done in steps down
1418 the headline hierarchy. Going in steps is probably the best if you
1419 do not use a special completion package like `ido' or `icicles'.
1420 However, when using these packages, going in one step can be very
1421 fast, while still showing the whole path to the entry."
1422 :group 'org-refile
1423 :type 'boolean)
1425 (defgroup org-todo nil
1426 "Options concerning TODO items in Org-mode."
1427 :tag "Org TODO"
1428 :group 'org)
1430 (defgroup org-progress nil
1431 "Options concerning Progress logging in Org-mode."
1432 :tag "Org Progress"
1433 :group 'org-time)
1435 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1436 "List of TODO entry keyword sequences and their interpretation.
1437 \\<org-mode-map>This is a list of sequences.
1439 Each sequence starts with a symbol, either `sequence' or `type',
1440 indicating if the keywords should be interpreted as a sequence of
1441 action steps, or as different types of TODO items. The first
1442 keywords are states requiring action - these states will select a headline
1443 for inclusion into the global TODO list Org-mode produces. If one of
1444 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1445 signify that no further action is necessary. If \"|\" is not found,
1446 the last keyword is treated as the only DONE state of the sequence.
1448 The command \\[org-todo] cycles an entry through these states, and one
1449 additional state where no keyword is present. For details about this
1450 cycling, see the manual.
1452 TODO keywords and interpretation can also be set on a per-file basis with
1453 the special #+SEQ_TODO and #+TYP_TODO lines.
1455 Each keyword can optionally specify a character for fast state selection
1456 \(in combination with the variable `org-use-fast-todo-selection')
1457 and specifiers for state change logging, using the same syntax
1458 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1459 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1460 indicates to record a time stamp each time this state is selected.
1462 Each keyword may also specify if a timestamp or a note should be
1463 recorded when entering or leaving the state, by adding additional
1464 characters in the parenthesis after the keyword. This looks like this:
1465 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1466 record only the time of the state change. With X and Y being either
1467 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1468 Y when leaving the state if and only if the *target* state does not
1469 define X. You may omit any of the fast-selection key or X or /Y,
1470 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1472 For backward compatibility, this variable may also be just a list
1473 of keywords - in this case the interpretation (sequence or type) will be
1474 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1475 :group 'org-todo
1476 :group 'org-keywords
1477 :type '(choice
1478 (repeat :tag "Old syntax, just keywords"
1479 (string :tag "Keyword"))
1480 (repeat :tag "New syntax"
1481 (cons
1482 (choice
1483 :tag "Interpretation"
1484 (const :tag "Sequence (cycling hits every state)" sequence)
1485 (const :tag "Type (cycling directly to DONE)" type))
1486 (repeat
1487 (string :tag "Keyword"))))))
1489 (defvar org-todo-keywords-1 nil
1490 "All TODO and DONE keywords active in a buffer.")
1491 (make-variable-buffer-local 'org-todo-keywords-1)
1492 (defvar org-todo-keywords-for-agenda nil)
1493 (defvar org-done-keywords-for-agenda nil)
1494 (defvar org-todo-keyword-alist-for-agenda nil)
1495 (defvar org-tag-alist-for-agenda nil)
1496 (defvar org-agenda-contributing-files nil)
1497 (defvar org-not-done-keywords nil)
1498 (make-variable-buffer-local 'org-not-done-keywords)
1499 (defvar org-done-keywords nil)
1500 (make-variable-buffer-local 'org-done-keywords)
1501 (defvar org-todo-heads nil)
1502 (make-variable-buffer-local 'org-todo-heads)
1503 (defvar org-todo-sets nil)
1504 (make-variable-buffer-local 'org-todo-sets)
1505 (defvar org-todo-log-states nil)
1506 (make-variable-buffer-local 'org-todo-log-states)
1507 (defvar org-todo-kwd-alist nil)
1508 (make-variable-buffer-local 'org-todo-kwd-alist)
1509 (defvar org-todo-key-alist nil)
1510 (make-variable-buffer-local 'org-todo-key-alist)
1511 (defvar org-todo-key-trigger nil)
1512 (make-variable-buffer-local 'org-todo-key-trigger)
1514 (defcustom org-todo-interpretation 'sequence
1515 "Controls how TODO keywords are interpreted.
1516 This variable is in principle obsolete and is only used for
1517 backward compatibility, if the interpretation of todo keywords is
1518 not given already in `org-todo-keywords'. See that variable for
1519 more information."
1520 :group 'org-todo
1521 :group 'org-keywords
1522 :type '(choice (const sequence)
1523 (const type)))
1525 (defcustom org-use-fast-todo-selection 'prefix
1526 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1527 This variable describes if and under what circumstances the cycling
1528 mechanism for TODO keywords will be replaced by a single-key, direct
1529 selection scheme.
1531 When nil, fast selection is never used.
1533 When the symbol `prefix', it will be used when `org-todo' is called with
1534 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1535 in an agenda buffer.
1537 When t, fast selection is used by default. In this case, the prefix
1538 argument forces cycling instead.
1540 In all cases, the special interface is only used if access keys have actually
1541 been assigned by the user, i.e. if keywords in the configuration are followed
1542 by a letter in parenthesis, like TODO(t)."
1543 :group 'org-todo
1544 :type '(choice
1545 (const :tag "Never" nil)
1546 (const :tag "By default" t)
1547 (const :tag "Only with C-u C-c C-t" prefix)))
1549 (defcustom org-provide-todo-statistics t
1550 "Non-nil means, update todo statistics after insert and toggle.
1551 When this is set, todo statistics is updated in the parent of the current
1552 entry each time a todo state is changed."
1553 :group 'org-todo
1554 :type 'boolean)
1556 (defcustom org-after-todo-state-change-hook nil
1557 "Hook which is run after the state of a TODO item was changed.
1558 The new state (a string with a TODO keyword, or nil) is available in the
1559 Lisp variable `state'."
1560 :group 'org-todo
1561 :type 'hook)
1563 (defcustom org-todo-state-tags-triggers nil
1564 "Tag changes that should be triggered by TODO state changes.
1565 This is a list. Each entry is
1567 (state-change (tag . flag) .......)
1569 State-change can be a string with a state, and empty string to indicate the
1570 state that has no TODO keyword, or it can be one of the symbols `todo'
1571 or `done', meaning any not-done or done state, respectively."
1572 :group 'org-todo
1573 :group 'org-tags
1574 :type '(repeat
1575 (cons (choice :tag "When changing to"
1576 (const :tag "Not-done state" todo)
1577 (const :tag "Done state" done)
1578 (string :tag "State"))
1579 (repeat
1580 (cons :tag "Tag action"
1581 (string :tag "Tag")
1582 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1584 (defcustom org-log-done nil
1585 "Information to record when a task moves to the DONE state.
1587 Possible values are:
1589 nil Don't add anything, just change the keyword
1590 time Add a time stamp to the task
1591 note Prompt a closing note and add it with template `org-log-note-headings'
1593 This option can also be set with on a per-file-basis with
1595 #+STARTUP: nologdone
1596 #+STARTUP: logdone
1597 #+STARTUP: lognotedone
1599 You can have local logging settings for a subtree by setting the LOGGING
1600 property to one or more of these keywords."
1601 :group 'org-todo
1602 :group 'org-progress
1603 :type '(choice
1604 (const :tag "No logging" nil)
1605 (const :tag "Record CLOSED timestamp" time)
1606 (const :tag "Record CLOSED timestamp with closing note." note)))
1608 ;; Normalize old uses of org-log-done.
1609 (cond
1610 ((eq org-log-done t) (setq org-log-done 'time))
1611 ((and (listp org-log-done) (memq 'done org-log-done))
1612 (setq org-log-done 'note)))
1614 (defcustom org-log-note-clock-out nil
1615 "Non-nil means, record a note when clocking out of an item.
1616 This can also be configured on a per-file basis by adding one of
1617 the following lines anywhere in the buffer:
1619 #+STARTUP: lognoteclock-out
1620 #+STARTUP: nolognoteclock-out"
1621 :group 'org-todo
1622 :group 'org-progress
1623 :type 'boolean)
1625 (defcustom org-log-done-with-time t
1626 "Non-nil means, the CLOSED time stamp will contain date and time.
1627 When nil, only the date will be recorded."
1628 :group 'org-progress
1629 :type 'boolean)
1631 (defcustom org-log-note-headings
1632 '((done . "CLOSING NOTE %t")
1633 (state . "State %-12s %t")
1634 (note . "Note taken on %t")
1635 (clock-out . ""))
1636 "Headings for notes added to entries.
1637 The value is an alist, with the car being a symbol indicating the note
1638 context, and the cdr is the heading to be used. The heading may also be the
1639 empty string.
1640 %t in the heading will be replaced by a time stamp.
1641 %s will be replaced by the new TODO state, in double quotes.
1642 %u will be replaced by the user name.
1643 %U will be replaced by the full user name."
1644 :group 'org-todo
1645 :group 'org-progress
1646 :type '(list :greedy t
1647 (cons (const :tag "Heading when closing an item" done) string)
1648 (cons (const :tag
1649 "Heading when changing todo state (todo sequence only)"
1650 state) string)
1651 (cons (const :tag "Heading when just taking a note" note) string)
1652 (cons (const :tag "Heading when clocking out" clock-out) string)))
1654 (unless (assq 'note org-log-note-headings)
1655 (push '(note . "%t") org-log-note-headings))
1657 (defcustom org-log-state-notes-insert-after-drawers nil
1658 "Non-nil means, insert state change notes after any drawers in entry.
1659 Only the drawers that *immediately* follow the headline and the
1660 deadline/scheduled line are skipped.
1661 When nil, insert notes right after the heading and perhaps the line
1662 with deadline/scheduling if present."
1663 :group 'org-todo
1664 :group 'org-progress
1665 :type 'boolean)
1667 (defcustom org-log-states-order-reversed t
1668 "Non-nil means, the latest state change note will be directly after heading.
1669 When nil, the notes will be orderer according to time."
1670 :group 'org-todo
1671 :group 'org-progress
1672 :type 'boolean)
1674 (defcustom org-log-repeat 'time
1675 "Non-nil means, record moving through the DONE state when triggering repeat.
1676 An auto-repeating tasks is immediately switched back to TODO when marked
1677 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1678 the TODO keyword definition, or recording a closing note by setting
1679 `org-log-done', there will be no record of the task moving through DONE.
1680 This variable forces taking a note anyway. Possible values are:
1682 nil Don't force a record
1683 time Record a time stamp
1684 note Record a note
1686 This option can also be set with on a per-file-basis with
1688 #+STARTUP: logrepeat
1689 #+STARTUP: lognoterepeat
1690 #+STARTUP: nologrepeat
1692 You can have local logging settings for a subtree by setting the LOGGING
1693 property to one or more of these keywords."
1694 :group 'org-todo
1695 :group 'org-progress
1696 :type '(choice
1697 (const :tag "Don't force a record" nil)
1698 (const :tag "Force recording the DONE state" time)
1699 (const :tag "Force recording a note with the DONE state" note)))
1702 (defgroup org-priorities nil
1703 "Priorities in Org-mode."
1704 :tag "Org Priorities"
1705 :group 'org-todo)
1707 (defcustom org-highest-priority ?A
1708 "The highest priority of TODO items. A character like ?A, ?B etc.
1709 Must have a smaller ASCII number than `org-lowest-priority'."
1710 :group 'org-priorities
1711 :type 'character)
1713 (defcustom org-lowest-priority ?C
1714 "The lowest priority of TODO items. A character like ?A, ?B etc.
1715 Must have a larger ASCII number than `org-highest-priority'."
1716 :group 'org-priorities
1717 :type 'character)
1719 (defcustom org-default-priority ?B
1720 "The default priority of TODO items.
1721 This is the priority an item get if no explicit priority is given."
1722 :group 'org-priorities
1723 :type 'character)
1725 (defcustom org-priority-start-cycle-with-default t
1726 "Non-nil means, start with default priority when starting to cycle.
1727 When this is nil, the first step in the cycle will be (depending on the
1728 command used) one higher or lower that the default priority."
1729 :group 'org-priorities
1730 :type 'boolean)
1732 (defgroup org-time nil
1733 "Options concerning time stamps and deadlines in Org-mode."
1734 :tag "Org Time"
1735 :group 'org)
1737 (defcustom org-insert-labeled-timestamps-at-point nil
1738 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1739 When nil, these labeled time stamps are forces into the second line of an
1740 entry, just after the headline. When scheduling from the global TODO list,
1741 the time stamp will always be forced into the second line."
1742 :group 'org-time
1743 :type 'boolean)
1745 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1746 "Formats for `format-time-string' which are used for time stamps.
1747 It is not recommended to change this constant.")
1749 (defcustom org-time-stamp-rounding-minutes '(0 5)
1750 "Number of minutes to round time stamps to.
1751 These are two values, the first applies when first creating a time stamp.
1752 The second applies when changing it with the commands `S-up' and `S-down'.
1753 When changing the time stamp, this means that it will change in steps
1754 of N minutes, as given by the second value.
1756 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1757 numbers should be factors of 60, so for example 5, 10, 15.
1759 When this is larger than 1, you can still force an exact time-stamp by using
1760 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1761 and by using a prefix arg to `S-up/down' to specify the exact number
1762 of minutes to shift."
1763 :group 'org-time
1764 :get '(lambda (var) ; Make sure all entries have 5 elements
1765 (if (integerp (default-value var))
1766 (list (default-value var) 5)
1767 (default-value var)))
1768 :type '(list
1769 (integer :tag "when inserting times")
1770 (integer :tag "when modifying times")))
1772 ;; Normalize old customizations of this variable.
1773 (when (integerp org-time-stamp-rounding-minutes)
1774 (setq org-time-stamp-rounding-minutes
1775 (list org-time-stamp-rounding-minutes
1776 org-time-stamp-rounding-minutes)))
1778 (defcustom org-display-custom-times nil
1779 "Non-nil means, overlay custom formats over all time stamps.
1780 The formats are defined through the variable `org-time-stamp-custom-formats'.
1781 To turn this on on a per-file basis, insert anywhere in the file:
1782 #+STARTUP: customtime"
1783 :group 'org-time
1784 :set 'set-default
1785 :type 'sexp)
1786 (make-variable-buffer-local 'org-display-custom-times)
1788 (defcustom org-time-stamp-custom-formats
1789 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1790 "Custom formats for time stamps. See `format-time-string' for the syntax.
1791 These are overlayed over the default ISO format if the variable
1792 `org-display-custom-times' is set. Time like %H:%M should be at the
1793 end of the second format."
1794 :group 'org-time
1795 :type 'sexp)
1797 (defun org-time-stamp-format (&optional long inactive)
1798 "Get the right format for a time string."
1799 (let ((f (if long (cdr org-time-stamp-formats)
1800 (car org-time-stamp-formats))))
1801 (if inactive
1802 (concat "[" (substring f 1 -1) "]")
1803 f)))
1805 (defcustom org-time-clocksum-format "%d:%02d"
1806 "The format string used when creating CLOCKSUM lines, or when
1807 org-mode generates a time duration."
1808 :group 'org-time
1809 :type 'string)
1811 (defcustom org-deadline-warning-days 14
1812 "No. of days before expiration during which a deadline becomes active.
1813 This variable governs the display in sparse trees and in the agenda.
1814 When 0 or negative, it means use this number (the absolute value of it)
1815 even if a deadline has a different individual lead time specified."
1816 :group 'org-time
1817 :group 'org-agenda-daily/weekly
1818 :type 'number)
1820 (defcustom org-read-date-prefer-future t
1821 "Non-nil means, assume future for incomplete date input from user.
1822 This affects the following situations:
1823 1. The user gives a day, but no month.
1824 For example, if today is the 15th, and you enter \"3\", Org-mode will
1825 read this as the third of *next* month. However, if you enter \"17\",
1826 it will be considered as *this* month.
1827 2. The user gives a month but not a year.
1828 For example, if it is april and you enter \"feb 2\", this will be read
1829 as feb 2, *next* year. \"May 5\", however, will be this year.
1831 Currently this does not work for ISO week specifications.
1833 When this option is nil, the current month and year will always be used
1834 as defaults."
1835 :group 'org-time
1836 :type 'boolean)
1838 (defcustom org-read-date-display-live t
1839 "Non-nil means, display current interpretation of date prompt live.
1840 This display will be in an overlay, in the minibuffer."
1841 :group 'org-time
1842 :type 'boolean)
1844 (defcustom org-read-date-popup-calendar t
1845 "Non-nil means, pop up a calendar when prompting for a date.
1846 In the calendar, the date can be selected with mouse-1. However, the
1847 minibuffer will also be active, and you can simply enter the date as well.
1848 When nil, only the minibuffer will be available."
1849 :group 'org-time
1850 :type 'boolean)
1851 (if (fboundp 'defvaralias)
1852 (defvaralias 'org-popup-calendar-for-date-prompt
1853 'org-read-date-popup-calendar))
1855 (defcustom org-extend-today-until 0
1856 "The hour when your day really ends. Must be an integer.
1857 This has influence for the following applications:
1858 - When switching the agenda to \"today\". It it is still earlier than
1859 the time given here, the day recognized as TODAY is actually yesterday.
1860 - When a date is read from the user and it is still before the time given
1861 here, the current date and time will be assumed to be yesterday, 23:59.
1862 Also, timestamps inserted in remember templates follow this rule.
1864 IMPORTANT: This is a feature whose implementation is and likely will
1865 remain incomplete. Really, it is only here because past midnight seems to
1866 be the favorite working time of John Wiegley :-)"
1867 :group 'org-time
1868 :type 'number)
1870 (defcustom org-edit-timestamp-down-means-later nil
1871 "Non-nil means, S-down will increase the time in a time stamp.
1872 When nil, S-up will increase."
1873 :group 'org-time
1874 :type 'boolean)
1876 (defcustom org-calendar-follow-timestamp-change t
1877 "Non-nil means, make the calendar window follow timestamp changes.
1878 When a timestamp is modified and the calendar window is visible, it will be
1879 moved to the new date."
1880 :group 'org-time
1881 :type 'boolean)
1883 (defgroup org-tags nil
1884 "Options concerning tags in Org-mode."
1885 :tag "Org Tags"
1886 :group 'org)
1888 (defcustom org-tag-alist nil
1889 "List of tags allowed in Org-mode files.
1890 When this list is nil, Org-mode will base TAG input on what is already in the
1891 buffer.
1892 The value of this variable is an alist, the car of each entry must be a
1893 keyword as a string, the cdr may be a character that is used to select
1894 that tag through the fast-tag-selection interface.
1895 See the manual for details."
1896 :group 'org-tags
1897 :type '(repeat
1898 (choice
1899 (cons (string :tag "Tag name")
1900 (character :tag "Access char"))
1901 (const :tag "Start radio group" (:startgroup))
1902 (const :tag "End radio group" (:endgroup)))))
1904 (defvar org-file-tags nil
1905 "List of tags that can be inherited by all entries in the file.
1906 The tags will be inherited if the variable `org-use-tag-inheritance'
1907 says they should be.
1908 This variable is populated from #+TAG lines.")
1910 (defcustom org-use-fast-tag-selection 'auto
1911 "Non-nil means, use fast tag selection scheme.
1912 This is a special interface to select and deselect tags with single keys.
1913 When nil, fast selection is never used.
1914 When the symbol `auto', fast selection is used if and only if selection
1915 characters for tags have been configured, either through the variable
1916 `org-tag-alist' or through a #+TAGS line in the buffer.
1917 When t, fast selection is always used and selection keys are assigned
1918 automatically if necessary."
1919 :group 'org-tags
1920 :type '(choice
1921 (const :tag "Always" t)
1922 (const :tag "Never" nil)
1923 (const :tag "When selection characters are configured" 'auto)))
1925 (defcustom org-fast-tag-selection-single-key nil
1926 "Non-nil means, fast tag selection exits after first change.
1927 When nil, you have to press RET to exit it.
1928 During fast tag selection, you can toggle this flag with `C-c'.
1929 This variable can also have the value `expert'. In this case, the window
1930 displaying the tags menu is not even shown, until you press C-c again."
1931 :group 'org-tags
1932 :type '(choice
1933 (const :tag "No" nil)
1934 (const :tag "Yes" t)
1935 (const :tag "Expert" expert)))
1937 (defvar org-fast-tag-selection-include-todo nil
1938 "Non-nil means, fast tags selection interface will also offer TODO states.
1939 This is an undocumented feature, you should not rely on it.")
1941 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1942 "The column to which tags should be indented in a headline.
1943 If this number is positive, it specifies the column. If it is negative,
1944 it means that the tags should be flushright to that column. For example,
1945 -80 works well for a normal 80 character screen."
1946 :group 'org-tags
1947 :type 'integer)
1949 (defcustom org-auto-align-tags t
1950 "Non-nil means, realign tags after pro/demotion of TODO state change.
1951 These operations change the length of a headline and therefore shift
1952 the tags around. With this options turned on, after each such operation
1953 the tags are again aligned to `org-tags-column'."
1954 :group 'org-tags
1955 :type 'boolean)
1957 (defcustom org-use-tag-inheritance t
1958 "Non-nil means, tags in levels apply also for sublevels.
1959 When nil, only the tags directly given in a specific line apply there.
1960 This may also be a list of tags that should be inherited, or a regexp that
1961 matches tags that should be inherited. Additional control is possible
1962 with the variable `org-tags-exclude-from-inheritance' which gives an
1963 explicit list of tags to be excluded from inheritance., even if the value of
1964 `org-use-tag-inheritance' would select it for inheritance.
1966 If this option is t, a match early-on in a tree can lead to a large
1967 number of matches in the subtree when constructing the agenda or creating
1968 a sparse tree. If you only want to see the first match in a tree during
1969 a search, check out the variable `org-tags-match-list-sublevels'."
1970 :group 'org-tags
1971 :type '(choice
1972 (const :tag "Not" nil)
1973 (const :tag "Always" t)
1974 (repeat :tag "Specific tags" (string :tag "Tag"))
1975 (regexp :tag "Tags matched by regexp")))
1977 (defcustom org-tags-exclude-from-inheritance nil
1978 "List of tags that should never be inherited.
1979 This is a way to exclude a few tags from inheritance. For way to do
1980 the opposite, to actively allow inheritance for selected tags,
1981 see the variable `org-use-tag-inheritance'."
1982 :group 'org-tags
1983 :type '(repeat (string :tag "Tag")))
1985 (defun org-tag-inherit-p (tag)
1986 "Check if TAG is one that should be inherited."
1987 (cond
1988 ((member tag org-tags-exclude-from-inheritance) nil)
1989 ((eq org-use-tag-inheritance t) t)
1990 ((not org-use-tag-inheritance) nil)
1991 ((stringp org-use-tag-inheritance)
1992 (string-match org-use-tag-inheritance tag))
1993 ((listp org-use-tag-inheritance)
1994 (member tag org-use-tag-inheritance))
1995 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1997 (defcustom org-tags-match-list-sublevels t
1998 "Non-nil means list also sublevels of headlines matching tag search.
1999 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2000 the sublevels of a headline matching a tag search often also match
2001 the same search. Listing all of them can create very long lists.
2002 Setting this variable to nil causes subtrees of a match to be skipped.
2003 This option is off by default, because inheritance in on. If you turn
2004 inheritance off, you very likely want to turn this option on.
2006 As a special case, if the tag search is restricted to TODO items, the
2007 value of this variable is ignored and sublevels are always checked, to
2008 make sure all corresponding TODO items find their way into the list.
2010 This variable is semi-obsolete and probably should always be true. It
2011 is better to limit inheritance to certain tags using the variables
2012 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2013 :group 'org-tags
2014 :type 'boolean)
2016 (defvar org-tags-history nil
2017 "History of minibuffer reads for tags.")
2018 (defvar org-last-tags-completion-table nil
2019 "The last used completion table for tags.")
2020 (defvar org-after-tags-change-hook nil
2021 "Hook that is run after the tags in a line have changed.")
2023 (defgroup org-properties nil
2024 "Options concerning properties in Org-mode."
2025 :tag "Org Properties"
2026 :group 'org)
2028 (defcustom org-property-format "%-10s %s"
2029 "How property key/value pairs should be formatted by `indent-line'.
2030 When `indent-line' hits a property definition, it will format the line
2031 according to this format, mainly to make sure that the values are
2032 lined-up with respect to each other."
2033 :group 'org-properties
2034 :type 'string)
2036 (defcustom org-use-property-inheritance nil
2037 "Non-nil means, properties apply also for sublevels.
2039 This setting is chiefly used during property searches. Turning it on can
2040 cause significant overhead when doing a search, which is why it is not
2041 on by default.
2043 When nil, only the properties directly given in the current entry count.
2044 When t, every property is inherited. The value may also be a list of
2045 properties that should have inheritance, or a regular expression matching
2046 properties that should be inherited.
2048 However, note that some special properties use inheritance under special
2049 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2050 and the properties ending in \"_ALL\" when they are used as descriptor
2051 for valid values of a property.
2053 Note for programmers:
2054 When querying an entry with `org-entry-get', you can control if inheritance
2055 should be used. By default, `org-entry-get' looks only at the local
2056 properties. You can request inheritance by setting the inherit argument
2057 to t (to force inheritance) or to `selective' (to respect the setting
2058 in this variable)."
2059 :group 'org-properties
2060 :type '(choice
2061 (const :tag "Not" nil)
2062 (const :tag "Always" t)
2063 (repeat :tag "Specific properties" (string :tag "Property"))
2064 (regexp :tag "Properties matched by regexp")))
2066 (defun org-property-inherit-p (property)
2067 "Check if PROPERTY is one that should be inherited."
2068 (cond
2069 ((eq org-use-property-inheritance t) t)
2070 ((not org-use-property-inheritance) nil)
2071 ((stringp org-use-property-inheritance)
2072 (string-match org-use-property-inheritance property))
2073 ((listp org-use-property-inheritance)
2074 (member property org-use-property-inheritance))
2075 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2077 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2078 "The default column format, if no other format has been defined.
2079 This variable can be set on the per-file basis by inserting a line
2081 #+COLUMNS: %25ITEM ....."
2082 :group 'org-properties
2083 :type 'string)
2085 (defcustom org-columns-ellipses ".."
2086 "The ellipses to be used when a field in column view is truncated.
2087 When this is the empty string, as many characters as possible are shown,
2088 but then there will be no visual indication that the field has been truncated.
2089 When this is a string of length N, the last N characters of a truncated
2090 field are replaced by this string. If the column is narrower than the
2091 ellipses string, only part of the ellipses string will be shown."
2092 :group 'org-properties
2093 :type 'string)
2095 (defcustom org-columns-modify-value-for-display-function nil
2096 "Function that modifies values for display in column view.
2097 For example, it can be used to cut out a certain part from a time stamp.
2098 The function must take 2 arguments:
2100 column-title The title of the column (*not* the property name)
2101 value The value that should be modified.
2103 The function should return the value that should be displayed,
2104 or nil if the normal value should be used."
2105 :group 'org-properties
2106 :type 'function)
2108 (defcustom org-effort-property "Effort"
2109 "The property that is being used to keep track of effort estimates.
2110 Effort estimates given in this property need to have the format H:MM."
2111 :group 'org-properties
2112 :group 'org-progress
2113 :type '(string :tag "Property"))
2115 (defconst org-global-properties-fixed
2116 '(("VISIBILITY_ALL" . "folded children content all"))
2117 "List of property/value pairs that can be inherited by any entry.
2118 These are fixed values, for the preset properties.")
2121 (defcustom org-global-properties nil
2122 "List of property/value pairs that can be inherited by any entry.
2123 You can set buffer-local values for the same purpose in the variable
2124 `org-file-properties' this by adding lines like
2126 #+PROPERTY: NAME VALUE"
2127 :group 'org-properties
2128 :type '(repeat
2129 (cons (string :tag "Property")
2130 (string :tag "Value"))))
2132 (defvar org-file-properties nil
2133 "List of property/value pairs that can be inherited by any entry.
2134 Valid for the current buffer.
2135 This variable is populated from #+PROPERTY lines.")
2136 (make-variable-buffer-local 'org-file-properties)
2138 (defgroup org-agenda nil
2139 "Options concerning agenda views in Org-mode."
2140 :tag "Org Agenda"
2141 :group 'org)
2143 (defvar org-category nil
2144 "Variable used by org files to set a category for agenda display.
2145 Such files should use a file variable to set it, for example
2147 # -*- mode: org; org-category: \"ELisp\"
2149 or contain a special line
2151 #+CATEGORY: ELisp
2153 If the file does not specify a category, then file's base name
2154 is used instead.")
2155 (make-variable-buffer-local 'org-category)
2156 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2158 (defcustom org-agenda-files nil
2159 "The files to be used for agenda display.
2160 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2161 \\[org-remove-file]. You can also use customize to edit the list.
2163 If an entry is a directory, all files in that directory that are matched by
2164 `org-agenda-file-regexp' will be part of the file list.
2166 If the value of the variable is not a list but a single file name, then
2167 the list of agenda files is actually stored and maintained in that file, one
2168 agenda file per line."
2169 :group 'org-agenda
2170 :type '(choice
2171 (repeat :tag "List of files and directories" file)
2172 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2174 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2175 "Regular expression to match files for `org-agenda-files'.
2176 If any element in the list in that variable contains a directory instead
2177 of a normal file, all files in that directory that are matched by this
2178 regular expression will be included."
2179 :group 'org-agenda
2180 :type 'regexp)
2182 (defcustom org-agenda-text-search-extra-files nil
2183 "List of extra files to be searched by text search commands.
2184 These files will be search in addition to the agenda files by the
2185 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2186 Note that these files will only be searched for text search commands,
2187 not for the other agenda views like todo lists, tag searches or the weekly
2188 agenda. This variable is intended to list notes and possibly archive files
2189 that should also be searched by these two commands.
2190 In fact, if the first element in the list is the symbol `agenda-archives',
2191 than all archive files of all agenda files will be added to the search
2192 scope."
2193 :group 'org-agenda
2194 :type '(set :greedy t
2195 (const :tag "Agenda Archives" agenda-archives)
2196 (repeat :inline t (file))))
2198 (if (fboundp 'defvaralias)
2199 (defvaralias 'org-agenda-multi-occur-extra-files
2200 'org-agenda-text-search-extra-files))
2202 (defcustom org-agenda-skip-unavailable-files nil
2203 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2204 A nil value means to remove them, after a query, from the list."
2205 :group 'org-agenda
2206 :type 'boolean)
2208 (defcustom org-calendar-to-agenda-key [?c]
2209 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2210 The command `org-calendar-goto-agenda' will be bound to this key. The
2211 default is the character `c' because then `c' can be used to switch back and
2212 forth between agenda and calendar."
2213 :group 'org-agenda
2214 :type 'sexp)
2216 (defcustom org-calendar-agenda-action-key [?k]
2217 "The key to be installed in `calendar-mode-map' for agenda-action.
2218 The command `org-agenda-action' will be bound to this key. The
2219 default is the character `k' because we use the same key in the agenda."
2220 :group 'org-agenda
2221 :type 'sexp)
2223 (eval-after-load "calendar"
2224 '(progn
2225 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2226 'org-calendar-goto-agenda)
2227 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2228 'org-agenda-action)))
2230 (defgroup org-latex nil
2231 "Options for embedding LaTeX code into Org-mode."
2232 :tag "Org LaTeX"
2233 :group 'org)
2235 (defcustom org-format-latex-options
2236 '(:foreground default :background default :scale 1.0
2237 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2238 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2239 "Options for creating images from LaTeX fragments.
2240 This is a property list with the following properties:
2241 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2242 `default' means use the foreground of the default face.
2243 :background the background color, or \"Transparent\".
2244 `default' means use the background of the default face.
2245 :scale a scaling factor for the size of the images.
2246 :html-foreground, :html-background, :html-scale
2247 the same numbers for HTML export.
2248 :matchers a list indicating which matchers should be used to
2249 find LaTeX fragments. Valid members of this list are:
2250 \"begin\" find environments
2251 \"$1\" find single characters surrounded by $.$
2252 \"$\" find math expressions surrounded by $...$
2253 \"$$\" find math expressions surrounded by $$....$$
2254 \"\\(\" find math expressions surrounded by \\(...\\)
2255 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2256 :group 'org-latex
2257 :type 'plist)
2259 (defcustom org-format-latex-header "\\documentclass{article}
2260 \\usepackage{fullpage} % do not remove
2261 \\usepackage{amssymb}
2262 \\usepackage[usenames]{color}
2263 \\usepackage{amsmath}
2264 \\usepackage{latexsym}
2265 \\usepackage[mathscr]{eucal}
2266 \\pagestyle{empty} % do not remove"
2267 "The document header used for processing LaTeX fragments."
2268 :group 'org-latex
2269 :type 'string)
2272 (defgroup org-font-lock nil
2273 "Font-lock settings for highlighting in Org-mode."
2274 :tag "Org Font Lock"
2275 :group 'org)
2277 (defcustom org-level-color-stars-only nil
2278 "Non-nil means fontify only the stars in each headline.
2279 When nil, the entire headline is fontified.
2280 Changing it requires restart of `font-lock-mode' to become effective
2281 also in regions already fontified."
2282 :group 'org-font-lock
2283 :type 'boolean)
2285 (defcustom org-hide-leading-stars nil
2286 "Non-nil means, hide the first N-1 stars in a headline.
2287 This works by using the face `org-hide' for these stars. This
2288 face is white for a light background, and black for a dark
2289 background. You may have to customize the face `org-hide' to
2290 make this work.
2291 Changing it requires restart of `font-lock-mode' to become effective
2292 also in regions already fontified.
2293 You may also set this on a per-file basis by adding one of the following
2294 lines to the buffer:
2296 #+STARTUP: hidestars
2297 #+STARTUP: showstars"
2298 :group 'org-font-lock
2299 :type 'boolean)
2301 (defcustom org-fontify-done-headline nil
2302 "Non-nil means, change the face of a headline if it is marked DONE.
2303 Normally, only the TODO/DONE keyword indicates the state of a headline.
2304 When this is non-nil, the headline after the keyword is set to the
2305 `org-headline-done' as an additional indication."
2306 :group 'org-font-lock
2307 :type 'boolean)
2309 (defcustom org-fontify-emphasized-text t
2310 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2311 Changing this variable requires a restart of Emacs to take effect."
2312 :group 'org-font-lock
2313 :type 'boolean)
2315 (defcustom org-highlight-latex-fragments-and-specials nil
2316 "Non-nil means, fontify what is treated specially by the exporters."
2317 :group 'org-font-lock
2318 :type 'boolean)
2320 (defcustom org-hide-emphasis-markers nil
2321 "Non-nil mean font-lock should hide the emphasis marker characters."
2322 :group 'org-font-lock
2323 :type 'boolean)
2325 (defvar org-emph-re nil
2326 "Regular expression for matching emphasis.")
2327 (defvar org-verbatim-re nil
2328 "Regular expression for matching verbatim text.")
2329 (defvar org-emphasis-regexp-components) ; defined just below
2330 (defvar org-emphasis-alist) ; defined just below
2331 (defun org-set-emph-re (var val)
2332 "Set variable and compute the emphasis regular expression."
2333 (set var val)
2334 (when (and (boundp 'org-emphasis-alist)
2335 (boundp 'org-emphasis-regexp-components)
2336 org-emphasis-alist org-emphasis-regexp-components)
2337 (let* ((e org-emphasis-regexp-components)
2338 (pre (car e))
2339 (post (nth 1 e))
2340 (border (nth 2 e))
2341 (body (nth 3 e))
2342 (nl (nth 4 e))
2343 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2344 (body1 (concat body "*?"))
2345 (markers (mapconcat 'car org-emphasis-alist ""))
2346 (vmarkers (mapconcat
2347 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2348 org-emphasis-alist "")))
2349 ;; make sure special characters appear at the right position in the class
2350 (if (string-match "\\^" markers)
2351 (setq markers (concat (replace-match "" t t markers) "^")))
2352 (if (string-match "-" markers)
2353 (setq markers (concat (replace-match "" t t markers) "-")))
2354 (if (string-match "\\^" vmarkers)
2355 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2356 (if (string-match "-" vmarkers)
2357 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2358 (if (> nl 0)
2359 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2360 (int-to-string nl) "\\}")))
2361 ;; Make the regexp
2362 (setq org-emph-re
2363 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2364 "\\("
2365 "\\([" markers "]\\)"
2366 "\\("
2367 "[^" border "]\\|"
2368 "[^" border (if (and nil stacked) markers) "]"
2369 body1
2370 "[^" border (if (and nil stacked) markers) "]"
2371 "\\)"
2372 "\\3\\)"
2373 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2374 (setq org-verbatim-re
2375 (concat "\\([" pre "]\\|^\\)"
2376 "\\("
2377 "\\([" vmarkers "]\\)"
2378 "\\("
2379 "[^" border "]\\|"
2380 "[^" border "]"
2381 body1
2382 "[^" border "]"
2383 "\\)"
2384 "\\3\\)"
2385 "\\([" post "]\\|$\\)")))))
2387 (defcustom org-emphasis-regexp-components
2388 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2389 "Components used to build the regular expression for emphasis.
2390 This is a list with 6 entries. Terminology: In an emphasis string
2391 like \" *strong word* \", we call the initial space PREMATCH, the final
2392 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2393 and \"trong wor\" is the body. The different components in this variable
2394 specify what is allowed/forbidden in each part:
2396 pre Chars allowed as prematch. Beginning of line will be allowed too.
2397 post Chars allowed as postmatch. End of line will be allowed too.
2398 border The chars *forbidden* as border characters.
2399 body-regexp A regexp like \".\" to match a body character. Don't use
2400 non-shy groups here, and don't allow newline here.
2401 newline The maximum number of newlines allowed in an emphasis exp.
2403 Use customize to modify this, or restart Emacs after changing it."
2404 :group 'org-font-lock
2405 :set 'org-set-emph-re
2406 :type '(list
2407 (sexp :tag "Allowed chars in pre ")
2408 (sexp :tag "Allowed chars in post ")
2409 (sexp :tag "Forbidden chars in border ")
2410 (sexp :tag "Regexp for body ")
2411 (integer :tag "number of newlines allowed")
2412 (option (boolean :tag "Please ignore this button"))))
2414 (defcustom org-emphasis-alist
2415 `(("*" bold "<b>" "</b>")
2416 ("/" italic "<i>" "</i>")
2417 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2418 ("=" org-code "<code>" "</code>" verbatim)
2419 ("~" org-verbatim "<code>" "</code>" verbatim)
2420 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2421 "<del>" "</del>")
2423 "Special syntax for emphasized text.
2424 Text starting and ending with a special character will be emphasized, for
2425 example *bold*, _underlined_ and /italic/. This variable sets the marker
2426 characters, the face to be used by font-lock for highlighting in Org-mode
2427 Emacs buffers, and the HTML tags to be used for this.
2428 Use customize to modify this, or restart Emacs after changing it."
2429 :group 'org-font-lock
2430 :set 'org-set-emph-re
2431 :type '(repeat
2432 (list
2433 (string :tag "Marker character")
2434 (choice
2435 (face :tag "Font-lock-face")
2436 (plist :tag "Face property list"))
2437 (string :tag "HTML start tag")
2438 (string :tag "HTML end tag")
2439 (option (const verbatim)))))
2441 ;;; Miscellaneous options
2443 (defgroup org-completion nil
2444 "Completion in Org-mode."
2445 :tag "Org Completion"
2446 :group 'org)
2448 (defcustom org-completion-use-ido nil
2449 "Non-nil means, use ido completion wherever possible.
2450 Note that `ido-mode' must be active for this variable to be relevant.
2451 If you decide to turn this variable on, you might well want to turn off
2452 `org-outline-path-complete-in-steps'."
2453 :group 'org-completion
2454 :type 'boolean)
2456 (defcustom org-completion-fallback-command 'hippie-expand
2457 "The expansion command called by \\[org-complete] in normal context.
2458 Normal means, no org-mode-specific context."
2459 :group 'org-completion
2460 :type 'function)
2462 ;;; Functions and variables from ther packages
2463 ;; Declared here to avoid compiler warnings
2465 ;; XEmacs only
2466 (defvar outline-mode-menu-heading)
2467 (defvar outline-mode-menu-show)
2468 (defvar outline-mode-menu-hide)
2469 (defvar zmacs-regions) ; XEmacs regions
2471 ;; Emacs only
2472 (defvar mark-active)
2474 ;; Various packages
2475 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2476 (declare-function calendar-forward-day "cal-move" (arg))
2477 (declare-function calendar-goto-date "cal-move" (date))
2478 (declare-function calendar-goto-today "cal-move" ())
2479 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2480 (defvar calc-embedded-close-formula)
2481 (defvar calc-embedded-open-formula)
2482 (declare-function cdlatex-tab "ext:cdlatex" ())
2483 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2484 (defvar font-lock-unfontify-region-function)
2485 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2486 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2487 (defvar iswitchb-temp-buflist)
2488 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2489 (declare-function org-agenda-skip "org-agenda" ())
2490 (declare-function org-format-agenda-item "org-agenda"
2491 (extra txt &optional category tags dotime noprefix remove-re))
2492 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2493 (declare-function org-agenda-change-all-lines "org-agenda"
2494 (newhead hdmarker &optional fixface just-this))
2495 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2496 (declare-function org-agenda-maybe-redo "org-agenda" ())
2497 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2498 (beg end))
2499 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2500 (declare-function parse-time-string "parse-time" (string))
2501 (declare-function remember "remember" (&optional initial))
2502 (declare-function remember-buffer-desc "remember" ())
2503 (declare-function remember-finalize "remember" ())
2504 (defvar remember-save-after-remembering)
2505 (defvar remember-data-file)
2506 (defvar remember-register)
2507 (defvar remember-buffer)
2508 (defvar remember-handler-functions)
2509 (defvar remember-annotation-functions)
2510 (defvar texmathp-why)
2511 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2512 (declare-function table--at-cell-p "table" (position &optional object at-column))
2514 (defvar w3m-current-url)
2515 (defvar w3m-current-title)
2517 (defvar org-latex-regexps)
2519 ;;; Autoload and prepare some org modules
2521 ;; Some table stuff that needs to be defined here, because it is used
2522 ;; by the functions setting up org-mode or checking for table context.
2524 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2525 "Detects an org-type or table-type table.")
2526 (defconst org-table-line-regexp "^[ \t]*|"
2527 "Detects an org-type table line.")
2528 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2529 "Detects an org-type table line.")
2530 (defconst org-table-hline-regexp "^[ \t]*|-"
2531 "Detects an org-type table hline.")
2532 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2533 "Detects a table-type table hline.")
2534 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2535 "Searching from within a table (any type) this finds the first line
2536 outside the table.")
2538 ;; Autoload the functions in org-table.el that are needed by functions here.
2540 (eval-and-compile
2541 (org-autoload "org-table"
2542 '(org-table-align org-table-begin org-table-blank-field
2543 org-table-convert org-table-convert-region org-table-copy-down
2544 org-table-copy-region org-table-create
2545 org-table-create-or-convert-from-region
2546 org-table-create-with-table.el org-table-current-dline
2547 org-table-cut-region org-table-delete-column org-table-edit-field
2548 org-table-edit-formulas org-table-end org-table-eval-formula
2549 org-table-export org-table-field-info
2550 org-table-get-stored-formulas org-table-goto-column
2551 org-table-hline-and-move org-table-import org-table-insert-column
2552 org-table-insert-hline org-table-insert-row org-table-iterate
2553 org-table-justify-field-maybe org-table-kill-row
2554 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2555 org-table-move-column org-table-move-column-left
2556 org-table-move-column-right org-table-move-row
2557 org-table-move-row-down org-table-move-row-up
2558 org-table-next-field org-table-next-row org-table-paste-rectangle
2559 org-table-previous-field org-table-recalculate
2560 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2561 org-table-toggle-coordinate-overlays
2562 org-table-toggle-formula-debugger org-table-wrap-region
2563 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2565 (defun org-at-table-p (&optional table-type)
2566 "Return t if the cursor is inside an org-type table.
2567 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2568 (if org-enable-table-editor
2569 (save-excursion
2570 (beginning-of-line 1)
2571 (looking-at (if table-type org-table-any-line-regexp
2572 org-table-line-regexp)))
2573 nil))
2574 (defsubst org-table-p () (org-at-table-p))
2576 (defun org-at-table.el-p ()
2577 "Return t if and only if we are at a table.el table."
2578 (and (org-at-table-p 'any)
2579 (save-excursion
2580 (goto-char (org-table-begin 'any))
2581 (looking-at org-table1-hline-regexp))))
2582 (defun org-table-recognize-table.el ()
2583 "If there is a table.el table nearby, recognize it and move into it."
2584 (if org-table-tab-recognizes-table.el
2585 (if (org-at-table.el-p)
2586 (progn
2587 (beginning-of-line 1)
2588 (if (looking-at org-table-dataline-regexp)
2590 (if (looking-at org-table1-hline-regexp)
2591 (progn
2592 (beginning-of-line 2)
2593 (if (looking-at org-table-any-border-regexp)
2594 (beginning-of-line -1)))))
2595 (if (re-search-forward "|" (org-table-end t) t)
2596 (progn
2597 (require 'table)
2598 (if (table--at-cell-p (point))
2600 (message "recognizing table.el table...")
2601 (table-recognize-table)
2602 (message "recognizing table.el table...done")))
2603 (error "This should not happen..."))
2605 nil)
2606 nil))
2608 (defun org-at-table-hline-p ()
2609 "Return t if the cursor is inside a hline in a table."
2610 (if org-enable-table-editor
2611 (save-excursion
2612 (beginning-of-line 1)
2613 (looking-at org-table-hline-regexp))
2614 nil))
2616 (defvar org-table-clean-did-remove-column nil)
2618 (defun org-table-map-tables (function)
2619 "Apply FUNCTION to the start of all tables in the buffer."
2620 (save-excursion
2621 (save-restriction
2622 (widen)
2623 (goto-char (point-min))
2624 (while (re-search-forward org-table-any-line-regexp nil t)
2625 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2626 (beginning-of-line 1)
2627 (if (looking-at org-table-line-regexp)
2628 (save-excursion (funcall function)))
2629 (re-search-forward org-table-any-border-regexp nil 1))))
2630 (message "Mapping tables: done"))
2632 ;; Declare and autoload functions from org-exp.el
2634 (declare-function org-default-export-plist "org-exp")
2635 (declare-function org-infile-export-plist "org-exp")
2636 (declare-function org-get-current-options "org-exp")
2637 (eval-and-compile
2638 (org-autoload "org-exp"
2639 '(org-export org-export-as-ascii org-export-visible
2640 org-insert-export-options-template org-export-as-html-and-open
2641 org-export-as-html-batch org-export-as-html-to-buffer
2642 org-replace-region-by-html org-export-region-as-html
2643 org-export-as-html org-export-icalendar-this-file
2644 org-export-icalendar-all-agenda-files
2645 org-table-clean-before-export
2646 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2648 ;; Declare and autoload functions from org-agenda.el
2650 (eval-and-compile
2651 (org-autoload "org-agenda"
2652 '(org-agenda org-agenda-list org-search-view
2653 org-todo-list org-tags-view org-agenda-list-stuck-projects
2654 org-diary org-agenda-to-appt)))
2656 ;; Autoload org-remember
2658 (eval-and-compile
2659 (org-autoload "org-remember"
2660 '(org-remember-insinuate org-remember-annotation
2661 org-remember-apply-template org-remember org-remember-handler)))
2663 ;; Autoload org-clock.el
2666 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2667 (beg end))
2668 (declare-function org-update-mode-line "org-clock" ())
2669 (defvar org-clock-start-time)
2670 (defvar org-clock-marker (make-marker)
2671 "Marker recording the last clock-in.")
2673 (eval-and-compile
2674 (org-autoload
2675 "org-clock"
2676 '(org-clock-in org-clock-out org-clock-cancel
2677 org-clock-goto org-clock-sum org-clock-display
2678 org-clock-remove-overlays org-clock-report
2679 org-clocktable-shift org-dblock-write:clocktable
2680 org-get-clocktable)))
2682 (defun org-clock-update-time-maybe ()
2683 "If this is a CLOCK line, update it and return t.
2684 Otherwise, return nil."
2685 (interactive)
2686 (save-excursion
2687 (beginning-of-line 1)
2688 (skip-chars-forward " \t")
2689 (when (looking-at org-clock-string)
2690 (let ((re (concat "[ \t]*" org-clock-string
2691 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2692 "\\([ \t]*=>.*\\)?\\)?"))
2693 ts te h m s neg)
2694 (cond
2695 ((not (looking-at re))
2696 nil)
2697 ((not (match-end 2))
2698 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2699 (> org-clock-marker (point))
2700 (<= org-clock-marker (point-at-eol)))
2701 ;; The clock is running here
2702 (setq org-clock-start-time
2703 (apply 'encode-time
2704 (org-parse-time-string (match-string 1))))
2705 (org-update-mode-line)))
2707 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2708 (end-of-line 1)
2709 (setq ts (match-string 1)
2710 te (match-string 3))
2711 (setq s (- (time-to-seconds
2712 (apply 'encode-time (org-parse-time-string te)))
2713 (time-to-seconds
2714 (apply 'encode-time (org-parse-time-string ts))))
2715 neg (< s 0)
2716 s (abs s)
2717 h (floor (/ s 3600))
2718 s (- s (* 3600 h))
2719 m (floor (/ s 60))
2720 s (- s (* 60 s)))
2721 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2722 t))))))
2724 (defun org-check-running-clock ()
2725 "Check if the current buffer contains the running clock.
2726 If yes, offer to stop it and to save the buffer with the changes."
2727 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2728 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2729 (buffer-name))))
2730 (org-clock-out)
2731 (when (y-or-n-p "Save changed buffer?")
2732 (save-buffer))))
2734 (defun org-clocktable-try-shift (dir n)
2735 "Check if this line starts a clock table, if yes, shift the time block."
2736 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2737 (org-clocktable-shift dir n)))
2739 ;; Autoload org-timer.el
2741 ;(declare-function org-timer "org-timer")
2743 (eval-and-compile
2744 (org-autoload
2745 "org-timer"
2746 '(org-timer-start org-timer org-timer-item
2747 org-timer-change-times-in-region)))
2750 ;; Autoload archiving code
2751 ;; The stuff that is needed for cycling and tags has to be defined here.
2753 (defgroup org-archive nil
2754 "Options concerning archiving in Org-mode."
2755 :tag "Org Archive"
2756 :group 'org-structure)
2758 (defcustom org-archive-location "%s_archive::"
2759 "The location where subtrees should be archived.
2761 The value of this variable is a string, consisting of two parts,
2762 separated by a double-colon. The first part is a filename and
2763 the second part is a headline.
2765 When the filename is omitted, archiving happens in the same file.
2766 %s in the filename will be replaced by the current file
2767 name (without the directory part). Archiving to a different file
2768 is useful to keep archived entries from contributing to the
2769 Org-mode Agenda.
2771 The archived entries will be filed as subtrees of the specified
2772 headline. When the headline is omitted, the subtrees are simply
2773 filed away at the end of the file, as top-level entries.
2775 Here are a few examples:
2776 \"%s_archive::\"
2777 If the current file is Projects.org, archive in file
2778 Projects.org_archive, as top-level trees. This is the default.
2780 \"::* Archived Tasks\"
2781 Archive in the current file, under the top-level headline
2782 \"* Archived Tasks\".
2784 \"~/org/archive.org::\"
2785 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2787 \"basement::** Finished Tasks\"
2788 Archive in file ./basement (relative path), as level 3 trees
2789 below the level 2 heading \"** Finished Tasks\".
2791 You may set this option on a per-file basis by adding to the buffer a
2792 line like
2794 #+ARCHIVE: basement::** Finished Tasks
2796 You may also define it locally for a subtree by setting an ARCHIVE property
2797 in the entry. If such a property is found in an entry, or anywhere up
2798 the hierarchy, it will be used."
2799 :group 'org-archive
2800 :type 'string)
2802 (defcustom org-archive-tag "ARCHIVE"
2803 "The tag that marks a subtree as archived.
2804 An archived subtree does not open during visibility cycling, and does
2805 not contribute to the agenda listings.
2806 After changing this, font-lock must be restarted in the relevant buffers to
2807 get the proper fontification."
2808 :group 'org-archive
2809 :group 'org-keywords
2810 :type 'string)
2812 (defcustom org-agenda-skip-archived-trees t
2813 "Non-nil means, the agenda will skip any items located in archived trees.
2814 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2815 variable is no longer recommended, you should leave it at the value t.
2816 Instead, use the key `v' to cycle the archives-mode in the agenda."
2817 :group 'org-archive
2818 :group 'org-agenda-skip
2819 :type 'boolean)
2821 (defcustom org-cycle-open-archived-trees nil
2822 "Non-nil means, `org-cycle' will open archived trees.
2823 An archived tree is a tree marked with the tag ARCHIVE.
2824 When nil, archived trees will stay folded. You can still open them with
2825 normal outline commands like `show-all', but not with the cycling commands."
2826 :group 'org-archive
2827 :group 'org-cycle
2828 :type 'boolean)
2830 (defcustom org-sparse-tree-open-archived-trees nil
2831 "Non-nil means sparse tree construction shows matches in archived trees.
2832 When nil, matches in these trees are highlighted, but the trees are kept in
2833 collapsed state."
2834 :group 'org-archive
2835 :group 'org-sparse-trees
2836 :type 'boolean)
2838 (defun org-cycle-hide-archived-subtrees (state)
2839 "Re-hide all archived subtrees after a visibility state change."
2840 (when (and (not org-cycle-open-archived-trees)
2841 (not (memq state '(overview folded))))
2842 (save-excursion
2843 (let* ((globalp (memq state '(contents all)))
2844 (beg (if globalp (point-min) (point)))
2845 (end (if globalp (point-max) (org-end-of-subtree t))))
2846 (org-hide-archived-subtrees beg end)
2847 (goto-char beg)
2848 (if (looking-at (concat ".*:" org-archive-tag ":"))
2849 (message "%s" (substitute-command-keys
2850 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2852 (defun org-force-cycle-archived ()
2853 "Cycle subtree even if it is archived."
2854 (interactive)
2855 (setq this-command 'org-cycle)
2856 (let ((org-cycle-open-archived-trees t))
2857 (call-interactively 'org-cycle)))
2859 (defun org-hide-archived-subtrees (beg end)
2860 "Re-hide all archived subtrees after a visibility state change."
2861 (save-excursion
2862 (let* ((re (concat ":" org-archive-tag ":")))
2863 (goto-char beg)
2864 (while (re-search-forward re end t)
2865 (and (org-on-heading-p) (hide-subtree))
2866 (org-end-of-subtree t)))))
2868 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2870 (eval-and-compile
2871 (org-autoload "org-archive"
2872 '(org-add-archive-files org-archive-subtree
2873 org-archive-to-archive-sibling org-toggle-archive-tag)))
2875 ;; Autoload Column View Code
2877 (declare-function org-columns-number-to-string "org-colview")
2878 (declare-function org-columns-get-format-and-top-level "org-colview")
2879 (declare-function org-columns-compute "org-colview")
2881 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2882 '(org-columns-number-to-string org-columns-get-format-and-top-level
2883 org-columns-compute org-agenda-columns org-columns-remove-overlays
2884 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2886 ;; Autoload ID code
2888 (declare-function org-id-store-link "org-id")
2889 (org-autoload "org-id"
2890 '(org-id-get-create org-id-new org-id-copy org-id-get
2891 org-id-get-with-outline-path-completion
2892 org-id-get-with-outline-drilling
2893 org-id-goto org-id-find org-id-store-link))
2895 ;;; Variables for pre-computed regular expressions, all buffer local
2897 (defvar org-drawer-regexp nil
2898 "Matches first line of a hidden block.")
2899 (make-variable-buffer-local 'org-drawer-regexp)
2900 (defvar org-todo-regexp nil
2901 "Matches any of the TODO state keywords.")
2902 (make-variable-buffer-local 'org-todo-regexp)
2903 (defvar org-not-done-regexp nil
2904 "Matches any of the TODO state keywords except the last one.")
2905 (make-variable-buffer-local 'org-not-done-regexp)
2906 (defvar org-todo-line-regexp nil
2907 "Matches a headline and puts TODO state into group 2 if present.")
2908 (make-variable-buffer-local 'org-todo-line-regexp)
2909 (defvar org-complex-heading-regexp nil
2910 "Matches a headline and puts everything into groups:
2911 group 1: the stars
2912 group 2: The todo keyword, maybe
2913 group 3: Priority cookie
2914 group 4: True headline
2915 group 5: Tags")
2916 (make-variable-buffer-local 'org-complex-heading-regexp)
2917 (defvar org-todo-line-tags-regexp nil
2918 "Matches a headline and puts TODO state into group 2 if present.
2919 Also put tags into group 4 if tags are present.")
2920 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2921 (defvar org-nl-done-regexp nil
2922 "Matches newline followed by a headline with the DONE keyword.")
2923 (make-variable-buffer-local 'org-nl-done-regexp)
2924 (defvar org-looking-at-done-regexp nil
2925 "Matches the DONE keyword a point.")
2926 (make-variable-buffer-local 'org-looking-at-done-regexp)
2927 (defvar org-ds-keyword-length 12
2928 "Maximum length of the Deadline and SCHEDULED keywords.")
2929 (make-variable-buffer-local 'org-ds-keyword-length)
2930 (defvar org-deadline-regexp nil
2931 "Matches the DEADLINE keyword.")
2932 (make-variable-buffer-local 'org-deadline-regexp)
2933 (defvar org-deadline-time-regexp nil
2934 "Matches the DEADLINE keyword together with a time stamp.")
2935 (make-variable-buffer-local 'org-deadline-time-regexp)
2936 (defvar org-deadline-line-regexp nil
2937 "Matches the DEADLINE keyword and the rest of the line.")
2938 (make-variable-buffer-local 'org-deadline-line-regexp)
2939 (defvar org-scheduled-regexp nil
2940 "Matches the SCHEDULED keyword.")
2941 (make-variable-buffer-local 'org-scheduled-regexp)
2942 (defvar org-scheduled-time-regexp nil
2943 "Matches the SCHEDULED keyword together with a time stamp.")
2944 (make-variable-buffer-local 'org-scheduled-time-regexp)
2945 (defvar org-closed-time-regexp nil
2946 "Matches the CLOSED keyword together with a time stamp.")
2947 (make-variable-buffer-local 'org-closed-time-regexp)
2949 (defvar org-keyword-time-regexp nil
2950 "Matches any of the 4 keywords, together with the time stamp.")
2951 (make-variable-buffer-local 'org-keyword-time-regexp)
2952 (defvar org-keyword-time-not-clock-regexp nil
2953 "Matches any of the 3 keywords, together with the time stamp.")
2954 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2955 (defvar org-maybe-keyword-time-regexp nil
2956 "Matches a timestamp, possibly preceeded by a keyword.")
2957 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2958 (defvar org-planning-or-clock-line-re nil
2959 "Matches a line with planning or clock info.")
2960 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2962 (defconst org-plain-time-of-day-regexp
2963 (concat
2964 "\\(\\<[012]?[0-9]"
2965 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2966 "\\(--?"
2967 "\\(\\<[012]?[0-9]"
2968 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2969 "\\)?")
2970 "Regular expression to match a plain time or time range.
2971 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2972 groups carry important information:
2973 0 the full match
2974 1 the first time, range or not
2975 8 the second time, if it is a range.")
2977 (defconst org-plain-time-extension-regexp
2978 (concat
2979 "\\(\\<[012]?[0-9]"
2980 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2981 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2982 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2983 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2984 groups carry important information:
2985 0 the full match
2986 7 hours of duration
2987 9 minutes of duration")
2989 (defconst org-stamp-time-of-day-regexp
2990 (concat
2991 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2992 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2993 "\\(--?"
2994 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2995 "Regular expression to match a timestamp time or time range.
2996 After a match, the following groups carry important information:
2997 0 the full match
2998 1 date plus weekday, for backreferencing to make sure both times on same day
2999 2 the first time, range or not
3000 4 the second time, if it is a range.")
3002 (defconst org-startup-options
3003 '(("fold" org-startup-folded t)
3004 ("overview" org-startup-folded t)
3005 ("nofold" org-startup-folded nil)
3006 ("showall" org-startup-folded nil)
3007 ("content" org-startup-folded content)
3008 ("hidestars" org-hide-leading-stars t)
3009 ("showstars" org-hide-leading-stars nil)
3010 ("odd" org-odd-levels-only t)
3011 ("oddeven" org-odd-levels-only nil)
3012 ("align" org-startup-align-all-tables t)
3013 ("noalign" org-startup-align-all-tables nil)
3014 ("customtime" org-display-custom-times t)
3015 ("logdone" org-log-done time)
3016 ("lognotedone" org-log-done note)
3017 ("nologdone" org-log-done nil)
3018 ("lognoteclock-out" org-log-note-clock-out t)
3019 ("nolognoteclock-out" org-log-note-clock-out nil)
3020 ("logrepeat" org-log-repeat state)
3021 ("lognoterepeat" org-log-repeat note)
3022 ("nologrepeat" org-log-repeat nil)
3023 ("fninline" org-footnote-define-inline t)
3024 ("nofninline" org-footnote-define-inline nil)
3025 ("fnlocal" org-footnote-section nil)
3026 ("fnauto" org-footnote-auto-label t)
3027 ("fnprompt" org-footnote-auto-label nil)
3028 ("fnconfirm" org-footnote-auto-label confirm)
3029 ("fnplain" org-footnote-auto-label plain)
3030 ("constcgs" constants-unit-system cgs)
3031 ("constSI" constants-unit-system SI))
3032 "Variable associated with STARTUP options for org-mode.
3033 Each element is a list of three items: The startup options as written
3034 in the #+STARTUP line, the corresponding variable, and the value to
3035 set this variable to if the option is found. An optional forth element PUSH
3036 means to push this value onto the list in the variable.")
3038 (defun org-set-regexps-and-options ()
3039 "Precompute regular expressions for current buffer."
3040 (when (org-mode-p)
3041 (org-set-local 'org-todo-kwd-alist nil)
3042 (org-set-local 'org-todo-key-alist nil)
3043 (org-set-local 'org-todo-key-trigger nil)
3044 (org-set-local 'org-todo-keywords-1 nil)
3045 (org-set-local 'org-done-keywords nil)
3046 (org-set-local 'org-todo-heads nil)
3047 (org-set-local 'org-todo-sets nil)
3048 (org-set-local 'org-todo-log-states nil)
3049 (org-set-local 'org-file-properties nil)
3050 (org-set-local 'org-file-tags nil)
3051 (let ((re (org-make-options-regexp
3052 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3053 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3054 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3055 (splitre "[ \t]+")
3056 kwds kws0 kwsa key log value cat arch tags const links hw dws
3057 tail sep kws1 prio props ftags drawers
3058 ext-setup-or-nil setup-contents (start 0))
3059 (save-excursion
3060 (save-restriction
3061 (widen)
3062 (goto-char (point-min))
3063 (while (or (and ext-setup-or-nil
3064 (string-match re ext-setup-or-nil start)
3065 (setq start (match-end 0)))
3066 (and (setq ext-setup-or-nil nil start 0)
3067 (re-search-forward re nil t)))
3068 (setq key (upcase (match-string 1 ext-setup-or-nil))
3069 value (org-match-string-no-properties 2 ext-setup-or-nil))
3070 (cond
3071 ((equal key "CATEGORY")
3072 (if (string-match "[ \t]+$" value)
3073 (setq value (replace-match "" t t value)))
3074 (setq cat value))
3075 ((member key '("SEQ_TODO" "TODO"))
3076 (push (cons 'sequence (org-split-string value splitre)) kwds))
3077 ((equal key "TYP_TODO")
3078 (push (cons 'type (org-split-string value splitre)) kwds))
3079 ((equal key "TAGS")
3080 (setq tags (append tags (org-split-string value splitre))))
3081 ((equal key "COLUMNS")
3082 (org-set-local 'org-columns-default-format value))
3083 ((equal key "LINK")
3084 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3085 (push (cons (match-string 1 value)
3086 (org-trim (match-string 2 value)))
3087 links)))
3088 ((equal key "PRIORITIES")
3089 (setq prio (org-split-string value " +")))
3090 ((equal key "PROPERTY")
3091 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3092 (push (cons (match-string 1 value) (match-string 2 value))
3093 props)))
3094 ((equal key "FILETAGS")
3095 (when (string-match "\\S-" value)
3096 (setq ftags
3097 (append
3098 ftags
3099 (apply 'append
3100 (mapcar (lambda (x) (org-split-string x ":"))
3101 (org-split-string value)))))))
3102 ((equal key "DRAWERS")
3103 (setq drawers (org-split-string value splitre)))
3104 ((equal key "CONSTANTS")
3105 (setq const (append const (org-split-string value splitre))))
3106 ((equal key "STARTUP")
3107 (let ((opts (org-split-string value splitre))
3108 l var val)
3109 (while (setq l (pop opts))
3110 (when (setq l (assoc l org-startup-options))
3111 (setq var (nth 1 l) val (nth 2 l))
3112 (if (not (nth 3 l))
3113 (set (make-local-variable var) val)
3114 (if (not (listp (symbol-value var)))
3115 (set (make-local-variable var) nil))
3116 (set (make-local-variable var) (symbol-value var))
3117 (add-to-list var val))))))
3118 ((equal key "ARCHIVE")
3119 (string-match " *$" value)
3120 (setq arch (replace-match "" t t value))
3121 (remove-text-properties 0 (length arch)
3122 '(face t fontified t) arch))
3123 ((equal key "SETUPFILE")
3124 (setq setup-contents (org-file-contents
3125 (expand-file-name
3126 (org-remove-double-quotes value))
3127 'noerror))
3128 (if (not ext-setup-or-nil)
3129 (setq ext-setup-or-nil setup-contents start 0)
3130 (setq ext-setup-or-nil
3131 (concat (substring ext-setup-or-nil 0 start)
3132 "\n" setup-contents "\n"
3133 (substring ext-setup-or-nil start)))))
3134 ))))
3135 (when cat
3136 (org-set-local 'org-category (intern cat))
3137 (push (cons "CATEGORY" cat) props))
3138 (when prio
3139 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3140 (setq prio (mapcar 'string-to-char prio))
3141 (org-set-local 'org-highest-priority (nth 0 prio))
3142 (org-set-local 'org-lowest-priority (nth 1 prio))
3143 (org-set-local 'org-default-priority (nth 2 prio)))
3144 (and props (org-set-local 'org-file-properties (nreverse props)))
3145 (and ftags (org-set-local 'org-file-tags ftags))
3146 (and drawers (org-set-local 'org-drawers drawers))
3147 (and arch (org-set-local 'org-archive-location arch))
3148 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3149 ;; Process the TODO keywords
3150 (unless kwds
3151 ;; Use the global values as if they had been given locally.
3152 (setq kwds (default-value 'org-todo-keywords))
3153 (if (stringp (car kwds))
3154 (setq kwds (list (cons org-todo-interpretation
3155 (default-value 'org-todo-keywords)))))
3156 (setq kwds (reverse kwds)))
3157 (setq kwds (nreverse kwds))
3158 (let (inter kws kw)
3159 (while (setq kws (pop kwds))
3160 (setq inter (pop kws) sep (member "|" kws)
3161 kws0 (delete "|" (copy-sequence kws))
3162 kwsa nil
3163 kws1 (mapcar
3164 (lambda (x)
3165 ;; 1 2
3166 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3167 (progn
3168 (setq kw (match-string 1 x)
3169 key (and (match-end 2) (match-string 2 x))
3170 log (org-extract-log-state-settings x))
3171 (push (cons kw (and key (string-to-char key))) kwsa)
3172 (and log (push log org-todo-log-states))
3174 (error "Invalid TODO keyword %s" x)))
3175 kws0)
3176 kwsa (if kwsa (append '((:startgroup))
3177 (nreverse kwsa)
3178 '((:endgroup))))
3179 hw (car kws1)
3180 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3181 tail (list inter hw (car dws) (org-last dws)))
3182 (add-to-list 'org-todo-heads hw 'append)
3183 (push kws1 org-todo-sets)
3184 (setq org-done-keywords (append org-done-keywords dws nil))
3185 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3186 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3187 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3188 (setq org-todo-sets (nreverse org-todo-sets)
3189 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3190 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3191 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3192 ;; Process the constants
3193 (when const
3194 (let (e cst)
3195 (while (setq e (pop const))
3196 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3197 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3198 (setq org-table-formula-constants-local cst)))
3200 ;; Process the tags.
3201 (when tags
3202 (let (e tgs)
3203 (while (setq e (pop tags))
3204 (cond
3205 ((equal e "{") (push '(:startgroup) tgs))
3206 ((equal e "}") (push '(:endgroup) tgs))
3207 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3208 (push (cons (match-string 1 e)
3209 (string-to-char (match-string 2 e)))
3210 tgs))
3211 (t (push (list e) tgs))))
3212 (org-set-local 'org-tag-alist nil)
3213 (while (setq e (pop tgs))
3214 (or (and (stringp (car e))
3215 (assoc (car e) org-tag-alist))
3216 (push e org-tag-alist)))))
3218 ;; Compute the regular expressions and other local variables
3219 (if (not org-done-keywords)
3220 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3221 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3222 (length org-scheduled-string)
3223 (length org-clock-string)
3224 (length org-closed-string)))
3225 org-drawer-regexp
3226 (concat "^[ \t]*:\\("
3227 (mapconcat 'regexp-quote org-drawers "\\|")
3228 "\\):[ \t]*$")
3229 org-not-done-keywords
3230 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3231 org-todo-regexp
3232 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3233 "\\|") "\\)\\>")
3234 org-not-done-regexp
3235 (concat "\\<\\("
3236 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3237 "\\)\\>")
3238 org-todo-line-regexp
3239 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3240 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3241 "\\)\\>\\)?[ \t]*\\(.*\\)")
3242 org-complex-heading-regexp
3243 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3244 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3245 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3246 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3247 org-nl-done-regexp
3248 (concat "\n\\*+[ \t]+"
3249 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3250 "\\)" "\\>")
3251 org-todo-line-tags-regexp
3252 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3253 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3254 (org-re
3255 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3256 org-looking-at-done-regexp
3257 (concat "^" "\\(?:"
3258 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3259 "\\>")
3260 org-deadline-regexp (concat "\\<" org-deadline-string)
3261 org-deadline-time-regexp
3262 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3263 org-deadline-line-regexp
3264 (concat "\\<\\(" org-deadline-string "\\).*")
3265 org-scheduled-regexp
3266 (concat "\\<" org-scheduled-string)
3267 org-scheduled-time-regexp
3268 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3269 org-closed-time-regexp
3270 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3271 org-keyword-time-regexp
3272 (concat "\\<\\(" org-scheduled-string
3273 "\\|" org-deadline-string
3274 "\\|" org-closed-string
3275 "\\|" org-clock-string "\\)"
3276 " *[[<]\\([^]>]+\\)[]>]")
3277 org-keyword-time-not-clock-regexp
3278 (concat "\\<\\(" org-scheduled-string
3279 "\\|" org-deadline-string
3280 "\\|" org-closed-string
3281 "\\)"
3282 " *[[<]\\([^]>]+\\)[]>]")
3283 org-maybe-keyword-time-regexp
3284 (concat "\\(\\<\\(" org-scheduled-string
3285 "\\|" org-deadline-string
3286 "\\|" org-closed-string
3287 "\\|" org-clock-string "\\)\\)?"
3288 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3289 org-planning-or-clock-line-re
3290 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3291 "\\|" org-deadline-string
3292 "\\|" org-closed-string "\\|" org-clock-string
3293 "\\)\\>\\)")
3295 (org-compute-latex-and-specials-regexp)
3296 (org-set-font-lock-defaults))))
3298 (defun org-file-contents (file &optional noerror)
3299 "Return the contents of FILE, as a string."
3300 (if (or (not file)
3301 (not (file-readable-p file)))
3302 (if noerror
3303 (progn
3304 (message "Cannot read file %s" file)
3305 (ding) (sit-for 2)
3307 (error "Cannot read file %s" file))
3308 (with-temp-buffer
3309 (insert-file-contents file)
3310 (buffer-string))))
3312 (defun org-extract-log-state-settings (x)
3313 "Extract the log state setting from a TODO keyword string.
3314 This will extract info from a string like \"WAIT(w@/!)\"."
3315 (let (kw key log1 log2)
3316 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3317 (setq kw (match-string 1 x)
3318 key (and (match-end 2) (match-string 2 x))
3319 log1 (and (match-end 3) (match-string 3 x))
3320 log2 (and (match-end 4) (match-string 4 x)))
3321 (and (or log1 log2)
3322 (list kw
3323 (and log1 (if (equal log1 "!") 'time 'note))
3324 (and log2 (if (equal log2 "!") 'time 'note)))))))
3326 (defun org-remove-keyword-keys (list)
3327 "Remove a pair of parenthesis at the end of each string in LIST."
3328 (mapcar (lambda (x)
3329 (if (string-match "(.*)$" x)
3330 (substring x 0 (match-beginning 0))
3332 list))
3334 ;; FIXME: this could be done much better, using second characters etc.
3335 (defun org-assign-fast-keys (alist)
3336 "Assign fast keys to a keyword-key alist.
3337 Respect keys that are already there."
3338 (let (new e k c c1 c2 (char ?a))
3339 (while (setq e (pop alist))
3340 (cond
3341 ((equal e '(:startgroup)) (push e new))
3342 ((equal e '(:endgroup)) (push e new))
3344 (setq k (car e) c2 nil)
3345 (if (cdr e)
3346 (setq c (cdr e))
3347 ;; automatically assign a character.
3348 (setq c1 (string-to-char
3349 (downcase (substring
3350 k (if (= (string-to-char k) ?@) 1 0)))))
3351 (if (or (rassoc c1 new) (rassoc c1 alist))
3352 (while (or (rassoc char new) (rassoc char alist))
3353 (setq char (1+ char)))
3354 (setq c2 c1))
3355 (setq c (or c2 char)))
3356 (push (cons k c) new))))
3357 (nreverse new)))
3359 ;;; Some variables used in various places
3361 (defvar org-window-configuration nil
3362 "Used in various places to store a window configuration.")
3363 (defvar org-finish-function nil
3364 "Function to be called when `C-c C-c' is used.
3365 This is for getting out of special buffers like remember.")
3368 ;; FIXME: Occasionally check by commenting these, to make sure
3369 ;; no other functions uses these, forgetting to let-bind them.
3370 (defvar entry)
3371 (defvar state)
3372 (defvar last-state)
3373 (defvar date)
3374 (defvar description)
3376 ;; Defined somewhere in this file, but used before definition.
3377 (defvar org-html-entities)
3378 (defvar org-struct-menu)
3379 (defvar org-org-menu)
3380 (defvar org-tbl-menu)
3381 (defvar org-agenda-keymap)
3383 ;;;; Define the Org-mode
3385 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3386 (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."))
3389 ;; We use a before-change function to check if a table might need
3390 ;; an update.
3391 (defvar org-table-may-need-update t
3392 "Indicates that a table might need an update.
3393 This variable is set by `org-before-change-function'.
3394 `org-table-align' sets it back to nil.")
3395 (defun org-before-change-function (beg end)
3396 "Every change indicates that a table might need an update."
3397 (setq org-table-may-need-update t))
3398 (defvar org-mode-map)
3399 (defvar org-mode-hook nil
3400 "Mode hook for Org-mode, run after the mode was turned on.")
3401 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3402 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3403 (defvar org-table-buffer-is-an nil)
3404 (defconst org-outline-regexp "\\*+ ")
3406 ;;;###autoload
3407 (define-derived-mode org-mode outline-mode "Org"
3408 "Outline-based notes management and organizer, alias
3409 \"Carsten's outline-mode for keeping track of everything.\"
3411 Org-mode develops organizational tasks around a NOTES file which
3412 contains information about projects as plain text. Org-mode is
3413 implemented on top of outline-mode, which is ideal to keep the content
3414 of large files well structured. It supports ToDo items, deadlines and
3415 time stamps, which magically appear in the diary listing of the Emacs
3416 calendar. Tables are easily created with a built-in table editor.
3417 Plain text URL-like links connect to websites, emails (VM), Usenet
3418 messages (Gnus), BBDB entries, and any files related to the project.
3419 For printing and sharing of notes, an Org-mode file (or a part of it)
3420 can be exported as a structured ASCII or HTML file.
3422 The following commands are available:
3424 \\{org-mode-map}"
3426 ;; Get rid of Outline menus, they are not needed
3427 ;; Need to do this here because define-derived-mode sets up
3428 ;; the keymap so late. Still, it is a waste to call this each time
3429 ;; we switch another buffer into org-mode.
3430 (if (featurep 'xemacs)
3431 (when (boundp 'outline-mode-menu-heading)
3432 ;; Assume this is Greg's port, it used easymenu
3433 (easy-menu-remove outline-mode-menu-heading)
3434 (easy-menu-remove outline-mode-menu-show)
3435 (easy-menu-remove outline-mode-menu-hide))
3436 (define-key org-mode-map [menu-bar headings] 'undefined)
3437 (define-key org-mode-map [menu-bar hide] 'undefined)
3438 (define-key org-mode-map [menu-bar show] 'undefined))
3440 (org-load-modules-maybe)
3441 (easy-menu-add org-org-menu)
3442 (easy-menu-add org-tbl-menu)
3443 (org-install-agenda-files-menu)
3444 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3445 (org-add-to-invisibility-spec '(org-cwidth))
3446 (when (featurep 'xemacs)
3447 (org-set-local 'line-move-ignore-invisible t))
3448 (org-set-local 'outline-regexp org-outline-regexp)
3449 (org-set-local 'outline-level 'org-outline-level)
3450 (when (and org-ellipsis
3451 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3452 (fboundp 'make-glyph-code))
3453 (unless org-display-table
3454 (setq org-display-table (make-display-table)))
3455 (set-display-table-slot
3456 org-display-table 4
3457 (vconcat (mapcar
3458 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3459 org-ellipsis)))
3460 (if (stringp org-ellipsis) org-ellipsis "..."))))
3461 (setq buffer-display-table org-display-table))
3462 (org-set-regexps-and-options)
3463 (when (and org-tag-faces (not org-tags-special-faces-re))
3464 ;; tag faces set outside customize.... force initialization.
3465 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3466 ;; Calc embedded
3467 (org-set-local 'calc-embedded-open-mode "# ")
3468 (modify-syntax-entry ?# "<")
3469 (modify-syntax-entry ?@ "w")
3470 (if org-startup-truncated (setq truncate-lines t))
3471 (org-set-local 'font-lock-unfontify-region-function
3472 'org-unfontify-region)
3473 ;; Activate before-change-function
3474 (org-set-local 'org-table-may-need-update t)
3475 (org-add-hook 'before-change-functions 'org-before-change-function nil
3476 'local)
3477 ;; Check for running clock before killing a buffer
3478 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3479 ;; Paragraphs and auto-filling
3480 (org-set-autofill-regexps)
3481 (setq indent-line-function 'org-indent-line-function)
3482 (org-update-radio-target-regexp)
3484 ;; Comment characters
3485 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3486 (org-set-local 'comment-padding " ")
3488 ;; Align options lines
3489 (org-set-local
3490 'align-mode-rules-list
3491 '((org-in-buffer-settings
3492 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3493 (modes . '(org-mode)))))
3495 ;; Imenu
3496 (org-set-local 'imenu-create-index-function
3497 'org-imenu-get-tree)
3499 ;; Make isearch reveal context
3500 (if (or (featurep 'xemacs)
3501 (not (boundp 'outline-isearch-open-invisible-function)))
3502 ;; Emacs 21 and XEmacs make use of the hook
3503 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3504 ;; Emacs 22 deals with this through a special variable
3505 (org-set-local 'outline-isearch-open-invisible-function
3506 (lambda (&rest ignore) (org-show-context 'isearch))))
3508 ;; If empty file that did not turn on org-mode automatically, make it to.
3509 (if (and org-insert-mode-line-in-empty-file
3510 (interactive-p)
3511 (= (point-min) (point-max)))
3512 (insert "# -*- mode: org -*-\n\n"))
3514 (unless org-inhibit-startup
3515 (when org-startup-align-all-tables
3516 (let ((bmp (buffer-modified-p)))
3517 (org-table-map-tables 'org-table-align)
3518 (set-buffer-modified-p bmp)))
3519 (org-set-startup-visibility)))
3521 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3523 (defun org-current-time ()
3524 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3525 (if (> (car org-time-stamp-rounding-minutes) 1)
3526 (let ((r (car org-time-stamp-rounding-minutes))
3527 (time (decode-time)))
3528 (apply 'encode-time
3529 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3530 (nthcdr 2 time))))
3531 (current-time)))
3533 ;;;; Font-Lock stuff, including the activators
3535 (defvar org-mouse-map (make-sparse-keymap))
3536 (org-defkey org-mouse-map
3537 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3538 (org-defkey org-mouse-map
3539 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3540 (when org-mouse-1-follows-link
3541 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3542 (when org-tab-follows-link
3543 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3544 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3545 (when org-return-follows-link
3546 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3547 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3549 (require 'font-lock)
3551 (defconst org-non-link-chars "]\t\n\r<>")
3552 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3553 "shell" "elisp"))
3554 (defvar org-link-types-re nil
3555 "Matches a link that has a url-like prefix like \"http:\"")
3556 (defvar org-link-re-with-space nil
3557 "Matches a link with spaces, optional angular brackets around it.")
3558 (defvar org-link-re-with-space2 nil
3559 "Matches a link with spaces, optional angular brackets around it.")
3560 (defvar org-link-re-with-space3 nil
3561 "Matches a link with spaces, only for internal part in bracket links.")
3562 (defvar org-angle-link-re nil
3563 "Matches link with angular brackets, spaces are allowed.")
3564 (defvar org-plain-link-re nil
3565 "Matches plain link, without spaces.")
3566 (defvar org-bracket-link-regexp nil
3567 "Matches a link in double brackets.")
3568 (defvar org-bracket-link-analytic-regexp nil
3569 "Regular expression used to analyze links.
3570 Here is what the match groups contain after a match:
3571 1: http:
3572 2: http
3573 3: path
3574 4: [desc]
3575 5: desc")
3576 (defvar org-bracket-link-analytic-regexp++ nil
3577 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3578 (defvar org-any-link-re nil
3579 "Regular expression matching any link.")
3581 (defun org-make-link-regexps ()
3582 "Update the link regular expressions.
3583 This should be called after the variable `org-link-types' has changed."
3584 (setq org-link-types-re
3585 (concat
3586 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3587 org-link-re-with-space
3588 (concat
3589 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3590 "\\([^" org-non-link-chars " ]"
3591 "[^" org-non-link-chars "]*"
3592 "[^" org-non-link-chars " ]\\)>?")
3593 org-link-re-with-space2
3594 (concat
3595 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3596 "\\([^" org-non-link-chars " ]"
3597 "[^\t\n\r]*"
3598 "[^" org-non-link-chars " ]\\)>?")
3599 org-link-re-with-space3
3600 (concat
3601 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3602 "\\([^" org-non-link-chars " ]"
3603 "[^\t\n\r]*\\)")
3604 org-angle-link-re
3605 (concat
3606 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3607 "\\([^" org-non-link-chars " ]"
3608 "[^" org-non-link-chars "]*"
3609 "\\)>")
3610 org-plain-link-re
3611 (concat
3612 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3613 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3614 org-bracket-link-regexp
3615 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3616 org-bracket-link-analytic-regexp
3617 (concat
3618 "\\[\\["
3619 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3620 "\\([^]]+\\)"
3621 "\\]"
3622 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3623 "\\]")
3624 org-bracket-link-analytic-regexp++
3625 (concat
3626 "\\[\\["
3627 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3628 "\\([^]]+\\)"
3629 "\\]"
3630 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3631 "\\]")
3632 org-any-link-re
3633 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3634 org-angle-link-re "\\)\\|\\("
3635 org-plain-link-re "\\)")))
3637 (org-make-link-regexps)
3639 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3640 "Regular expression for fast time stamp matching.")
3641 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3642 "Regular expression for fast time stamp matching.")
3643 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3644 "Regular expression matching time strings for analysis.
3645 This one does not require the space after the date, so it can be used
3646 on a string that terminates immediately after the date.")
3647 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3648 "Regular expression matching time strings for analysis.")
3649 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3650 "Regular expression matching time stamps, with groups.")
3651 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3652 "Regular expression matching time stamps (also [..]), with groups.")
3653 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3654 "Regular expression matching a time stamp range.")
3655 (defconst org-tr-regexp-both
3656 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3657 "Regular expression matching a time stamp range.")
3658 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3659 org-ts-regexp "\\)?")
3660 "Regular expression matching a time stamp or time stamp range.")
3661 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3662 org-ts-regexp-both "\\)?")
3663 "Regular expression matching a time stamp or time stamp range.
3664 The time stamps may be either active or inactive.")
3666 (defvar org-emph-face nil)
3668 (defun org-do-emphasis-faces (limit)
3669 "Run through the buffer and add overlays to links."
3670 (let (rtn)
3671 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3672 (if (not (= (char-after (match-beginning 3))
3673 (char-after (match-beginning 4))))
3674 (progn
3675 (setq rtn t)
3676 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3677 'face
3678 (nth 1 (assoc (match-string 3)
3679 org-emphasis-alist)))
3680 (add-text-properties (match-beginning 2) (match-end 2)
3681 '(font-lock-multiline t))
3682 (when org-hide-emphasis-markers
3683 (add-text-properties (match-end 4) (match-beginning 5)
3684 '(invisible org-link))
3685 (add-text-properties (match-beginning 3) (match-end 3)
3686 '(invisible org-link)))))
3687 (backward-char 1))
3688 rtn))
3690 (defun org-emphasize (&optional char)
3691 "Insert or change an emphasis, i.e. a font like bold or italic.
3692 If there is an active region, change that region to a new emphasis.
3693 If there is no region, just insert the marker characters and position
3694 the cursor between them.
3695 CHAR should be either the marker character, or the first character of the
3696 HTML tag associated with that emphasis. If CHAR is a space, the means
3697 to remove the emphasis of the selected region.
3698 If char is not given (for example in an interactive call) it
3699 will be prompted for."
3700 (interactive)
3701 (let ((eal org-emphasis-alist) e det
3702 (erc org-emphasis-regexp-components)
3703 (prompt "")
3704 (string "") beg end move tag c s)
3705 (if (org-region-active-p)
3706 (setq beg (region-beginning) end (region-end)
3707 string (buffer-substring beg end))
3708 (setq move t))
3710 (while (setq e (pop eal))
3711 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3712 c (aref tag 0))
3713 (push (cons c (string-to-char (car e))) det)
3714 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3715 (substring tag 1)))))
3716 (setq det (nreverse det))
3717 (unless char
3718 (message "%s" (concat "Emphasis marker or tag:" prompt))
3719 (setq char (read-char-exclusive)))
3720 (setq char (or (cdr (assoc char det)) char))
3721 (if (equal char ?\ )
3722 (setq s "" move nil)
3723 (unless (assoc (char-to-string char) org-emphasis-alist)
3724 (error "No such emphasis marker: \"%c\"" char))
3725 (setq s (char-to-string char)))
3726 (while (and (> (length string) 1)
3727 (equal (substring string 0 1) (substring string -1))
3728 (assoc (substring string 0 1) org-emphasis-alist))
3729 (setq string (substring string 1 -1)))
3730 (setq string (concat s string s))
3731 (if beg (delete-region beg end))
3732 (unless (or (bolp)
3733 (string-match (concat "[" (nth 0 erc) "\n]")
3734 (char-to-string (char-before (point)))))
3735 (insert " "))
3736 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3737 (char-to-string (char-after (point))))
3738 (insert " ") (backward-char 1))
3739 (insert string)
3740 (and move (backward-char 1))))
3742 (defconst org-nonsticky-props
3743 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3746 (defun org-activate-plain-links (limit)
3747 "Run through the buffer and add overlays to links."
3748 (catch 'exit
3749 (let (f)
3750 (while (re-search-forward org-plain-link-re limit t)
3751 (setq f (get-text-property (match-beginning 0) 'face))
3752 (if (or (eq f 'org-tag)
3753 (and (listp f) (memq 'org-tag f)))
3755 (add-text-properties (match-beginning 0) (match-end 0)
3756 (list 'mouse-face 'highlight
3757 'rear-nonsticky org-nonsticky-props
3758 'keymap org-mouse-map
3760 (throw 'exit t))))))
3762 (defun org-activate-code (limit)
3763 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3764 (progn
3765 (remove-text-properties (match-beginning 0) (match-end 0)
3766 '(display t invisible t intangible t))
3767 t)))
3769 (defun org-activate-angle-links (limit)
3770 "Run through the buffer and add overlays to links."
3771 (if (re-search-forward org-angle-link-re limit t)
3772 (progn
3773 (add-text-properties (match-beginning 0) (match-end 0)
3774 (list 'mouse-face 'highlight
3775 'rear-nonsticky org-nonsticky-props
3776 'keymap org-mouse-map
3778 t)))
3780 (defun org-activate-footnote-links (limit)
3781 "Run through the buffer and add overlays to links."
3782 (if (re-search-forward "\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)"
3783 limit t)
3784 (progn
3785 (add-text-properties (match-beginning 0) (match-end 0)
3786 (list 'mouse-face 'highlight
3787 'rear-nonsticky org-nonsticky-props
3788 'keymap org-mouse-map
3789 'help-echo
3790 (if (= (point-at-bol) (match-beginning 0))
3791 "Footnote definition"
3792 "Footnote reference")
3794 t)))
3796 (defun org-activate-bracket-links (limit)
3797 "Run through the buffer and add overlays to bracketed links."
3798 (if (re-search-forward org-bracket-link-regexp limit t)
3799 (let* ((help (concat "LINK: "
3800 (org-match-string-no-properties 1)))
3801 ;; FIXME: above we should remove the escapes.
3802 ;; but that requires another match, protecting match data,
3803 ;; a lot of overhead for font-lock.
3804 (ip (org-maybe-intangible
3805 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3806 'keymap org-mouse-map 'mouse-face 'highlight
3807 'font-lock-multiline t 'help-echo help)))
3808 (vp (list 'rear-nonsticky org-nonsticky-props
3809 'keymap org-mouse-map 'mouse-face 'highlight
3810 ' font-lock-multiline t 'help-echo help)))
3811 ;; We need to remove the invisible property here. Table narrowing
3812 ;; may have made some of this invisible.
3813 (remove-text-properties (match-beginning 0) (match-end 0)
3814 '(invisible nil))
3815 (if (match-end 3)
3816 (progn
3817 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3818 (add-text-properties (match-beginning 3) (match-end 3) vp)
3819 (add-text-properties (match-end 3) (match-end 0) ip))
3820 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3821 (add-text-properties (match-beginning 1) (match-end 1) vp)
3822 (add-text-properties (match-end 1) (match-end 0) ip))
3823 t)))
3825 (defun org-activate-dates (limit)
3826 "Run through the buffer and add overlays to dates."
3827 (if (re-search-forward org-tsr-regexp-both limit t)
3828 (progn
3829 (add-text-properties (match-beginning 0) (match-end 0)
3830 (list 'mouse-face 'highlight
3831 'rear-nonsticky org-nonsticky-props
3832 'keymap org-mouse-map))
3833 (when org-display-custom-times
3834 (if (match-end 3)
3835 (org-display-custom-time (match-beginning 3) (match-end 3)))
3836 (org-display-custom-time (match-beginning 1) (match-end 1)))
3837 t)))
3839 (defvar org-target-link-regexp nil
3840 "Regular expression matching radio targets in plain text.")
3841 (make-variable-buffer-local 'org-target-link-regexp)
3842 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3843 "Regular expression matching a link target.")
3844 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3845 "Regular expression matching a radio target.")
3846 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3847 "Regular expression matching any target.")
3849 (defun org-activate-target-links (limit)
3850 "Run through the buffer and add overlays to target matches."
3851 (when org-target-link-regexp
3852 (let ((case-fold-search t))
3853 (if (re-search-forward org-target-link-regexp limit t)
3854 (progn
3855 (add-text-properties (match-beginning 0) (match-end 0)
3856 (list 'mouse-face 'highlight
3857 'rear-nonsticky org-nonsticky-props
3858 'keymap org-mouse-map
3859 'help-echo "Radio target link"
3860 'org-linked-text t))
3861 t)))))
3863 (defun org-update-radio-target-regexp ()
3864 "Find all radio targets in this file and update the regular expression."
3865 (interactive)
3866 (when (memq 'radio org-activate-links)
3867 (setq org-target-link-regexp
3868 (org-make-target-link-regexp (org-all-targets 'radio)))
3869 (org-restart-font-lock)))
3871 (defun org-hide-wide-columns (limit)
3872 (let (s e)
3873 (setq s (text-property-any (point) (or limit (point-max))
3874 'org-cwidth t))
3875 (when s
3876 (setq e (next-single-property-change s 'org-cwidth))
3877 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3878 (goto-char e)
3879 t)))
3881 (defvar org-latex-and-specials-regexp nil
3882 "Regular expression for highlighting export special stuff.")
3883 (defvar org-match-substring-regexp)
3884 (defvar org-match-substring-with-braces-regexp)
3885 (defvar org-export-html-special-string-regexps)
3887 (defun org-compute-latex-and-specials-regexp ()
3888 "Compute regular expression for stuff treated specially by exporters."
3889 (if (not org-highlight-latex-fragments-and-specials)
3890 (org-set-local 'org-latex-and-specials-regexp nil)
3891 (require 'org-exp)
3892 (let*
3893 ((matchers (plist-get org-format-latex-options :matchers))
3894 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3895 org-latex-regexps)))
3896 (options (org-combine-plists (org-default-export-plist)
3897 (org-infile-export-plist)))
3898 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3899 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3900 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3901 (org-export-html-expand (plist-get options :expand-quoted-html))
3902 (org-export-with-special-strings (plist-get options :special-strings))
3903 (re-sub
3904 (cond
3905 ((equal org-export-with-sub-superscripts '{})
3906 (list org-match-substring-with-braces-regexp))
3907 (org-export-with-sub-superscripts
3908 (list org-match-substring-regexp))
3909 (t nil)))
3910 (re-latex
3911 (if org-export-with-LaTeX-fragments
3912 (mapcar (lambda (x) (nth 1 x)) latexs)))
3913 (re-macros
3914 (if org-export-with-TeX-macros
3915 (list (concat "\\\\"
3916 (regexp-opt
3917 (append (mapcar 'car org-html-entities)
3918 (if (boundp 'org-latex-entities)
3919 org-latex-entities nil))
3920 'words))) ; FIXME
3922 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3923 (re-special (if org-export-with-special-strings
3924 (mapcar (lambda (x) (car x))
3925 org-export-html-special-string-regexps)))
3926 (re-rest
3927 (delq nil
3928 (list
3929 (if org-export-html-expand "@<[^>\n]+>")
3930 ))))
3931 (org-set-local
3932 'org-latex-and-specials-regexp
3933 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3934 re-rest) "\\|")))))
3936 (defun org-do-latex-and-special-faces (limit)
3937 "Run through the buffer and add overlays to links."
3938 (when org-latex-and-specials-regexp
3939 (let (rtn d)
3940 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3941 limit t))
3942 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3943 'face))
3944 '(org-code org-verbatim underline)))
3945 (progn
3946 (setq rtn t
3947 d (cond ((member (char-after (1+ (match-beginning 0)))
3948 '(?_ ?^)) 1)
3949 (t 0)))
3950 (font-lock-prepend-text-property
3951 (+ d (match-beginning 0)) (match-end 0)
3952 'face 'org-latex-and-export-specials)
3953 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3954 '(font-lock-multiline t)))))
3955 rtn)))
3957 (defun org-restart-font-lock ()
3958 "Restart font-lock-mode, to force refontification."
3959 (when (and (boundp 'font-lock-mode) font-lock-mode)
3960 (font-lock-mode -1)
3961 (font-lock-mode 1)))
3963 (defun org-all-targets (&optional radio)
3964 "Return a list of all targets in this file.
3965 With optional argument RADIO, only find radio targets."
3966 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3967 rtn)
3968 (save-excursion
3969 (goto-char (point-min))
3970 (while (re-search-forward re nil t)
3971 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3972 rtn)))
3974 (defun org-make-target-link-regexp (targets)
3975 "Make regular expression matching all strings in TARGETS.
3976 The regular expression finds the targets also if there is a line break
3977 between words."
3978 (and targets
3979 (concat
3980 "\\<\\("
3981 (mapconcat
3982 (lambda (x)
3983 (while (string-match " +" x)
3984 (setq x (replace-match "\\s-+" t t x)))
3986 targets
3987 "\\|")
3988 "\\)\\>")))
3990 (defun org-activate-tags (limit)
3991 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3992 (progn
3993 (add-text-properties (match-beginning 1) (match-end 1)
3994 (list 'mouse-face 'highlight
3995 'rear-nonsticky org-nonsticky-props
3996 'keymap org-mouse-map))
3997 t)))
3999 (defun org-outline-level ()
4000 (save-excursion
4001 (looking-at outline-regexp)
4002 (if (match-beginning 1)
4003 (+ (org-get-string-indentation (match-string 1)) 1000)
4004 (1- (- (match-end 0) (match-beginning 0))))))
4006 (defvar org-font-lock-keywords nil)
4008 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4009 "Regular expression matching a property line.")
4011 (defvar org-font-lock-hook nil
4012 "Functions to be called for special font lock stuff.")
4014 (defun org-font-lock-hook (limit)
4015 (run-hook-with-args 'org-font-lock-hook limit))
4017 (defun org-set-font-lock-defaults ()
4018 (let* ((em org-fontify-emphasized-text)
4019 (lk org-activate-links)
4020 (org-font-lock-extra-keywords
4021 (list
4022 ;; Call the hook
4023 '(org-font-lock-hook)
4024 ;; Headlines
4025 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4026 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4027 ;; Table lines
4028 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4029 (1 'org-table t))
4030 ;; Table internals
4031 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4032 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4033 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4034 ;; Drawers
4035 (list org-drawer-regexp '(0 'org-special-keyword t))
4036 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4037 ;; Properties
4038 (list org-property-re
4039 '(1 'org-special-keyword t)
4040 '(3 'org-property-value t))
4041 (if org-format-transports-properties-p
4042 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4043 ;; Links
4044 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4045 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4046 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4047 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4048 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4049 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4050 (if (memq 'footnote lk) '(org-activate-footnote-links
4051 (0 'org-footnote t)))
4052 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4053 '(org-hide-wide-columns (0 nil append))
4054 ;; TODO lines
4055 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4056 '(1 (org-get-todo-face 1) t))
4057 ;; DONE
4058 (if org-fontify-done-headline
4059 (list (concat "^[*]+ +\\<\\("
4060 (mapconcat 'regexp-quote org-done-keywords "\\|")
4061 "\\)\\(.*\\)")
4062 '(2 'org-headline-done t))
4063 nil)
4064 ;; Priorities
4065 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4066 ;; Tags
4067 '(org-font-lock-add-tag-faces)
4068 ;; Special keywords
4069 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4070 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4071 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4072 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4073 ;; Emphasis
4074 (if em
4075 (if (featurep 'xemacs)
4076 '(org-do-emphasis-faces (0 nil append))
4077 '(org-do-emphasis-faces)))
4078 ;; Checkboxes
4079 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4080 2 'bold prepend)
4081 (if org-provide-checkbox-statistics
4082 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4083 (0 (org-get-checkbox-statistics-face) t)))
4084 ;; Description list items
4085 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4086 2 'bold prepend)
4087 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4088 '(1 'org-archived prepend))
4089 ;; Specials
4090 '(org-do-latex-and-special-faces)
4091 ;; Code
4092 '(org-activate-code (1 'org-code t))
4093 ;; COMMENT
4094 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4095 "\\|" org-quote-string "\\)\\>")
4096 '(1 'org-special-keyword t))
4097 '("^#.*" (0 'font-lock-comment-face t))
4099 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4100 ;; Now set the full font-lock-keywords
4101 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4102 (org-set-local 'font-lock-defaults
4103 '(org-font-lock-keywords t nil nil backward-paragraph))
4104 (kill-local-variable 'font-lock-keywords) nil))
4106 (defvar org-m nil)
4107 (defvar org-l nil)
4108 (defvar org-f nil)
4109 (defun org-get-level-face (n)
4110 "Get the right face for match N in font-lock matching of headlines."
4111 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4112 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4113 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4114 (cond
4115 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4116 ((eq n 2) org-f)
4117 (t (if org-level-color-stars-only nil org-f))))
4119 (defun org-get-todo-face (kwd)
4120 "Get the right face for a TODO keyword KWD.
4121 If KWD is a number, get the corresponding match group."
4122 (if (numberp kwd) (setq kwd (match-string kwd)))
4123 (or (cdr (assoc kwd org-todo-keyword-faces))
4124 (and (member kwd org-done-keywords) 'org-done)
4125 'org-todo))
4127 (defun org-font-lock-add-tag-faces (limit)
4128 "Add the special tag faces."
4129 (when (and org-tag-faces org-tags-special-faces-re)
4130 (while (re-search-forward org-tags-special-faces-re limit t)
4131 (add-text-properties (match-beginning 1) (match-end 1)
4132 (list 'face (org-get-tag-face 1)
4133 'font-lock-fontified t))
4134 (backward-char 1))))
4136 (defun org-get-tag-face (kwd)
4137 "Get the right face for a TODO keyword KWD.
4138 If KWD is a number, get the corresponding match group."
4139 (if (numberp kwd) (setq kwd (match-string kwd)))
4140 (or (cdr (assoc kwd org-tag-faces))
4141 'org-tag))
4143 (defun org-unfontify-region (beg end &optional maybe_loudly)
4144 "Remove fontification and activation overlays from links."
4145 (font-lock-default-unfontify-region beg end)
4146 (let* ((buffer-undo-list t)
4147 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4148 (inhibit-modification-hooks t)
4149 deactivate-mark buffer-file-name buffer-file-truename)
4150 (remove-text-properties beg end
4151 '(mouse-face t keymap t org-linked-text t
4152 invisible t intangible t))))
4154 ;;;; Visibility cycling, including org-goto and indirect buffer
4156 ;;; Cycling
4158 (defvar org-cycle-global-status nil)
4159 (make-variable-buffer-local 'org-cycle-global-status)
4160 (defvar org-cycle-subtree-status nil)
4161 (make-variable-buffer-local 'org-cycle-subtree-status)
4163 ;;;###autoload
4164 (defun org-cycle (&optional arg)
4165 "Visibility cycling for Org-mode.
4167 - When this function is called with a prefix argument, rotate the entire
4168 buffer through 3 states (global cycling)
4169 1. OVERVIEW: Show only top-level headlines.
4170 2. CONTENTS: Show all headlines of all levels, but no body text.
4171 3. SHOW ALL: Show everything.
4172 When called with two C-u C-u prefixes, switch to the startup visibility,
4173 determined by the variable `org-startup-folded', and by any VISIBILITY
4174 properties in the buffer.
4175 When called with three C-u C-u C-u prefixed, show the entire buffer,
4176 including drawers.
4178 - When point is at the beginning of a headline, rotate the subtree started
4179 by this line through 3 different states (local cycling)
4180 1. FOLDED: Only the main headline is shown.
4181 2. CHILDREN: The main headline and the direct children are shown.
4182 From this state, you can move to one of the children
4183 and zoom in further.
4184 3. SUBTREE: Show the entire subtree, including body text.
4186 - When there is a numeric prefix, go up to a heading with level ARG, do
4187 a `show-subtree' and return to the previous cursor position. If ARG
4188 is negative, go up that many levels.
4190 - When point is not at the beginning of a headline, execute the global
4191 binding for TAB, which is re-indenting the line. See the option
4192 `org-cycle-emulate-tab' for details.
4194 - Special case: if point is at the beginning of the buffer and there is
4195 no headline in line 1, this function will act as if called with prefix arg.
4196 But only if also the variable `org-cycle-global-at-bob' is t."
4197 (interactive "P")
4198 (org-load-modules-maybe)
4199 (let* ((outline-regexp
4200 (if (and (org-mode-p) org-cycle-include-plain-lists)
4201 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4202 outline-regexp))
4203 (bob-special (and org-cycle-global-at-bob (bobp)
4204 (not (looking-at outline-regexp))))
4205 (org-cycle-hook
4206 (if bob-special
4207 (delq 'org-optimize-window-after-visibility-change
4208 (copy-sequence org-cycle-hook))
4209 org-cycle-hook))
4210 (pos (point)))
4212 (if (or bob-special (equal arg '(4)))
4213 ;; special case: use global cycling
4214 (setq arg t))
4216 (cond
4218 ((equal arg '(16))
4219 (org-set-startup-visibility)
4220 (message "Startup visibility, plus VISIBILITY properties"))
4222 ((equal arg '(64))
4223 (show-all)
4224 (message "Entire buffer visible, including drawers"))
4226 ((org-at-table-p 'any)
4227 ;; Enter the table or move to the next field in the table
4228 (or (org-table-recognize-table.el)
4229 (progn
4230 (if arg (org-table-edit-field t)
4231 (org-table-justify-field-maybe)
4232 (call-interactively 'org-table-next-field)))))
4234 ((eq arg t) ;; Global cycling
4236 (cond
4237 ((and (eq last-command this-command)
4238 (eq org-cycle-global-status 'overview))
4239 ;; We just created the overview - now do table of contents
4240 ;; This can be slow in very large buffers, so indicate action
4241 (message "CONTENTS...")
4242 (org-content)
4243 (message "CONTENTS...done")
4244 (setq org-cycle-global-status 'contents)
4245 (run-hook-with-args 'org-cycle-hook 'contents))
4247 ((and (eq last-command this-command)
4248 (eq org-cycle-global-status 'contents))
4249 ;; We just showed the table of contents - now show everything
4250 (show-all)
4251 (message "SHOW ALL")
4252 (setq org-cycle-global-status 'all)
4253 (run-hook-with-args 'org-cycle-hook 'all))
4256 ;; Default action: go to overview
4257 (org-overview)
4258 (message "OVERVIEW")
4259 (setq org-cycle-global-status 'overview)
4260 (run-hook-with-args 'org-cycle-hook 'overview))))
4262 ((and org-drawers org-drawer-regexp
4263 (save-excursion
4264 (beginning-of-line 1)
4265 (looking-at org-drawer-regexp)))
4266 ;; Toggle block visibility
4267 (org-flag-drawer
4268 (not (get-char-property (match-end 0) 'invisible))))
4270 ((integerp arg)
4271 ;; Show-subtree, ARG levels up from here.
4272 (save-excursion
4273 (org-back-to-heading)
4274 (outline-up-heading (if (< arg 0) (- arg)
4275 (- (funcall outline-level) arg)))
4276 (org-show-subtree)))
4278 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4279 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4280 ;; At a heading: rotate between three different views
4281 (org-back-to-heading)
4282 (let ((goal-column 0) eoh eol eos)
4283 ;; First, some boundaries
4284 (save-excursion
4285 (org-back-to-heading)
4286 (save-excursion
4287 (beginning-of-line 2)
4288 (while (and (not (eobp)) ;; this is like `next-line'
4289 (get-char-property (1- (point)) 'invisible))
4290 (beginning-of-line 2)) (setq eol (point)))
4291 (outline-end-of-heading) (setq eoh (point))
4292 (org-end-of-subtree t)
4293 (unless (eobp)
4294 (skip-chars-forward " \t\n")
4295 (beginning-of-line 1) ; in case this is an item
4297 (setq eos (1- (point))))
4298 ;; Find out what to do next and set `this-command'
4299 (cond
4300 ((= eos eoh)
4301 ;; Nothing is hidden behind this heading
4302 (message "EMPTY ENTRY")
4303 (setq org-cycle-subtree-status nil)
4304 (save-excursion
4305 (goto-char eos)
4306 (outline-next-heading)
4307 (if (org-invisible-p) (org-flag-heading nil))))
4308 ((or (>= eol eos)
4309 (not (string-match "\\S-" (buffer-substring eol eos))))
4310 ;; Entire subtree is hidden in one line: open it
4311 (org-show-entry)
4312 (show-children)
4313 (message "CHILDREN")
4314 (save-excursion
4315 (goto-char eos)
4316 (outline-next-heading)
4317 (if (org-invisible-p) (org-flag-heading nil)))
4318 (setq org-cycle-subtree-status 'children)
4319 (run-hook-with-args 'org-cycle-hook 'children))
4320 ((and (eq last-command this-command)
4321 (eq org-cycle-subtree-status 'children))
4322 ;; We just showed the children, now show everything.
4323 (org-show-subtree)
4324 (message "SUBTREE")
4325 (setq org-cycle-subtree-status 'subtree)
4326 (run-hook-with-args 'org-cycle-hook 'subtree))
4328 ;; Default action: hide the subtree.
4329 (hide-subtree)
4330 (message "FOLDED")
4331 (setq org-cycle-subtree-status 'folded)
4332 (run-hook-with-args 'org-cycle-hook 'folded)))))
4334 ;; TAB emulation and template completion
4335 (buffer-read-only (org-back-to-heading))
4337 ((org-try-structure-completion))
4339 ((org-try-cdlatex-tab))
4341 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4342 (or (not (bolp))
4343 (not (looking-at outline-regexp))))
4344 (call-interactively (global-key-binding "\t")))
4346 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4347 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4348 (or (and (eq org-cycle-emulate-tab 'white)
4349 (= (match-end 0) (point-at-eol)))
4350 (and (eq org-cycle-emulate-tab 'whitestart)
4351 (>= (match-end 0) pos))))
4353 (eq org-cycle-emulate-tab t))
4354 (call-interactively (global-key-binding "\t")))
4356 (t (save-excursion
4357 (org-back-to-heading)
4358 (org-cycle))))))
4360 ;;;###autoload
4361 (defun org-global-cycle (&optional arg)
4362 "Cycle the global visibility. For details see `org-cycle'.
4363 With C-u prefix arg, switch to startup visibility.
4364 With a numeric prefix, show all headlines up to that level."
4365 (interactive "P")
4366 (let ((org-cycle-include-plain-lists
4367 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4368 (cond
4369 ((integerp arg)
4370 (show-all)
4371 (hide-sublevels arg)
4372 (setq org-cycle-global-status 'contents))
4373 ((equal arg '(4))
4374 (org-set-startup-visibility)
4375 (message "Startup visibility, plus VISIBILITY properties."))
4377 (org-cycle '(4))))))
4379 (defun org-set-startup-visibility ()
4380 "Set the visibility required by startup options and properties."
4381 (cond
4382 ((eq org-startup-folded t)
4383 (org-cycle '(4)))
4384 ((eq org-startup-folded 'content)
4385 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4386 (org-cycle '(4)) (org-cycle '(4)))))
4387 (org-set-visibility-according-to-property 'no-cleanup)
4388 (org-cycle-hide-archived-subtrees 'all)
4389 (org-cycle-hide-drawers 'all)
4390 (org-cycle-show-empty-lines 'all))
4392 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4393 "Switch subtree visibilities according to :VISIBILITY: property."
4394 (interactive)
4395 (let (state)
4396 (save-excursion
4397 (goto-char (point-min))
4398 (while (re-search-forward
4399 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4400 nil t)
4401 (setq state (match-string 1))
4402 (save-excursion
4403 (org-back-to-heading t)
4404 (hide-subtree)
4405 (org-reveal)
4406 (cond
4407 ((equal state '("fold" "folded"))
4408 (hide-subtree))
4409 ((equal state "children")
4410 (org-show-hidden-entry)
4411 (show-children))
4412 ((equal state "content")
4413 (save-excursion
4414 (save-restriction
4415 (org-narrow-to-subtree)
4416 (org-content))))
4417 ((member state '("all" "showall"))
4418 (show-subtree)))))
4419 (unless no-cleanup
4420 (org-cycle-hide-archived-subtrees 'all)
4421 (org-cycle-hide-drawers 'all)
4422 (org-cycle-show-empty-lines 'all)))))
4424 (defun org-overview ()
4425 "Switch to overview mode, showing only top-level headlines.
4426 Really, this shows all headlines with level equal or greater than the level
4427 of the first headline in the buffer. This is important, because if the
4428 first headline is not level one, then (hide-sublevels 1) gives confusing
4429 results."
4430 (interactive)
4431 (let ((level (save-excursion
4432 (goto-char (point-min))
4433 (if (re-search-forward (concat "^" outline-regexp) nil t)
4434 (progn
4435 (goto-char (match-beginning 0))
4436 (funcall outline-level))))))
4437 (and level (hide-sublevels level))))
4439 (defun org-content (&optional arg)
4440 "Show all headlines in the buffer, like a table of contents.
4441 With numerical argument N, show content up to level N."
4442 (interactive "P")
4443 (save-excursion
4444 ;; Visit all headings and show their offspring
4445 (and (integerp arg) (org-overview))
4446 (goto-char (point-max))
4447 (catch 'exit
4448 (while (and (progn (condition-case nil
4449 (outline-previous-visible-heading 1)
4450 (error (goto-char (point-min))))
4452 (looking-at outline-regexp))
4453 (if (integerp arg)
4454 (show-children (1- arg))
4455 (show-branches))
4456 (if (bobp) (throw 'exit nil))))))
4459 (defun org-optimize-window-after-visibility-change (state)
4460 "Adjust the window after a change in outline visibility.
4461 This function is the default value of the hook `org-cycle-hook'."
4462 (when (get-buffer-window (current-buffer))
4463 (cond
4464 ; ((eq state 'overview) (org-first-headline-recenter 1))
4465 ; ((eq state 'overview) (org-beginning-of-line))
4466 ((eq state 'content) nil)
4467 ((eq state 'all) nil)
4468 ((eq state 'folded) nil)
4469 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4470 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4472 (defun org-compact-display-after-subtree-move ()
4473 (let (beg end)
4474 (save-excursion
4475 (if (org-up-heading-safe)
4476 (progn
4477 (hide-subtree)
4478 (show-entry)
4479 (show-children)
4480 (org-cycle-show-empty-lines 'children)
4481 (org-cycle-hide-drawers 'children))
4482 (org-overview)))))
4484 (defun org-cycle-show-empty-lines (state)
4485 "Show empty lines above all visible headlines.
4486 The region to be covered depends on STATE when called through
4487 `org-cycle-hook'. Lisp program can use t for STATE to get the
4488 entire buffer covered. Note that an empty line is only shown if there
4489 are at least `org-cycle-separator-lines' empty lines before the headline."
4490 (when (> org-cycle-separator-lines 0)
4491 (save-excursion
4492 (let* ((n org-cycle-separator-lines)
4493 (re (cond
4494 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4495 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4496 (t (let ((ns (number-to-string (- n 2))))
4497 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4498 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4499 beg end)
4500 (cond
4501 ((memq state '(overview contents t))
4502 (setq beg (point-min) end (point-max)))
4503 ((memq state '(children folded))
4504 (setq beg (point) end (progn (org-end-of-subtree t t)
4505 (beginning-of-line 2)
4506 (point)))))
4507 (when beg
4508 (goto-char beg)
4509 (while (re-search-forward re end t)
4510 (if (not (get-char-property (match-end 1) 'invisible))
4511 (outline-flag-region
4512 (match-beginning 1) (match-end 1) nil)))))))
4513 ;; Never hide empty lines at the end of the file.
4514 (save-excursion
4515 (goto-char (point-max))
4516 (outline-previous-heading)
4517 (outline-end-of-heading)
4518 (if (and (looking-at "[ \t\n]+")
4519 (= (match-end 0) (point-max)))
4520 (outline-flag-region (point) (match-end 0) nil))))
4522 (defun org-show-empty-lines-in-parent ()
4523 "Move to the parent and re-show empty lines before visible headlines."
4524 (save-excursion
4525 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4526 (org-cycle-show-empty-lines context))))
4528 (defun org-cycle-hide-drawers (state)
4529 "Re-hide all drawers after a visibility state change."
4530 (when (and (org-mode-p)
4531 (not (memq state '(overview folded))))
4532 (save-excursion
4533 (let* ((globalp (memq state '(contents all)))
4534 (beg (if globalp (point-min) (point)))
4535 (end (if globalp (point-max) (org-end-of-subtree t))))
4536 (goto-char beg)
4537 (while (re-search-forward org-drawer-regexp end t)
4538 (org-flag-drawer t))))))
4540 (defun org-flag-drawer (flag)
4541 (save-excursion
4542 (beginning-of-line 1)
4543 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4544 (let ((b (match-end 0))
4545 (outline-regexp org-outline-regexp))
4546 (if (re-search-forward
4547 "^[ \t]*:END:"
4548 (save-excursion (outline-next-heading) (point)) t)
4549 (outline-flag-region b (point-at-eol) flag)
4550 (error ":END: line missing"))))))
4552 (defun org-subtree-end-visible-p ()
4553 "Is the end of the current subtree visible?"
4554 (pos-visible-in-window-p
4555 (save-excursion (org-end-of-subtree t) (point))))
4557 (defun org-first-headline-recenter (&optional N)
4558 "Move cursor to the first headline and recenter the headline.
4559 Optional argument N means, put the headline into the Nth line of the window."
4560 (goto-char (point-min))
4561 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4562 (beginning-of-line)
4563 (recenter (prefix-numeric-value N))))
4565 ;;; Org-goto
4567 (defvar org-goto-window-configuration nil)
4568 (defvar org-goto-marker nil)
4569 (defvar org-goto-map
4570 (let ((map (make-sparse-keymap)))
4571 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4572 (while (setq cmd (pop cmds))
4573 (substitute-key-definition cmd cmd map global-map)))
4574 (suppress-keymap map)
4575 (org-defkey map "\C-m" 'org-goto-ret)
4576 (org-defkey map [(return)] 'org-goto-ret)
4577 (org-defkey map [(left)] 'org-goto-left)
4578 (org-defkey map [(right)] 'org-goto-right)
4579 (org-defkey map [(control ?g)] 'org-goto-quit)
4580 (org-defkey map "\C-i" 'org-cycle)
4581 (org-defkey map [(tab)] 'org-cycle)
4582 (org-defkey map [(down)] 'outline-next-visible-heading)
4583 (org-defkey map [(up)] 'outline-previous-visible-heading)
4584 (if org-goto-auto-isearch
4585 (if (fboundp 'define-key-after)
4586 (define-key-after map [t] 'org-goto-local-auto-isearch)
4587 nil)
4588 (org-defkey map "q" 'org-goto-quit)
4589 (org-defkey map "n" 'outline-next-visible-heading)
4590 (org-defkey map "p" 'outline-previous-visible-heading)
4591 (org-defkey map "f" 'outline-forward-same-level)
4592 (org-defkey map "b" 'outline-backward-same-level)
4593 (org-defkey map "u" 'outline-up-heading))
4594 (org-defkey map "/" 'org-occur)
4595 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4596 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4597 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4598 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4599 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4600 map))
4602 (defconst org-goto-help
4603 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4604 RET=jump to location [Q]uit and return to previous location
4605 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4607 (defvar org-goto-start-pos) ; dynamically scoped parameter
4609 ;; FIXME: Docstring doe not mention both interfaces
4610 (defun org-goto (&optional alternative-interface)
4611 "Look up a different location in the current file, keeping current visibility.
4613 When you want look-up or go to a different location in a document, the
4614 fastest way is often to fold the entire buffer and then dive into the tree.
4615 This method has the disadvantage, that the previous location will be folded,
4616 which may not be what you want.
4618 This command works around this by showing a copy of the current buffer
4619 in an indirect buffer, in overview mode. You can dive into the tree in
4620 that copy, use org-occur and incremental search to find a location.
4621 When pressing RET or `Q', the command returns to the original buffer in
4622 which the visibility is still unchanged. After RET is will also jump to
4623 the location selected in the indirect buffer and expose the
4624 the headline hierarchy above."
4625 (interactive "P")
4626 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4627 (org-refile-use-outline-path t)
4628 (interface
4629 (if (not alternative-interface)
4630 org-goto-interface
4631 (if (eq org-goto-interface 'outline)
4632 'outline-path-completion
4633 'outline)))
4634 (org-goto-start-pos (point))
4635 (selected-point
4636 (if (eq interface 'outline)
4637 (car (org-get-location (current-buffer) org-goto-help))
4638 (nth 3 (org-refile-get-location "Goto: ")))))
4639 (if selected-point
4640 (progn
4641 (org-mark-ring-push org-goto-start-pos)
4642 (goto-char selected-point)
4643 (if (or (org-invisible-p) (org-invisible-p2))
4644 (org-show-context 'org-goto)))
4645 (message "Quit"))))
4647 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4648 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4649 (defvar org-goto-local-auto-isearch-map) ; defined below
4651 (defun org-get-location (buf help)
4652 "Let the user select a location in the Org-mode buffer BUF.
4653 This function uses a recursive edit. It returns the selected position
4654 or nil."
4655 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4656 (isearch-hide-immediately nil)
4657 (isearch-search-fun-function
4658 (lambda () 'org-goto-local-search-headings))
4659 (org-goto-selected-point org-goto-exit-command))
4660 (save-excursion
4661 (save-window-excursion
4662 (delete-other-windows)
4663 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4664 (switch-to-buffer
4665 (condition-case nil
4666 (make-indirect-buffer (current-buffer) "*org-goto*")
4667 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4668 (with-output-to-temp-buffer "*Help*"
4669 (princ help))
4670 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4671 (setq buffer-read-only nil)
4672 (let ((org-startup-truncated t)
4673 (org-startup-folded nil)
4674 (org-startup-align-all-tables nil))
4675 (org-mode)
4676 (org-overview))
4677 (setq buffer-read-only t)
4678 (if (and (boundp 'org-goto-start-pos)
4679 (integer-or-marker-p org-goto-start-pos))
4680 (let ((org-show-hierarchy-above t)
4681 (org-show-siblings t)
4682 (org-show-following-heading t))
4683 (goto-char org-goto-start-pos)
4684 (and (org-invisible-p) (org-show-context)))
4685 (goto-char (point-min)))
4686 (org-beginning-of-line)
4687 (message "Select location and press RET")
4688 (use-local-map org-goto-map)
4689 (recursive-edit)
4691 (kill-buffer "*org-goto*")
4692 (cons org-goto-selected-point org-goto-exit-command)))
4694 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4695 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4696 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4697 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4699 (defun org-goto-local-search-headings (string bound noerror)
4700 "Search and make sure that any matches are in headlines."
4701 (catch 'return
4702 (while (if isearch-forward
4703 (search-forward string bound noerror)
4704 (search-backward string bound noerror))
4705 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4706 (and (member :headline context)
4707 (not (member :tags context))))
4708 (throw 'return (point))))))
4710 (defun org-goto-local-auto-isearch ()
4711 "Start isearch."
4712 (interactive)
4713 (goto-char (point-min))
4714 (let ((keys (this-command-keys)))
4715 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4716 (isearch-mode t)
4717 (isearch-process-search-char (string-to-char keys)))))
4719 (defun org-goto-ret (&optional arg)
4720 "Finish `org-goto' by going to the new location."
4721 (interactive "P")
4722 (setq org-goto-selected-point (point)
4723 org-goto-exit-command 'return)
4724 (throw 'exit nil))
4726 (defun org-goto-left ()
4727 "Finish `org-goto' by going to the new location."
4728 (interactive)
4729 (if (org-on-heading-p)
4730 (progn
4731 (beginning-of-line 1)
4732 (setq org-goto-selected-point (point)
4733 org-goto-exit-command 'left)
4734 (throw 'exit nil))
4735 (error "Not on a heading")))
4737 (defun org-goto-right ()
4738 "Finish `org-goto' by going to the new location."
4739 (interactive)
4740 (if (org-on-heading-p)
4741 (progn
4742 (setq org-goto-selected-point (point)
4743 org-goto-exit-command 'right)
4744 (throw 'exit nil))
4745 (error "Not on a heading")))
4747 (defun org-goto-quit ()
4748 "Finish `org-goto' without cursor motion."
4749 (interactive)
4750 (setq org-goto-selected-point nil)
4751 (setq org-goto-exit-command 'quit)
4752 (throw 'exit nil))
4754 ;;; Indirect buffer display of subtrees
4756 (defvar org-indirect-dedicated-frame nil
4757 "This is the frame being used for indirect tree display.")
4758 (defvar org-last-indirect-buffer nil)
4760 (defun org-tree-to-indirect-buffer (&optional arg)
4761 "Create indirect buffer and narrow it to current subtree.
4762 With numerical prefix ARG, go up to this level and then take that tree.
4763 If ARG is negative, go up that many levels.
4764 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4765 indirect buffer previously made with this command, to avoid proliferation of
4766 indirect buffers. However, when you call the command with a `C-u' prefix, or
4767 when `org-indirect-buffer-display' is `new-frame', the last buffer
4768 is kept so that you can work with several indirect buffers at the same time.
4769 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4770 requests that a new frame be made for the new buffer, so that the dedicated
4771 frame is not changed."
4772 (interactive "P")
4773 (let ((cbuf (current-buffer))
4774 (cwin (selected-window))
4775 (pos (point))
4776 beg end level heading ibuf)
4777 (save-excursion
4778 (org-back-to-heading t)
4779 (when (numberp arg)
4780 (setq level (org-outline-level))
4781 (if (< arg 0) (setq arg (+ level arg)))
4782 (while (> (setq level (org-outline-level)) arg)
4783 (outline-up-heading 1 t)))
4784 (setq beg (point)
4785 heading (org-get-heading))
4786 (org-end-of-subtree t) (setq end (point)))
4787 (if (and (buffer-live-p org-last-indirect-buffer)
4788 (not (eq org-indirect-buffer-display 'new-frame))
4789 (not arg))
4790 (kill-buffer org-last-indirect-buffer))
4791 (setq ibuf (org-get-indirect-buffer cbuf)
4792 org-last-indirect-buffer ibuf)
4793 (cond
4794 ((or (eq org-indirect-buffer-display 'new-frame)
4795 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4796 (select-frame (make-frame))
4797 (delete-other-windows)
4798 (switch-to-buffer ibuf)
4799 (org-set-frame-title heading))
4800 ((eq org-indirect-buffer-display 'dedicated-frame)
4801 (raise-frame
4802 (select-frame (or (and org-indirect-dedicated-frame
4803 (frame-live-p org-indirect-dedicated-frame)
4804 org-indirect-dedicated-frame)
4805 (setq org-indirect-dedicated-frame (make-frame)))))
4806 (delete-other-windows)
4807 (switch-to-buffer ibuf)
4808 (org-set-frame-title (concat "Indirect: " heading)))
4809 ((eq org-indirect-buffer-display 'current-window)
4810 (switch-to-buffer ibuf))
4811 ((eq org-indirect-buffer-display 'other-window)
4812 (pop-to-buffer ibuf))
4813 (t (error "Invalid value.")))
4814 (if (featurep 'xemacs)
4815 (save-excursion (org-mode) (turn-on-font-lock)))
4816 (narrow-to-region beg end)
4817 (show-all)
4818 (goto-char pos)
4819 (and (window-live-p cwin) (select-window cwin))))
4821 (defun org-get-indirect-buffer (&optional buffer)
4822 (setq buffer (or buffer (current-buffer)))
4823 (let ((n 1) (base (buffer-name buffer)) bname)
4824 (while (buffer-live-p
4825 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4826 (setq n (1+ n)))
4827 (condition-case nil
4828 (make-indirect-buffer buffer bname 'clone)
4829 (error (make-indirect-buffer buffer bname)))))
4831 (defun org-set-frame-title (title)
4832 "Set the title of the current frame to the string TITLE."
4833 ;; FIXME: how to name a single frame in XEmacs???
4834 (unless (featurep 'xemacs)
4835 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4837 ;;;; Structure editing
4839 ;;; Inserting headlines
4841 (defun org-previous-line-empty-p ()
4842 (save-excursion
4843 (and (not (bobp))
4844 (or (beginning-of-line 0) t)
4845 (save-match-data
4846 (looking-at "[ \t]*$")))))
4848 (defun org-insert-heading (&optional force-heading)
4849 "Insert a new heading or item with same depth at point.
4850 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4851 If point is at the beginning of a headline, insert a sibling before the
4852 current headline. If point is not at the beginning, do not split the line,
4853 but create the new headline after the current line."
4854 (interactive "P")
4855 (if (= (buffer-size) 0)
4856 (insert "\n* ")
4857 (when (or force-heading (not (org-insert-item)))
4858 (let* ((empty-line-p nil)
4859 (head (save-excursion
4860 (condition-case nil
4861 (progn
4862 (org-back-to-heading)
4863 (setq empty-line-p (org-previous-line-empty-p))
4864 (match-string 0))
4865 (error "*"))))
4866 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4867 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4868 pos hide-previous previous-pos)
4869 (cond
4870 ((and (org-on-heading-p) (bolp)
4871 (or (bobp)
4872 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4873 ;; insert before the current line
4874 (open-line (if blank 2 1)))
4875 ((and (bolp)
4876 (or (bobp)
4877 (save-excursion
4878 (backward-char 1) (not (org-invisible-p)))))
4879 ;; insert right here
4880 nil)
4882 ;; somewhere in the line
4883 (save-excursion
4884 (setq previous-pos (point-at-bol))
4885 (end-of-line)
4886 (setq hide-previous (org-invisible-p)))
4887 (and org-insert-heading-respect-content (org-show-subtree))
4888 (let ((split
4889 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4890 (save-excursion
4891 (let ((p (point)))
4892 (goto-char (point-at-bol))
4893 (and (looking-at org-complex-heading-regexp)
4894 (> p (match-beginning 4)))))))
4895 tags pos)
4896 (cond
4897 (org-insert-heading-respect-content
4898 (org-end-of-subtree nil t)
4899 (or (bolp) (newline))
4900 (or (org-previous-line-empty-p)
4901 (and blank (newline)))
4902 (open-line 1))
4903 ((org-on-heading-p)
4904 (when hide-previous
4905 (show-children)
4906 (org-show-entry))
4907 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4908 (setq tags (and (match-end 2) (match-string 2)))
4909 (and (match-end 1)
4910 (delete-region (match-beginning 1) (match-end 1)))
4911 (setq pos (point-at-bol))
4912 (or split (end-of-line 1))
4913 (delete-horizontal-space)
4914 (newline (if blank 2 1))
4915 (when tags
4916 (save-excursion
4917 (goto-char pos)
4918 (end-of-line 1)
4919 (insert " " tags)
4920 (org-set-tags nil 'align))))
4922 (or split (end-of-line 1))
4923 (newline (if blank 2 1)))))))
4924 (insert head) (just-one-space)
4925 (setq pos (point))
4926 (end-of-line 1)
4927 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4928 (when (and org-insert-heading-respect-content hide-previous)
4929 (save-excursion
4930 (goto-char previous-pos)
4931 (hide-subtree)))
4932 (run-hooks 'org-insert-heading-hook)))))
4934 (defun org-get-heading (&optional no-tags)
4935 "Return the heading of the current entry, without the stars."
4936 (save-excursion
4937 (org-back-to-heading t)
4938 (if (looking-at
4939 (if no-tags
4940 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4941 "\\*+[ \t]+\\([^\r\n]*\\)"))
4942 (match-string 1) "")))
4944 (defun org-heading-components ()
4945 "Return the components of the current heading.
4946 This is a list with the following elements:
4947 - the level as an integer
4948 - the reduced level, different if `org-odd-levels-only' is set.
4949 - the TODO keyword, or nil
4950 - the priority character, like ?A, or nil if no priority is given
4951 - the headline text itself, or the tags string if no headline text
4952 - the tags string, or nil."
4953 (save-excursion
4954 (org-back-to-heading t)
4955 (if (looking-at org-complex-heading-regexp)
4956 (list (length (match-string 1))
4957 (org-reduced-level (length (match-string 1)))
4958 (org-match-string-no-properties 2)
4959 (and (match-end 3) (aref (match-string 3) 2))
4960 (org-match-string-no-properties 4)
4961 (org-match-string-no-properties 5)))))
4963 (defun org-insert-heading-after-current ()
4964 "Insert a new heading with same level as current, after current subtree."
4965 (interactive)
4966 (org-back-to-heading)
4967 (org-insert-heading)
4968 (org-move-subtree-down)
4969 (end-of-line 1))
4971 (defun org-insert-heading-respect-content ()
4972 (interactive)
4973 (let ((org-insert-heading-respect-content t))
4974 (org-insert-heading t)))
4976 (defun org-insert-todo-heading-respect-content (&optional force-state)
4977 (interactive "P")
4978 (let ((org-insert-heading-respect-content t))
4979 (org-insert-todo-heading force-state t)))
4981 (defun org-insert-todo-heading (arg &optional force-heading)
4982 "Insert a new heading with the same level and TODO state as current heading.
4983 If the heading has no TODO state, or if the state is DONE, use the first
4984 state (TODO by default). Also with prefix arg, force first state."
4985 (interactive "P")
4986 (when (or force-heading (not (org-insert-item 'checkbox)))
4987 (org-insert-heading force-heading)
4988 (save-excursion
4989 (org-back-to-heading)
4990 (outline-previous-heading)
4991 (looking-at org-todo-line-regexp))
4992 (if (or arg
4993 (not (match-beginning 2))
4994 (member (match-string 2) org-done-keywords))
4995 (insert (car org-todo-keywords-1) " ")
4996 (insert (match-string 2) " "))
4997 (when org-provide-todo-statistics
4998 (org-update-parent-todo-statistics))))
5000 (defun org-insert-subheading (arg)
5001 "Insert a new subheading and demote it.
5002 Works for outline headings and for plain lists alike."
5003 (interactive "P")
5004 (org-insert-heading arg)
5005 (cond
5006 ((org-on-heading-p) (org-do-demote))
5007 ((org-at-item-p) (org-indent-item 1))))
5009 (defun org-insert-todo-subheading (arg)
5010 "Insert a new subheading with TODO keyword or checkbox and demote it.
5011 Works for outline headings and for plain lists alike."
5012 (interactive "P")
5013 (org-insert-todo-heading arg)
5014 (cond
5015 ((org-on-heading-p) (org-do-demote))
5016 ((org-at-item-p) (org-indent-item 1))))
5018 ;;; Promotion and Demotion
5020 (defun org-promote-subtree ()
5021 "Promote the entire subtree.
5022 See also `org-promote'."
5023 (interactive)
5024 (save-excursion
5025 (org-map-tree 'org-promote))
5026 (org-fix-position-after-promote))
5028 (defun org-demote-subtree ()
5029 "Demote the entire subtree. See `org-demote'.
5030 See also `org-promote'."
5031 (interactive)
5032 (save-excursion
5033 (org-map-tree 'org-demote))
5034 (org-fix-position-after-promote))
5037 (defun org-do-promote ()
5038 "Promote the current heading higher up the tree.
5039 If the region is active in `transient-mark-mode', promote all headings
5040 in the region."
5041 (interactive)
5042 (save-excursion
5043 (if (org-region-active-p)
5044 (org-map-region 'org-promote (region-beginning) (region-end))
5045 (org-promote)))
5046 (org-fix-position-after-promote))
5048 (defun org-do-demote ()
5049 "Demote the current heading lower down the tree.
5050 If the region is active in `transient-mark-mode', demote all headings
5051 in the region."
5052 (interactive)
5053 (save-excursion
5054 (if (org-region-active-p)
5055 (org-map-region 'org-demote (region-beginning) (region-end))
5056 (org-demote)))
5057 (org-fix-position-after-promote))
5059 (defun org-fix-position-after-promote ()
5060 "Make sure that after pro/demotion cursor position is right."
5061 (let ((pos (point)))
5062 (when (save-excursion
5063 (beginning-of-line 1)
5064 (looking-at org-todo-line-regexp)
5065 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5066 (cond ((eobp) (insert " "))
5067 ((eolp) (insert " "))
5068 ((equal (char-after) ?\ ) (forward-char 1))))))
5070 (defun org-reduced-level (l)
5071 "Compute the effective level of a heading.
5072 This takes into account the setting of `org-odd-levels-only'."
5073 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5075 (defun org-get-valid-level (level &optional change)
5076 "Rectify a level change under the influence of `org-odd-levels-only'
5077 LEVEL is a current level, CHANGE is by how much the level should be
5078 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5079 even level numbers will become the next higher odd number."
5080 (if org-odd-levels-only
5081 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5082 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5083 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5084 (max 1 (+ level change))))
5086 (if (boundp 'define-obsolete-function-alias)
5087 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5088 (define-obsolete-function-alias 'org-get-legal-level
5089 'org-get-valid-level)
5090 (define-obsolete-function-alias 'org-get-legal-level
5091 'org-get-valid-level "23.1")))
5093 (defun org-promote ()
5094 "Promote the current heading higher up the tree.
5095 If the region is active in `transient-mark-mode', promote all headings
5096 in the region."
5097 (org-back-to-heading t)
5098 (let* ((level (save-match-data (funcall outline-level)))
5099 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5100 (diff (abs (- level (length up-head) -1))))
5101 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5102 (replace-match up-head nil t)
5103 ;; Fixup tag positioning
5104 (and org-auto-align-tags (org-set-tags nil t))
5105 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5107 (defun org-demote ()
5108 "Demote the current heading lower down the tree.
5109 If the region is active in `transient-mark-mode', demote all headings
5110 in the region."
5111 (org-back-to-heading t)
5112 (let* ((level (save-match-data (funcall outline-level)))
5113 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5114 (diff (abs (- level (length down-head) -1))))
5115 (replace-match down-head nil t)
5116 ;; Fixup tag positioning
5117 (and org-auto-align-tags (org-set-tags nil t))
5118 (if org-adapt-indentation (org-fixup-indentation diff))))
5120 (defun org-map-tree (fun)
5121 "Call FUN for every heading underneath the current one."
5122 (org-back-to-heading)
5123 (let ((level (funcall outline-level)))
5124 (save-excursion
5125 (funcall fun)
5126 (while (and (progn
5127 (outline-next-heading)
5128 (> (funcall outline-level) level))
5129 (not (eobp)))
5130 (funcall fun)))))
5132 (defun org-map-region (fun beg end)
5133 "Call FUN for every heading between BEG and END."
5134 (let ((org-ignore-region t))
5135 (save-excursion
5136 (setq end (copy-marker end))
5137 (goto-char beg)
5138 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5139 (< (point) end))
5140 (funcall fun))
5141 (while (and (progn
5142 (outline-next-heading)
5143 (< (point) end))
5144 (not (eobp)))
5145 (funcall fun)))))
5147 (defun org-fixup-indentation (diff)
5148 "Change the indentation in the current entry by DIFF
5149 However, if any line in the current entry has no indentation, or if it
5150 would end up with no indentation after the change, nothing at all is done."
5151 (save-excursion
5152 (let ((end (save-excursion (outline-next-heading)
5153 (point-marker)))
5154 (prohibit (if (> diff 0)
5155 "^\\S-"
5156 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5157 col)
5158 (unless (save-excursion (end-of-line 1)
5159 (re-search-forward prohibit end t))
5160 (while (and (< (point) end)
5161 (re-search-forward "^[ \t]+" end t))
5162 (goto-char (match-end 0))
5163 (setq col (current-column))
5164 (if (< diff 0) (replace-match ""))
5165 (org-indent-to-column (+ diff col))))
5166 (move-marker end nil))))
5168 (defun org-convert-to-odd-levels ()
5169 "Convert an org-mode file with all levels allowed to one with odd levels.
5170 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5171 level 5 etc."
5172 (interactive)
5173 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5174 (let ((org-odd-levels-only nil) n)
5175 (save-excursion
5176 (goto-char (point-min))
5177 (while (re-search-forward "^\\*\\*+ " nil t)
5178 (setq n (- (length (match-string 0)) 2))
5179 (while (>= (setq n (1- n)) 0)
5180 (org-demote))
5181 (end-of-line 1))))))
5184 (defun org-convert-to-oddeven-levels ()
5185 "Convert an org-mode file with only odd levels to one with odd and even levels.
5186 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5187 section with an even level, conversion would destroy the structure of the file. An error
5188 is signaled in this case."
5189 (interactive)
5190 (goto-char (point-min))
5191 ;; First check if there are no even levels
5192 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5193 (org-show-context t)
5194 (error "Not all levels are odd in this file. Conversion not possible."))
5195 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5196 (let ((org-odd-levels-only nil) n)
5197 (save-excursion
5198 (goto-char (point-min))
5199 (while (re-search-forward "^\\*\\*+ " nil t)
5200 (setq n (/ (1- (length (match-string 0))) 2))
5201 (while (>= (setq n (1- n)) 0)
5202 (org-promote))
5203 (end-of-line 1))))))
5205 (defun org-tr-level (n)
5206 "Make N odd if required."
5207 (if org-odd-levels-only (1+ (/ n 2)) n))
5209 ;;; Vertical tree motion, cutting and pasting of subtrees
5211 (defun org-move-subtree-up (&optional arg)
5212 "Move the current subtree up past ARG headlines of the same level."
5213 (interactive "p")
5214 (org-move-subtree-down (- (prefix-numeric-value arg))))
5216 (defun org-move-subtree-down (&optional arg)
5217 "Move the current subtree down past ARG headlines of the same level."
5218 (interactive "p")
5219 (setq arg (prefix-numeric-value arg))
5220 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5221 'outline-get-last-sibling))
5222 (ins-point (make-marker))
5223 (cnt (abs arg))
5224 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5225 ;; Select the tree
5226 (org-back-to-heading)
5227 (setq beg0 (point))
5228 (save-excursion
5229 (setq ne-beg (org-back-over-empty-lines))
5230 (setq beg (point)))
5231 (save-match-data
5232 (save-excursion (outline-end-of-heading)
5233 (setq folded (org-invisible-p)))
5234 (outline-end-of-subtree))
5235 (outline-next-heading)
5236 (setq ne-end (org-back-over-empty-lines))
5237 (setq end (point))
5238 (goto-char beg0)
5239 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5240 ;; include less whitespace
5241 (save-excursion
5242 (goto-char beg)
5243 (forward-line (- ne-beg ne-end))
5244 (setq beg (point))))
5245 ;; Find insertion point, with error handling
5246 (while (> cnt 0)
5247 (or (and (funcall movfunc) (looking-at outline-regexp))
5248 (progn (goto-char beg0)
5249 (error "Cannot move past superior level or buffer limit")))
5250 (setq cnt (1- cnt)))
5251 (if (> arg 0)
5252 ;; Moving forward - still need to move over subtree
5253 (progn (org-end-of-subtree t t)
5254 (save-excursion
5255 (org-back-over-empty-lines)
5256 (or (bolp) (newline)))))
5257 (setq ne-ins (org-back-over-empty-lines))
5258 (move-marker ins-point (point))
5259 (setq txt (buffer-substring beg end))
5260 (org-save-markers-in-region beg end)
5261 (delete-region beg end)
5262 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5263 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5264 (let ((bbb (point)))
5265 (insert-before-markers txt)
5266 (org-reinstall-markers-in-region bbb)
5267 (move-marker ins-point bbb))
5268 (or (bolp) (insert "\n"))
5269 (setq ins-end (point))
5270 (goto-char ins-point)
5271 (org-skip-whitespace)
5272 (when (and (< arg 0)
5273 (org-first-sibling-p)
5274 (> ne-ins ne-beg))
5275 ;; Move whitespace back to beginning
5276 (save-excursion
5277 (goto-char ins-end)
5278 (let ((kill-whole-line t))
5279 (kill-line (- ne-ins ne-beg)) (point)))
5280 (insert (make-string (- ne-ins ne-beg) ?\n)))
5281 (move-marker ins-point nil)
5282 (org-compact-display-after-subtree-move)
5283 (org-show-empty-lines-in-parent)
5284 (unless folded
5285 (org-show-entry)
5286 (show-children)
5287 (org-cycle-hide-drawers 'children))))
5289 (defvar org-subtree-clip ""
5290 "Clipboard for cut and paste of subtrees.
5291 This is actually only a copy of the kill, because we use the normal kill
5292 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5294 (defvar org-subtree-clip-folded nil
5295 "Was the last copied subtree folded?
5296 This is used to fold the tree back after pasting.")
5298 (defun org-cut-subtree (&optional n)
5299 "Cut the current subtree into the clipboard.
5300 With prefix arg N, cut this many sequential subtrees.
5301 This is a short-hand for marking the subtree and then cutting it."
5302 (interactive "p")
5303 (org-copy-subtree n 'cut))
5305 (defun org-copy-subtree (&optional n cut force-store-markers)
5306 "Cut the current subtree into the clipboard.
5307 With prefix arg N, cut this many sequential subtrees.
5308 This is a short-hand for marking the subtree and then copying it.
5309 If CUT is non-nil, actually cut the subtree.
5310 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5311 of some markers in the region, even if CUT is non-nil. This is
5312 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5313 (interactive "p")
5314 (let (beg end folded (beg0 (point)))
5315 (if (interactive-p)
5316 (org-back-to-heading nil) ; take what looks like a subtree
5317 (org-back-to-heading t)) ; take what is really there
5318 (org-back-over-empty-lines)
5319 (setq beg (point))
5320 (skip-chars-forward " \t\r\n")
5321 (save-match-data
5322 (save-excursion (outline-end-of-heading)
5323 (setq folded (org-invisible-p)))
5324 (condition-case nil
5325 (outline-forward-same-level (1- n))
5326 (error nil))
5327 (org-end-of-subtree t t))
5328 (org-back-over-empty-lines)
5329 (setq end (point))
5330 (goto-char beg0)
5331 (when (> end beg)
5332 (setq org-subtree-clip-folded folded)
5333 (when (or cut force-store-markers)
5334 (org-save-markers-in-region beg end))
5335 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5336 (setq org-subtree-clip (current-kill 0))
5337 (message "%s: Subtree(s) with %d characters"
5338 (if cut "Cut" "Copied")
5339 (length org-subtree-clip)))))
5341 (defun org-paste-subtree (&optional level tree for-yank)
5342 "Paste the clipboard as a subtree, with modification of headline level.
5343 The entire subtree is promoted or demoted in order to match a new headline
5344 level.
5346 If the cursor is at the beginning of a headline, the same level as
5347 that headline is used to paste the tree
5349 If not, the new level is derived from the *visible* headings
5350 before and after the insertion point, and taken to be the inferior headline
5351 level of the two. So if the previous visible heading is level 3 and the
5352 next is level 4 (or vice versa), level 4 will be used for insertion.
5353 This makes sure that the subtree remains an independent subtree and does
5354 not swallow low level entries.
5356 You can also force a different level, either by using a numeric prefix
5357 argument, or by inserting the heading marker by hand. For example, if the
5358 cursor is after \"*****\", then the tree will be shifted to level 5.
5360 If optional TREE is given, use this text instead of the kill ring.
5362 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5363 move back over whitespace before inserting, and move point to the end of
5364 the inserted text when done."
5365 (interactive "P")
5366 (unless (org-kill-is-subtree-p tree)
5367 (error "%s"
5368 (substitute-command-keys
5369 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5370 (let* ((visp (not (org-invisible-p)))
5371 (txt (or tree (and kill-ring (current-kill 0))))
5372 (^re (concat "^\\(" outline-regexp "\\)"))
5373 (re (concat "\\(" outline-regexp "\\)"))
5374 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5376 (old-level (if (string-match ^re txt)
5377 (- (match-end 0) (match-beginning 0) 1)
5378 -1))
5379 (force-level (cond (level (prefix-numeric-value level))
5380 ((and (looking-at "[ \t]*$")
5381 (string-match
5382 ^re_ (buffer-substring
5383 (point-at-bol) (point))))
5384 (- (match-end 1) (match-beginning 1)))
5385 ((and (bolp)
5386 (looking-at org-outline-regexp))
5387 (- (match-end 0) (point) 1))
5388 (t nil)))
5389 (previous-level (save-excursion
5390 (condition-case nil
5391 (progn
5392 (outline-previous-visible-heading 1)
5393 (if (looking-at re)
5394 (- (match-end 0) (match-beginning 0) 1)
5396 (error 1))))
5397 (next-level (save-excursion
5398 (condition-case nil
5399 (progn
5400 (or (looking-at outline-regexp)
5401 (outline-next-visible-heading 1))
5402 (if (looking-at re)
5403 (- (match-end 0) (match-beginning 0) 1)
5405 (error 1))))
5406 (new-level (or force-level (max previous-level next-level)))
5407 (shift (if (or (= old-level -1)
5408 (= new-level -1)
5409 (= old-level new-level))
5411 (- new-level old-level)))
5412 (delta (if (> shift 0) -1 1))
5413 (func (if (> shift 0) 'org-demote 'org-promote))
5414 (org-odd-levels-only nil)
5415 beg end newend)
5416 ;; Remove the forced level indicator
5417 (if force-level
5418 (delete-region (point-at-bol) (point)))
5419 ;; Paste
5420 (beginning-of-line 1)
5421 (unless for-yank (org-back-over-empty-lines))
5422 (setq beg (point))
5423 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5424 (insert-before-markers txt)
5425 (unless (string-match "\n\\'" txt) (insert "\n"))
5426 (setq newend (point))
5427 (org-reinstall-markers-in-region beg)
5428 (setq end (point))
5429 (goto-char beg)
5430 (skip-chars-forward " \t\n\r")
5431 (setq beg (point))
5432 (if (and (org-invisible-p) visp)
5433 (save-excursion (outline-show-heading)))
5434 ;; Shift if necessary
5435 (unless (= shift 0)
5436 (save-restriction
5437 (narrow-to-region beg end)
5438 (while (not (= shift 0))
5439 (org-map-region func (point-min) (point-max))
5440 (setq shift (+ delta shift)))
5441 (goto-char (point-min))
5442 (setq newend (point-max))))
5443 (when (or (interactive-p) for-yank)
5444 (message "Clipboard pasted as level %d subtree" new-level))
5445 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5446 kill-ring
5447 (eq org-subtree-clip (current-kill 0))
5448 org-subtree-clip-folded)
5449 ;; The tree was folded before it was killed/copied
5450 (hide-subtree))
5451 (and for-yank (goto-char newend))))
5453 (defun org-kill-is-subtree-p (&optional txt)
5454 "Check if the current kill is an outline subtree, or a set of trees.
5455 Returns nil if kill does not start with a headline, or if the first
5456 headline level is not the largest headline level in the tree.
5457 So this will actually accept several entries of equal levels as well,
5458 which is OK for `org-paste-subtree'.
5459 If optional TXT is given, check this string instead of the current kill."
5460 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5461 (start-level (and kill
5462 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5463 org-outline-regexp "\\)")
5464 kill)
5465 (- (match-end 2) (match-beginning 2) 1)))
5466 (re (concat "^" org-outline-regexp))
5467 (start (1+ (or (match-beginning 2) -1))))
5468 (if (not start-level)
5469 (progn
5470 nil) ;; does not even start with a heading
5471 (catch 'exit
5472 (while (setq start (string-match re kill (1+ start)))
5473 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5474 (throw 'exit nil)))
5475 t))))
5477 (defvar org-markers-to-move nil
5478 "Markers that should be moved with a cut-and-paste operation.
5479 Those markers are stored together with their positions relative to
5480 the start of the region.")
5482 (defun org-save-markers-in-region (beg end)
5483 "Check markers in region.
5484 If these markers are between BEG and END, record their position relative
5485 to BEG, so that after moving the block of text, we can put the markers back
5486 into place.
5487 This function gets called just before an entry or tree gets cut from the
5488 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5489 called immediately, to move the markers with the entries."
5490 (setq org-markers-to-move nil)
5491 (when (featurep 'org-clock)
5492 (org-clock-save-markers-for-cut-and-paste beg end))
5493 (when (featurep 'org-agenda)
5494 (org-agenda-save-markers-for-cut-and-paste beg end)))
5496 (defun org-check-and-save-marker (marker beg end)
5497 "Check if MARKER is between BEG and END.
5498 If yes, remember the marker and the distance to BEG."
5499 (when (and (marker-buffer marker)
5500 (equal (marker-buffer marker) (current-buffer)))
5501 (if (and (>= marker beg) (< marker end))
5502 (push (cons marker (- marker beg)) org-markers-to-move))))
5504 (defun org-reinstall-markers-in-region (beg)
5505 "Move all remembered markers to their position relative to BEG."
5506 (mapc (lambda (x)
5507 (move-marker (car x) (+ beg (cdr x))))
5508 org-markers-to-move)
5509 (setq org-markers-to-move nil))
5511 (defun org-narrow-to-subtree ()
5512 "Narrow buffer to the current subtree."
5513 (interactive)
5514 (save-excursion
5515 (save-match-data
5516 (narrow-to-region
5517 (progn (org-back-to-heading) (point))
5518 (progn (org-end-of-subtree t) (point))))))
5521 ;;; Outline Sorting
5523 (defun org-sort (with-case)
5524 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5525 Optional argument WITH-CASE means sort case-sensitively."
5526 (interactive "P")
5527 (if (org-at-table-p)
5528 (org-call-with-arg 'org-table-sort-lines with-case)
5529 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5531 (defun org-sort-remove-invisible (s)
5532 (remove-text-properties 0 (length s) org-rm-props s)
5533 (while (string-match org-bracket-link-regexp s)
5534 (setq s (replace-match (if (match-end 2)
5535 (match-string 3 s)
5536 (match-string 1 s)) t t s)))
5539 (defvar org-priority-regexp) ; defined later in the file
5541 (defun org-sort-entries-or-items
5542 (&optional with-case sorting-type getkey-func compare-func property)
5543 "Sort entries on a certain level of an outline tree.
5544 If there is an active region, the entries in the region are sorted.
5545 Else, if the cursor is before the first entry, sort the top-level items.
5546 Else, the children of the entry at point are sorted.
5548 Sorting can be alphabetically, numerically, and by date/time as given by
5549 the first time stamp in the entry. The command prompts for the sorting
5550 type unless it has been given to the function through the SORTING-TYPE
5551 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5552 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5553 called with point at the beginning of the record. It must return either
5554 a string or a number that should serve as the sorting key for that record.
5556 Comparing entries ignores case by default. However, with an optional argument
5557 WITH-CASE, the sorting considers case as well."
5558 (interactive "P")
5559 (let ((case-func (if with-case 'identity 'downcase))
5560 start beg end stars re re2
5561 txt what tmp plain-list-p)
5562 ;; Find beginning and end of region to sort
5563 (cond
5564 ((org-region-active-p)
5565 ;; we will sort the region
5566 (setq end (region-end)
5567 what "region")
5568 (goto-char (region-beginning))
5569 (if (not (org-on-heading-p)) (outline-next-heading))
5570 (setq start (point)))
5571 ((org-at-item-p)
5572 ;; we will sort this plain list
5573 (org-beginning-of-item-list) (setq start (point))
5574 (org-end-of-item-list) (setq end (point))
5575 (goto-char start)
5576 (setq plain-list-p t
5577 what "plain list"))
5578 ((or (org-on-heading-p)
5579 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5580 ;; we will sort the children of the current headline
5581 (org-back-to-heading)
5582 (setq start (point)
5583 end (progn (org-end-of-subtree t t)
5584 (org-back-over-empty-lines)
5585 (point))
5586 what "children")
5587 (goto-char start)
5588 (show-subtree)
5589 (outline-next-heading))
5591 ;; we will sort the top-level entries in this file
5592 (goto-char (point-min))
5593 (or (org-on-heading-p) (outline-next-heading))
5594 (setq start (point) end (point-max) what "top-level")
5595 (goto-char start)
5596 (show-all)))
5598 (setq beg (point))
5599 (if (>= beg end) (error "Nothing to sort"))
5601 (unless plain-list-p
5602 (looking-at "\\(\\*+\\)")
5603 (setq stars (match-string 1)
5604 re (concat "^" (regexp-quote stars) " +")
5605 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5606 txt (buffer-substring beg end))
5607 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5608 (if (and (not (equal stars "*")) (string-match re2 txt))
5609 (error "Region to sort contains a level above the first entry")))
5611 (unless sorting-type
5612 (message
5613 (if plain-list-p
5614 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5615 "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:")
5616 what)
5617 (setq sorting-type (read-char-exclusive))
5619 (and (= (downcase sorting-type) ?f)
5620 (setq getkey-func
5621 (org-ido-completing-read "Sort using function: "
5622 obarray 'fboundp t nil nil))
5623 (setq getkey-func (intern getkey-func)))
5625 (and (= (downcase sorting-type) ?r)
5626 (setq property
5627 (org-ido-completing-read "Property: "
5628 (mapcar 'list (org-buffer-property-keys t))
5629 nil t))))
5631 (message "Sorting entries...")
5633 (save-restriction
5634 (narrow-to-region start end)
5636 (let ((dcst (downcase sorting-type))
5637 (now (current-time)))
5638 (sort-subr
5639 (/= dcst sorting-type)
5640 ;; This function moves to the beginning character of the "record" to
5641 ;; be sorted.
5642 (if plain-list-p
5643 (lambda nil
5644 (if (org-at-item-p) t (goto-char (point-max))))
5645 (lambda nil
5646 (if (re-search-forward re nil t)
5647 (goto-char (match-beginning 0))
5648 (goto-char (point-max)))))
5649 ;; This function moves to the last character of the "record" being
5650 ;; sorted.
5651 (if plain-list-p
5652 'org-end-of-item
5653 (lambda nil
5654 (save-match-data
5655 (condition-case nil
5656 (outline-forward-same-level 1)
5657 (error
5658 (goto-char (point-max)))))))
5660 ;; This function returns the value that gets sorted against.
5661 (if plain-list-p
5662 (lambda nil
5663 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5664 (cond
5665 ((= dcst ?n)
5666 (string-to-number (buffer-substring (match-end 0)
5667 (point-at-eol))))
5668 ((= dcst ?a)
5669 (buffer-substring (match-end 0) (point-at-eol)))
5670 ((= dcst ?t)
5671 (if (re-search-forward org-ts-regexp
5672 (point-at-eol) t)
5673 (org-time-string-to-time (match-string 0))
5674 now))
5675 ((= dcst ?f)
5676 (if getkey-func
5677 (progn
5678 (setq tmp (funcall getkey-func))
5679 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5680 tmp)
5681 (error "Invalid key function `%s'" getkey-func)))
5682 (t (error "Invalid sorting type `%c'" sorting-type)))))
5683 (lambda nil
5684 (cond
5685 ((= dcst ?n)
5686 (if (looking-at org-complex-heading-regexp)
5687 (string-to-number (match-string 4))
5688 nil))
5689 ((= dcst ?a)
5690 (if (looking-at org-complex-heading-regexp)
5691 (funcall case-func (match-string 4))
5692 nil))
5693 ((= dcst ?t)
5694 (if (re-search-forward org-ts-regexp
5695 (save-excursion
5696 (forward-line 2)
5697 (point)) t)
5698 (org-time-string-to-time (match-string 0))
5699 now))
5700 ((= dcst ?p)
5701 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5702 (string-to-char (match-string 2))
5703 org-default-priority))
5704 ((= dcst ?r)
5705 (or (org-entry-get nil property) ""))
5706 ((= dcst ?o)
5707 (if (looking-at org-complex-heading-regexp)
5708 (- 9999 (length (member (match-string 2)
5709 org-todo-keywords-1)))))
5710 ((= dcst ?f)
5711 (if getkey-func
5712 (progn
5713 (setq tmp (funcall getkey-func))
5714 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5715 tmp)
5716 (error "Invalid key function `%s'" getkey-func)))
5717 (t (error "Invalid sorting type `%c'" sorting-type)))))
5719 (cond
5720 ((= dcst ?a) 'string<)
5721 ((= dcst ?t) 'time-less-p)
5722 ((= dcst ?f) compare-func)
5723 (t nil)))))
5724 (message "Sorting entries...done")))
5726 (defun org-do-sort (table what &optional with-case sorting-type)
5727 "Sort TABLE of WHAT according to SORTING-TYPE.
5728 The user will be prompted for the SORTING-TYPE if the call to this
5729 function does not specify it. WHAT is only for the prompt, to indicate
5730 what is being sorted. The sorting key will be extracted from
5731 the car of the elements of the table.
5732 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5733 (unless sorting-type
5734 (message
5735 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5736 what)
5737 (setq sorting-type (read-char-exclusive)))
5738 (let ((dcst (downcase sorting-type))
5739 extractfun comparefun)
5740 ;; Define the appropriate functions
5741 (cond
5742 ((= dcst ?n)
5743 (setq extractfun 'string-to-number
5744 comparefun (if (= dcst sorting-type) '< '>)))
5745 ((= dcst ?a)
5746 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5747 (lambda(x) (downcase (org-sort-remove-invisible x))))
5748 comparefun (if (= dcst sorting-type)
5749 'string<
5750 (lambda (a b) (and (not (string< a b))
5751 (not (string= a b)))))))
5752 ((= dcst ?t)
5753 (setq extractfun
5754 (lambda (x)
5755 (if (string-match org-ts-regexp x)
5756 (time-to-seconds
5757 (org-time-string-to-time (match-string 0 x)))
5759 comparefun (if (= dcst sorting-type) '< '>)))
5760 (t (error "Invalid sorting type `%c'" sorting-type)))
5762 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5763 table)
5764 (lambda (a b) (funcall comparefun (car a) (car b))))))
5766 ;;; Editing source examples
5768 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5769 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5770 (defvar org-edit-src-force-single-line nil)
5771 (defvar org-edit-src-from-org-mode nil)
5772 (defvar org-edit-src-picture nil)
5774 (define-minor-mode org-exit-edit-mode
5775 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5777 (defun org-edit-src-code ()
5778 "Edit the source code example at point.
5779 An indirect buffer is created, and that buffer is then narrowed to the
5780 example at point and switched to the correct language mode. When done,
5781 exit by killing the buffer with \\[org-edit-src-exit]."
5782 (interactive)
5783 (let ((line (org-current-line))
5784 (case-fold-search t)
5785 (msg (substitute-command-keys
5786 "Edit, then exit with C-c ' (C-c and single quote)"))
5787 (info (org-edit-src-find-region-and-lang))
5788 (org-mode-p (eq major-mode 'org-mode))
5789 beg end lang lang-f single lfmt)
5790 (if (not info)
5792 (setq beg (nth 0 info)
5793 end (nth 1 info)
5794 lang (nth 2 info)
5795 single (nth 3 info)
5796 lfmt (nth 4 info)
5797 lang-f (intern (concat lang "-mode")))
5798 (unless (functionp lang-f)
5799 (error "No such language mode: %s" lang-f))
5800 (goto-line line)
5801 (if (get-buffer "*Org Edit Src Example*")
5802 (kill-buffer "*Org Edit Src Example*"))
5803 (switch-to-buffer (make-indirect-buffer (current-buffer)
5804 "*Org Edit Src Example*"))
5805 (narrow-to-region beg end)
5806 (remove-text-properties beg end '(display nil invisible nil
5807 intangible nil))
5808 (let ((org-inhibit-startup t))
5809 (funcall lang-f))
5810 (set (make-local-variable 'org-edit-src-force-single-line) single)
5811 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5812 (when lfmt
5813 (set (make-local-variable 'org-coderef-label-format) lfmt))
5814 (when org-mode-p
5815 (goto-char (point-min))
5816 (while (re-search-forward "^," nil t)
5817 (replace-match "")))
5818 (goto-line line)
5819 (org-exit-edit-mode)
5820 (org-set-local 'header-line-format msg)
5821 (message "%s" msg)
5822 t)))
5824 (defun org-edit-fixed-width-region ()
5825 "Edit the fixed-width ascii drawing at point.
5826 This must be a region where each line starts with a colon followed by
5827 a space character.
5828 An indirect buffer is created, and that buffer is then narrowed to the
5829 example at point and switched to artist-mode. When done,
5830 exit by killing the buffer with \\[org-edit-src-exit]."
5831 (interactive)
5832 (let ((line (org-current-line))
5833 (case-fold-search t)
5834 (msg (substitute-command-keys
5835 "Edit, then exit with C-c ' (C-c and single quote)"))
5836 (org-mode-p (eq major-mode 'org-mode))
5837 beg end lang lang-f)
5838 (beginning-of-line 1)
5839 (if (looking-at "[ \t]*[^:\n \t]")
5841 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5842 (setq beg (point) end beg)
5843 (save-excursion
5844 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5845 (setq beg (point-at-bol 2))
5846 (setq beg (point))))
5847 (save-excursion
5848 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5849 (setq end (1- (match-beginning 0)))
5850 (setq end (point))))
5851 (goto-line line))
5852 (if (get-buffer "*Org Edit Picture*")
5853 (kill-buffer "*Org Edit Picture*"))
5854 (switch-to-buffer (make-indirect-buffer (current-buffer)
5855 "*Org Edit Picture*"))
5856 (narrow-to-region beg end)
5857 (remove-text-properties beg end '(display nil invisible nil
5858 intangible nil))
5859 (when (fboundp 'font-lock-unfontify-region)
5860 (font-lock-unfontify-region (point-min) (point-max)))
5861 (cond
5862 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5863 (fundamental-mode)
5864 (artist-mode 1))
5865 (t (funcall org-edit-fixed-width-region-mode)))
5866 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5867 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5868 (set (make-local-variable 'org-edit-src-picture) t)
5869 (goto-char (point-min))
5870 (while (re-search-forward "^[ \t]*: ?" nil t)
5871 (replace-match ""))
5872 (goto-line line)
5873 (org-exit-edit-mode)
5874 (org-set-local 'header-line-format msg)
5875 (message "%s" msg)
5876 t)))
5879 (defun org-edit-src-find-region-and-lang ()
5880 "Find the region and language for a local edit.
5881 Return a list with beginning and end of the region, a string representing
5882 the language, a switch telling of the content should be in a single line."
5883 (let ((re-list
5884 (append
5885 org-edit-src-region-extra
5887 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5888 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5889 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5890 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5891 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5892 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5893 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5894 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5895 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5896 ("^#\\+html:" "\n" "html" single-line)
5897 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5898 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5899 ("^#\\+latex:" "\n" "latex" single-line)
5900 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5901 ("^#\\+ascii:" "\n" "ascii" single-line)
5903 (pos (point))
5904 re re1 re2 single beg end lang lfmt match-re1)
5905 (catch 'exit
5906 (while (setq entry (pop re-list))
5907 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5908 single (nth 3 entry))
5909 (save-excursion
5910 (if (or (looking-at re1)
5911 (re-search-backward re1 nil t))
5912 (progn
5913 (setq match-re1 (match-string 0))
5914 (setq beg (match-end 0)
5915 lang (org-edit-src-get-lang lang)
5916 lfmt (org-edit-src-get-label-format match-re1))
5917 (if (and (re-search-forward re2 nil t)
5918 (>= (match-end 0) pos))
5919 (throw 'exit (list beg (match-beginning 0)
5920 lang single lfmt))))
5921 (if (or (looking-at re2)
5922 (re-search-forward re2 nil t))
5923 (progn
5924 (setq end (match-beginning 0))
5925 (if (and (re-search-backward re1 nil t)
5926 (<= (match-beginning 0) pos))
5927 (progn
5928 (setq lfmt (org-edit-src-get-label-format
5929 (match-string 0)))
5930 (throw 'exit
5931 (list (match-end 0) end
5932 (org-edit-src-get-lang lang)
5933 single lfmt))))))))))))
5935 (defun org-edit-src-get-lang (lang)
5936 "Extract the src language."
5937 (let ((m (match-string 0)))
5938 (cond
5939 ((stringp lang) lang)
5940 ((integerp lang) (match-string lang))
5941 ((and (eq lang 'lang)
5942 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5943 (match-string 1 m))
5944 ((and (eq lang 'style)
5945 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5946 (match-string 1 m))
5947 (t "fundamental"))))
5949 (defun org-edit-src-get-label-format (s)
5950 "Extract the label format."
5951 (save-match-data
5952 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
5953 (match-string 1 s))))
5955 (defun org-edit-src-exit ()
5956 "Exit special edit and protect problematic lines."
5957 (interactive)
5958 (unless (buffer-base-buffer (current-buffer))
5959 (error "This is not an indirect buffer, something is wrong..."))
5960 (unless (> (point-min) 1)
5961 (error "This buffer is not narrowed, something is wrong..."))
5962 (goto-char (point-min))
5963 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5964 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5965 (when (org-bound-and-true-p org-edit-src-force-single-line)
5966 (goto-char (point-min))
5967 (while (re-search-forward "\n" nil t)
5968 (replace-match " "))
5969 (goto-char (point-min))
5970 (if (looking-at "\\s-*") (replace-match " "))
5971 (if (re-search-forward "\\s-+\\'" nil t)
5972 (replace-match "")))
5973 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5974 (goto-char (point-min))
5975 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5976 (replace-match ",\\1"))
5977 (when font-lock-mode
5978 (font-lock-unfontify-region (point-min) (point-max)))
5979 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5980 (when (org-bound-and-true-p org-edit-src-picture)
5981 (untabify (point-min) (point-max))
5982 (goto-char (point-min))
5983 (while (re-search-forward "^" nil t)
5984 (replace-match ": "))
5985 (when font-lock-mode
5986 (font-lock-unfontify-region (point-min) (point-max)))
5987 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5988 (kill-buffer (current-buffer))
5989 (and (org-mode-p) (org-restart-font-lock)))
5992 ;;; The orgstruct minor mode
5994 ;; Define a minor mode which can be used in other modes in order to
5995 ;; integrate the org-mode structure editing commands.
5997 ;; This is really a hack, because the org-mode structure commands use
5998 ;; keys which normally belong to the major mode. Here is how it
5999 ;; works: The minor mode defines all the keys necessary to operate the
6000 ;; structure commands, but wraps the commands into a function which
6001 ;; tests if the cursor is currently at a headline or a plain list
6002 ;; item. If that is the case, the structure command is used,
6003 ;; temporarily setting many Org-mode variables like regular
6004 ;; expressions for filling etc. However, when any of those keys is
6005 ;; used at a different location, function uses `key-binding' to look
6006 ;; up if the key has an associated command in another currently active
6007 ;; keymap (minor modes, major mode, global), and executes that
6008 ;; command. There might be problems if any of the keys is otherwise
6009 ;; used as a prefix key.
6011 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6012 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6013 ;; addresses this by checking explicitly for both bindings.
6015 (defvar orgstruct-mode-map (make-sparse-keymap)
6016 "Keymap for the minor `orgstruct-mode'.")
6018 (defvar org-local-vars nil
6019 "List of local variables, for use by `orgstruct-mode'")
6021 ;;;###autoload
6022 (define-minor-mode orgstruct-mode
6023 "Toggle the minor more `orgstruct-mode'.
6024 This mode is for using Org-mode structure commands in other modes.
6025 The following key behave as if Org-mode was active, if the cursor
6026 is on a headline, or on a plain list item (both in the definition
6027 of Org-mode).
6029 M-up Move entry/item up
6030 M-down Move entry/item down
6031 M-left Promote
6032 M-right Demote
6033 M-S-up Move entry/item up
6034 M-S-down Move entry/item down
6035 M-S-left Promote subtree
6036 M-S-right Demote subtree
6037 M-q Fill paragraph and items like in Org-mode
6038 C-c ^ Sort entries
6039 C-c - Cycle list bullet
6040 TAB Cycle item visibility
6041 M-RET Insert new heading/item
6042 S-M-RET Insert new TODO heading / Checkbox item
6043 C-c C-c Set tags / toggle checkbox"
6044 nil " OrgStruct" nil
6045 (org-load-modules-maybe)
6046 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6048 ;;;###autoload
6049 (defun turn-on-orgstruct ()
6050 "Unconditionally turn on `orgstruct-mode'."
6051 (orgstruct-mode 1))
6053 ;;;###autoload
6054 (defun turn-on-orgstruct++ ()
6055 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6056 In addition to setting orgstruct-mode, this also exports all indentation and
6057 autofilling variables from org-mode into the buffer. Note that turning
6058 off orgstruct-mode will *not* remove these additional settings."
6059 (orgstruct-mode 1)
6060 (let (var val)
6061 (mapc
6062 (lambda (x)
6063 (when (string-match
6064 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6065 (symbol-name (car x)))
6066 (setq var (car x) val (nth 1 x))
6067 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6068 org-local-vars)))
6070 (defun orgstruct-error ()
6071 "Error when there is no default binding for a structure key."
6072 (interactive)
6073 (error "This key has no function outside structure elements"))
6075 (defun orgstruct-setup ()
6076 "Setup orgstruct keymaps."
6077 (let ((nfunc 0)
6078 (bindings
6079 (list
6080 '([(meta up)] org-metaup)
6081 '([(meta down)] org-metadown)
6082 '([(meta left)] org-metaleft)
6083 '([(meta right)] org-metaright)
6084 '([(meta shift up)] org-shiftmetaup)
6085 '([(meta shift down)] org-shiftmetadown)
6086 '([(meta shift left)] org-shiftmetaleft)
6087 '([(meta shift right)] org-shiftmetaright)
6088 '([(shift up)] org-shiftup)
6089 '([(shift down)] org-shiftdown)
6090 '([(shift left)] org-shiftleft)
6091 '([(shift right)] org-shiftright)
6092 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6093 '("\M-q" fill-paragraph)
6094 '("\C-c^" org-sort)
6095 '("\C-c-" org-cycle-list-bullet)))
6096 elt key fun cmd)
6097 (while (setq elt (pop bindings))
6098 (setq nfunc (1+ nfunc))
6099 (setq key (org-key (car elt))
6100 fun (nth 1 elt)
6101 cmd (orgstruct-make-binding fun nfunc key))
6102 (org-defkey orgstruct-mode-map key cmd))
6104 ;; Special treatment needed for TAB and RET
6105 (org-defkey orgstruct-mode-map [(tab)]
6106 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6107 (org-defkey orgstruct-mode-map "\C-i"
6108 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6110 (org-defkey orgstruct-mode-map "\M-\C-m"
6111 (orgstruct-make-binding 'org-insert-heading 105
6112 "\M-\C-m" [(meta return)]))
6113 (org-defkey orgstruct-mode-map [(meta return)]
6114 (orgstruct-make-binding 'org-insert-heading 106
6115 [(meta return)] "\M-\C-m"))
6117 (org-defkey orgstruct-mode-map [(shift meta return)]
6118 (orgstruct-make-binding 'org-insert-todo-heading 107
6119 [(meta return)] "\M-\C-m"))
6121 (unless org-local-vars
6122 (setq org-local-vars (org-get-local-variables)))
6126 (defun orgstruct-make-binding (fun n &rest keys)
6127 "Create a function for binding in the structure minor mode.
6128 FUN is the command to call inside a table. N is used to create a unique
6129 command name. KEYS are keys that should be checked in for a command
6130 to execute outside of tables."
6131 (eval
6132 (list 'defun
6133 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6134 '(arg)
6135 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6136 "Outside of structure, run the binding of `"
6137 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6138 "'.")
6139 '(interactive "p")
6140 (list 'if
6141 '(org-context-p 'headline 'item)
6142 (list 'org-run-like-in-org-mode (list 'quote fun))
6143 (list 'let '(orgstruct-mode)
6144 (list 'call-interactively
6145 (append '(or)
6146 (mapcar (lambda (k)
6147 (list 'key-binding k))
6148 keys)
6149 '('orgstruct-error))))))))
6151 (defun org-context-p (&rest contexts)
6152 "Check if local context is any of CONTEXTS.
6153 Possible values in the list of contexts are `table', `headline', and `item'."
6154 (let ((pos (point)))
6155 (goto-char (point-at-bol))
6156 (prog1 (or (and (memq 'table contexts)
6157 (looking-at "[ \t]*|"))
6158 (and (memq 'headline contexts)
6159 ;;????????? (looking-at "\\*+"))
6160 (looking-at outline-regexp))
6161 (and (memq 'item contexts)
6162 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6163 (goto-char pos))))
6165 (defun org-get-local-variables ()
6166 "Return a list of all local variables in an org-mode buffer."
6167 (let (varlist)
6168 (with-current-buffer (get-buffer-create "*Org tmp*")
6169 (erase-buffer)
6170 (org-mode)
6171 (setq varlist (buffer-local-variables)))
6172 (kill-buffer "*Org tmp*")
6173 (delq nil
6174 (mapcar
6175 (lambda (x)
6176 (setq x
6177 (if (symbolp x)
6178 (list x)
6179 (list (car x) (list 'quote (cdr x)))))
6180 (if (string-match
6181 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6182 (symbol-name (car x)))
6183 x nil))
6184 varlist))))
6186 ;;;###autoload
6187 (defun org-run-like-in-org-mode (cmd)
6188 (org-load-modules-maybe)
6189 (unless org-local-vars
6190 (setq org-local-vars (org-get-local-variables)))
6191 (eval (list 'let org-local-vars
6192 (list 'call-interactively (list 'quote cmd)))))
6194 ;;;; Archiving
6196 (defun org-get-category (&optional pos)
6197 "Get the category applying to position POS."
6198 (get-text-property (or pos (point)) 'org-category))
6200 (defun org-refresh-category-properties ()
6201 "Refresh category text properties in the buffer."
6202 (let ((def-cat (cond
6203 ((null org-category)
6204 (if buffer-file-name
6205 (file-name-sans-extension
6206 (file-name-nondirectory buffer-file-name))
6207 "???"))
6208 ((symbolp org-category) (symbol-name org-category))
6209 (t org-category)))
6210 beg end cat pos optionp)
6211 (org-unmodified
6212 (save-excursion
6213 (save-restriction
6214 (widen)
6215 (goto-char (point-min))
6216 (put-text-property (point) (point-max) 'org-category def-cat)
6217 (while (re-search-forward
6218 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6219 (setq pos (match-end 0)
6220 optionp (equal (char-after (match-beginning 0)) ?#)
6221 cat (org-trim (match-string 2)))
6222 (if optionp
6223 (setq beg (point-at-bol) end (point-max))
6224 (org-back-to-heading t)
6225 (setq beg (point) end (org-end-of-subtree t t)))
6226 (put-text-property beg end 'org-category cat)
6227 (goto-char pos)))))))
6230 ;;;; Link Stuff
6232 ;;; Link abbreviations
6234 (defun org-link-expand-abbrev (link)
6235 "Apply replacements as defined in `org-link-abbrev-alist."
6236 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6237 (let* ((key (match-string 1 link))
6238 (as (or (assoc key org-link-abbrev-alist-local)
6239 (assoc key org-link-abbrev-alist)))
6240 (tag (and (match-end 2) (match-string 3 link)))
6241 rpl)
6242 (if (not as)
6243 link
6244 (setq rpl (cdr as))
6245 (cond
6246 ((symbolp rpl) (funcall rpl tag))
6247 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6248 ((string-match "%h" rpl)
6249 (replace-match (url-hexify-string (or tag "")) t t rpl))
6250 (t (concat rpl tag)))))
6251 link))
6253 ;;; Storing and inserting links
6255 (defvar org-insert-link-history nil
6256 "Minibuffer history for links inserted with `org-insert-link'.")
6258 (defvar org-stored-links nil
6259 "Contains the links stored with `org-store-link'.")
6261 (defvar org-store-link-plist nil
6262 "Plist with info about the most recently link created with `org-store-link'.")
6264 (defvar org-link-protocols nil
6265 "Link protocols added to Org-mode using `org-add-link-type'.")
6267 (defvar org-store-link-functions nil
6268 "List of functions that are called to create and store a link.
6269 Each function will be called in turn until one returns a non-nil
6270 value. Each function should check if it is responsible for creating
6271 this link (for example by looking at the major mode).
6272 If not, it must exit and return nil.
6273 If yes, it should return a non-nil value after a calling
6274 `org-store-link-props' with a list of properties and values.
6275 Special properties are:
6277 :type The link prefix. like \"http\". This must be given.
6278 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6279 This is obligatory as well.
6280 :description Optional default description for the second pair
6281 of brackets in an Org-mode link. The user can still change
6282 this when inserting this link into an Org-mode buffer.
6284 In addition to these, any additional properties can be specified
6285 and then used in remember templates.")
6287 (defun org-add-link-type (type &optional follow export)
6288 "Add TYPE to the list of `org-link-types'.
6289 Re-compute all regular expressions depending on `org-link-types'
6291 FOLLOW and EXPORT are two functions.
6293 FOLLOW should take the link path as the single argument and do whatever
6294 is necessary to follow the link, for example find a file or display
6295 a mail message.
6297 EXPORT should format the link path for export to one of the export formats.
6298 It should be a function accepting three arguments:
6300 path the path of the link, the text after the prefix (like \"http:\")
6301 desc the description of the link, if any, nil if there was no description
6302 format the export format, a symbol like `html' or `latex'.
6304 The function may use the FORMAT information to return different values
6305 depending on the format. The return value will be put literally into
6306 the exported file.
6307 Org-mode has a built-in default for exporting links. If you are happy with
6308 this default, there is no need to define an export function for the link
6309 type. For a simple example of an export function, see `org-bbdb.el'."
6310 (add-to-list 'org-link-types type t)
6311 (org-make-link-regexps)
6312 (if (assoc type org-link-protocols)
6313 (setcdr (assoc type org-link-protocols) (list follow export))
6314 (push (list type follow export) org-link-protocols)))
6316 ;;;###autoload
6317 (defun org-store-link (arg)
6318 "\\<org-mode-map>Store an org-link to the current location.
6319 This link is added to `org-stored-links' and can later be inserted
6320 into an org-buffer with \\[org-insert-link].
6322 For some link types, a prefix arg is interpreted:
6323 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6324 For file links, arg negates `org-context-in-file-links'."
6325 (interactive "P")
6326 (org-load-modules-maybe)
6327 (setq org-store-link-plist nil) ; reset
6328 (let (link cpltxt desc description search txt)
6329 (cond
6331 ((run-hook-with-args-until-success 'org-store-link-functions)
6332 (setq link (plist-get org-store-link-plist :link)
6333 desc (or (plist-get org-store-link-plist :description) link)))
6335 ((equal (buffer-name) "*Org Edit Src Example*")
6336 (let (label gc)
6337 (while (or (not label)
6338 (save-excursion
6339 (save-restriction
6340 (widen)
6341 (goto-char (point-min))
6342 (re-search-forward
6343 (regexp-quote (format org-coderef-label-format label))
6344 nil t))))
6345 (when label (message "Label exists already") (sit-for 2))
6346 (setq label (read-string "Code line label: " label)))
6347 (end-of-line 1)
6348 (setq link (format org-coderef-label-format label))
6349 (setq gc (- 79 (length link)))
6350 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6351 (insert link)
6352 (setq link (concat "(" label ")") desc nil)))
6354 ((eq major-mode 'calendar-mode)
6355 (let ((cd (calendar-cursor-to-date)))
6356 (setq link
6357 (format-time-string
6358 (car org-time-stamp-formats)
6359 (apply 'encode-time
6360 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6361 nil nil nil))))
6362 (org-store-link-props :type "calendar" :date cd)))
6364 ((eq major-mode 'w3-mode)
6365 (setq cpltxt (url-view-url t)
6366 link (org-make-link cpltxt))
6367 (org-store-link-props :type "w3" :url (url-view-url t)))
6369 ((eq major-mode 'w3m-mode)
6370 (setq cpltxt (or w3m-current-title w3m-current-url)
6371 link (org-make-link w3m-current-url))
6372 (org-store-link-props :type "w3m" :url (url-view-url t)))
6374 ((setq search (run-hook-with-args-until-success
6375 'org-create-file-search-functions))
6376 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6377 "::" search))
6378 (setq cpltxt (or description link)))
6380 ((eq major-mode 'image-mode)
6381 (setq cpltxt (concat "file:"
6382 (abbreviate-file-name buffer-file-name))
6383 link (org-make-link cpltxt))
6384 (org-store-link-props :type "image" :file buffer-file-name))
6386 ((eq major-mode 'dired-mode)
6387 ;; link to the file in the current line
6388 (setq cpltxt (concat "file:"
6389 (abbreviate-file-name
6390 (expand-file-name
6391 (dired-get-filename nil t))))
6392 link (org-make-link cpltxt)))
6394 ((and buffer-file-name (org-mode-p))
6395 (cond
6396 ((org-in-regexp "<<\\(.*?\\)>>")
6397 (setq cpltxt
6398 (concat "file:"
6399 (abbreviate-file-name buffer-file-name)
6400 "::" (match-string 1))
6401 link (org-make-link cpltxt)))
6402 ((and (featurep 'org-id)
6403 (or (eq org-link-to-org-use-id t)
6404 (and (eq org-link-to-org-use-id 'create-if-interactive)
6405 (interactive-p))
6406 (and org-link-to-org-use-id
6407 (condition-case nil
6408 (org-entry-get nil "ID")
6409 (error nil)))))
6410 ;; We can make a link using the ID.
6411 (setq link (condition-case nil
6412 (prog1 (org-id-store-link)
6413 (setq desc (plist-get org-store-link-plist
6414 :description)))
6415 (error
6416 ;; probably before first headline, link to file only
6417 (concat "file:"
6418 (abbreviate-file-name buffer-file-name))))))
6420 ;; Just link to current headline
6421 (setq cpltxt (concat "file:"
6422 (abbreviate-file-name buffer-file-name)))
6423 ;; Add a context search string
6424 (when (org-xor org-context-in-file-links arg)
6425 (setq txt (cond
6426 ((org-on-heading-p) nil)
6427 ((org-region-active-p)
6428 (buffer-substring (region-beginning) (region-end)))
6429 (t nil)))
6430 (when (or (null txt) (string-match "\\S-" txt))
6431 (setq cpltxt
6432 (concat cpltxt "::"
6433 (condition-case nil
6434 (org-make-org-heading-search-string txt)
6435 (error "")))
6436 desc "NONE")))
6437 (if (string-match "::\\'" cpltxt)
6438 (setq cpltxt (substring cpltxt 0 -2)))
6439 (setq link (org-make-link cpltxt)))))
6441 ((buffer-file-name (buffer-base-buffer))
6442 ;; Just link to this file here.
6443 (setq cpltxt (concat "file:"
6444 (abbreviate-file-name
6445 (buffer-file-name (buffer-base-buffer)))))
6446 ;; Add a context string
6447 (when (org-xor org-context-in-file-links arg)
6448 (setq txt (if (org-region-active-p)
6449 (buffer-substring (region-beginning) (region-end))
6450 (buffer-substring (point-at-bol) (point-at-eol))))
6451 ;; Only use search option if there is some text.
6452 (when (string-match "\\S-" txt)
6453 (setq cpltxt
6454 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6455 desc "NONE")))
6456 (setq link (org-make-link cpltxt)))
6458 ((interactive-p)
6459 (error "Cannot link to a buffer which is not visiting a file"))
6461 (t (setq link nil)))
6463 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6464 (setq link (or link cpltxt)
6465 desc (or desc cpltxt))
6466 (if (equal desc "NONE") (setq desc nil))
6468 (if (and (interactive-p) link)
6469 (progn
6470 (setq org-stored-links
6471 (cons (list link desc) org-stored-links))
6472 (message "Stored: %s" (or desc link)))
6473 (and link (org-make-link-string link desc)))))
6475 (defun org-store-link-props (&rest plist)
6476 "Store link properties, extract names and addresses."
6477 (let (x adr)
6478 (when (setq x (plist-get plist :from))
6479 (setq adr (mail-extract-address-components x))
6480 (setq plist (plist-put plist :fromname (car adr)))
6481 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6482 (when (setq x (plist-get plist :to))
6483 (setq adr (mail-extract-address-components x))
6484 (setq plist (plist-put plist :toname (car adr)))
6485 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6486 (let ((from (plist-get plist :from))
6487 (to (plist-get plist :to)))
6488 (when (and from to org-from-is-user-regexp)
6489 (setq plist
6490 (plist-put plist :fromto
6491 (if (string-match org-from-is-user-regexp from)
6492 (concat "to %t")
6493 (concat "from %f"))))))
6494 (setq org-store-link-plist plist))
6496 (defun org-add-link-props (&rest plist)
6497 "Add these properties to the link property list."
6498 (let (key value)
6499 (while plist
6500 (setq key (pop plist) value (pop plist))
6501 (setq org-store-link-plist
6502 (plist-put org-store-link-plist key value)))))
6504 (defun org-email-link-description (&optional fmt)
6505 "Return the description part of an email link.
6506 This takes information from `org-store-link-plist' and formats it
6507 according to FMT (default from `org-email-link-description-format')."
6508 (setq fmt (or fmt org-email-link-description-format))
6509 (let* ((p org-store-link-plist)
6510 (to (plist-get p :toaddress))
6511 (from (plist-get p :fromaddress))
6512 (table
6513 (list
6514 (cons "%c" (plist-get p :fromto))
6515 (cons "%F" (plist-get p :from))
6516 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6517 (cons "%T" (plist-get p :to))
6518 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6519 (cons "%s" (plist-get p :subject))
6520 (cons "%m" (plist-get p :message-id)))))
6521 (when (string-match "%c" fmt)
6522 ;; Check if the user wrote this message
6523 (if (and org-from-is-user-regexp from to
6524 (save-match-data (string-match org-from-is-user-regexp from)))
6525 (setq fmt (replace-match "to %t" t t fmt))
6526 (setq fmt (replace-match "from %f" t t fmt))))
6527 (org-replace-escapes fmt table)))
6529 (defun org-make-org-heading-search-string (&optional string heading)
6530 "Make search string for STRING or current headline."
6531 (interactive)
6532 (let ((s (or string (org-get-heading))))
6533 (unless (and string (not heading))
6534 ;; We are using a headline, clean up garbage in there.
6535 (if (string-match org-todo-regexp s)
6536 (setq s (replace-match "" t t s)))
6537 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6538 (setq s (replace-match "" t t s)))
6539 (setq s (org-trim s))
6540 (if (string-match (concat "^\\(" org-quote-string "\\|"
6541 org-comment-string "\\)") s)
6542 (setq s (replace-match "" t t s)))
6543 (while (string-match org-ts-regexp s)
6544 (setq s (replace-match "" t t s))))
6545 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6546 (setq s (replace-match " " t t s)))
6547 (or string (setq s (concat "*" s))) ; Add * for headlines
6548 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6550 (defun org-make-link (&rest strings)
6551 "Concatenate STRINGS."
6552 (apply 'concat strings))
6554 (defun org-make-link-string (link &optional description)
6555 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6556 (unless (string-match "\\S-" link)
6557 (error "Empty link"))
6558 (when (stringp description)
6559 ;; Remove brackets from the description, they are fatal.
6560 (while (string-match "\\[" description)
6561 (setq description (replace-match "{" t t description)))
6562 (while (string-match "\\]" description)
6563 (setq description (replace-match "}" t t description))))
6564 (when (equal (org-link-escape link) description)
6565 ;; No description needed, it is identical
6566 (setq description nil))
6567 (when (and (not description)
6568 (not (equal link (org-link-escape link))))
6569 (setq description (org-extract-attributes link)))
6570 (concat "[[" (org-link-escape link) "]"
6571 (if description (concat "[" description "]") "")
6572 "]"))
6574 (defconst org-link-escape-chars
6575 '((?\ . "%20")
6576 (?\[ . "%5B")
6577 (?\] . "%5D")
6578 (?\340 . "%E0") ; `a
6579 (?\342 . "%E2") ; ^a
6580 (?\347 . "%E7") ; ,c
6581 (?\350 . "%E8") ; `e
6582 (?\351 . "%E9") ; 'e
6583 (?\352 . "%EA") ; ^e
6584 (?\356 . "%EE") ; ^i
6585 (?\364 . "%F4") ; ^o
6586 (?\371 . "%F9") ; `u
6587 (?\373 . "%FB") ; ^u
6588 (?\; . "%3B")
6589 (?? . "%3F")
6590 (?= . "%3D")
6591 (?+ . "%2B")
6593 "Association list of escapes for some characters problematic in links.
6594 This is the list that is used for internal purposes.")
6596 (defconst org-link-escape-chars-browser
6597 '((?\ . "%20")) ; 32 for the SPC char
6598 "Association list of escapes for some characters problematic in links.
6599 This is the list that is used before handing over to the browser.")
6601 (defun org-link-escape (text &optional table)
6602 "Escape characters in TEXT that are problematic for links."
6603 (setq table (or table org-link-escape-chars))
6604 (when text
6605 (let ((re (mapconcat (lambda (x) (regexp-quote
6606 (char-to-string (car x))))
6607 table "\\|")))
6608 (while (string-match re text)
6609 (setq text
6610 (replace-match
6611 (cdr (assoc (string-to-char (match-string 0 text))
6612 table))
6613 t t text)))
6614 text)))
6616 (defun org-link-unescape (text &optional table)
6617 "Reverse the action of `org-link-escape'."
6618 (setq table (or table org-link-escape-chars))
6619 (when text
6620 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6621 table "\\|")))
6622 (while (string-match re text)
6623 (setq text
6624 (replace-match
6625 (char-to-string (car (rassoc (match-string 0 text) table)))
6626 t t text)))
6627 text)))
6629 (defun org-xor (a b)
6630 "Exclusive or."
6631 (if a (not b) b))
6633 (defun org-fixup-message-id-for-http (s)
6634 "Replace special characters in a message id, so it can be used in an http query."
6635 (while (string-match "<" s)
6636 (setq s (replace-match "%3C" t t s)))
6637 (while (string-match ">" s)
6638 (setq s (replace-match "%3E" t t s)))
6639 (while (string-match "@" s)
6640 (setq s (replace-match "%40" t t s)))
6643 ;;;###autoload
6644 (defun org-insert-link-global ()
6645 "Insert a link like Org-mode does.
6646 This command can be called in any mode to insert a link in Org-mode syntax."
6647 (interactive)
6648 (org-load-modules-maybe)
6649 (org-run-like-in-org-mode 'org-insert-link))
6651 (defun org-insert-link (&optional complete-file link-location)
6652 "Insert a link. At the prompt, enter the link.
6654 Completion can be used to insert any of the link protocol prefixes like
6655 http or ftp in use.
6657 The history can be used to select a link previously stored with
6658 `org-store-link'. When the empty string is entered (i.e. if you just
6659 press RET at the prompt), the link defaults to the most recently
6660 stored link. As SPC triggers completion in the minibuffer, you need to
6661 use M-SPC or C-q SPC to force the insertion of a space character.
6663 You will also be prompted for a description, and if one is given, it will
6664 be displayed in the buffer instead of the link.
6666 If there is already a link at point, this command will allow you to edit link
6667 and description parts.
6669 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6670 be selected using completion. The path to the file will be relative to the
6671 current directory if the file is in the current directory or a subdirectory.
6672 Otherwise, the link will be the absolute path as completed in the minibuffer
6673 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6674 option `org-link-file-path-type'.
6676 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6677 the current directory or below.
6679 With three \\[universal-argument] prefixes, negate the meaning of
6680 `org-keep-stored-link-after-insertion'.
6682 If `org-make-link-description-function' is non-nil, this function will be
6683 called with the link target, and the result will be the default
6684 link description.
6686 If the LINK-LOCATION parameter is non-nil, this value will be
6687 used as the link location instead of reading one interactively."
6688 (interactive "P")
6689 (let* ((wcf (current-window-configuration))
6690 (region (if (org-region-active-p)
6691 (buffer-substring (region-beginning) (region-end))))
6692 (remove (and region (list (region-beginning) (region-end))))
6693 (desc region)
6694 tmphist ; byte-compile incorrectly complains about this
6695 (link link-location)
6696 entry file)
6697 (cond
6698 (link-location) ; specified by arg, just use it.
6699 ((org-in-regexp org-bracket-link-regexp 1)
6700 ;; We do have a link at point, and we are going to edit it.
6701 (setq remove (list (match-beginning 0) (match-end 0)))
6702 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6703 (setq link (read-string "Link: "
6704 (org-link-unescape
6705 (org-match-string-no-properties 1)))))
6706 ((or (org-in-regexp org-angle-link-re)
6707 (org-in-regexp org-plain-link-re))
6708 ;; Convert to bracket link
6709 (setq remove (list (match-beginning 0) (match-end 0))
6710 link (read-string "Link: "
6711 (org-remove-angle-brackets (match-string 0)))))
6712 ((member complete-file '((4) (16)))
6713 ;; Completing read for file names.
6714 (setq file (read-file-name "File: "))
6715 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6716 (pwd1 (file-name-as-directory (abbreviate-file-name
6717 (expand-file-name ".")))))
6718 (cond
6719 ((equal complete-file '(16))
6720 (setq link (org-make-link
6721 "file:"
6722 (abbreviate-file-name (expand-file-name file)))))
6723 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6724 (setq link (org-make-link "file:" (match-string 1 file))))
6725 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6726 (expand-file-name file))
6727 (setq link (org-make-link
6728 "file:" (match-string 1 (expand-file-name file)))))
6729 (t (setq link (org-make-link "file:" file))))))
6731 ;; Read link, with completion for stored links.
6732 (with-output-to-temp-buffer "*Org Links*"
6733 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6734 (when org-stored-links
6735 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6736 (princ (mapconcat
6737 (lambda (x)
6738 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6739 (reverse org-stored-links) "\n"))))
6740 (let ((cw (selected-window)))
6741 (select-window (get-buffer-window "*Org Links*"))
6742 (setq truncate-lines t)
6743 (org-fit-window-to-buffer)
6744 (select-window cw))
6745 ;; Fake a link history, containing the stored links.
6746 (setq tmphist (append (mapcar 'car org-stored-links)
6747 org-insert-link-history))
6748 (unwind-protect
6749 (setq link
6750 (let ((org-completion-use-ido nil))
6751 (org-completing-read
6752 "Link: "
6753 (append
6754 (mapcar (lambda (x) (list (concat (car x) ":")))
6755 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6756 (mapcar (lambda (x) (list (concat x ":")))
6757 org-link-types))
6758 nil nil nil
6759 'tmphist
6760 (or (car (car org-stored-links))))))
6761 (set-window-configuration wcf)
6762 (kill-buffer "*Org Links*"))
6763 (setq entry (assoc link org-stored-links))
6764 (or entry (push link org-insert-link-history))
6765 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6766 (not org-keep-stored-link-after-insertion))
6767 (setq org-stored-links (delq (assoc link org-stored-links)
6768 org-stored-links)))
6769 (setq desc (or desc (nth 1 entry)))))
6771 (if (string-match org-plain-link-re link)
6772 ;; URL-like link, normalize the use of angular brackets.
6773 (setq link (org-make-link (org-remove-angle-brackets link))))
6775 ;; Check if we are linking to the current file with a search option
6776 ;; If yes, simplify the link by using only the search option.
6777 (when (and buffer-file-name
6778 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6779 (let* ((path (match-string 1 link))
6780 (case-fold-search nil)
6781 (search (match-string 2 link)))
6782 (save-match-data
6783 (if (equal (file-truename buffer-file-name) (file-truename path))
6784 ;; We are linking to this same file, with a search option
6785 (setq link search)))))
6787 ;; Check if we can/should use a relative path. If yes, simplify the link
6788 (when (string-match "^file:\\(.*\\)" link)
6789 (let* ((path (match-string 1 link))
6790 (origpath path)
6791 (case-fold-search nil))
6792 (cond
6793 ((or (eq org-link-file-path-type 'absolute)
6794 (equal complete-file '(16)))
6795 (setq path (abbreviate-file-name (expand-file-name path))))
6796 ((eq org-link-file-path-type 'noabbrev)
6797 (setq path (expand-file-name path)))
6798 ((eq org-link-file-path-type 'relative)
6799 (setq path (file-relative-name path)))
6801 (save-match-data
6802 (if (string-match (concat "^" (regexp-quote
6803 (file-name-as-directory
6804 (expand-file-name "."))))
6805 (expand-file-name path))
6806 ;; We are linking a file with relative path name.
6807 (setq path (substring (expand-file-name path)
6808 (match-end 0)))
6809 (setq path (abbreviate-file-name (expand-file-name path)))))))
6810 (setq link (concat "file:" path))
6811 (if (equal desc origpath)
6812 (setq desc path))))
6814 (if org-make-link-description-function
6815 (setq desc (funcall org-make-link-description-function link desc)))
6817 (setq desc (read-string "Description: " desc))
6818 (unless (string-match "\\S-" desc) (setq desc nil))
6819 (if remove (apply 'delete-region remove))
6820 (insert (org-make-link-string link desc))))
6822 (defun org-completing-read (&rest args)
6823 "Completing-read with SPACE being a normal character."
6824 (let ((minibuffer-local-completion-map
6825 (copy-keymap minibuffer-local-completion-map)))
6826 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6827 (apply 'org-ido-completing-read args)))
6829 (defun org-ido-completing-read (&rest args)
6830 "Completing-read using `ido-mode' speedups if available"
6831 (if (and org-completion-use-ido
6832 (fboundp 'ido-completing-read)
6833 (boundp 'ido-mode) ido-mode
6834 (listp (second args)))
6835 (apply 'ido-completing-read (concat (car args)) (cdr args))
6836 (apply 'completing-read args)))
6838 (defun org-extract-attributes (s)
6839 "Extract the attributes cookie from a string and set as text property."
6840 (let (a attr (start 0) key value)
6841 (save-match-data
6842 (when (string-match "{{\\([^}]+\\)}}$" s)
6843 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6844 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6845 (setq key (match-string 1 a) value (match-string 2 a)
6846 start (match-end 0)
6847 attr (plist-put attr (intern key) value))))
6848 (org-add-props s nil 'org-attr attr))
6851 (defun org-attributes-to-string (plist)
6852 "Format a property list into an HTML attribute list."
6853 (let ((s "") key value)
6854 (while plist
6855 (setq key (pop plist) value (pop plist))
6856 (and value
6857 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6860 ;;; Opening/following a link
6862 (defvar org-link-search-failed nil)
6864 (defun org-next-link ()
6865 "Move forward to the next link.
6866 If the link is in hidden text, expose it."
6867 (interactive)
6868 (when (and org-link-search-failed (eq this-command last-command))
6869 (goto-char (point-min))
6870 (message "Link search wrapped back to beginning of buffer"))
6871 (setq org-link-search-failed nil)
6872 (let* ((pos (point))
6873 (ct (org-context))
6874 (a (assoc :link ct)))
6875 (if a (goto-char (nth 2 a)))
6876 (if (re-search-forward org-any-link-re nil t)
6877 (progn
6878 (goto-char (match-beginning 0))
6879 (if (org-invisible-p) (org-show-context)))
6880 (goto-char pos)
6881 (setq org-link-search-failed t)
6882 (error "No further link found"))))
6884 (defun org-previous-link ()
6885 "Move backward to the previous link.
6886 If the link is in hidden text, expose it."
6887 (interactive)
6888 (when (and org-link-search-failed (eq this-command last-command))
6889 (goto-char (point-max))
6890 (message "Link search wrapped back to end of buffer"))
6891 (setq org-link-search-failed nil)
6892 (let* ((pos (point))
6893 (ct (org-context))
6894 (a (assoc :link ct)))
6895 (if a (goto-char (nth 1 a)))
6896 (if (re-search-backward org-any-link-re nil t)
6897 (progn
6898 (goto-char (match-beginning 0))
6899 (if (org-invisible-p) (org-show-context)))
6900 (goto-char pos)
6901 (setq org-link-search-failed t)
6902 (error "No further link found"))))
6904 (defun org-translate-link (s)
6905 "Translate a link string if a translation function has been defined."
6906 (if (and org-link-translation-function
6907 (fboundp org-link-translation-function)
6908 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6909 (progn
6910 (setq s (funcall org-link-translation-function
6911 (match-string 1) (match-string 2)))
6912 (concat (car s) ":" (cdr s)))
6915 (defun org-translate-link-from-planner (type path)
6916 "Translate a link from Emacs Planner syntax so that Org can follow it.
6917 This is still an experimental function, your mileage may vary."
6918 (cond
6919 ((member type '("http" "https" "news" "ftp"))
6920 ;; standard Internet links are the same.
6921 nil)
6922 ((and (equal type "irc") (string-match "^//" path))
6923 ;; Planner has two / at the beginning of an irc link, we have 1.
6924 ;; We should have zero, actually....
6925 (setq path (substring path 1)))
6926 ((and (equal type "lisp") (string-match "^/" path))
6927 ;; Planner has a slash, we do not.
6928 (setq type "elisp" path (substring path 1)))
6929 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6930 ;; A typical message link. Planner has the id after the fina slash,
6931 ;; we separate it with a hash mark
6932 (setq path (concat (match-string 1 path) "#"
6933 (org-remove-angle-brackets (match-string 2 path)))))
6935 (cons type path))
6937 (defun org-find-file-at-mouse (ev)
6938 "Open file link or URL at mouse."
6939 (interactive "e")
6940 (mouse-set-point ev)
6941 (org-open-at-point 'in-emacs))
6943 (defun org-open-at-mouse (ev)
6944 "Open file link or URL at mouse."
6945 (interactive "e")
6946 (mouse-set-point ev)
6947 (if (eq major-mode 'org-agenda-mode)
6948 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6949 (org-open-at-point))
6951 (defvar org-window-config-before-follow-link nil
6952 "The window configuration before following a link.
6953 This is saved in case the need arises to restore it.")
6955 (defvar org-open-link-marker (make-marker)
6956 "Marker pointing to the location where `org-open-at-point; was called.")
6958 ;;;###autoload
6959 (defun org-open-at-point-global ()
6960 "Follow a link like Org-mode does.
6961 This command can be called in any mode to follow a link that has
6962 Org-mode syntax."
6963 (interactive)
6964 (org-run-like-in-org-mode 'org-open-at-point))
6966 ;;;###autoload
6967 (defun org-open-link-from-string (s &optional arg)
6968 "Open a link in the string S, as if it was in Org-mode."
6969 (interactive "sLink: \nP")
6970 (with-temp-buffer
6971 (let ((org-inhibit-startup t))
6972 (org-mode)
6973 (insert s)
6974 (goto-char (point-min))
6975 (org-open-at-point arg))))
6977 (defun org-open-at-point (&optional in-emacs)
6978 "Open link at or after point.
6979 If there is no link at point, this function will search forward up to
6980 the end of the current subtree.
6981 Normally, files will be opened by an appropriate application. If the
6982 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6983 With a double prefix argument, try to open outside of Emacs, in the
6984 application the system uses for this file type."
6985 (interactive "P")
6986 (org-load-modules-maybe)
6987 (move-marker org-open-link-marker (point))
6988 (setq org-window-config-before-follow-link (current-window-configuration))
6989 (org-remove-occur-highlights nil nil t)
6990 (cond
6991 ((org-at-timestamp-p t) (org-follow-timestamp-link))
6992 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
6993 (org-footnote-action))
6995 (let (type path link line search (pos (point)))
6996 (catch 'match
6997 (save-excursion
6998 (skip-chars-forward "^]\n\r")
6999 (when (org-in-regexp org-bracket-link-regexp)
7000 (setq link (org-extract-attributes
7001 (org-link-unescape (org-match-string-no-properties 1))))
7002 (while (string-match " *\n *" link)
7003 (setq link (replace-match " " t t link)))
7004 (setq link (org-link-expand-abbrev link))
7005 (cond
7006 ((or (file-name-absolute-p link)
7007 (string-match "^\\.\\.?/" link))
7008 (setq type "file" path link))
7009 ((string-match org-link-re-with-space3 link)
7010 (setq type (match-string 1 link) path (match-string 2 link)))
7011 (t (setq type "thisfile" path link)))
7012 (throw 'match t)))
7014 (when (get-text-property (point) 'org-linked-text)
7015 (setq type "thisfile"
7016 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7017 (1+ (point)) (point))
7018 path (buffer-substring
7019 (previous-single-property-change pos 'org-linked-text)
7020 (next-single-property-change pos 'org-linked-text)))
7021 (throw 'match t))
7023 (save-excursion
7024 (when (or (org-in-regexp org-angle-link-re)
7025 (org-in-regexp org-plain-link-re))
7026 (setq type (match-string 1) path (match-string 2))
7027 (throw 'match t)))
7028 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7029 (setq type "tree-match"
7030 path (match-string 1))
7031 (throw 'match t))
7032 (save-excursion
7033 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7034 (setq type "tags"
7035 path (match-string 1))
7036 (while (string-match ":" path)
7037 (setq path (replace-match "+" t t path)))
7038 (throw 'match t))))
7039 (unless path
7040 (error "No link found"))
7041 ;; Remove any trailing spaces in path
7042 (if (string-match " +\\'" path)
7043 (setq path (replace-match "" t t path)))
7044 (if (and org-link-translation-function
7045 (fboundp org-link-translation-function))
7046 ;; Check if we need to translate the link
7047 (let ((tmp (funcall org-link-translation-function type path)))
7048 (setq type (car tmp) path (cdr tmp))))
7050 (cond
7052 ((assoc type org-link-protocols)
7053 (funcall (nth 1 (assoc type org-link-protocols)) path))
7055 ((equal type "mailto")
7056 (let ((cmd (car org-link-mailto-program))
7057 (args (cdr org-link-mailto-program)) args1
7058 (address path) (subject "") a)
7059 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7060 (setq address (match-string 1 path)
7061 subject (org-link-escape (match-string 2 path))))
7062 (while args
7063 (cond
7064 ((not (stringp (car args))) (push (pop args) args1))
7065 (t (setq a (pop args))
7066 (if (string-match "%a" a)
7067 (setq a (replace-match address t t a)))
7068 (if (string-match "%s" a)
7069 (setq a (replace-match subject t t a)))
7070 (push a args1))))
7071 (apply cmd (nreverse args1))))
7073 ((member type '("http" "https" "ftp" "news"))
7074 (browse-url (concat type ":" (org-link-escape
7075 path org-link-escape-chars-browser))))
7077 ((member type '("message"))
7078 (browse-url (concat type ":" path)))
7080 ((string= type "tags")
7081 (org-tags-view in-emacs path))
7082 ((string= type "thisfile")
7083 (if in-emacs
7084 (switch-to-buffer-other-window
7085 (org-get-buffer-for-internal-link (current-buffer)))
7086 (org-mark-ring-push))
7087 (let ((cmd `(org-link-search
7088 ,path
7089 ,(cond ((equal in-emacs '(4)) 'occur)
7090 ((equal in-emacs '(16)) 'org-occur)
7091 (t nil))
7092 ,pos)))
7093 (condition-case nil (eval cmd)
7094 (error (progn (widen) (eval cmd))))))
7096 ((string= type "tree-match")
7097 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7099 ((string= type "file")
7100 (if (string-match "::\\([0-9]+\\)\\'" path)
7101 (setq line (string-to-number (match-string 1 path))
7102 path (substring path 0 (match-beginning 0)))
7103 (if (string-match "::\\(.+\\)\\'" path)
7104 (setq search (match-string 1 path)
7105 path (substring path 0 (match-beginning 0)))))
7106 (if (string-match "[*?{]" (file-name-nondirectory path))
7107 (dired path)
7108 (org-open-file path in-emacs line search)))
7110 ((string= type "news")
7111 (require 'org-gnus)
7112 (org-gnus-follow-link path))
7114 ((string= type "shell")
7115 (let ((cmd path))
7116 (if (or (not org-confirm-shell-link-function)
7117 (funcall org-confirm-shell-link-function
7118 (format "Execute \"%s\" in shell? "
7119 (org-add-props cmd nil
7120 'face 'org-warning))))
7121 (progn
7122 (message "Executing %s" cmd)
7123 (shell-command cmd))
7124 (error "Abort"))))
7126 ((string= type "elisp")
7127 (let ((cmd path))
7128 (if (or (not org-confirm-elisp-link-function)
7129 (funcall org-confirm-elisp-link-function
7130 (format "Execute \"%s\" as elisp? "
7131 (org-add-props cmd nil
7132 'face 'org-warning))))
7133 (message "%s => %s" cmd
7134 (if (equal (string-to-char cmd) ?\()
7135 (eval (read cmd))
7136 (call-interactively (read cmd))))
7137 (error "Abort"))))
7140 (browse-url-at-point))))))
7141 (move-marker org-open-link-marker nil)
7142 (run-hook-with-args 'org-follow-link-hook))
7144 ;;;; Time estimates
7146 (defun org-get-effort (&optional pom)
7147 "Get the effort estimate for the current entry."
7148 (org-entry-get pom org-effort-property))
7150 ;;; File search
7152 (defvar org-create-file-search-functions nil
7153 "List of functions to construct the right search string for a file link.
7154 These functions are called in turn with point at the location to
7155 which the link should point.
7157 A function in the hook should first test if it would like to
7158 handle this file type, for example by checking the major-mode or
7159 the file extension. If it decides not to handle this file, it
7160 should just return nil to give other functions a chance. If it
7161 does handle the file, it must return the search string to be used
7162 when following the link. The search string will be part of the
7163 file link, given after a double colon, and `org-open-at-point'
7164 will automatically search for it. If special measures must be
7165 taken to make the search successful, another function should be
7166 added to the companion hook `org-execute-file-search-functions',
7167 which see.
7169 A function in this hook may also use `setq' to set the variable
7170 `description' to provide a suggestion for the descriptive text to
7171 be used for this link when it gets inserted into an Org-mode
7172 buffer with \\[org-insert-link].")
7174 (defvar org-execute-file-search-functions nil
7175 "List of functions to execute a file search triggered by a link.
7177 Functions added to this hook must accept a single argument, the
7178 search string that was part of the file link, the part after the
7179 double colon. The function must first check if it would like to
7180 handle this search, for example by checking the major-mode or the
7181 file extension. If it decides not to handle this search, it
7182 should just return nil to give other functions a chance. If it
7183 does handle the search, it must return a non-nil value to keep
7184 other functions from trying.
7186 Each function can access the current prefix argument through the
7187 variable `current-prefix-argument'. Note that a single prefix is
7188 used to force opening a link in Emacs, so it may be good to only
7189 use a numeric or double prefix to guide the search function.
7191 In case this is needed, a function in this hook can also restore
7192 the window configuration before `org-open-at-point' was called using:
7194 (set-window-configuration org-window-config-before-follow-link)")
7196 (defun org-link-search (s &optional type avoid-pos)
7197 "Search for a link search option.
7198 If S is surrounded by forward slashes, it is interpreted as a
7199 regular expression. In org-mode files, this will create an `org-occur'
7200 sparse tree. In ordinary files, `occur' will be used to list matches.
7201 If the current buffer is in `dired-mode', grep will be used to search
7202 in all files. If AVOID-POS is given, ignore matches near that position."
7203 (let ((case-fold-search t)
7204 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7205 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7206 (append '(("") (" ") ("\t") ("\n"))
7207 org-emphasis-alist)
7208 "\\|") "\\)"))
7209 (pos (point))
7210 (pre nil) (post nil)
7211 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7212 (cond
7213 ;; First check if there are any special
7214 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7215 ;; Now try the builtin stuff
7216 ((save-excursion
7217 (goto-char (point-min))
7218 (and
7219 (re-search-forward
7220 (concat "<<" (regexp-quote s0) ">>") nil t)
7221 (setq type 'dedicated
7222 pos (match-beginning 0))))
7223 ;; There is an exact target for this
7224 (goto-char pos))
7225 ((and (string-match "^(\\(.*\\))$" s0)
7226 (save-excursion
7227 (goto-char (point-min))
7228 (and
7229 (re-search-forward
7230 (concat "[^[]" (regexp-quote
7231 (format org-coderef-label-format
7232 (match-string 1 s0))))
7233 nil t)
7234 (setq type 'dedicated
7235 pos (1+ (match-beginning 0))))))
7236 ;; There is a coderef target for this
7237 (goto-char pos))
7238 ((string-match "^/\\(.*\\)/$" s)
7239 ;; A regular expression
7240 (cond
7241 ((org-mode-p)
7242 (org-occur (match-string 1 s)))
7243 ;;((eq major-mode 'dired-mode)
7244 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7245 (t (org-do-occur (match-string 1 s)))))
7247 ;; A normal search strings
7248 (when (equal (string-to-char s) ?*)
7249 ;; Anchor on headlines, post may include tags.
7250 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7251 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7252 s (substring s 1)))
7253 (remove-text-properties
7254 0 (length s)
7255 '(face nil mouse-face nil keymap nil fontified nil) s)
7256 ;; Make a series of regular expressions to find a match
7257 (setq words (org-split-string s "[ \n\r\t]+")
7259 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7260 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7261 "\\)" markers)
7262 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7263 re2a (concat "[ \t\r\n]" re2a_)
7264 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7265 re4 (concat "[^a-zA-Z_]" re4_)
7267 re1 (concat pre re2 post)
7268 re3 (concat pre (if pre re4_ re4) post)
7269 re5 (concat pre ".*" re4)
7270 re2 (concat pre re2)
7271 re2a (concat pre (if pre re2a_ re2a))
7272 re4 (concat pre (if pre re4_ re4))
7273 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7274 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7275 re5 "\\)"
7277 (cond
7278 ((eq type 'org-occur) (org-occur reall))
7279 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7280 (t (goto-char (point-min))
7281 (setq type 'fuzzy)
7282 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7283 (org-search-not-self 1 re1 nil t)
7284 (org-search-not-self 1 re2 nil t)
7285 (org-search-not-self 1 re2a nil t)
7286 (org-search-not-self 1 re3 nil t)
7287 (org-search-not-self 1 re4 nil t)
7288 (org-search-not-self 1 re5 nil t)
7290 (goto-char (match-beginning 1))
7291 (goto-char pos)
7292 (error "No match")))))
7294 ;; Normal string-search
7295 (goto-char (point-min))
7296 (if (search-forward s nil t)
7297 (goto-char (match-beginning 0))
7298 (error "No match"))))
7299 (and (org-mode-p) (org-show-context 'link-search))
7300 type))
7302 (defun org-search-not-self (group &rest args)
7303 "Execute `re-search-forward', but only accept matches that do not
7304 enclose the position of `org-open-link-marker'."
7305 (let ((m org-open-link-marker))
7306 (catch 'exit
7307 (while (apply 're-search-forward args)
7308 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7309 (goto-char (match-end group))
7310 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7311 (> (match-beginning 0) (marker-position m))
7312 (< (match-end 0) (marker-position m)))
7313 (save-match-data
7314 (or (not (org-in-regexp
7315 org-bracket-link-analytic-regexp 1))
7316 (not (match-end 4)) ; no description
7317 (and (<= (match-beginning 4) (point))
7318 (>= (match-end 4) (point))))))
7319 (throw 'exit (point))))))))
7321 (defun org-get-buffer-for-internal-link (buffer)
7322 "Return a buffer to be used for displaying the link target of internal links."
7323 (cond
7324 ((not org-display-internal-link-with-indirect-buffer)
7325 buffer)
7326 ((string-match "(Clone)$" (buffer-name buffer))
7327 (message "Buffer is already a clone, not making another one")
7328 ;; we also do not modify visibility in this case
7329 buffer)
7330 (t ; make a new indirect buffer for displaying the link
7331 (let* ((bn (buffer-name buffer))
7332 (ibn (concat bn "(Clone)"))
7333 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7334 (with-current-buffer ib (org-overview))
7335 ib))))
7337 (defun org-do-occur (regexp &optional cleanup)
7338 "Call the Emacs command `occur'.
7339 If CLEANUP is non-nil, remove the printout of the regular expression
7340 in the *Occur* buffer. This is useful if the regex is long and not useful
7341 to read."
7342 (occur regexp)
7343 (when cleanup
7344 (let ((cwin (selected-window)) win beg end)
7345 (when (setq win (get-buffer-window "*Occur*"))
7346 (select-window win))
7347 (goto-char (point-min))
7348 (when (re-search-forward "match[a-z]+" nil t)
7349 (setq beg (match-end 0))
7350 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7351 (setq end (1- (match-beginning 0)))))
7352 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7353 (goto-char (point-min))
7354 (select-window cwin))))
7356 ;;; The mark ring for links jumps
7358 (defvar org-mark-ring nil
7359 "Mark ring for positions before jumps in Org-mode.")
7360 (defvar org-mark-ring-last-goto nil
7361 "Last position in the mark ring used to go back.")
7362 ;; Fill and close the ring
7363 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7364 (loop for i from 1 to org-mark-ring-length do
7365 (push (make-marker) org-mark-ring))
7366 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7367 org-mark-ring)
7369 (defun org-mark-ring-push (&optional pos buffer)
7370 "Put the current position or POS into the mark ring and rotate it."
7371 (interactive)
7372 (setq pos (or pos (point)))
7373 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7374 (move-marker (car org-mark-ring)
7375 (or pos (point))
7376 (or buffer (current-buffer)))
7377 (message "%s"
7378 (substitute-command-keys
7379 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7381 (defun org-mark-ring-goto (&optional n)
7382 "Jump to the previous position in the mark ring.
7383 With prefix arg N, jump back that many stored positions. When
7384 called several times in succession, walk through the entire ring.
7385 Org-mode commands jumping to a different position in the current file,
7386 or to another Org-mode file, automatically push the old position
7387 onto the ring."
7388 (interactive "p")
7389 (let (p m)
7390 (if (eq last-command this-command)
7391 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7392 (setq p org-mark-ring))
7393 (setq org-mark-ring-last-goto p)
7394 (setq m (car p))
7395 (switch-to-buffer (marker-buffer m))
7396 (goto-char m)
7397 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7399 (defun org-remove-angle-brackets (s)
7400 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7401 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7403 (defun org-add-angle-brackets (s)
7404 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7405 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7407 (defun org-remove-double-quotes (s)
7408 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7409 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7412 ;;; Following specific links
7414 (defun org-follow-timestamp-link ()
7415 (cond
7416 ((org-at-date-range-p t)
7417 (let ((org-agenda-start-on-weekday)
7418 (t1 (match-string 1))
7419 (t2 (match-string 2)))
7420 (setq t1 (time-to-days (org-time-string-to-time t1))
7421 t2 (time-to-days (org-time-string-to-time t2)))
7422 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7423 ((org-at-timestamp-p t)
7424 (org-agenda-list nil (time-to-days (org-time-string-to-time
7425 (substring (match-string 1) 0 10)))
7427 (t (error "This should not happen"))))
7430 ;;; Following file links
7431 (defvar org-wait nil)
7432 (defun org-open-file (path &optional in-emacs line search)
7433 "Open the file at PATH.
7434 First, this expands any special file name abbreviations. Then the
7435 configuration variable `org-file-apps' is checked if it contains an
7436 entry for this file type, and if yes, the corresponding command is launched.
7438 If no application is found, Emacs simply visits the file.
7440 With optional prefix argument IN-EMACS, Emacs will visit the file.
7441 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7442 and o use an external application to visit the file.
7444 Optional LINE specifies a line to go to, optional SEARCH a string to
7445 search for. If LINE or SEARCH is given, the file will always be
7446 opened in Emacs.
7447 If the file does not exist, an error is thrown."
7448 (setq in-emacs (or in-emacs line search))
7449 (let* ((file (if (equal path "")
7450 buffer-file-name
7451 (substitute-in-file-name (expand-file-name path))))
7452 (apps (append org-file-apps (org-default-apps)))
7453 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7454 (dirp (if remp nil (file-directory-p file)))
7455 (file (if (and dirp org-open-directory-means-index-dot-org)
7456 (concat (file-name-as-directory file) "index.org")
7457 file))
7458 (a-m-a-p (assq 'auto-mode apps))
7459 (dfile (downcase file))
7460 (old-buffer (current-buffer))
7461 (old-pos (point))
7462 (old-mode major-mode)
7463 ext cmd)
7464 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7465 (setq ext (match-string 1 dfile))
7466 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7467 (setq ext (match-string 1 dfile))))
7468 (cond
7469 ((equal in-emacs '(16))
7470 (setq cmd (cdr (assoc 'system apps))))
7471 (in-emacs (setq cmd 'emacs))
7473 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7474 (and dirp (cdr (assoc 'directory apps)))
7475 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7476 'string-match)
7477 (cdr (assoc ext apps))
7478 (cdr (assoc t apps))))))
7479 (when (eq cmd 'system)
7480 (setq cmd (cdr (assoc 'system apps))))
7481 (when (eq cmd 'default)
7482 (setq cmd (cdr (assoc t apps))))
7483 (when (eq cmd 'mailcap)
7484 (require 'mailcap)
7485 (mailcap-parse-mailcaps)
7486 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7487 (command (mailcap-mime-info mime-type)))
7488 (if (stringp command)
7489 (setq cmd command)
7490 (setq cmd 'emacs))))
7491 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7492 (not (file-exists-p file))
7493 (not org-open-non-existing-files))
7494 (error "No such file: %s" file))
7495 (cond
7496 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7497 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7498 (while (string-match "['\"]%s['\"]" cmd)
7499 (setq cmd (replace-match "%s" t t cmd)))
7500 (while (string-match "%s" cmd)
7501 (setq cmd (replace-match
7502 (save-match-data
7503 (shell-quote-argument
7504 (convert-standard-filename file)))
7505 t t cmd)))
7506 (save-window-excursion
7507 (start-process-shell-command cmd nil cmd)
7508 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7510 ((or (stringp cmd)
7511 (eq cmd 'emacs))
7512 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7513 (widen)
7514 (if line (goto-line line)
7515 (if search (org-link-search search))))
7516 ((consp cmd)
7517 (let ((file (convert-standard-filename file)))
7518 (eval cmd)))
7519 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7520 (and (org-mode-p) (eq old-mode 'org-mode)
7521 (or (not (equal old-buffer (current-buffer)))
7522 (not (equal old-pos (point))))
7523 (org-mark-ring-push old-pos old-buffer))))
7525 (defun org-default-apps ()
7526 "Return the default applications for this operating system."
7527 (cond
7528 ((eq system-type 'darwin)
7529 org-file-apps-defaults-macosx)
7530 ((eq system-type 'windows-nt)
7531 org-file-apps-defaults-windowsnt)
7532 (t org-file-apps-defaults-gnu)))
7534 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7535 "Convert extensions to regular expressions in the cars of LIST.
7536 Also, weed out any non-string entries, because the return value is used
7537 only for regexp matching.
7538 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7539 point to the symbol `emacs', indicating that the file should
7540 be opened in Emacs."
7541 (append
7542 (delq nil
7543 (mapcar (lambda (x)
7544 (if (not (stringp (car x)))
7546 (if (string-match "\\W" (car x))
7548 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7549 list))
7550 (if add-auto-mode
7551 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7553 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7554 (defun org-file-remote-p (file)
7555 "Test whether FILE specifies a location on a remote system.
7556 Return non-nil if the location is indeed remote.
7558 For example, the filename \"/user@host:/foo\" specifies a location
7559 on the system \"/user@host:\"."
7560 (cond ((fboundp 'file-remote-p)
7561 (file-remote-p file))
7562 ((fboundp 'tramp-handle-file-remote-p)
7563 (tramp-handle-file-remote-p file))
7564 ((and (boundp 'ange-ftp-name-format)
7565 (string-match (car ange-ftp-name-format) file))
7567 (t nil)))
7570 ;;;; Refiling
7572 (defun org-get-org-file ()
7573 "Read a filename, with default directory `org-directory'."
7574 (let ((default (or org-default-notes-file remember-data-file)))
7575 (read-file-name (format "File name [%s]: " default)
7576 (file-name-as-directory org-directory)
7577 default)))
7579 (defun org-notes-order-reversed-p ()
7580 "Check if the current file should receive notes in reversed order."
7581 (cond
7582 ((not org-reverse-note-order) nil)
7583 ((eq t org-reverse-note-order) t)
7584 ((not (listp org-reverse-note-order)) nil)
7585 (t (catch 'exit
7586 (let ((all org-reverse-note-order)
7587 entry)
7588 (while (setq entry (pop all))
7589 (if (string-match (car entry) buffer-file-name)
7590 (throw 'exit (cdr entry))))
7591 nil)))))
7593 (defvar org-refile-target-table nil
7594 "The list of refile targets, created by `org-refile'.")
7596 (defvar org-agenda-new-buffers nil
7597 "Buffers created to visit agenda files.")
7599 (defun org-get-refile-targets (&optional default-buffer)
7600 "Produce a table with refile targets."
7601 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7602 targets txt re files f desc descre fast-path-p level)
7603 (message "Getting targets...")
7604 (with-current-buffer (or default-buffer (current-buffer))
7605 (while (setq entry (pop entries))
7606 (setq files (car entry) desc (cdr entry))
7607 (setq fast-path-p nil)
7608 (cond
7609 ((null files) (setq files (list (current-buffer))))
7610 ((eq files 'org-agenda-files)
7611 (setq files (org-agenda-files 'unrestricted)))
7612 ((and (symbolp files) (fboundp files))
7613 (setq files (funcall files)))
7614 ((and (symbolp files) (boundp files))
7615 (setq files (symbol-value files))))
7616 (if (stringp files) (setq files (list files)))
7617 (cond
7618 ((eq (car desc) :tag)
7619 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7620 ((eq (car desc) :todo)
7621 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7622 ((eq (car desc) :regexp)
7623 (setq descre (cdr desc)))
7624 ((eq (car desc) :level)
7625 (setq descre (concat "^\\*\\{" (number-to-string
7626 (if org-odd-levels-only
7627 (1- (* 2 (cdr desc)))
7628 (cdr desc)))
7629 "\\}[ \t]")))
7630 ((eq (car desc) :maxlevel)
7631 (setq fast-path-p t)
7632 (setq descre (concat "^\\*\\{1," (number-to-string
7633 (if org-odd-levels-only
7634 (1- (* 2 (cdr desc)))
7635 (cdr desc)))
7636 "\\}[ \t]")))
7637 (t (error "Bad refiling target description %s" desc)))
7638 (while (setq f (pop files))
7639 (save-excursion
7640 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7641 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7642 (setq f (expand-file-name f))
7643 (save-excursion
7644 (save-restriction
7645 (widen)
7646 (goto-char (point-min))
7647 (while (re-search-forward descre nil t)
7648 (goto-char (point-at-bol))
7649 (when (looking-at org-complex-heading-regexp)
7650 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7651 txt (org-link-display-format (match-string 4))
7652 re (concat "^" (regexp-quote
7653 (buffer-substring (match-beginning 1)
7654 (match-end 4)))))
7655 (if (match-end 5) (setq re (concat re "[ \t]+"
7656 (regexp-quote
7657 (match-string 5)))))
7658 (setq re (concat re "[ \t]*$"))
7659 (when org-refile-use-outline-path
7660 (setq txt (mapconcat 'org-protect-slash
7661 (append
7662 (if (eq org-refile-use-outline-path 'file)
7663 (list (file-name-nondirectory
7664 (buffer-file-name (buffer-base-buffer))))
7665 (if (eq org-refile-use-outline-path 'full-file-path)
7666 (list (buffer-file-name (buffer-base-buffer)))))
7667 (org-get-outline-path fast-path-p level txt)
7668 (list txt))
7669 "/")))
7670 (push (list txt f re (point)) targets))
7671 (goto-char (point-at-eol))))))))
7672 (message "Getting targets...done")
7673 (nreverse targets))))
7675 (defun org-protect-slash (s)
7676 (while (string-match "/" s)
7677 (setq s (replace-match "\\" t t s)))
7680 (defvar org-olpa (make-vector 20 nil))
7682 (defun org-get-outline-path (&optional fastp level heading)
7683 "Return the outline path to the current entry, as a list."
7684 (if fastp
7685 (progn
7686 (if (> level 19)
7687 (error "Outline path failure, more than 19 levels."))
7688 (loop for i from level upto 19 do
7689 (aset org-olpa i nil))
7690 (prog1
7691 (delq nil (append org-olpa nil))
7692 (aset org-olpa level heading)))
7693 (let (rtn)
7694 (save-excursion
7695 (while (org-up-heading-safe)
7696 (when (looking-at org-complex-heading-regexp)
7697 (push (org-match-string-no-properties 4) rtn)))
7698 rtn))))
7700 (defvar org-refile-history nil
7701 "History for refiling operations.")
7703 (defun org-refile (&optional goto default-buffer)
7704 "Move the entry at point to another heading.
7705 The list of target headings is compiled using the information in
7706 `org-refile-targets', which see. This list is created before each use
7707 and will therefore always be up-to-date.
7709 At the target location, the entry is filed as a subitem of the target heading.
7710 Depending on `org-reverse-note-order', the new subitem will either be the
7711 first or the last subitem.
7713 If there is an active region, all entries in that region will be moved.
7714 However, the region must fulfil the requirement that the first heading
7715 is the first one sets the top-level of the moved text - at most siblings
7716 below it are allowed.
7718 With prefix arg GOTO, the command will only visit the target location,
7719 not actually move anything.
7720 With a double prefix `C-u C-u', go to the location where the last refiling
7721 operation has put the subtree."
7722 (interactive "P")
7723 (let* ((cbuf (current-buffer))
7724 (regionp (org-region-active-p))
7725 (region-start (and regionp (region-beginning)))
7726 (region-end (and regionp (region-end)))
7727 (region-length (and regionp (- region-end region-start)))
7728 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7729 pos it nbuf file re level reversed)
7730 (when regionp (goto-char region-start)
7731 (unless (org-kill-is-subtree-p
7732 (buffer-substring region-start region-end))
7733 (error "The region is not a (sequence of) subtree(s)")))
7734 (if (equal goto '(16))
7735 (org-refile-goto-last-stored)
7736 (when (setq it (org-refile-get-location
7737 (if goto "Goto: " "Refile to: ") default-buffer))
7738 (setq file (nth 1 it)
7739 re (nth 2 it)
7740 pos (nth 3 it))
7741 (if (and (equal (buffer-file-name) file)
7742 (if regionp
7743 (and (>= pos region-start)
7744 (<= pos region-end))
7745 (and (>= pos (point))
7746 (< pos (save-excursion
7747 (org-end-of-subtree t t))))))
7748 (error "Cannot refile to position inside the tree or region"))
7750 (setq nbuf (or (find-buffer-visiting file)
7751 (find-file-noselect file)))
7752 (if goto
7753 (progn
7754 (switch-to-buffer nbuf)
7755 (goto-char pos)
7756 (org-show-context 'org-goto))
7757 (if regionp
7758 (progn
7759 (kill-new (buffer-substring region-start region-end))
7760 (org-save-markers-in-region region-start region-end))
7761 (org-copy-subtree 1 nil t))
7762 (save-excursion
7763 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7764 (find-file-noselect file))))
7765 (setq reversed (org-notes-order-reversed-p))
7766 (save-excursion
7767 (save-restriction
7768 (widen)
7769 (goto-char pos)
7770 (looking-at outline-regexp)
7771 (setq level (org-get-valid-level (funcall outline-level) 1))
7772 (goto-char
7773 (if reversed
7774 (or (outline-next-heading) (point-max))
7775 (or (save-excursion (outline-get-next-sibling))
7776 (org-end-of-subtree t t)
7777 (point-max))))
7778 (if (not (bolp)) (newline))
7779 (bookmark-set "org-refile-last-stored")
7780 (org-paste-subtree level))))
7781 (if regionp
7782 (delete-region (point) (+ (point) region-length))
7783 (org-cut-subtree))
7784 (setq org-markers-to-move nil)
7785 (message "Refiled to \"%s\"" (car it)))))))
7787 (defun org-refile-goto-last-stored ()
7788 "Go to the location where the last refile was stored."
7789 (interactive)
7790 (bookmark-jump "org-refile-last-stored")
7791 (message "This is the location of the last refile"))
7793 (defun org-refile-get-location (&optional prompt default-buffer)
7794 "Prompt the user for a refile location, using PROMPT."
7795 (let ((org-refile-targets org-refile-targets)
7796 (org-refile-use-outline-path org-refile-use-outline-path))
7797 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7798 (unless org-refile-target-table
7799 (error "No refile targets"))
7800 (let* ((cbuf (current-buffer))
7801 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7802 (cfunc (if (and org-refile-use-outline-path
7803 org-outline-path-complete-in-steps)
7804 'org-olpath-completing-read
7805 'org-ido-completing-read))
7806 (extra (if org-refile-use-outline-path "/" ""))
7807 (filename (and cfn (expand-file-name cfn)))
7808 (tbl (mapcar
7809 (lambda (x)
7810 (if (not (equal filename (nth 1 x)))
7811 (cons (concat (car x) extra " ("
7812 (file-name-nondirectory (nth 1 x)) ")")
7813 (cdr x))
7814 (cons (concat (car x) extra) (cdr x))))
7815 org-refile-target-table))
7816 (completion-ignore-case t))
7817 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7818 tbl)))
7820 (defun org-olpath-completing-read (prompt collection &rest args)
7821 "Read an outline path like a file name."
7822 (let ((thetable collection))
7823 (apply
7824 'org-ido-completing-read prompt
7825 (lambda (string predicate &optional flag)
7826 (let (rtn r s f (l (length string)))
7827 (cond
7828 ((eq flag nil)
7829 ;; try completion
7830 (try-completion string thetable))
7831 ((eq flag t)
7832 ;; all-completions
7833 (setq rtn (all-completions string thetable predicate))
7834 (mapcar
7835 (lambda (x)
7836 (setq r (substring x l))
7837 (if (string-match " ([^)]*)$" x)
7838 (setq f (match-string 0 x))
7839 (setq f ""))
7840 (if (string-match "/" r)
7841 (concat string (substring r 0 (match-end 0)) f)
7843 rtn))
7844 ((eq flag 'lambda)
7845 ;; exact match?
7846 (assoc string thetable)))
7848 args)))
7850 ;;;; Dynamic blocks
7852 (defun org-find-dblock (name)
7853 "Find the first dynamic block with name NAME in the buffer.
7854 If not found, stay at current position and return nil."
7855 (let (pos)
7856 (save-excursion
7857 (goto-char (point-min))
7858 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7859 nil t)
7860 (match-beginning 0))))
7861 (if pos (goto-char pos))
7862 pos))
7864 (defconst org-dblock-start-re
7865 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7866 "Matches the startline of a dynamic block, with parameters.")
7868 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7869 "Matches the end of a dynamic block.")
7871 (defun org-create-dblock (plist)
7872 "Create a dynamic block section, with parameters taken from PLIST.
7873 PLIST must contain a :name entry which is used as name of the block."
7874 (unless (bolp) (newline))
7875 (let ((name (plist-get plist :name)))
7876 (insert "#+BEGIN: " name)
7877 (while plist
7878 (if (eq (car plist) :name)
7879 (setq plist (cddr plist))
7880 (insert " " (prin1-to-string (pop plist)))))
7881 (insert "\n\n#+END:\n")
7882 (beginning-of-line -2)))
7884 (defun org-prepare-dblock ()
7885 "Prepare dynamic block for refresh.
7886 This empties the block, puts the cursor at the insert position and returns
7887 the property list including an extra property :name with the block name."
7888 (unless (looking-at org-dblock-start-re)
7889 (error "Not at a dynamic block"))
7890 (let* ((begdel (1+ (match-end 0)))
7891 (name (org-no-properties (match-string 1)))
7892 (params (append (list :name name)
7893 (read (concat "(" (match-string 3) ")")))))
7894 (unless (re-search-forward org-dblock-end-re nil t)
7895 (error "Dynamic block not terminated"))
7896 (setq params
7897 (append params
7898 (list :content (buffer-substring
7899 begdel (match-beginning 0)))))
7900 (delete-region begdel (match-beginning 0))
7901 (goto-char begdel)
7902 (open-line 1)
7903 params))
7905 (defun org-map-dblocks (&optional command)
7906 "Apply COMMAND to all dynamic blocks in the current buffer.
7907 If COMMAND is not given, use `org-update-dblock'."
7908 (let ((cmd (or command 'org-update-dblock))
7909 pos)
7910 (save-excursion
7911 (goto-char (point-min))
7912 (while (re-search-forward org-dblock-start-re nil t)
7913 (goto-char (setq pos (match-beginning 0)))
7914 (condition-case nil
7915 (funcall cmd)
7916 (error (message "Error during update of dynamic block")))
7917 (goto-char pos)
7918 (unless (re-search-forward org-dblock-end-re nil t)
7919 (error "Dynamic block not terminated"))))))
7921 (defun org-dblock-update (&optional arg)
7922 "User command for updating dynamic blocks.
7923 Update the dynamic block at point. With prefix ARG, update all dynamic
7924 blocks in the buffer."
7925 (interactive "P")
7926 (if arg
7927 (org-update-all-dblocks)
7928 (or (looking-at org-dblock-start-re)
7929 (org-beginning-of-dblock))
7930 (org-update-dblock)))
7932 (defun org-update-dblock ()
7933 "Update the dynamic block at point
7934 This means to empty the block, parse for parameters and then call
7935 the correct writing function."
7936 (save-window-excursion
7937 (let* ((pos (point))
7938 (line (org-current-line))
7939 (params (org-prepare-dblock))
7940 (name (plist-get params :name))
7941 (cmd (intern (concat "org-dblock-write:" name))))
7942 (message "Updating dynamic block `%s' at line %d..." name line)
7943 (funcall cmd params)
7944 (message "Updating dynamic block `%s' at line %d...done" name line)
7945 (goto-char pos))))
7947 (defun org-beginning-of-dblock ()
7948 "Find the beginning of the dynamic block at point.
7949 Error if there is no such block at point."
7950 (let ((pos (point))
7951 beg)
7952 (end-of-line 1)
7953 (if (and (re-search-backward org-dblock-start-re nil t)
7954 (setq beg (match-beginning 0))
7955 (re-search-forward org-dblock-end-re nil t)
7956 (> (match-end 0) pos))
7957 (goto-char beg)
7958 (goto-char pos)
7959 (error "Not in a dynamic block"))))
7961 (defun org-update-all-dblocks ()
7962 "Update all dynamic blocks in the buffer.
7963 This function can be used in a hook."
7964 (when (org-mode-p)
7965 (org-map-dblocks 'org-update-dblock)))
7968 ;;;; Completion
7970 (defconst org-additional-option-like-keywords
7971 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7972 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7973 "BEGIN_EXAMPLE" "END_EXAMPLE"
7974 "BEGIN_QUOTE" "END_QUOTE"
7975 "BEGIN_VERSE" "END_VERSE"
7976 "BEGIN_SRC" "END_SRC"
7977 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7979 (defcustom org-structure-template-alist
7981 ("s" "#+begin_src ?\n\n#+end_src"
7982 "<src lang=\"?\">\n\n</src>")
7983 ("e" "#+begin_example\n?\n#+end_example"
7984 "<example>\n?\n</example>")
7985 ("q" "#+begin_quote\n?\n#+end_quote"
7986 "<quote>\n?\n</quote>")
7987 ("v" "#+begin_verse\n?\n#+end_verse"
7988 "<verse>\n?\n/verse>")
7989 ("l" "#+begin_latex\n?\n#+end_latex"
7990 "<literal style=\"latex\">\n?\n</literal>")
7991 ("L" "#+latex: "
7992 "<literal style=\"latex\">?</literal>")
7993 ("h" "#+begin_html\n?\n#+end_html"
7994 "<literal style=\"html\">\n?\n</literal>")
7995 ("H" "#+html: "
7996 "<literal style=\"html\">?</literal>")
7997 ("a" "#+begin_ascii\n?\n#+end_ascii")
7998 ("A" "#+ascii: ")
7999 ("i" "#+include %file ?"
8000 "<include file=%file markup=\"?\">")
8002 "Structure completion elements.
8003 This is a list of abbreviation keys and values. The value gets inserted
8004 it you type @samp{.} followed by the key and then the completion key,
8005 usually `M-TAB'. %file will be replaced by a file name after prompting
8006 for the file using completion.
8007 There are two templates for each key, the first uses the original Org syntax,
8008 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8009 the default when the /org-mtags.el/ module has been loaded. See also the
8010 variable `org-mtags-prefer-muse-templates'.
8011 This is an experimental feature, it is undecided if it is going to stay in."
8012 :group 'org-completion
8013 :type '(repeat
8014 (string :tag "Key")
8015 (string :tag "Template")
8016 (string :tag "Muse Template")))
8018 (defun org-try-structure-completion ()
8019 "Try to complete a structure template before point.
8020 This looks for strings like \"<e\" on an otherwise empty line and
8021 expands them."
8022 (let ((l (buffer-substring (point-at-bol) (point)))
8024 (when (and (looking-at "[ \t]*$")
8025 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8026 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8027 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8028 (match-beginning 1)) a)
8029 t)))
8031 (defun org-complete-expand-structure-template (start cell)
8032 "Expand a structure template."
8033 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8034 (rpl (nth (if musep 2 1) cell)))
8035 (delete-region start (point))
8036 (when (string-match "\\`#\\+" rpl)
8037 (cond
8038 ((bolp))
8039 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8040 (delete-region (point-at-bol) (point)))
8041 (t (newline))))
8042 (setq start (point))
8043 (if (string-match "%file" rpl)
8044 (setq rpl (replace-match
8045 (concat
8046 "\""
8047 (save-match-data
8048 (abbreviate-file-name (read-file-name "Include file: ")))
8049 "\"")
8050 t t rpl)))
8051 (insert rpl)
8052 (if (re-search-backward "\\?" start t) (delete-char 1))))
8055 (defun org-complete (&optional arg)
8056 "Perform completion on word at point.
8057 At the beginning of a headline, this completes TODO keywords as given in
8058 `org-todo-keywords'.
8059 If the current word is preceded by a backslash, completes the TeX symbols
8060 that are supported for HTML support.
8061 If the current word is preceded by \"#+\", completes special words for
8062 setting file options.
8063 In the line after \"#+STARTUP:, complete valid keywords.\"
8064 At all other locations, this simply calls the value of
8065 `org-completion-fallback-command'."
8066 (interactive "P")
8067 (org-without-partial-completion
8068 (catch 'exit
8069 (let* ((a nil)
8070 (end (point))
8071 (beg1 (save-excursion
8072 (skip-chars-backward (org-re "[:alnum:]_@"))
8073 (point)))
8074 (beg (save-excursion
8075 (skip-chars-backward "a-zA-Z0-9_:$")
8076 (point)))
8077 (confirm (lambda (x) (stringp (car x))))
8078 (searchhead (equal (char-before beg) ?*))
8079 (struct
8080 (when (and (member (char-before beg1) '(?. ?<))
8081 (setq a (assoc (buffer-substring beg1 (point))
8082 org-structure-template-alist)))
8083 (org-complete-expand-structure-template (1- beg1) a)
8084 (throw 'exit t)))
8085 (tag (and (equal (char-before beg1) ?:)
8086 (equal (char-after (point-at-bol)) ?*)))
8087 (prop (and (equal (char-before beg1) ?:)
8088 (not (equal (char-after (point-at-bol)) ?*))))
8089 (texp (equal (char-before beg) ?\\))
8090 (link (equal (char-before beg) ?\[))
8091 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8092 beg)
8093 "#+"))
8094 (startup (string-match "^#\\+STARTUP:.*"
8095 (buffer-substring (point-at-bol) (point))))
8096 (completion-ignore-case opt)
8097 (type nil)
8098 (tbl nil)
8099 (table (cond
8100 (opt
8101 (setq type :opt)
8102 (require 'org-exp)
8103 (append
8104 (mapcar
8105 (lambda (x)
8106 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8107 (cons (match-string 2 x) (match-string 1 x)))
8108 (org-split-string (org-get-current-options) "\n"))
8109 (mapcar 'list org-additional-option-like-keywords)))
8110 (startup
8111 (setq type :startup)
8112 org-startup-options)
8113 (link (append org-link-abbrev-alist-local
8114 org-link-abbrev-alist))
8115 (texp
8116 (setq type :tex)
8117 org-html-entities)
8118 ((string-match "\\`\\*+[ \t]+\\'"
8119 (buffer-substring (point-at-bol) beg))
8120 (setq type :todo)
8121 (mapcar 'list org-todo-keywords-1))
8122 (searchhead
8123 (setq type :searchhead)
8124 (save-excursion
8125 (goto-char (point-min))
8126 (while (re-search-forward org-todo-line-regexp nil t)
8127 (push (list
8128 (org-make-org-heading-search-string
8129 (match-string 3) t))
8130 tbl)))
8131 tbl)
8132 (tag (setq type :tag beg beg1)
8133 (or org-tag-alist (org-get-buffer-tags)))
8134 (prop (setq type :prop beg beg1)
8135 (mapcar 'list (org-buffer-property-keys nil t t)))
8136 (t (progn
8137 (call-interactively org-completion-fallback-command)
8138 (throw 'exit nil)))))
8139 (pattern (buffer-substring-no-properties beg end))
8140 (completion (try-completion pattern table confirm)))
8141 (cond ((eq completion t)
8142 (if (not (assoc (upcase pattern) table))
8143 (message "Already complete")
8144 (if (and (equal type :opt)
8145 (not (member (car (assoc (upcase pattern) table))
8146 org-additional-option-like-keywords)))
8147 (insert (substring (cdr (assoc (upcase pattern) table))
8148 (length pattern)))
8149 (if (memq type '(:tag :prop)) (insert ":")))))
8150 ((null completion)
8151 (message "Can't find completion for \"%s\"" pattern)
8152 (ding))
8153 ((not (string= pattern completion))
8154 (delete-region beg end)
8155 (if (string-match " +$" completion)
8156 (setq completion (replace-match "" t t completion)))
8157 (insert completion)
8158 (if (get-buffer-window "*Completions*")
8159 (delete-window (get-buffer-window "*Completions*")))
8160 (if (assoc completion table)
8161 (if (eq type :todo) (insert " ")
8162 (if (memq type '(:tag :prop)) (insert ":"))))
8163 (if (and (equal type :opt) (assoc completion table))
8164 (message "%s" (substitute-command-keys
8165 "Press \\[org-complete] again to insert example settings"))))
8167 (message "Making completion list...")
8168 (let ((list (sort (all-completions pattern table confirm)
8169 'string<)))
8170 (with-output-to-temp-buffer "*Completions*"
8171 (condition-case nil
8172 ;; Protection needed for XEmacs and emacs 21
8173 (display-completion-list list pattern)
8174 (error (display-completion-list list)))))
8175 (message "Making completion list...%s" "done")))))))
8177 ;;;; TODO, DEADLINE, Comments
8179 (defun org-toggle-comment ()
8180 "Change the COMMENT state of an entry."
8181 (interactive)
8182 (save-excursion
8183 (org-back-to-heading)
8184 (let (case-fold-search)
8185 (if (looking-at (concat outline-regexp
8186 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8187 (replace-match "" t t nil 1)
8188 (if (looking-at outline-regexp)
8189 (progn
8190 (goto-char (match-end 0))
8191 (insert org-comment-string " ")))))))
8193 (defvar org-last-todo-state-is-todo nil
8194 "This is non-nil when the last TODO state change led to a TODO state.
8195 If the last change removed the TODO tag or switched to DONE, then
8196 this is nil.")
8198 (defvar org-setting-tags nil) ; dynamically skipped
8200 (defun org-parse-local-options (string var)
8201 "Parse STRING for startup setting relevant for variable VAR."
8202 (let ((rtn (symbol-value var))
8203 e opts)
8204 (save-match-data
8205 (if (or (not string) (not (string-match "\\S-" string)))
8207 (setq opts (delq nil (mapcar (lambda (x)
8208 (setq e (assoc x org-startup-options))
8209 (if (eq (nth 1 e) var) e nil))
8210 (org-split-string string "[ \t]+"))))
8211 (if (not opts)
8213 (setq rtn nil)
8214 (while (setq e (pop opts))
8215 (if (not (nth 3 e))
8216 (setq rtn (nth 2 e))
8217 (if (not (listp rtn)) (setq rtn nil))
8218 (push (nth 2 e) rtn)))
8219 rtn)))))
8221 (defvar org-blocker-hook nil
8222 "Hook for functions that are allowed to block a state change.
8224 Each function gets as its single argument a property list, see
8225 `org-trigger-hook' for more information about this list.
8227 If any of the functions in this hook returns nil, the state change
8228 is blocked.")
8230 (defvar org-trigger-hook nil
8231 "Hook for functions that are triggered by a state change.
8233 Each function gets as its single argument a property list with at least
8234 the following elements:
8236 (:type type-of-change :position pos-at-entry-start
8237 :from old-state :to new-state)
8239 Depending on the type, more properties may be present.
8241 This mechanism is currently implemented for:
8243 TODO state changes
8244 ------------------
8245 :type todo-state-change
8246 :from previous state (keyword as a string), or nil
8247 :to new state (keyword as a string), or nil")
8249 (defvar org-agenda-headline-snapshot-before-repeat)
8250 (defun org-todo (&optional arg)
8251 "Change the TODO state of an item.
8252 The state of an item is given by a keyword at the start of the heading,
8253 like
8254 *** TODO Write paper
8255 *** DONE Call mom
8257 The different keywords are specified in the variable `org-todo-keywords'.
8258 By default the available states are \"TODO\" and \"DONE\".
8259 So for this example: when the item starts with TODO, it is changed to DONE.
8260 When it starts with DONE, the DONE is removed. And when neither TODO nor
8261 DONE are present, add TODO at the beginning of the heading.
8263 With C-u prefix arg, use completion to determine the new state.
8264 With numeric prefix arg, switch to that state.
8266 For calling through lisp, arg is also interpreted in the following way:
8267 'none -> empty state
8268 \"\"(empty string) -> switch to empty state
8269 'done -> switch to DONE
8270 'nextset -> switch to the next set of keywords
8271 'previousset -> switch to the previous set of keywords
8272 \"WAITING\" -> switch to the specified keyword, but only if it
8273 really is a member of `org-todo-keywords'."
8274 (interactive "P")
8275 (save-excursion
8276 (catch 'exit
8277 (org-back-to-heading)
8278 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8279 (or (looking-at (concat " +" org-todo-regexp " *"))
8280 (looking-at " *"))
8281 (let* ((match-data (match-data))
8282 (startpos (point-at-bol))
8283 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8284 (org-log-done org-log-done)
8285 (org-log-repeat org-log-repeat)
8286 (org-todo-log-states org-todo-log-states)
8287 (this (match-string 1))
8288 (hl-pos (match-beginning 0))
8289 (head (org-get-todo-sequence-head this))
8290 (ass (assoc head org-todo-kwd-alist))
8291 (interpret (nth 1 ass))
8292 (done-word (nth 3 ass))
8293 (final-done-word (nth 4 ass))
8294 (last-state (or this ""))
8295 (completion-ignore-case t)
8296 (member (member this org-todo-keywords-1))
8297 (tail (cdr member))
8298 (state (cond
8299 ((and org-todo-key-trigger
8300 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8301 (and (not arg) org-use-fast-todo-selection
8302 (not (eq org-use-fast-todo-selection 'prefix)))))
8303 ;; Use fast selection
8304 (org-fast-todo-selection))
8305 ((and (equal arg '(4))
8306 (or (not org-use-fast-todo-selection)
8307 (not org-todo-key-trigger)))
8308 ;; Read a state with completion
8309 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8310 org-todo-keywords-1)
8311 nil t))
8312 ((eq arg 'right)
8313 (if this
8314 (if tail (car tail) nil)
8315 (car org-todo-keywords-1)))
8316 ((eq arg 'left)
8317 (if (equal member org-todo-keywords-1)
8319 (if this
8320 (nth (- (length org-todo-keywords-1) (length tail) 2)
8321 org-todo-keywords-1)
8322 (org-last org-todo-keywords-1))))
8323 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8324 (setq arg nil))) ; hack to fall back to cycling
8325 (arg
8326 ;; user or caller requests a specific state
8327 (cond
8328 ((equal arg "") nil)
8329 ((eq arg 'none) nil)
8330 ((eq arg 'done) (or done-word (car org-done-keywords)))
8331 ((eq arg 'nextset)
8332 (or (car (cdr (member head org-todo-heads)))
8333 (car org-todo-heads)))
8334 ((eq arg 'previousset)
8335 (let ((org-todo-heads (reverse org-todo-heads)))
8336 (or (car (cdr (member head org-todo-heads)))
8337 (car org-todo-heads))))
8338 ((car (member arg org-todo-keywords-1)))
8339 ((nth (1- (prefix-numeric-value arg))
8340 org-todo-keywords-1))))
8341 ((null member) (or head (car org-todo-keywords-1)))
8342 ((equal this final-done-word) nil) ;; -> make empty
8343 ((null tail) nil) ;; -> first entry
8344 ((eq interpret 'sequence)
8345 (car tail))
8346 ((memq interpret '(type priority))
8347 (if (eq this-command last-command)
8348 (car tail)
8349 (if (> (length tail) 0)
8350 (or done-word (car org-done-keywords))
8351 nil)))
8352 (t nil)))
8353 (next (if state (concat " " state " ") " "))
8354 (change-plist (list :type 'todo-state-change :from this :to state
8355 :position startpos))
8356 dolog now-done-p)
8357 (when org-blocker-hook
8358 (unless (save-excursion
8359 (save-match-data
8360 (run-hook-with-args-until-failure
8361 'org-blocker-hook change-plist)))
8362 (if (interactive-p)
8363 (error "TODO state change from %s to %s blocked" this state)
8364 ;; fail silently
8365 (message "TODO state change from %s to %s blocked" this state)
8366 (throw 'exit nil))))
8367 (store-match-data match-data)
8368 (replace-match next t t)
8369 (unless (pos-visible-in-window-p hl-pos)
8370 (message "TODO state changed to %s" (org-trim next)))
8371 (unless head
8372 (setq head (org-get-todo-sequence-head state)
8373 ass (assoc head org-todo-kwd-alist)
8374 interpret (nth 1 ass)
8375 done-word (nth 3 ass)
8376 final-done-word (nth 4 ass)))
8377 (when (memq arg '(nextset previousset))
8378 (message "Keyword-Set %d/%d: %s"
8379 (- (length org-todo-sets) -1
8380 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8381 (length org-todo-sets)
8382 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8383 (setq org-last-todo-state-is-todo
8384 (not (member state org-done-keywords)))
8385 (setq now-done-p (and (member state org-done-keywords)
8386 (not (member this org-done-keywords))))
8387 (and logging (org-local-logging logging))
8388 (when (and (or org-todo-log-states org-log-done)
8389 (not (memq arg '(nextset previousset))))
8390 ;; we need to look at recording a time and note
8391 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8392 (nth 2 (assoc this org-todo-log-states))))
8393 (when (and state
8394 (member state org-not-done-keywords)
8395 (not (member this org-not-done-keywords)))
8396 ;; This is now a todo state and was not one before
8397 ;; If there was a CLOSED time stamp, get rid of it.
8398 (org-add-planning-info nil nil 'closed))
8399 (when (and now-done-p org-log-done)
8400 ;; It is now done, and it was not done before
8401 (org-add-planning-info 'closed (org-current-time))
8402 (if (and (not dolog) (eq 'note org-log-done))
8403 (org-add-log-setup 'done state 'findpos 'note)))
8404 (when (and state dolog)
8405 ;; This is a non-nil state, and we need to log it
8406 (org-add-log-setup 'state state 'findpos dolog)))
8407 ;; Fixup tag positioning
8408 (org-todo-trigger-tag-changes state)
8409 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8410 (when org-provide-todo-statistics
8411 (org-update-parent-todo-statistics))
8412 (run-hooks 'org-after-todo-state-change-hook)
8413 (if (and arg (not (member state org-done-keywords)))
8414 (setq head (org-get-todo-sequence-head state)))
8415 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8416 ;; Do we need to trigger a repeat?
8417 (when now-done-p
8418 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8419 ;; This is for the agenda, take a snapshot of the headline.
8420 (save-match-data
8421 (setq org-agenda-headline-snapshot-before-repeat
8422 (org-get-heading))))
8423 (org-auto-repeat-maybe state))
8424 ;; Fixup cursor location if close to the keyword
8425 (if (and (outline-on-heading-p)
8426 (not (bolp))
8427 (save-excursion (beginning-of-line 1)
8428 (looking-at org-todo-line-regexp))
8429 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8430 (progn
8431 (goto-char (or (match-end 2) (match-end 1)))
8432 (just-one-space)))
8433 (when org-trigger-hook
8434 (save-excursion
8435 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8437 (defun org-update-parent-todo-statistics ()
8438 "Update any statistics cookie in the parent of the current headline."
8439 (interactive)
8440 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8441 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8442 (catch 'exit
8443 (save-excursion
8444 (setq level (org-up-heading-safe))
8445 (unless (and level
8446 (re-search-forward box-re (point-at-eol) t))
8447 (throw 'exit nil))
8448 (setq is-percent (match-end 2))
8449 (save-match-data
8450 (unless (outline-next-heading) (throw 'exit nil))
8451 (while (looking-at org-todo-line-regexp)
8452 (setq kwd (match-string 2))
8453 (and kwd (setq cnt-all (1+ cnt-all)))
8454 (and (member kwd org-done-keywords)
8455 (setq cnt-done (1+ cnt-done)))
8456 (condition-case nil
8457 (org-forward-same-level 1)
8458 (error (end-of-line 1)))))
8459 (replace-match
8460 (if is-percent
8461 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8462 (format "[%d/%d]" cnt-done cnt-all)))
8463 (run-hook-with-args 'org-after-todo-statistics-hook
8464 cnt-done (- cnt-all cnt-done))))))
8466 (defvar org-after-todo-statistics-hook nil
8467 "Hook that is called after a TODO statistics cookie has been updated.
8468 Each function is called with two arguments: the number of not-done entries
8469 and the number of done entries.
8471 For example, the following function, when added to this hook, will switch
8472 an entry to DONE when all children are done, and back to TODO when new
8473 entries are set to a TODO status. Note that this hook is only called
8474 when there is a statistics cookie in the headline!
8476 (defun org-summary-todo (n-done n-not-done)
8477 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8478 (let (org-log-done org-log-states) ; turn off logging
8479 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8482 (defun org-todo-trigger-tag-changes (state)
8483 "Apply the changes defined in `org-todo-state-tags-triggers'."
8484 (let ((l org-todo-state-tags-triggers)
8485 changes)
8486 (when (or (not state) (equal state ""))
8487 (setq changes (append changes (cdr (assoc "" l)))))
8488 (when (and (stringp state) (> (length state) 0))
8489 (setq changes (append changes (cdr (assoc state l)))))
8490 (when (member state org-not-done-keywords)
8491 (setq changes (append changes (cdr (assoc 'todo l)))))
8492 (when (member state org-done-keywords)
8493 (setq changes (append changes (cdr (assoc 'done l)))))
8494 (dolist (c changes)
8495 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8497 (defun org-local-logging (value)
8498 "Get logging settings from a property VALUE."
8499 (let* (words w a)
8500 ;; directly set the variables, they are already local.
8501 (setq org-log-done nil
8502 org-log-repeat nil
8503 org-todo-log-states nil)
8504 (setq words (org-split-string value))
8505 (while (setq w (pop words))
8506 (cond
8507 ((setq a (assoc w org-startup-options))
8508 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8509 (set (nth 1 a) (nth 2 a))))
8510 ((setq a (org-extract-log-state-settings w))
8511 (and (member (car a) org-todo-keywords-1)
8512 (push a org-todo-log-states)))))))
8514 (defun org-get-todo-sequence-head (kwd)
8515 "Return the head of the TODO sequence to which KWD belongs.
8516 If KWD is not set, check if there is a text property remembering the
8517 right sequence."
8518 (let (p)
8519 (cond
8520 ((not kwd)
8521 (or (get-text-property (point-at-bol) 'org-todo-head)
8522 (progn
8523 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8524 nil (point-at-eol)))
8525 (get-text-property p 'org-todo-head))))
8526 ((not (member kwd org-todo-keywords-1))
8527 (car org-todo-keywords-1))
8528 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8530 (defun org-fast-todo-selection ()
8531 "Fast TODO keyword selection with single keys.
8532 Returns the new TODO keyword, or nil if no state change should occur."
8533 (let* ((fulltable org-todo-key-alist)
8534 (done-keywords org-done-keywords) ;; needed for the faces.
8535 (maxlen (apply 'max (mapcar
8536 (lambda (x)
8537 (if (stringp (car x)) (string-width (car x)) 0))
8538 fulltable)))
8539 (expert nil)
8540 (fwidth (+ maxlen 3 1 3))
8541 (ncol (/ (- (window-width) 4) fwidth))
8542 tg cnt e c tbl
8543 groups ingroup)
8544 (save-window-excursion
8545 (if expert
8546 (set-buffer (get-buffer-create " *Org todo*"))
8547 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8548 (erase-buffer)
8549 (org-set-local 'org-done-keywords done-keywords)
8550 (setq tbl fulltable cnt 0)
8551 (while (setq e (pop tbl))
8552 (cond
8553 ((equal e '(:startgroup))
8554 (push '() groups) (setq ingroup t)
8555 (when (not (= cnt 0))
8556 (setq cnt 0)
8557 (insert "\n"))
8558 (insert "{ "))
8559 ((equal e '(:endgroup))
8560 (setq ingroup nil cnt 0)
8561 (insert "}\n"))
8563 (setq tg (car e) c (cdr e))
8564 (if ingroup (push tg (car groups)))
8565 (setq tg (org-add-props tg nil 'face
8566 (org-get-todo-face tg)))
8567 (if (and (= cnt 0) (not ingroup)) (insert " "))
8568 (insert "[" c "] " tg (make-string
8569 (- fwidth 4 (length tg)) ?\ ))
8570 (when (= (setq cnt (1+ cnt)) ncol)
8571 (insert "\n")
8572 (if ingroup (insert " "))
8573 (setq cnt 0)))))
8574 (insert "\n")
8575 (goto-char (point-min))
8576 (if (not expert) (org-fit-window-to-buffer))
8577 (message "[a-z..]:Set [SPC]:clear")
8578 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8579 (cond
8580 ((or (= c ?\C-g)
8581 (and (= c ?q) (not (rassoc c fulltable))))
8582 (setq quit-flag t))
8583 ((= c ?\ ) nil)
8584 ((setq e (rassoc c fulltable) tg (car e))
8586 (t (setq quit-flag t))))))
8588 (defun org-entry-is-todo-p ()
8589 (member (org-get-todo-state) org-not-done-keywords))
8591 (defun org-entry-is-done-p ()
8592 (member (org-get-todo-state) org-done-keywords))
8594 (defun org-get-todo-state ()
8595 (save-excursion
8596 (org-back-to-heading t)
8597 (and (looking-at org-todo-line-regexp)
8598 (match-end 2)
8599 (match-string 2))))
8601 (defun org-at-date-range-p (&optional inactive-ok)
8602 "Is the cursor inside a date range?"
8603 (interactive)
8604 (save-excursion
8605 (catch 'exit
8606 (let ((pos (point)))
8607 (skip-chars-backward "^[<\r\n")
8608 (skip-chars-backward "<[")
8609 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8610 (>= (match-end 0) pos)
8611 (throw 'exit t))
8612 (skip-chars-backward "^<[\r\n")
8613 (skip-chars-backward "<[")
8614 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8615 (>= (match-end 0) pos)
8616 (throw 'exit t)))
8617 nil)))
8619 (defun org-get-repeat ()
8620 "Check if there is a deadline/schedule with repeater in this entry."
8621 (save-match-data
8622 (save-excursion
8623 (org-back-to-heading t)
8624 (if (re-search-forward
8625 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8626 (match-string 1)))))
8628 (defvar org-last-changed-timestamp)
8629 (defvar org-last-inserted-timestamp)
8630 (defvar org-log-post-message)
8631 (defvar org-log-note-purpose)
8632 (defvar org-log-note-how)
8633 (defvar org-log-note-extra)
8634 (defun org-auto-repeat-maybe (done-word)
8635 "Check if the current headline contains a repeated deadline/schedule.
8636 If yes, set TODO state back to what it was and change the base date
8637 of repeating deadline/scheduled time stamps to new date.
8638 This function is run automatically after each state change to a DONE state."
8639 ;; last-state is dynamically scoped into this function
8640 (let* ((repeat (org-get-repeat))
8641 (aa (assoc last-state org-todo-kwd-alist))
8642 (interpret (nth 1 aa))
8643 (head (nth 2 aa))
8644 (whata '(("d" . day) ("m" . month) ("y" . year)))
8645 (msg "Entry repeats: ")
8646 (org-log-done nil)
8647 (org-todo-log-states nil)
8648 (nshiftmax 10) (nshift 0)
8649 re type n what ts mb0 time)
8650 (when repeat
8651 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8652 (org-todo (if (eq interpret 'type) last-state head))
8653 (when org-log-repeat
8654 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8655 (memq 'org-add-log-note post-command-hook))
8656 ;; OK, we are already setup for some record
8657 (if (eq org-log-repeat 'note)
8658 ;; make sure we take a note, not only a time stamp
8659 (setq org-log-note-how 'note))
8660 ;; Set up for taking a record
8661 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8662 'findpos org-log-repeat)))
8663 (org-back-to-heading t)
8664 (org-add-planning-info nil nil 'closed)
8665 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8666 org-deadline-time-regexp "\\)\\|\\("
8667 org-ts-regexp "\\)"))
8668 (while (re-search-forward
8669 re (save-excursion (outline-next-heading) (point)) t)
8670 (setq type (if (match-end 1) org-scheduled-string
8671 (if (match-end 3) org-deadline-string "Plain:"))
8672 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8673 mb0 (match-beginning 0))
8674 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8675 (setq n (string-to-number (match-string 2 ts))
8676 what (match-string 3 ts))
8677 (if (equal what "w") (setq n (* n 7) what "d"))
8678 ;; Preparation, see if we need to modify the start date for the change
8679 (when (match-end 1)
8680 (setq time (save-match-data (org-time-string-to-time ts)))
8681 (cond
8682 ((equal (match-string 1 ts) ".")
8683 ;; Shift starting date to today
8684 (org-timestamp-change
8685 (- (time-to-days (current-time)) (time-to-days time))
8686 'day))
8687 ((equal (match-string 1 ts) "+")
8688 (while (or (= nshift 0)
8689 (<= (time-to-days time) (time-to-days (current-time))))
8690 (when (= (incf nshift) nshiftmax)
8691 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8692 (error "Abort")))
8693 (org-timestamp-change n (cdr (assoc what whata)))
8694 (org-at-timestamp-p t)
8695 (setq ts (match-string 1))
8696 (setq time (save-match-data (org-time-string-to-time ts))))
8697 (org-timestamp-change (- n) (cdr (assoc what whata)))
8698 ;; rematch, so that we have everything in place for the real shift
8699 (org-at-timestamp-p t)
8700 (setq ts (match-string 1))
8701 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8702 (org-timestamp-change n (cdr (assoc what whata)))
8703 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8704 (setq org-log-post-message msg)
8705 (message "%s" msg))))
8707 (defun org-show-todo-tree (arg)
8708 "Make a compact tree which shows all headlines marked with TODO.
8709 The tree will show the lines where the regexp matches, and all higher
8710 headlines above the match.
8711 With a \\[universal-argument] prefix, also show the DONE entries.
8712 With a numeric prefix N, construct a sparse tree for the Nth element
8713 of `org-todo-keywords-1'."
8714 (interactive "P")
8715 (let ((case-fold-search nil)
8716 (kwd-re
8717 (cond ((null arg) org-not-done-regexp)
8718 ((equal arg '(4))
8719 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8720 (mapcar 'list org-todo-keywords-1))))
8721 (concat "\\("
8722 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8723 "\\)\\>")))
8724 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8725 (regexp-quote (nth (1- (prefix-numeric-value arg))
8726 org-todo-keywords-1)))
8727 (t (error "Invalid prefix argument: %s" arg)))))
8728 (message "%d TODO entries found"
8729 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8731 (defun org-deadline (&optional remove time)
8732 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8733 With argument REMOVE, remove any deadline from the item.
8734 When TIME is set, it should be an internal time specification, and the
8735 scheduling will use the corresponding date."
8736 (interactive "P")
8737 (if remove
8738 (progn
8739 (org-remove-timestamp-with-keyword org-deadline-string)
8740 (message "Item no longer has a deadline."))
8741 (if (org-get-repeat)
8742 (error "Cannot change deadline on task with repeater, please do that by hand")
8743 (org-add-planning-info 'deadline time 'closed)
8744 (message "Deadline on %s" org-last-inserted-timestamp))))
8746 (defun org-schedule (&optional remove time)
8747 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8748 With argument REMOVE, remove any scheduling date from the item.
8749 When TIME is set, it should be an internal time specification, and the
8750 scheduling will use the corresponding date."
8751 (interactive "P")
8752 (if remove
8753 (progn
8754 (org-remove-timestamp-with-keyword org-scheduled-string)
8755 (message "Item is no longer scheduled."))
8756 (if (org-get-repeat)
8757 (error "Cannot reschedule task with repeater, please do that by hand")
8758 (org-add-planning-info 'scheduled time 'closed)
8759 (message "Scheduled to %s" org-last-inserted-timestamp))))
8761 (defun org-remove-timestamp-with-keyword (keyword)
8762 "Remove all time stamps with KEYWORD in the current entry."
8763 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8764 beg)
8765 (save-excursion
8766 (org-back-to-heading t)
8767 (setq beg (point))
8768 (org-end-of-subtree t t)
8769 (while (re-search-backward re beg t)
8770 (replace-match "")
8771 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8772 (equal (char-before) ?\ ))
8773 (backward-delete-char 1)
8774 (if (string-match "^[ \t]*$" (buffer-substring
8775 (point-at-bol) (point-at-eol)))
8776 (delete-region (point-at-bol)
8777 (min (point-max) (1+ (point-at-eol))))))))))
8779 (defun org-add-planning-info (what &optional time &rest remove)
8780 "Insert new timestamp with keyword in the line directly after the headline.
8781 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8782 If non is given, the user is prompted for a date.
8783 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8784 be removed."
8785 (interactive)
8786 (let (org-time-was-given org-end-time-was-given ts
8787 end default-time default-input)
8789 (when (and (not time) (memq what '(scheduled deadline)))
8790 ;; Try to get a default date/time from existing timestamp
8791 (save-excursion
8792 (org-back-to-heading t)
8793 (setq end (save-excursion (outline-next-heading) (point)))
8794 (when (re-search-forward (if (eq what 'scheduled)
8795 org-scheduled-time-regexp
8796 org-deadline-time-regexp)
8797 end t)
8798 (setq ts (match-string 1)
8799 default-time
8800 (apply 'encode-time (org-parse-time-string ts))
8801 default-input (and ts (org-get-compact-tod ts))))))
8802 (when what
8803 ;; If necessary, get the time from the user
8804 (setq time (or time (org-read-date nil 'to-time nil nil
8805 default-time default-input))))
8807 (when (and org-insert-labeled-timestamps-at-point
8808 (member what '(scheduled deadline)))
8809 (insert
8810 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8811 (org-insert-time-stamp time org-time-was-given
8812 nil nil nil (list org-end-time-was-given))
8813 (setq what nil))
8814 (save-excursion
8815 (save-restriction
8816 (let (col list elt ts buffer-invisibility-spec)
8817 (org-back-to-heading t)
8818 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8819 (goto-char (match-end 1))
8820 (setq col (current-column))
8821 (goto-char (match-end 0))
8822 (if (eobp) (insert "\n") (forward-char 1))
8823 (if (and (not (looking-at outline-regexp))
8824 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8825 "[^\r\n]*"))
8826 (not (equal (match-string 1) org-clock-string)))
8827 (narrow-to-region (match-beginning 0) (match-end 0))
8828 (insert-before-markers "\n")
8829 (backward-char 1)
8830 (narrow-to-region (point) (point))
8831 (and org-adapt-indentation (org-indent-to-column col)))
8832 ;; Check if we have to remove something.
8833 (setq list (cons what remove))
8834 (while list
8835 (setq elt (pop list))
8836 (goto-char (point-min))
8837 (when (or (and (eq elt 'scheduled)
8838 (re-search-forward org-scheduled-time-regexp nil t))
8839 (and (eq elt 'deadline)
8840 (re-search-forward org-deadline-time-regexp nil t))
8841 (and (eq elt 'closed)
8842 (re-search-forward org-closed-time-regexp nil t)))
8843 (replace-match "")
8844 (if (looking-at "--+<[^>]+>") (replace-match ""))
8845 (if (looking-at " +") (replace-match ""))))
8846 (goto-char (point-max))
8847 (when what
8848 (insert
8849 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8850 (cond ((eq what 'scheduled) org-scheduled-string)
8851 ((eq what 'deadline) org-deadline-string)
8852 ((eq what 'closed) org-closed-string))
8853 " ")
8854 (setq ts (org-insert-time-stamp
8855 time
8856 (or org-time-was-given
8857 (and (eq what 'closed) org-log-done-with-time))
8858 (eq what 'closed)
8859 nil nil (list org-end-time-was-given)))
8860 (end-of-line 1))
8861 (goto-char (point-min))
8862 (widen)
8863 (if (and (looking-at "[ \t]+\n")
8864 (equal (char-before) ?\n))
8865 (delete-region (1- (point)) (point-at-eol)))
8866 ts)))))
8868 (defvar org-log-note-marker (make-marker))
8869 (defvar org-log-note-purpose nil)
8870 (defvar org-log-note-state nil)
8871 (defvar org-log-note-how nil)
8872 (defvar org-log-note-extra nil)
8873 (defvar org-log-note-window-configuration nil)
8874 (defvar org-log-note-return-to (make-marker))
8875 (defvar org-log-post-message nil
8876 "Message to be displayed after a log note has been stored.
8877 The auto-repeater uses this.")
8879 (defun org-add-note ()
8880 "Add a note to the current entry.
8881 This is done in the same way as adding a state change note."
8882 (interactive)
8883 (org-add-log-setup 'note nil 'findpos nil))
8885 (defvar org-property-end-re)
8886 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8887 "Set up the post command hook to take a note.
8888 If this is about to TODO state change, the new state is expected in STATE.
8889 When FINDPOS is non-nil, find the correct position for the note in
8890 the current entry. If not, assume that it can be inserted at point.
8891 HOW is an indicator what kind of note should be created.
8892 EXTRA is additional text that will be inserted into the notes buffer."
8893 (save-restriction
8894 (save-excursion
8895 (when findpos
8896 (org-back-to-heading t)
8897 (narrow-to-region (point) (save-excursion
8898 (outline-next-heading) (point)))
8899 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8900 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8901 "[^\r\n]*\\)?"))
8902 (goto-char (match-end 0))
8903 (when (and org-log-state-notes-insert-after-drawers
8904 (save-excursion
8905 (forward-line) (looking-at org-drawer-regexp)))
8906 (progn (forward-line)
8907 (while (looking-at org-drawer-regexp)
8908 (goto-char (match-end 0))
8909 (re-search-forward org-property-end-re (point-max) t)
8910 (forward-line))
8911 (forward-line -1)))
8912 (unless org-log-states-order-reversed
8913 (and (= (char-after) ?\n) (forward-char 1))
8914 (org-skip-over-state-notes)
8915 (skip-chars-backward " \t\n\r")))
8916 (move-marker org-log-note-marker (point))
8917 (setq org-log-note-purpose purpose
8918 org-log-note-state state
8919 org-log-note-how how
8920 org-log-note-extra extra)
8921 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8923 (defun org-skip-over-state-notes ()
8924 "Skip past the list of State notes in an entry."
8925 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8926 (while (looking-at "[ \t]*- State")
8927 (condition-case nil
8928 (org-next-item)
8929 (error (org-end-of-item)))))
8931 (defun org-add-log-note (&optional purpose)
8932 "Pop up a window for taking a note, and add this note later at point."
8933 (remove-hook 'post-command-hook 'org-add-log-note)
8934 (setq org-log-note-window-configuration (current-window-configuration))
8935 (delete-other-windows)
8936 (move-marker org-log-note-return-to (point))
8937 (switch-to-buffer (marker-buffer org-log-note-marker))
8938 (goto-char org-log-note-marker)
8939 (org-switch-to-buffer-other-window "*Org Note*")
8940 (erase-buffer)
8941 (if (memq org-log-note-how '(time state))
8942 (let (current-prefix-arg) (org-store-log-note))
8943 (let ((org-inhibit-startup t)) (org-mode))
8944 (insert (format "# Insert note for %s.
8945 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8946 (cond
8947 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8948 ((eq org-log-note-purpose 'done) "closed todo item")
8949 ((eq org-log-note-purpose 'state)
8950 (format "state change to \"%s\"" org-log-note-state))
8951 ((eq org-log-note-purpose 'note)
8952 "this entry")
8953 (t (error "This should not happen")))))
8954 (if org-log-note-extra (insert org-log-note-extra))
8955 (org-set-local 'org-finish-function 'org-store-log-note)))
8957 (defvar org-note-abort nil) ; dynamically scoped
8958 (defun org-store-log-note ()
8959 "Finish taking a log note, and insert it to where it belongs."
8960 (let ((txt (buffer-string))
8961 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8962 lines ind)
8963 (kill-buffer (current-buffer))
8964 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8965 (setq txt (replace-match "" t t txt)))
8966 (if (string-match "\\s-+\\'" txt)
8967 (setq txt (replace-match "" t t txt)))
8968 (setq lines (org-split-string txt "\n"))
8969 (when (and note (string-match "\\S-" note))
8970 (setq note
8971 (org-replace-escapes
8972 note
8973 (list (cons "%u" (user-login-name))
8974 (cons "%U" user-full-name)
8975 (cons "%t" (format-time-string
8976 (org-time-stamp-format 'long 'inactive)
8977 (current-time)))
8978 (cons "%s" (if org-log-note-state
8979 (concat "\"" org-log-note-state "\"")
8980 "")))))
8981 (if lines (setq note (concat note " \\\\")))
8982 (push note lines))
8983 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8984 (when lines
8985 (save-excursion
8986 (set-buffer (marker-buffer org-log-note-marker))
8987 (save-excursion
8988 (goto-char org-log-note-marker)
8989 (move-marker org-log-note-marker nil)
8990 (end-of-line 1)
8991 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8992 (indent-relative nil)
8993 (insert "- " (pop lines))
8994 (org-indent-line-function)
8995 (beginning-of-line 1)
8996 (looking-at "[ \t]*")
8997 (setq ind (concat (match-string 0) " "))
8998 (end-of-line 1)
8999 (while lines (insert "\n" ind (pop lines)))))))
9000 (set-window-configuration org-log-note-window-configuration)
9001 (with-current-buffer (marker-buffer org-log-note-return-to)
9002 (goto-char org-log-note-return-to))
9003 (move-marker org-log-note-return-to nil)
9004 (and org-log-post-message (message "%s" org-log-post-message)))
9006 (defun org-sparse-tree (&optional arg)
9007 "Create a sparse tree, prompt for the details.
9008 This command can create sparse trees. You first need to select the type
9009 of match used to create the tree:
9011 t Show entries with a specific TODO keyword.
9012 T Show entries selected by a tags match.
9013 p Enter a property name and its value (both with completion on existing
9014 names/values) and show entries with that property.
9015 r Show entries matching a regular expression
9016 d Show deadlines due within `org-deadline-warning-days'."
9017 (interactive "P")
9018 (let (ans kwd value)
9019 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9020 (setq ans (read-char-exclusive))
9021 (cond
9022 ((equal ans ?d)
9023 (call-interactively 'org-check-deadlines))
9024 ((equal ans ?b)
9025 (call-interactively 'org-check-before-date))
9026 ((equal ans ?t)
9027 (org-show-todo-tree '(4)))
9028 ((equal ans ?T)
9029 (call-interactively 'org-tags-sparse-tree))
9030 ((member ans '(?p ?P))
9031 (setq kwd (org-ido-completing-read "Property: "
9032 (mapcar 'list (org-buffer-property-keys))))
9033 (setq value (org-ido-completing-read "Value: "
9034 (mapcar 'list (org-property-values kwd))))
9035 (unless (string-match "\\`{.*}\\'" value)
9036 (setq value (concat "\"" value "\"")))
9037 (org-tags-sparse-tree arg (concat kwd "=" value)))
9038 ((member ans '(?r ?R ?/))
9039 (call-interactively 'org-occur))
9040 (t (error "No such sparse tree command \"%c\"" ans)))))
9042 (defvar org-occur-highlights nil
9043 "List of overlays used for occur matches.")
9044 (make-variable-buffer-local 'org-occur-highlights)
9045 (defvar org-occur-parameters nil
9046 "Parameters of the active org-occur calls.
9047 This is a list, each call to org-occur pushes as cons cell,
9048 containing the regular expression and the callback, onto the list.
9049 The list can contain several entries if `org-occur' has been called
9050 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9051 will only contain one set of parameters. When the highlights are
9052 removed (for example with `C-c C-c', or with the next edit (depending
9053 on `org-remove-highlights-with-change'), this variable is emptied
9054 as well.")
9055 (make-variable-buffer-local 'org-occur-parameters)
9057 (defun org-occur (regexp &optional keep-previous callback)
9058 "Make a compact tree which shows all matches of REGEXP.
9059 The tree will show the lines where the regexp matches, and all higher
9060 headlines above the match. It will also show the heading after the match,
9061 to make sure editing the matching entry is easy.
9062 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9063 call to `org-occur' will be kept, to allow stacking of calls to this
9064 command.
9065 If CALLBACK is non-nil, it is a function which is called to confirm
9066 that the match should indeed be shown."
9067 (interactive "sRegexp: \nP")
9068 (unless keep-previous
9069 (org-remove-occur-highlights nil nil t))
9070 (push (cons regexp callback) org-occur-parameters)
9071 (let ((cnt 0))
9072 (save-excursion
9073 (goto-char (point-min))
9074 (if (or (not keep-previous) ; do not want to keep
9075 (not org-occur-highlights)) ; no previous matches
9076 ;; hide everything
9077 (org-overview))
9078 (while (re-search-forward regexp nil t)
9079 (when (or (not callback)
9080 (save-match-data (funcall callback)))
9081 (setq cnt (1+ cnt))
9082 (when org-highlight-sparse-tree-matches
9083 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9084 (org-show-context 'occur-tree))))
9085 (when org-remove-highlights-with-change
9086 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9087 nil 'local))
9088 (unless org-sparse-tree-open-archived-trees
9089 (org-hide-archived-subtrees (point-min) (point-max)))
9090 (run-hooks 'org-occur-hook)
9091 (if (interactive-p)
9092 (message "%d match(es) for regexp %s" cnt regexp))
9093 cnt))
9095 (defun org-show-context (&optional key)
9096 "Make sure point and context and visible.
9097 How much context is shown depends upon the variables
9098 `org-show-hierarchy-above', `org-show-following-heading'. and
9099 `org-show-siblings'."
9100 (let ((heading-p (org-on-heading-p t))
9101 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9102 (following-p (org-get-alist-option org-show-following-heading key))
9103 (entry-p (org-get-alist-option org-show-entry-below key))
9104 (siblings-p (org-get-alist-option org-show-siblings key)))
9105 (catch 'exit
9106 ;; Show heading or entry text
9107 (if (and heading-p (not entry-p))
9108 (org-flag-heading nil) ; only show the heading
9109 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9110 (org-show-hidden-entry))) ; show entire entry
9111 (when following-p
9112 ;; Show next sibling, or heading below text
9113 (save-excursion
9114 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9115 (org-flag-heading nil))))
9116 (when siblings-p (org-show-siblings))
9117 (when hierarchy-p
9118 ;; show all higher headings, possibly with siblings
9119 (save-excursion
9120 (while (and (condition-case nil
9121 (progn (org-up-heading-all 1) t)
9122 (error nil))
9123 (not (bobp)))
9124 (org-flag-heading nil)
9125 (when siblings-p (org-show-siblings))))))))
9127 (defun org-reveal (&optional siblings)
9128 "Show current entry, hierarchy above it, and the following headline.
9129 This can be used to show a consistent set of context around locations
9130 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9131 not t for the search context.
9133 With optional argument SIBLINGS, on each level of the hierarchy all
9134 siblings are shown. This repairs the tree structure to what it would
9135 look like when opened with hierarchical calls to `org-cycle'."
9136 (interactive "P")
9137 (let ((org-show-hierarchy-above t)
9138 (org-show-following-heading t)
9139 (org-show-siblings (if siblings t org-show-siblings)))
9140 (org-show-context nil)))
9142 (defun org-highlight-new-match (beg end)
9143 "Highlight from BEG to END and mark the highlight is an occur headline."
9144 (let ((ov (org-make-overlay beg end)))
9145 (org-overlay-put ov 'face 'secondary-selection)
9146 (push ov org-occur-highlights)))
9148 (defun org-remove-occur-highlights (&optional beg end noremove)
9149 "Remove the occur highlights from the buffer.
9150 BEG and END are ignored. If NOREMOVE is nil, remove this function
9151 from the `before-change-functions' in the current buffer."
9152 (interactive)
9153 (unless org-inhibit-highlight-removal
9154 (mapc 'org-delete-overlay org-occur-highlights)
9155 (setq org-occur-highlights nil)
9156 (setq org-occur-parameters nil)
9157 (unless noremove
9158 (remove-hook 'before-change-functions
9159 'org-remove-occur-highlights 'local))))
9161 ;;;; Priorities
9163 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9164 "Regular expression matching the priority indicator.")
9166 (defvar org-remove-priority-next-time nil)
9168 (defun org-priority-up ()
9169 "Increase the priority of the current item."
9170 (interactive)
9171 (org-priority 'up))
9173 (defun org-priority-down ()
9174 "Decrease the priority of the current item."
9175 (interactive)
9176 (org-priority 'down))
9178 (defun org-priority (&optional action)
9179 "Change the priority of an item by ARG.
9180 ACTION can be `set', `up', `down', or a character."
9181 (interactive)
9182 (setq action (or action 'set))
9183 (let (current new news have remove)
9184 (save-excursion
9185 (org-back-to-heading)
9186 (if (looking-at org-priority-regexp)
9187 (setq current (string-to-char (match-string 2))
9188 have t)
9189 (setq current org-default-priority))
9190 (cond
9191 ((or (eq action 'set)
9192 (if (featurep 'xemacs) (characterp action) (integerp action)))
9193 (if (not (eq action 'set))
9194 (setq new action)
9195 (message "Priority %c-%c, SPC to remove: "
9196 org-highest-priority org-lowest-priority)
9197 (setq new (read-char-exclusive)))
9198 (if (and (= (upcase org-highest-priority) org-highest-priority)
9199 (= (upcase org-lowest-priority) org-lowest-priority))
9200 (setq new (upcase new)))
9201 (cond ((equal new ?\ ) (setq remove t))
9202 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9203 (error "Priority must be between `%c' and `%c'"
9204 org-highest-priority org-lowest-priority))))
9205 ((eq action 'up)
9206 (if (and (not have) (eq last-command this-command))
9207 (setq new org-lowest-priority)
9208 (setq new (if (and org-priority-start-cycle-with-default (not have))
9209 org-default-priority (1- current)))))
9210 ((eq action 'down)
9211 (if (and (not have) (eq last-command this-command))
9212 (setq new org-highest-priority)
9213 (setq new (if (and org-priority-start-cycle-with-default (not have))
9214 org-default-priority (1+ current)))))
9215 (t (error "Invalid action")))
9216 (if (or (< (upcase new) org-highest-priority)
9217 (> (upcase new) org-lowest-priority))
9218 (setq remove t))
9219 (setq news (format "%c" new))
9220 (if have
9221 (if remove
9222 (replace-match "" t t nil 1)
9223 (replace-match news t t nil 2))
9224 (if remove
9225 (error "No priority cookie found in line")
9226 (looking-at org-todo-line-regexp)
9227 (if (match-end 2)
9228 (progn
9229 (goto-char (match-end 2))
9230 (insert " [#" news "]"))
9231 (goto-char (match-beginning 3))
9232 (insert "[#" news "] ")))))
9233 (org-preserve-lc (org-set-tags nil 'align))
9234 (if remove
9235 (message "Priority removed")
9236 (message "Priority of current item set to %s" news))))
9239 (defun org-get-priority (s)
9240 "Find priority cookie and return priority."
9241 (save-match-data
9242 (if (not (string-match org-priority-regexp s))
9243 (* 1000 (- org-lowest-priority org-default-priority))
9244 (* 1000 (- org-lowest-priority
9245 (string-to-char (match-string 2 s)))))))
9247 ;;;; Tags
9249 (defvar org-agenda-archives-mode)
9250 (defun org-scan-tags (action matcher &optional todo-only)
9251 "Scan headline tags with inheritance and produce output ACTION.
9253 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9254 or `agenda' to produce an entry list for an agenda view. It can also be
9255 a Lisp form or a function that should be called at each matched headline, in
9256 this case the return value is a list of all return values from these calls.
9258 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9259 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9260 only lines with a TODO keyword are included in the output."
9261 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9262 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9263 (org-re
9264 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9265 (props (list 'face 'default
9266 'done-face 'org-done
9267 'undone-face 'default
9268 'mouse-face 'highlight
9269 'org-not-done-regexp org-not-done-regexp
9270 'org-todo-regexp org-todo-regexp
9271 'keymap org-agenda-keymap
9272 'help-echo
9273 (format "mouse-2 or RET jump to org file %s"
9274 (abbreviate-file-name
9275 (or (buffer-file-name (buffer-base-buffer))
9276 (buffer-name (buffer-base-buffer)))))))
9277 (case-fold-search nil)
9278 lspos tags tags-list
9279 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9280 (llast 0) rtn rtn1 level category i txt
9281 todo marker entry priority)
9282 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9283 (setq action (list 'lambda nil action)))
9284 (save-excursion
9285 (goto-char (point-min))
9286 (when (eq action 'sparse-tree)
9287 (org-overview)
9288 (org-remove-occur-highlights))
9289 (while (re-search-forward re nil t)
9290 (catch :skip
9291 (setq todo (if (match-end 1) (match-string 2))
9292 tags (if (match-end 4) (match-string 4)))
9293 (goto-char (setq lspos (1+ (match-beginning 0))))
9294 (setq level (org-reduced-level (funcall outline-level))
9295 category (org-get-category))
9296 (setq i llast llast level)
9297 ;; remove tag lists from same and sublevels
9298 (while (>= i level)
9299 (when (setq entry (assoc i tags-alist))
9300 (setq tags-alist (delete entry tags-alist)))
9301 (setq i (1- i)))
9302 ;; add the next tags
9303 (when tags
9304 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9305 tags-alist
9306 (cons (cons level tags) tags-alist)))
9307 ;; compile tags for current headline
9308 (setq tags-list
9309 (if org-use-tag-inheritance
9310 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9311 tags))
9312 (when org-use-tag-inheritance
9313 (setcdr (car tags-alist)
9314 (mapcar (lambda (x)
9315 (setq x (copy-sequence x))
9316 (org-add-prop-inherited x))
9317 (cdar tags-alist))))
9318 (when (and tags org-use-tag-inheritance
9319 (not (eq t org-use-tag-inheritance)))
9320 ;; selective inheritance, remove uninherited ones
9321 (setcdr (car tags-alist)
9322 (org-remove-uniherited-tags (cdar tags-alist))))
9323 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9324 (let ((case-fold-search t)) (eval matcher))
9326 (not (member org-archive-tag tags-list))
9327 ;; we have an archive tag, should we use this anyway?
9328 (or (not org-agenda-skip-archived-trees)
9329 (and (eq action 'agenda) org-agenda-archives-mode))))
9330 (unless (eq action 'sparse-tree) (org-agenda-skip))
9332 ;; select this headline
9334 (cond
9335 ((eq action 'sparse-tree)
9336 (and org-highlight-sparse-tree-matches
9337 (org-get-heading) (match-end 0)
9338 (org-highlight-new-match
9339 (match-beginning 0) (match-beginning 1)))
9340 (org-show-context 'tags-tree))
9341 ((eq action 'agenda)
9342 (setq txt (org-format-agenda-item
9344 (concat
9345 (if org-tags-match-list-sublevels
9346 (make-string (1- level) ?.) "")
9347 (org-get-heading))
9348 category (org-get-tags-at))
9349 priority (org-get-priority txt))
9350 (goto-char lspos)
9351 (setq marker (org-agenda-new-marker))
9352 (org-add-props txt props
9353 'org-marker marker 'org-hd-marker marker 'org-category category
9354 'priority priority 'type "tagsmatch")
9355 (push txt rtn))
9356 ((functionp action)
9357 (save-excursion
9358 (setq rtn1 (funcall action))
9359 (push rtn1 rtn))
9360 (goto-char (point-at-eol)))
9361 (t (error "Invalid action")))
9363 ;; if we are to skip sublevels, jump to end of subtree
9364 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9365 (when (and (eq action 'sparse-tree)
9366 (not org-sparse-tree-open-archived-trees))
9367 (org-hide-archived-subtrees (point-min) (point-max)))
9368 (nreverse rtn)))
9370 (defun org-remove-uniherited-tags (tags)
9371 "Remove all tags that are not inherited from the list TAGS."
9372 (cond
9373 ((eq org-use-tag-inheritance t)
9374 (if org-tags-exclude-from-inheritance
9375 (org-delete-all org-tags-exclude-from-inheritance tags)
9376 tags))
9377 ((not org-use-tag-inheritance) nil)
9378 ((stringp org-use-tag-inheritance)
9379 (delq nil (mapcar
9380 (lambda (x)
9381 (if (and (string-match org-use-tag-inheritance x)
9382 (not (member x org-tags-exclude-from-inheritance)))
9383 x nil))
9384 tags)))
9385 ((listp org-use-tag-inheritance)
9386 (delq nil (mapcar
9387 (lambda (x)
9388 (if (member x org-use-tag-inheritance) x nil))
9389 tags)))))
9391 (defvar todo-only) ;; dynamically scoped
9393 (defun org-tags-sparse-tree (&optional todo-only match)
9394 "Create a sparse tree according to tags string MATCH.
9395 MATCH can contain positive and negative selection of tags, like
9396 \"+WORK+URGENT-WITHBOSS\".
9397 If optional argument TODO-ONLY is non-nil, only select lines that are
9398 also TODO lines."
9399 (interactive "P")
9400 (org-prepare-agenda-buffers (list (current-buffer)))
9401 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9403 (defvar org-cached-props nil)
9404 (defun org-cached-entry-get (pom property)
9405 (if (or (eq t org-use-property-inheritance)
9406 (and (stringp org-use-property-inheritance)
9407 (string-match org-use-property-inheritance property))
9408 (and (listp org-use-property-inheritance)
9409 (member property org-use-property-inheritance)))
9410 ;; Caching is not possible, check it directly
9411 (org-entry-get pom property 'inherit)
9412 ;; Get all properties, so that we can do complicated checks easily
9413 (cdr (assoc property (or org-cached-props
9414 (setq org-cached-props
9415 (org-entry-properties pom)))))))
9417 (defun org-global-tags-completion-table (&optional files)
9418 "Return the list of all tags in all agenda buffer/files."
9419 (save-excursion
9420 (org-uniquify
9421 (delq nil
9422 (apply 'append
9423 (mapcar
9424 (lambda (file)
9425 (set-buffer (find-file-noselect file))
9426 (append (org-get-buffer-tags)
9427 (mapcar (lambda (x) (if (stringp (car-safe x))
9428 (list (car-safe x)) nil))
9429 org-tag-alist)))
9430 (if (and files (car files))
9431 files
9432 (org-agenda-files))))))))
9434 (defun org-make-tags-matcher (match)
9435 "Create the TAGS//TODO matcher form for the selection string MATCH."
9436 ;; todo-only is scoped dynamically into this function, and the function
9437 ;; may change it if the matcher asks for it.
9438 (unless match
9439 ;; Get a new match request, with completion
9440 (let ((org-last-tags-completion-table
9441 (org-global-tags-completion-table)))
9442 (setq match (org-ido-completing-read
9443 "Match: " 'org-tags-completion-function nil nil nil
9444 'org-tags-history))))
9446 ;; Parse the string and create a lisp form
9447 (let ((match0 match)
9448 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9449 minus tag mm
9450 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9451 orterms term orlist re-p str-p level-p level-op time-p
9452 prop-p pn pv po cat-p gv rest)
9453 (if (string-match "/+" match)
9454 ;; match contains also a todo-matching request
9455 (progn
9456 (setq tagsmatch (substring match 0 (match-beginning 0))
9457 todomatch (substring match (match-end 0)))
9458 (if (string-match "^!" todomatch)
9459 (setq todo-only t todomatch (substring todomatch 1)))
9460 (if (string-match "^\\s-*$" todomatch)
9461 (setq todomatch nil)))
9462 ;; only matching tags
9463 (setq tagsmatch match todomatch nil))
9465 ;; Make the tags matcher
9466 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9467 (setq tagsmatcher t)
9468 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9469 (while (setq term (pop orterms))
9470 (while (and (equal (substring term -1) "\\") orterms)
9471 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9472 (while (string-match re term)
9473 (setq rest (substring term (match-end 0))
9474 minus (and (match-end 1)
9475 (equal (match-string 1 term) "-"))
9476 tag (match-string 2 term)
9477 re-p (equal (string-to-char tag) ?{)
9478 level-p (match-end 4)
9479 prop-p (match-end 5)
9480 mm (cond
9481 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9482 (level-p
9483 (setq level-op (org-op-to-function (match-string 3 term)))
9484 `(,level-op level ,(string-to-number
9485 (match-string 4 term))))
9486 (prop-p
9487 (setq pn (match-string 5 term)
9488 po (match-string 6 term)
9489 pv (match-string 7 term)
9490 cat-p (equal pn "CATEGORY")
9491 re-p (equal (string-to-char pv) ?{)
9492 str-p (equal (string-to-char pv) ?\")
9493 time-p (save-match-data
9494 (string-match "^\"[[<].*[]>]\"$" pv))
9495 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9496 (if time-p (setq pv (org-matcher-time pv)))
9497 (setq po (org-op-to-function po (if time-p 'time str-p)))
9498 (cond
9499 ((equal pn "CATEGORY")
9500 (setq gv '(get-text-property (point) 'org-category)))
9501 ((equal pn "TODO")
9502 (setq gv 'todo))
9504 (setq gv `(org-cached-entry-get nil ,pn))))
9505 (if re-p
9506 (if (eq po 'org<>)
9507 `(not (string-match ,pv (or ,gv "")))
9508 `(string-match ,pv (or ,gv "")))
9509 (if str-p
9510 `(,po (or ,gv "") ,pv)
9511 `(,po (string-to-number (or ,gv ""))
9512 ,(string-to-number pv) ))))
9513 (t `(member ,(downcase tag) tags-list)))
9514 mm (if minus (list 'not mm) mm)
9515 term rest)
9516 (push mm tagsmatcher))
9517 (push (if (> (length tagsmatcher) 1)
9518 (cons 'and tagsmatcher)
9519 (car tagsmatcher))
9520 orlist)
9521 (setq tagsmatcher nil))
9522 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9523 (setq tagsmatcher
9524 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9525 ;; Make the todo matcher
9526 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9527 (setq todomatcher t)
9528 (setq orterms (org-split-string todomatch "|") orlist nil)
9529 (while (setq term (pop orterms))
9530 (while (string-match re term)
9531 (setq minus (and (match-end 1)
9532 (equal (match-string 1 term) "-"))
9533 kwd (match-string 2 term)
9534 re-p (equal (string-to-char kwd) ?{)
9535 term (substring term (match-end 0))
9536 mm (if re-p
9537 `(string-match ,(substring kwd 1 -1) todo)
9538 (list 'equal 'todo kwd))
9539 mm (if minus (list 'not mm) mm))
9540 (push mm todomatcher))
9541 (push (if (> (length todomatcher) 1)
9542 (cons 'and todomatcher)
9543 (car todomatcher))
9544 orlist)
9545 (setq todomatcher nil))
9546 (setq todomatcher (if (> (length orlist) 1)
9547 (cons 'or orlist) (car orlist))))
9549 ;; Return the string and lisp forms of the matcher
9550 (setq matcher (if todomatcher
9551 (list 'and tagsmatcher todomatcher)
9552 tagsmatcher))
9553 (cons match0 matcher)))
9555 (defun org-op-to-function (op &optional stringp)
9556 "Turn an operator into the appropriate function."
9557 (setq op
9558 (cond
9559 ((equal op "<" ) '(< string< org-time<))
9560 ((equal op ">" ) '(> org-string> org-time>))
9561 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9562 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9563 ((member op '("=" "==")) '(= string= org-time=))
9564 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9565 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9567 (defun org<> (a b) (not (= a b)))
9568 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9569 (defun org-string>= (a b) (not (string< a b)))
9570 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9571 (defun org-string<> (a b) (not (string= a b)))
9572 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9573 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9574 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9575 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9576 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9577 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9578 (defun org-2ft (s)
9579 "Convert S to a floating point time.
9580 If S is already a number, just return it. If it is a string, parse
9581 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9582 (cond
9583 ((numberp s) s)
9584 ((stringp s)
9585 (condition-case nil
9586 (float-time (apply 'encode-time (org-parse-time-string s)))
9587 (error 0.)))
9588 (t 0.)))
9590 (defun org-time-today ()
9591 "Time in seconds today at 0:00.
9592 Returns the float number of seconds since the beginning of the
9593 epoch to the beginning of today (00:00)."
9594 (float-time (apply 'encode-time
9595 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9597 (defun org-matcher-time (s)
9598 "Interpret a time comparison value."
9599 (save-match-data
9600 (cond
9601 ((string= s "<now>") (float-time))
9602 ((string= s "<today>") (org-time-today))
9603 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9604 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9605 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9606 (+ (org-time-today)
9607 (* (string-to-number (match-string 1 s))
9608 (cdr (assoc (match-string 2 s)
9609 '(("d" . 86400.0) ("w" . 604800.0)
9610 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9611 (t (org-2ft s)))))
9613 (defun org-match-any-p (re list)
9614 "Does re match any element of list?"
9615 (setq list (mapcar (lambda (x) (string-match re x)) list))
9616 (delq nil list))
9618 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9619 (defvar org-tags-overlay (org-make-overlay 1 1))
9620 (org-detach-overlay org-tags-overlay)
9622 (defun org-get-local-tags-at (&optional pos)
9623 "Get a list of tags defined in the current headline."
9624 (org-get-tags-at pos 'local))
9626 (defun org-get-local-tags ()
9627 "Get a list of tags defined in the current headline."
9628 (org-get-tags-at nil 'local))
9630 (defun org-get-tags-at (&optional pos local)
9631 "Get a list of all headline tags applicable at POS.
9632 POS defaults to point. If tags are inherited, the list contains
9633 the targets in the same sequence as the headlines appear, i.e.
9634 the tags of the current headline come last.
9635 When LOCAL is non-nil, only return tags from the current headline,
9636 ignore inherited ones."
9637 (interactive)
9638 (let (tags ltags lastpos parent)
9639 (save-excursion
9640 (save-restriction
9641 (widen)
9642 (goto-char (or pos (point)))
9643 (save-match-data
9644 (catch 'done
9645 (condition-case nil
9646 (progn
9647 (org-back-to-heading t)
9648 (while (not (equal lastpos (point)))
9649 (setq lastpos (point))
9650 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9651 (setq ltags (org-split-string
9652 (org-match-string-no-properties 1) ":"))
9653 (when parent
9654 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9655 (setq tags (append
9656 (if parent
9657 (org-remove-uniherited-tags ltags)
9658 ltags)
9659 tags)))
9660 (or org-use-tag-inheritance (throw 'done t))
9661 (if local (throw 'done t))
9662 (org-up-heading-all 1)
9663 (setq parent t)))
9664 (error nil)))))
9665 (append (org-remove-uniherited-tags org-file-tags) tags))))
9667 (defun org-add-prop-inherited (s)
9668 (add-text-properties 0 (length s) '(inherited t) s)
9671 (defun org-toggle-tag (tag &optional onoff)
9672 "Toggle the tag TAG for the current line.
9673 If ONOFF is `on' or `off', don't toggle but set to this state."
9674 (let (res current)
9675 (save-excursion
9676 (org-back-to-heading t)
9677 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9678 (point-at-eol) t)
9679 (progn
9680 (setq current (match-string 1))
9681 (replace-match ""))
9682 (setq current ""))
9683 (setq current (nreverse (org-split-string current ":")))
9684 (cond
9685 ((eq onoff 'on)
9686 (setq res t)
9687 (or (member tag current) (push tag current)))
9688 ((eq onoff 'off)
9689 (or (not (member tag current)) (setq current (delete tag current))))
9690 (t (if (member tag current)
9691 (setq current (delete tag current))
9692 (setq res t)
9693 (push tag current))))
9694 (end-of-line 1)
9695 (if current
9696 (progn
9697 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9698 (org-set-tags nil t))
9699 (delete-horizontal-space))
9700 (run-hooks 'org-after-tags-change-hook))
9701 res))
9703 (defun org-align-tags-here (to-col)
9704 ;; Assumes that this is a headline
9705 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9706 (beginning-of-line 1)
9707 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9708 (< pos (match-beginning 2)))
9709 (progn
9710 (setq tags-l (- (match-end 2) (match-beginning 2)))
9711 (goto-char (match-beginning 1))
9712 (insert " ")
9713 (delete-region (point) (1+ (match-beginning 2)))
9714 (setq ncol (max (1+ (current-column))
9715 (1+ col)
9716 (if (> to-col 0)
9717 to-col
9718 (- (abs to-col) tags-l))))
9719 (setq p (point))
9720 (insert (make-string (- ncol (current-column)) ?\ ))
9721 (setq ncol (current-column))
9722 (when indent-tabs-mode (tabify p (point-at-eol)))
9723 (org-move-to-column (min ncol col) t))
9724 (goto-char pos))))
9726 (defun org-set-tags-command (&optional arg just-align)
9727 "Call the set-tags command for the current entry."
9728 (interactive "P")
9729 (if (org-on-heading-p)
9730 (org-set-tags arg just-align)
9731 (save-excursion
9732 (org-back-to-heading t)
9733 (org-set-tags arg just-align))))
9735 (defun org-set-tags (&optional arg just-align)
9736 "Set the tags for the current headline.
9737 With prefix ARG, realign all tags in headings in the current buffer."
9738 (interactive "P")
9739 (let* ((re (concat "^" outline-regexp))
9740 (current (org-get-tags-string))
9741 (col (current-column))
9742 (org-setting-tags t)
9743 table current-tags inherited-tags ; computed below when needed
9744 tags p0 c0 c1 rpl)
9745 (if arg
9746 (save-excursion
9747 (goto-char (point-min))
9748 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9749 (while (re-search-forward re nil t)
9750 (org-set-tags nil t)
9751 (end-of-line 1)))
9752 (message "All tags realigned to column %d" org-tags-column))
9753 (if just-align
9754 (setq tags current)
9755 ;; Get a new set of tags from the user
9756 (save-excursion
9757 (setq table (or org-tag-alist (org-get-buffer-tags))
9758 org-last-tags-completion-table table
9759 current-tags (org-split-string current ":")
9760 inherited-tags (nreverse
9761 (nthcdr (length current-tags)
9762 (nreverse (org-get-tags-at))))
9763 tags
9764 (if (or (eq t org-use-fast-tag-selection)
9765 (and org-use-fast-tag-selection
9766 (delq nil (mapcar 'cdr table))))
9767 (org-fast-tag-selection
9768 current-tags inherited-tags table
9769 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9770 (let ((org-add-colon-after-tag-completion t))
9771 (org-trim
9772 (org-without-partial-completion
9773 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9774 nil nil current 'org-tags-history)))))))
9775 (while (string-match "[-+&]+" tags)
9776 ;; No boolean logic, just a list
9777 (setq tags (replace-match ":" t t tags))))
9779 (if (string-match "\\`[\t ]*\\'" tags)
9780 (setq tags "")
9781 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9782 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9784 ;; Insert new tags at the correct column
9785 (beginning-of-line 1)
9786 (cond
9787 ((and (equal current "") (equal tags "")))
9788 ((re-search-forward
9789 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9790 (point-at-eol) t)
9791 (if (equal tags "")
9792 (setq rpl "")
9793 (goto-char (match-beginning 0))
9794 (setq c0 (current-column) p0 (point)
9795 c1 (max (1+ c0) (if (> org-tags-column 0)
9796 org-tags-column
9797 (- (- org-tags-column) (length tags))))
9798 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9799 (replace-match rpl t t)
9800 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9801 tags)
9802 (t (error "Tags alignment failed")))
9803 (org-move-to-column col)
9804 (unless just-align
9805 (run-hooks 'org-after-tags-change-hook)))))
9807 (defun org-change-tag-in-region (beg end tag off)
9808 "Add or remove TAG for each entry in the region.
9809 This works in the agenda, and also in an org-mode buffer."
9810 (interactive
9811 (list (region-beginning) (region-end)
9812 (let ((org-last-tags-completion-table
9813 (if (org-mode-p)
9814 (org-get-buffer-tags)
9815 (org-global-tags-completion-table))))
9816 (org-ido-completing-read
9817 "Tag: " 'org-tags-completion-function nil nil nil
9818 'org-tags-history))
9819 (progn
9820 (message "[s]et or [r]emove? ")
9821 (equal (read-char-exclusive) ?r))))
9822 (if (fboundp 'deactivate-mark) (deactivate-mark))
9823 (let ((agendap (equal major-mode 'org-agenda-mode))
9824 l1 l2 m buf pos newhead (cnt 0))
9825 (goto-char end)
9826 (setq l2 (1- (org-current-line)))
9827 (goto-char beg)
9828 (setq l1 (org-current-line))
9829 (loop for l from l1 to l2 do
9830 (goto-line l)
9831 (setq m (get-text-property (point) 'org-hd-marker))
9832 (when (or (and (org-mode-p) (org-on-heading-p))
9833 (and agendap m))
9834 (setq buf (if agendap (marker-buffer m) (current-buffer))
9835 pos (if agendap m (point)))
9836 (with-current-buffer buf
9837 (save-excursion
9838 (save-restriction
9839 (goto-char pos)
9840 (setq cnt (1+ cnt))
9841 (org-toggle-tag tag (if off 'off 'on))
9842 (setq newhead (org-get-heading)))))
9843 (and agendap (org-agenda-change-all-lines newhead m))))
9844 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9846 (defun org-tags-completion-function (string predicate &optional flag)
9847 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9848 (confirm (lambda (x) (stringp (car x)))))
9849 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9850 (setq s1 (match-string 1 string)
9851 s2 (match-string 2 string))
9852 (setq s1 "" s2 string))
9853 (cond
9854 ((eq flag nil)
9855 ;; try completion
9856 (setq rtn (try-completion s2 ctable confirm))
9857 (if (stringp rtn)
9858 (setq rtn
9859 (concat s1 s2 (substring rtn (length s2))
9860 (if (and org-add-colon-after-tag-completion
9861 (assoc rtn ctable))
9862 ":" ""))))
9863 rtn)
9864 ((eq flag t)
9865 ;; all-completions
9866 (all-completions s2 ctable confirm)
9868 ((eq flag 'lambda)
9869 ;; exact match?
9870 (assoc s2 ctable)))
9873 (defun org-fast-tag-insert (kwd tags face &optional end)
9874 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9875 (insert (format "%-12s" (concat kwd ":"))
9876 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9877 (or end "")))
9879 (defun org-fast-tag-show-exit (flag)
9880 (save-excursion
9881 (goto-line 3)
9882 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9883 (replace-match ""))
9884 (when flag
9885 (end-of-line 1)
9886 (org-move-to-column (- (window-width) 19) t)
9887 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9889 (defun org-set-current-tags-overlay (current prefix)
9890 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9891 (if (featurep 'xemacs)
9892 (org-overlay-display org-tags-overlay (concat prefix s)
9893 'secondary-selection)
9894 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9895 (org-overlay-display org-tags-overlay (concat prefix s)))))
9897 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9898 "Fast tag selection with single keys.
9899 CURRENT is the current list of tags in the headline, INHERITED is the
9900 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9901 possibly with grouping information. TODO-TABLE is a similar table with
9902 TODO keywords, should these have keys assigned to them.
9903 If the keys are nil, a-z are automatically assigned.
9904 Returns the new tags string, or nil to not change the current settings."
9905 (let* ((fulltable (append table todo-table))
9906 (maxlen (apply 'max (mapcar
9907 (lambda (x)
9908 (if (stringp (car x)) (string-width (car x)) 0))
9909 fulltable)))
9910 (buf (current-buffer))
9911 (expert (eq org-fast-tag-selection-single-key 'expert))
9912 (buffer-tags nil)
9913 (fwidth (+ maxlen 3 1 3))
9914 (ncol (/ (- (window-width) 4) fwidth))
9915 (i-face 'org-done)
9916 (c-face 'org-todo)
9917 tg cnt e c char c1 c2 ntable tbl rtn
9918 ov-start ov-end ov-prefix
9919 (exit-after-next org-fast-tag-selection-single-key)
9920 (done-keywords org-done-keywords)
9921 groups ingroup)
9922 (save-excursion
9923 (beginning-of-line 1)
9924 (if (looking-at
9925 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9926 (setq ov-start (match-beginning 1)
9927 ov-end (match-end 1)
9928 ov-prefix "")
9929 (setq ov-start (1- (point-at-eol))
9930 ov-end (1+ ov-start))
9931 (skip-chars-forward "^\n\r")
9932 (setq ov-prefix
9933 (concat
9934 (buffer-substring (1- (point)) (point))
9935 (if (> (current-column) org-tags-column)
9937 (make-string (- org-tags-column (current-column)) ?\ ))))))
9938 (org-move-overlay org-tags-overlay ov-start ov-end)
9939 (save-window-excursion
9940 (if expert
9941 (set-buffer (get-buffer-create " *Org tags*"))
9942 (delete-other-windows)
9943 (split-window-vertically)
9944 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9945 (erase-buffer)
9946 (org-set-local 'org-done-keywords done-keywords)
9947 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9948 (org-fast-tag-insert "Current" current c-face "\n\n")
9949 (org-fast-tag-show-exit exit-after-next)
9950 (org-set-current-tags-overlay current ov-prefix)
9951 (setq tbl fulltable char ?a cnt 0)
9952 (while (setq e (pop tbl))
9953 (cond
9954 ((equal e '(:startgroup))
9955 (push '() groups) (setq ingroup t)
9956 (when (not (= cnt 0))
9957 (setq cnt 0)
9958 (insert "\n"))
9959 (insert "{ "))
9960 ((equal e '(:endgroup))
9961 (setq ingroup nil cnt 0)
9962 (insert "}\n"))
9964 (setq tg (car e) c2 nil)
9965 (if (cdr e)
9966 (setq c (cdr e))
9967 ;; automatically assign a character.
9968 (setq c1 (string-to-char
9969 (downcase (substring
9970 tg (if (= (string-to-char tg) ?@) 1 0)))))
9971 (if (or (rassoc c1 ntable) (rassoc c1 table))
9972 (while (or (rassoc char ntable) (rassoc char table))
9973 (setq char (1+ char)))
9974 (setq c2 c1))
9975 (setq c (or c2 char)))
9976 (if ingroup (push tg (car groups)))
9977 (setq tg (org-add-props tg nil 'face
9978 (cond
9979 ((not (assoc tg table))
9980 (org-get-todo-face tg))
9981 ((member tg current) c-face)
9982 ((member tg inherited) i-face)
9983 (t nil))))
9984 (if (and (= cnt 0) (not ingroup)) (insert " "))
9985 (insert "[" c "] " tg (make-string
9986 (- fwidth 4 (length tg)) ?\ ))
9987 (push (cons tg c) ntable)
9988 (when (= (setq cnt (1+ cnt)) ncol)
9989 (insert "\n")
9990 (if ingroup (insert " "))
9991 (setq cnt 0)))))
9992 (setq ntable (nreverse ntable))
9993 (insert "\n")
9994 (goto-char (point-min))
9995 (if (not expert) (org-fit-window-to-buffer))
9996 (setq rtn
9997 (catch 'exit
9998 (while t
9999 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10000 (if groups " [!] no groups" " [!]groups")
10001 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10002 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10003 (cond
10004 ((= c ?\r) (throw 'exit t))
10005 ((= c ?!)
10006 (setq groups (not groups))
10007 (goto-char (point-min))
10008 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10009 ((= c ?\C-c)
10010 (if (not expert)
10011 (org-fast-tag-show-exit
10012 (setq exit-after-next (not exit-after-next)))
10013 (setq expert nil)
10014 (delete-other-windows)
10015 (split-window-vertically)
10016 (org-switch-to-buffer-other-window " *Org tags*")
10017 (org-fit-window-to-buffer)))
10018 ((or (= c ?\C-g)
10019 (and (= c ?q) (not (rassoc c ntable))))
10020 (org-detach-overlay org-tags-overlay)
10021 (setq quit-flag t))
10022 ((= c ?\ )
10023 (setq current nil)
10024 (if exit-after-next (setq exit-after-next 'now)))
10025 ((= c ?\t)
10026 (condition-case nil
10027 (setq tg (org-ido-completing-read
10028 "Tag: "
10029 (or buffer-tags
10030 (with-current-buffer buf
10031 (org-get-buffer-tags)))))
10032 (quit (setq tg "")))
10033 (when (string-match "\\S-" tg)
10034 (add-to-list 'buffer-tags (list tg))
10035 (if (member tg current)
10036 (setq current (delete tg current))
10037 (push tg current)))
10038 (if exit-after-next (setq exit-after-next 'now)))
10039 ((setq e (rassoc c todo-table) tg (car e))
10040 (with-current-buffer buf
10041 (save-excursion (org-todo tg)))
10042 (if exit-after-next (setq exit-after-next 'now)))
10043 ((setq e (rassoc c ntable) tg (car e))
10044 (if (member tg current)
10045 (setq current (delete tg current))
10046 (loop for g in groups do
10047 (if (member tg g)
10048 (mapc (lambda (x)
10049 (setq current (delete x current)))
10050 g)))
10051 (push tg current))
10052 (if exit-after-next (setq exit-after-next 'now))))
10054 ;; Create a sorted list
10055 (setq current
10056 (sort current
10057 (lambda (a b)
10058 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10059 (if (eq exit-after-next 'now) (throw 'exit t))
10060 (goto-char (point-min))
10061 (beginning-of-line 2)
10062 (delete-region (point) (point-at-eol))
10063 (org-fast-tag-insert "Current" current c-face)
10064 (org-set-current-tags-overlay current ov-prefix)
10065 (while (re-search-forward
10066 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10067 (setq tg (match-string 1))
10068 (add-text-properties
10069 (match-beginning 1) (match-end 1)
10070 (list 'face
10071 (cond
10072 ((member tg current) c-face)
10073 ((member tg inherited) i-face)
10074 (t (get-text-property (match-beginning 1) 'face))))))
10075 (goto-char (point-min)))))
10076 (org-detach-overlay org-tags-overlay)
10077 (if rtn
10078 (mapconcat 'identity current ":")
10079 nil))))
10081 (defun org-get-tags-string ()
10082 "Get the TAGS string in the current headline."
10083 (unless (org-on-heading-p t)
10084 (error "Not on a heading"))
10085 (save-excursion
10086 (beginning-of-line 1)
10087 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10088 (org-match-string-no-properties 1)
10089 "")))
10091 (defun org-get-tags ()
10092 "Get the list of tags specified in the current headline."
10093 (org-split-string (org-get-tags-string) ":"))
10095 (defun org-get-buffer-tags ()
10096 "Get a table of all tags used in the buffer, for completion."
10097 (let (tags)
10098 (save-excursion
10099 (goto-char (point-min))
10100 (while (re-search-forward
10101 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10102 (when (equal (char-after (point-at-bol 0)) ?*)
10103 (mapc (lambda (x) (add-to-list 'tags x))
10104 (org-split-string (org-match-string-no-properties 1) ":")))))
10105 (mapcar 'list tags)))
10107 ;;;; The mapping API
10109 ;;;###autoload
10110 (defun org-map-entries (func &optional match scope &rest skip)
10111 "Call FUNC at each headline selected by MATCH in SCOPE.
10113 FUNC is a function or a lisp form. The function will be called without
10114 arguments, with the cursor positioned at the beginning of the headline.
10115 The return values of all calls to the function will be collected and
10116 returned as a list.
10118 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10119 Only headlines that are matched by this query will be considered during
10120 the iteration. When MATCH is nil or t, all headlines will be
10121 visited by the iteration.
10123 SCOPE determines the scope of this command. It can be any of:
10125 nil The current buffer, respecting the restriction if any
10126 tree The subtree started with the entry at point
10127 file The current buffer, without restriction
10128 file-with-archives
10129 The current buffer, and any archives associated with it
10130 agenda All agenda files
10131 agenda-with-archives
10132 All agenda files with any archive files associated with them
10133 \(file1 file2 ...)
10134 If this is a list, all files in the list will be scanned
10136 The remaining args are treated as settings for the skipping facilities of
10137 the scanner. The following items can be given here:
10139 archive skip trees with the archive tag.
10140 comment skip trees with the COMMENT keyword
10141 function or Emacs Lisp form:
10142 will be used as value for `org-agenda-skip-function', so whenever
10143 the the function returns t, FUNC will not be called for that
10144 entry and search will continue from the point where the
10145 function leaves it."
10146 (let* ((org-agenda-archives-mode nil) ; just to make sure
10147 (org-agenda-skip-archived-trees (memq 'archive skip))
10148 (org-agenda-skip-comment-trees (memq 'comment skip))
10149 (org-agenda-skip-function
10150 (car (org-delete-all '(comment archive) skip)))
10151 (org-tags-match-list-sublevels t)
10152 matcher pos file res
10153 org-todo-keywords-for-agenda
10154 org-done-keywords-for-agenda
10155 org-todo-keyword-alist-for-agenda
10156 org-tag-alist-for-agenda)
10158 (cond
10159 ((eq match t) (setq matcher t))
10160 ((eq match nil) (setq matcher t))
10161 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10163 (when (eq scope 'tree)
10164 (org-back-to-heading t)
10165 (org-narrow-to-subtree)
10166 (setq scope nil))
10168 (if (not scope)
10169 (progn
10170 (org-prepare-agenda-buffers
10171 (list (buffer-file-name (current-buffer))))
10172 (org-scan-tags func matcher))
10173 ;; Get the right scope
10174 (setq pos (point))
10175 (cond
10176 ((and scope (listp scope) (symbolp (car scope)))
10177 (setq scope (eval scope)))
10178 ((eq scope 'agenda)
10179 (setq scope (org-agenda-files t)))
10180 ((eq scope 'agenda-with-archives)
10181 (setq scope (org-agenda-files t))
10182 (setq scope (org-add-archive-files scope)))
10183 ((eq scope 'file)
10184 (setq scope (list (buffer-file-name))))
10185 ((eq scope 'file-with-archives)
10186 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10187 (org-prepare-agenda-buffers scope)
10188 (while (setq file (pop scope))
10189 (with-current-buffer (org-find-base-buffer-visiting file)
10190 (save-excursion
10191 (save-restriction
10192 (widen)
10193 (goto-char (point-min))
10194 (setq res (append res (org-scan-tags func matcher)))))))
10195 res)))
10197 ;;;; Properties
10199 ;;; Setting and retrieving properties
10201 (defconst org-special-properties
10202 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10203 "TIMESTAMP" "TIMESTAMP_IA")
10204 "The special properties valid in Org-mode.
10206 These are properties that are not defined in the property drawer,
10207 but in some other way.")
10209 (defconst org-default-properties
10210 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10211 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10212 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10213 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10214 "Some properties that are used by Org-mode for various purposes.
10215 Being in this list makes sure that they are offered for completion.")
10217 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10218 "Regular expression matching the first line of a property drawer.")
10220 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10221 "Regular expression matching the first line of a property drawer.")
10223 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10224 "Regular expression matching the first line of a property drawer.")
10226 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10227 "Regular expression matching the first line of a property drawer.")
10229 (defconst org-property-drawer-re
10230 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10231 org-property-end-re "\\)\n?")
10232 "Matches an entire property drawer.")
10234 (defconst org-clock-drawer-re
10235 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10236 org-property-end-re "\\)\n?")
10237 "Matches an entire clock drawer.")
10239 (defun org-property-action ()
10240 "Do an action on properties."
10241 (interactive)
10242 (let (c)
10243 (org-at-property-p)
10244 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10245 (setq c (read-char-exclusive))
10246 (cond
10247 ((equal c ?s)
10248 (call-interactively 'org-set-property))
10249 ((equal c ?d)
10250 (call-interactively 'org-delete-property))
10251 ((equal c ?D)
10252 (call-interactively 'org-delete-property-globally))
10253 ((equal c ?c)
10254 (call-interactively 'org-compute-property-at-point))
10255 (t (error "No such property action %c" c)))))
10257 (defun org-at-property-p ()
10258 "Is the cursor in a property line?"
10259 ;; FIXME: Does not check if we are actually in the drawer.
10260 ;; FIXME: also returns true on any drawers.....
10261 ;; This is used by C-c C-c for property action.
10262 (save-excursion
10263 (beginning-of-line 1)
10264 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10266 (defun org-get-property-block (&optional beg end force)
10267 "Return the (beg . end) range of the body of the property drawer.
10268 BEG and END can be beginning and end of subtree, if not given
10269 they will be found.
10270 If the drawer does not exist and FORCE is non-nil, create the drawer."
10271 (catch 'exit
10272 (save-excursion
10273 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10274 (end (or end (progn (outline-next-heading) (point)))))
10275 (goto-char beg)
10276 (if (re-search-forward org-property-start-re end t)
10277 (setq beg (1+ (match-end 0)))
10278 (if force
10279 (save-excursion
10280 (org-insert-property-drawer)
10281 (setq end (progn (outline-next-heading) (point))))
10282 (throw 'exit nil))
10283 (goto-char beg)
10284 (if (re-search-forward org-property-start-re end t)
10285 (setq beg (1+ (match-end 0)))))
10286 (if (re-search-forward org-property-end-re end t)
10287 (setq end (match-beginning 0))
10288 (or force (throw 'exit nil))
10289 (goto-char beg)
10290 (setq end beg)
10291 (org-indent-line-function)
10292 (insert ":END:\n"))
10293 (cons beg end)))))
10295 (defun org-entry-properties (&optional pom which)
10296 "Get all properties of the entry at point-or-marker POM.
10297 This includes the TODO keyword, the tags, time strings for deadline,
10298 scheduled, and clocking, and any additional properties defined in the
10299 entry. The return value is an alist, keys may occur multiple times
10300 if the property key was used several times.
10301 POM may also be nil, in which case the current entry is used.
10302 If WHICH is nil or `all', get all properties. If WHICH is
10303 `special' or `standard', only get that subclass."
10304 (setq which (or which 'all))
10305 (org-with-point-at pom
10306 (let ((clockstr (substring org-clock-string 0 -1))
10307 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10308 beg end range props sum-props key value string clocksum)
10309 (save-excursion
10310 (when (condition-case nil
10311 (and (org-mode-p) (org-back-to-heading t))
10312 (error nil))
10313 (setq beg (point))
10314 (setq sum-props (get-text-property (point) 'org-summaries))
10315 (setq clocksum (get-text-property (point) :org-clock-minutes))
10316 (outline-next-heading)
10317 (setq end (point))
10318 (when (memq which '(all special))
10319 ;; Get the special properties, like TODO and tags
10320 (goto-char beg)
10321 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10322 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10323 (when (looking-at org-priority-regexp)
10324 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10325 (when (and (setq value (org-get-tags-string))
10326 (string-match "\\S-" value))
10327 (push (cons "TAGS" value) props))
10328 (when (setq value (org-get-tags-at))
10329 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10330 props))
10331 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10332 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10333 string (if (equal key clockstr)
10334 (org-no-properties
10335 (org-trim
10336 (buffer-substring
10337 (match-beginning 3) (goto-char (point-at-eol)))))
10338 (substring (org-match-string-no-properties 3) 1 -1)))
10339 (unless key
10340 (if (= (char-after (match-beginning 3)) ?\[)
10341 (setq key "TIMESTAMP_IA")
10342 (setq key "TIMESTAMP")))
10343 (when (or (equal key clockstr) (not (assoc key props)))
10344 (push (cons key string) props)))
10348 (when (memq which '(all standard))
10349 ;; Get the standard properties, like :PORP: ...
10350 (setq range (org-get-property-block beg end))
10351 (when range
10352 (goto-char (car range))
10353 (while (re-search-forward
10354 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10355 (cdr range) t)
10356 (setq key (org-match-string-no-properties 1)
10357 value (org-trim (or (org-match-string-no-properties 2) "")))
10358 (unless (member key excluded)
10359 (push (cons key (or value "")) props)))))
10360 (if clocksum
10361 (push (cons "CLOCKSUM"
10362 (org-columns-number-to-string (/ (float clocksum) 60.)
10363 'add_times))
10364 props))
10365 (unless (assoc "CATEGORY" props)
10366 (setq value (or (org-get-category)
10367 (progn (org-refresh-category-properties)
10368 (org-get-category))))
10369 (push (cons "CATEGORY" value) props))
10370 (append sum-props (nreverse props)))))))
10372 (defun org-entry-get (pom property &optional inherit)
10373 "Get value of PROPERTY for entry at point-or-marker POM.
10374 If INHERIT is non-nil and the entry does not have the property,
10375 then also check higher levels of the hierarchy.
10376 If INHERIT is the symbol `selective', use inheritance only if the setting
10377 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10378 If the property is present but empty, the return value is the empty string.
10379 If the property is not present at all, nil is returned."
10380 (org-with-point-at pom
10381 (if (and inherit (if (eq inherit 'selective)
10382 (org-property-inherit-p property)
10384 (org-entry-get-with-inheritance property)
10385 (if (member property org-special-properties)
10386 ;; We need a special property. Use brute force, get all properties.
10387 (cdr (assoc property (org-entry-properties nil 'special)))
10388 (let ((range (org-get-property-block)))
10389 (if (and range
10390 (goto-char (car range))
10391 (re-search-forward
10392 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10393 (cdr range) t))
10394 ;; Found the property, return it.
10395 (if (match-end 1)
10396 (org-match-string-no-properties 1)
10397 "")))))))
10399 (defun org-property-or-variable-value (var &optional inherit)
10400 "Check if there is a property fixing the value of VAR.
10401 If yes, return this value. If not, return the current value of the variable."
10402 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10403 (if (and prop (stringp prop) (string-match "\\S-" prop))
10404 (read prop)
10405 (symbol-value var))))
10407 (defun org-entry-delete (pom property)
10408 "Delete the property PROPERTY from entry at point-or-marker POM."
10409 (org-with-point-at pom
10410 (if (member property org-special-properties)
10411 nil ; cannot delete these properties.
10412 (let ((range (org-get-property-block)))
10413 (if (and range
10414 (goto-char (car range))
10415 (re-search-forward
10416 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10417 (cdr range) t))
10418 (progn
10419 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10421 nil)))))
10423 ;; Multi-values properties are properties that contain multiple values
10424 ;; These values are assumed to be single words, separated by whitespace.
10425 (defun org-entry-add-to-multivalued-property (pom property value)
10426 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10427 (let* ((old (org-entry-get pom property))
10428 (values (and old (org-split-string old "[ \t]"))))
10429 (setq value (org-entry-protect-space value))
10430 (unless (member value values)
10431 (setq values (cons value values))
10432 (org-entry-put pom property
10433 (mapconcat 'identity values " ")))))
10435 (defun org-entry-remove-from-multivalued-property (pom property value)
10436 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10437 (let* ((old (org-entry-get pom property))
10438 (values (and old (org-split-string old "[ \t]"))))
10439 (setq value (org-entry-protect-space value))
10440 (when (member value values)
10441 (setq values (delete value values))
10442 (org-entry-put pom property
10443 (mapconcat 'identity values " ")))))
10445 (defun org-entry-member-in-multivalued-property (pom property value)
10446 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10447 (let* ((old (org-entry-get pom property))
10448 (values (and old (org-split-string old "[ \t]"))))
10449 (setq value (org-entry-protect-space value))
10450 (member value values)))
10452 (defun org-entry-get-multivalued-property (pom property)
10453 "Return a list of values in a multivalued property."
10454 (let* ((value (org-entry-get pom property))
10455 (values (and value (org-split-string value "[ \t]"))))
10456 (mapcar 'org-entry-restore-space values)))
10458 (defun org-entry-put-multivalued-property (pom property &rest values)
10459 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10460 VALUES should be a list of strings. Spaces will be protected."
10461 (org-entry-put pom property
10462 (mapconcat 'org-entry-protect-space values " "))
10463 (let* ((value (org-entry-get pom property))
10464 (values (and value (org-split-string value "[ \t]"))))
10465 (mapcar 'org-entry-restore-space values)))
10467 (defun org-entry-protect-space (s)
10468 "Protect spaces and newline in string S."
10469 (while (string-match " " s)
10470 (setq s (replace-match "%20" t t s)))
10471 (while (string-match "\n" s)
10472 (setq s (replace-match "%0A" t t s)))
10475 (defun org-entry-restore-space (s)
10476 "Restore spaces and newline in string S."
10477 (while (string-match "%20" s)
10478 (setq s (replace-match " " t t s)))
10479 (while (string-match "%0A" s)
10480 (setq s (replace-match "\n" t t s)))
10483 (defvar org-entry-property-inherited-from (make-marker)
10484 "Marker pointing to the entry from where a property was inherited.
10485 Each call to `org-entry-get-with-inheritance' will set this marker to the
10486 location of the entry where the inheritance search matched. If there was
10487 no match, the marker will point nowhere.
10488 Note that also `org-entry-get' calls this function, if the INHERIT flag
10489 is set.")
10491 (defun org-entry-get-with-inheritance (property)
10492 "Get entry property, and search higher levels if not present."
10493 (move-marker org-entry-property-inherited-from nil)
10494 (let (tmp)
10495 (save-excursion
10496 (save-restriction
10497 (widen)
10498 (catch 'ex
10499 (while t
10500 (when (setq tmp (org-entry-get nil property))
10501 (org-back-to-heading t)
10502 (move-marker org-entry-property-inherited-from (point))
10503 (throw 'ex tmp))
10504 (or (org-up-heading-safe) (throw 'ex nil)))))
10505 (or tmp
10506 (cdr (assoc property org-file-properties))
10507 (cdr (assoc property org-global-properties))
10508 (cdr (assoc property org-global-properties-fixed))))))
10510 (defun org-entry-put (pom property value)
10511 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10512 (org-with-point-at pom
10513 (org-back-to-heading t)
10514 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10515 range)
10516 (cond
10517 ((equal property "TODO")
10518 (when (and (stringp value) (string-match "\\S-" value)
10519 (not (member value org-todo-keywords-1)))
10520 (error "\"%s\" is not a valid TODO state" value))
10521 (if (or (not value)
10522 (not (string-match "\\S-" value)))
10523 (setq value 'none))
10524 (org-todo value)
10525 (org-set-tags nil 'align))
10526 ((equal property "PRIORITY")
10527 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10528 (string-to-char value) ?\ ))
10529 (org-set-tags nil 'align))
10530 ((equal property "SCHEDULED")
10531 (if (re-search-forward org-scheduled-time-regexp end t)
10532 (cond
10533 ((eq value 'earlier) (org-timestamp-change -1 'day))
10534 ((eq value 'later) (org-timestamp-change 1 'day))
10535 (t (call-interactively 'org-schedule)))
10536 (call-interactively 'org-schedule)))
10537 ((equal property "DEADLINE")
10538 (if (re-search-forward org-deadline-time-regexp end t)
10539 (cond
10540 ((eq value 'earlier) (org-timestamp-change -1 'day))
10541 ((eq value 'later) (org-timestamp-change 1 'day))
10542 (t (call-interactively 'org-deadline)))
10543 (call-interactively 'org-deadline)))
10544 ((member property org-special-properties)
10545 (error "The %s property can not yet be set with `org-entry-put'"
10546 property))
10547 (t ; a non-special property
10548 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10549 (setq range (org-get-property-block beg end 'force))
10550 (goto-char (car range))
10551 (if (re-search-forward
10552 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10553 (progn
10554 (delete-region (match-beginning 1) (match-end 1))
10555 (goto-char (match-beginning 1)))
10556 (goto-char (cdr range))
10557 (insert "\n")
10558 (backward-char 1)
10559 (org-indent-line-function)
10560 (insert ":" property ":"))
10561 (and value (insert " " value))
10562 (org-indent-line-function)))))))
10564 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10565 "Get all property keys in the current buffer.
10566 With INCLUDE-SPECIALS, also list the special properties that reflect things
10567 like tags and TODO state.
10568 With INCLUDE-DEFAULTS, also include properties that has special meaning
10569 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10570 With INCLUDE-COLUMNS, also include property names given in COLUMN
10571 formats in the current buffer."
10572 (let (rtn range cfmt cols s p)
10573 (save-excursion
10574 (save-restriction
10575 (widen)
10576 (goto-char (point-min))
10577 (while (re-search-forward org-property-start-re nil t)
10578 (setq range (org-get-property-block))
10579 (goto-char (car range))
10580 (while (re-search-forward
10581 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10582 (cdr range) t)
10583 (add-to-list 'rtn (org-match-string-no-properties 1)))
10584 (outline-next-heading))))
10586 (when include-specials
10587 (setq rtn (append org-special-properties rtn)))
10589 (when include-defaults
10590 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10592 (when include-columns
10593 (save-excursion
10594 (save-restriction
10595 (widen)
10596 (goto-char (point-min))
10597 (while (re-search-forward
10598 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10599 nil t)
10600 (setq cfmt (match-string 2) s 0)
10601 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10602 cfmt s)
10603 (setq s (match-end 0)
10604 p (match-string 1 cfmt))
10605 (unless (or (equal p "ITEM")
10606 (member p org-special-properties))
10607 (add-to-list 'rtn (match-string 1 cfmt))))))))
10609 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10611 (defun org-property-values (key)
10612 "Return a list of all values of property KEY."
10613 (save-excursion
10614 (save-restriction
10615 (widen)
10616 (goto-char (point-min))
10617 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10618 values)
10619 (while (re-search-forward re nil t)
10620 (add-to-list 'values (org-trim (match-string 1))))
10621 (delete "" values)))))
10623 (defun org-insert-property-drawer ()
10624 "Insert a property drawer into the current entry."
10625 (interactive)
10626 (org-back-to-heading t)
10627 (looking-at outline-regexp)
10628 (let ((indent (- (match-end 0)(match-beginning 0)))
10629 (beg (point))
10630 (re (concat "^[ \t]*" org-keyword-time-regexp))
10631 end hiddenp)
10632 (outline-next-heading)
10633 (setq end (point))
10634 (goto-char beg)
10635 (while (re-search-forward re end t))
10636 (setq hiddenp (org-invisible-p))
10637 (end-of-line 1)
10638 (and (equal (char-after) ?\n) (forward-char 1))
10639 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10640 (beginning-of-line 2))
10641 (org-skip-over-state-notes)
10642 (skip-chars-backward " \t\n\r")
10643 (if (eq (char-before) ?*) (forward-char 1))
10644 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10645 (beginning-of-line 0)
10646 (org-indent-to-column indent)
10647 (beginning-of-line 2)
10648 (org-indent-to-column indent)
10649 (beginning-of-line 0)
10650 (if hiddenp
10651 (save-excursion
10652 (org-back-to-heading t)
10653 (hide-entry))
10654 (org-flag-drawer t))))
10656 (defun org-set-property (property value)
10657 "In the current entry, set PROPERTY to VALUE.
10658 When called interactively, this will prompt for a property name, offering
10659 completion on existing and default properties. And then it will prompt
10660 for a value, offering completion either on allowed values (via an inherited
10661 xxx_ALL property) or on existing values in other instances of this property
10662 in the current file."
10663 (interactive
10664 (let* ((completion-ignore-case t)
10665 (keys (org-buffer-property-keys nil t t))
10666 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10667 (prop (if (member prop0 keys)
10668 prop0
10669 (or (cdr (assoc (downcase prop0)
10670 (mapcar (lambda (x) (cons (downcase x) x))
10671 keys)))
10672 prop0)))
10673 (cur (org-entry-get nil prop))
10674 (allowed (org-property-get-allowed-values nil prop 'table))
10675 (existing (mapcar 'list (org-property-values prop)))
10676 (val (if allowed
10677 (org-completing-read "Value: " allowed nil 'req-match)
10678 (org-completing-read
10679 (concat "Value" (if (and cur (string-match "\\S-" cur))
10680 (concat "[" cur "]") "")
10681 ": ")
10682 existing nil nil "" nil cur))))
10683 (list prop (if (equal val "") cur val))))
10684 (unless (equal (org-entry-get nil property) value)
10685 (org-entry-put nil property value)))
10687 (defun org-delete-property (property)
10688 "In the current entry, delete PROPERTY."
10689 (interactive
10690 (let* ((completion-ignore-case t)
10691 (prop (org-ido-completing-read
10692 "Property: " (org-entry-properties nil 'standard))))
10693 (list prop)))
10694 (message "Property %s %s" property
10695 (if (org-entry-delete nil property)
10696 "deleted"
10697 "was not present in the entry")))
10699 (defun org-delete-property-globally (property)
10700 "Remove PROPERTY globally, from all entries."
10701 (interactive
10702 (let* ((completion-ignore-case t)
10703 (prop (org-ido-completing-read
10704 "Globally remove property: "
10705 (mapcar 'list (org-buffer-property-keys)))))
10706 (list prop)))
10707 (save-excursion
10708 (save-restriction
10709 (widen)
10710 (goto-char (point-min))
10711 (let ((cnt 0))
10712 (while (re-search-forward
10713 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10714 nil t)
10715 (setq cnt (1+ cnt))
10716 (replace-match ""))
10717 (message "Property \"%s\" removed from %d entries" property cnt)))))
10719 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10721 (defun org-compute-property-at-point ()
10722 "Compute the property at point.
10723 This looks for an enclosing column format, extracts the operator and
10724 then applies it to the property in the column format's scope."
10725 (interactive)
10726 (unless (org-at-property-p)
10727 (error "Not at a property"))
10728 (let ((prop (org-match-string-no-properties 2)))
10729 (org-columns-get-format-and-top-level)
10730 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10731 (error "No operator defined for property %s" prop))
10732 (org-columns-compute prop)))
10734 (defun org-property-get-allowed-values (pom property &optional table)
10735 "Get allowed values for the property PROPERTY.
10736 When TABLE is non-nil, return an alist that can directly be used for
10737 completion."
10738 (let (vals)
10739 (cond
10740 ((equal property "TODO")
10741 (setq vals (org-with-point-at pom
10742 (append org-todo-keywords-1 '("")))))
10743 ((equal property "PRIORITY")
10744 (let ((n org-lowest-priority))
10745 (while (>= n org-highest-priority)
10746 (push (char-to-string n) vals)
10747 (setq n (1- n)))))
10748 ((member property org-special-properties))
10750 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10752 (when (and vals (string-match "\\S-" vals))
10753 (setq vals (car (read-from-string (concat "(" vals ")"))))
10754 (setq vals (mapcar (lambda (x)
10755 (cond ((stringp x) x)
10756 ((numberp x) (number-to-string x))
10757 ((symbolp x) (symbol-name x))
10758 (t "???")))
10759 vals)))))
10760 (if table (mapcar 'list vals) vals)))
10762 (defun org-property-previous-allowed-value (&optional previous)
10763 "Switch to the next allowed value for this property."
10764 (interactive)
10765 (org-property-next-allowed-value t))
10767 (defun org-property-next-allowed-value (&optional previous)
10768 "Switch to the next allowed value for this property."
10769 (interactive)
10770 (unless (org-at-property-p)
10771 (error "Not at a property"))
10772 (let* ((key (match-string 2))
10773 (value (match-string 3))
10774 (allowed (or (org-property-get-allowed-values (point) key)
10775 (and (member value '("[ ]" "[-]" "[X]"))
10776 '("[ ]" "[X]"))))
10777 nval)
10778 (unless allowed
10779 (error "Allowed values for this property have not been defined"))
10780 (if previous (setq allowed (reverse allowed)))
10781 (if (member value allowed)
10782 (setq nval (car (cdr (member value allowed)))))
10783 (setq nval (or nval (car allowed)))
10784 (if (equal nval value)
10785 (error "Only one allowed value for this property"))
10786 (org-at-property-p)
10787 (replace-match (concat " :" key ": " nval) t t)
10788 (org-indent-line-function)
10789 (beginning-of-line 1)
10790 (skip-chars-forward " \t")))
10792 (defun org-find-entry-with-id (ident)
10793 "Locate the entry that contains the ID property with exact value IDENT.
10794 IDENT can be a string, a symbol or a number, this function will search for
10795 the string representation of it.
10796 Return the position where this entry starts, or nil if there is no such entry."
10797 (interactive "sID: ")
10798 (let ((id (cond
10799 ((stringp ident) ident)
10800 ((symbol-name ident) (symbol-name ident))
10801 ((numberp ident) (number-to-string ident))
10802 (t (error "IDENT %s must be a string, symbol or number" ident))))
10803 (case-fold-search nil))
10804 (save-excursion
10805 (save-restriction
10806 (widen)
10807 (goto-char (point-min))
10808 (when (re-search-forward
10809 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10810 nil t)
10811 (org-back-to-heading)
10812 (point))))))
10814 ;;;; Timestamps
10816 (defvar org-last-changed-timestamp nil)
10817 (defvar org-last-inserted-timestamp nil
10818 "The last time stamp inserted with `org-insert-time-stamp'.")
10819 (defvar org-time-was-given) ; dynamically scoped parameter
10820 (defvar org-end-time-was-given) ; dynamically scoped parameter
10821 (defvar org-ts-what) ; dynamically scoped parameter
10823 (defun org-time-stamp (arg &optional inactive)
10824 "Prompt for a date/time and insert a time stamp.
10825 If the user specifies a time like HH:MM, or if this command is called
10826 with a prefix argument, the time stamp will contain date and time.
10827 Otherwise, only the date will be included. All parts of a date not
10828 specified by the user will be filled in from the current date/time.
10829 So if you press just return without typing anything, the time stamp
10830 will represent the current date/time. If there is already a timestamp
10831 at the cursor, it will be modified."
10832 (interactive "P")
10833 (let* ((ts nil)
10834 (default-time
10835 ;; Default time is either today, or, when entering a range,
10836 ;; the range start.
10837 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10838 (save-excursion
10839 (re-search-backward
10840 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10841 (- (point) 20) t)))
10842 (apply 'encode-time (org-parse-time-string (match-string 1)))
10843 (current-time)))
10844 (default-input (and ts (org-get-compact-tod ts)))
10845 org-time-was-given org-end-time-was-given time)
10846 (cond
10847 ((and (org-at-timestamp-p t)
10848 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10849 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10850 (insert "--")
10851 (setq time (let ((this-command this-command))
10852 (org-read-date arg 'totime nil nil
10853 default-time default-input)))
10854 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10855 ((org-at-timestamp-p t)
10856 (setq time (let ((this-command this-command))
10857 (org-read-date arg 'totime nil nil default-time default-input)))
10858 (when (org-at-timestamp-p t) ; just to get the match data
10859 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10860 (replace-match "")
10861 (setq org-last-changed-timestamp
10862 (org-insert-time-stamp
10863 time (or org-time-was-given arg)
10864 inactive nil nil (list org-end-time-was-given))))
10865 (message "Timestamp updated"))
10867 (setq time (let ((this-command this-command))
10868 (org-read-date arg 'totime nil nil default-time default-input)))
10869 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10870 nil nil (list org-end-time-was-given))))))
10872 ;; FIXME: can we use this for something else, like computing time differences?
10873 (defun org-get-compact-tod (s)
10874 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10875 (let* ((t1 (match-string 1 s))
10876 (h1 (string-to-number (match-string 2 s)))
10877 (m1 (string-to-number (match-string 3 s)))
10878 (t2 (and (match-end 4) (match-string 5 s)))
10879 (h2 (and t2 (string-to-number (match-string 6 s))))
10880 (m2 (and t2 (string-to-number (match-string 7 s))))
10881 dh dm)
10882 (if (not t2)
10884 (setq dh (- h2 h1) dm (- m2 m1))
10885 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10886 (concat t1 "+" (number-to-string dh)
10887 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10889 (defun org-time-stamp-inactive (&optional arg)
10890 "Insert an inactive time stamp.
10891 An inactive time stamp is enclosed in square brackets instead of angle
10892 brackets. It is inactive in the sense that it does not trigger agenda entries,
10893 does not link to the calendar and cannot be changed with the S-cursor keys.
10894 So these are more for recording a certain time/date."
10895 (interactive "P")
10896 (org-time-stamp arg 'inactive))
10898 (defvar org-date-ovl (org-make-overlay 1 1))
10899 (org-overlay-put org-date-ovl 'face 'org-warning)
10900 (org-detach-overlay org-date-ovl)
10902 (defvar org-ans1) ; dynamically scoped parameter
10903 (defvar org-ans2) ; dynamically scoped parameter
10905 (defvar org-plain-time-of-day-regexp) ; defined below
10907 (defvar org-overriding-default-time nil) ; dynamically scoped
10908 (defvar org-read-date-overlay nil)
10909 (defvar org-dcst nil) ; dynamically scoped
10911 (defun org-read-date (&optional with-time to-time from-string prompt
10912 default-time default-input)
10913 "Read a date, possibly a time, and make things smooth for the user.
10914 The prompt will suggest to enter an ISO date, but you can also enter anything
10915 which will at least partially be understood by `parse-time-string'.
10916 Unrecognized parts of the date will default to the current day, month, year,
10917 hour and minute. If this command is called to replace a timestamp at point,
10918 of to enter the second timestamp of a range, the default time is taken from the
10919 existing stamp. For example,
10920 3-2-5 --> 2003-02-05
10921 feb 15 --> currentyear-02-15
10922 sep 12 9 --> 2009-09-12
10923 12:45 --> today 12:45
10924 22 sept 0:34 --> currentyear-09-22 0:34
10925 12 --> currentyear-currentmonth-12
10926 Fri --> nearest Friday (today or later)
10927 etc.
10929 Furthermore you can specify a relative date by giving, as the *first* thing
10930 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10931 change in days weeks, months, years.
10932 With a single plus or minus, the date is relative to today. With a double
10933 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10934 +4d --> four days from today
10935 +4 --> same as above
10936 +2w --> two weeks from today
10937 ++5 --> five days from default date
10939 The function understands only English month and weekday abbreviations,
10940 but this can be configured with the variables `parse-time-months' and
10941 `parse-time-weekdays'.
10943 While prompting, a calendar is popped up - you can also select the
10944 date with the mouse (button 1). The calendar shows a period of three
10945 months. To scroll it to other months, use the keys `>' and `<'.
10946 If you don't like the calendar, turn it off with
10947 \(setq org-read-date-popup-calendar nil)
10949 With optional argument TO-TIME, the date will immediately be converted
10950 to an internal time.
10951 With an optional argument WITH-TIME, the prompt will suggest to also
10952 insert a time. Note that when WITH-TIME is not set, you can still
10953 enter a time, and this function will inform the calling routine about
10954 this change. The calling routine may then choose to change the format
10955 used to insert the time stamp into the buffer to include the time.
10956 With optional argument FROM-STRING, read from this string instead from
10957 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10958 the time/date that is used for everything that is not specified by the
10959 user."
10960 (require 'parse-time)
10961 (let* ((org-time-stamp-rounding-minutes
10962 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10963 (org-dcst org-display-custom-times)
10964 (ct (org-current-time))
10965 (def (or org-overriding-default-time default-time ct))
10966 (defdecode (decode-time def))
10967 (dummy (progn
10968 (when (< (nth 2 defdecode) org-extend-today-until)
10969 (setcar (nthcdr 2 defdecode) -1)
10970 (setcar (nthcdr 1 defdecode) 59)
10971 (setq def (apply 'encode-time defdecode)
10972 defdecode (decode-time def)))))
10973 (calendar-move-hook nil)
10974 (calendar-view-diary-initially-flag nil)
10975 (view-diary-entries-initially nil)
10976 (calendar-view-holidays-initially-flag nil)
10977 (view-calendar-holidays-initially nil)
10978 (timestr (format-time-string
10979 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10980 (prompt (concat (if prompt (concat prompt " ") "")
10981 (format "Date+time [%s]: " timestr)))
10982 ans (org-ans0 "") org-ans1 org-ans2 final)
10984 (cond
10985 (from-string (setq ans from-string))
10986 (org-read-date-popup-calendar
10987 (save-excursion
10988 (save-window-excursion
10989 (calendar)
10990 (calendar-forward-day (- (time-to-days def)
10991 (calendar-absolute-from-gregorian
10992 (calendar-current-date))))
10993 (org-eval-in-calendar nil t)
10994 (let* ((old-map (current-local-map))
10995 (map (copy-keymap calendar-mode-map))
10996 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10997 (org-defkey map (kbd "RET") 'org-calendar-select)
10998 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10999 'org-calendar-select-mouse)
11000 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11001 'org-calendar-select-mouse)
11002 (org-defkey minibuffer-local-map [(meta shift left)]
11003 (lambda () (interactive)
11004 (org-eval-in-calendar '(calendar-backward-month 1))))
11005 (org-defkey minibuffer-local-map [(meta shift right)]
11006 (lambda () (interactive)
11007 (org-eval-in-calendar '(calendar-forward-month 1))))
11008 (org-defkey minibuffer-local-map [(meta shift up)]
11009 (lambda () (interactive)
11010 (org-eval-in-calendar '(calendar-backward-year 1))))
11011 (org-defkey minibuffer-local-map [(meta shift down)]
11012 (lambda () (interactive)
11013 (org-eval-in-calendar '(calendar-forward-year 1))))
11014 (org-defkey minibuffer-local-map [(shift up)]
11015 (lambda () (interactive)
11016 (org-eval-in-calendar '(calendar-backward-week 1))))
11017 (org-defkey minibuffer-local-map [(shift down)]
11018 (lambda () (interactive)
11019 (org-eval-in-calendar '(calendar-forward-week 1))))
11020 (org-defkey minibuffer-local-map [(shift left)]
11021 (lambda () (interactive)
11022 (org-eval-in-calendar '(calendar-backward-day 1))))
11023 (org-defkey minibuffer-local-map [(shift right)]
11024 (lambda () (interactive)
11025 (org-eval-in-calendar '(calendar-forward-day 1))))
11026 (org-defkey minibuffer-local-map ">"
11027 (lambda () (interactive)
11028 (org-eval-in-calendar '(scroll-calendar-left 1))))
11029 (org-defkey minibuffer-local-map "<"
11030 (lambda () (interactive)
11031 (org-eval-in-calendar '(scroll-calendar-right 1))))
11032 (unwind-protect
11033 (progn
11034 (use-local-map map)
11035 (add-hook 'post-command-hook 'org-read-date-display)
11036 (setq org-ans0 (read-string prompt default-input nil nil))
11037 ;; org-ans0: from prompt
11038 ;; org-ans1: from mouse click
11039 ;; org-ans2: from calendar motion
11040 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11041 (remove-hook 'post-command-hook 'org-read-date-display)
11042 (use-local-map old-map)
11043 (when org-read-date-overlay
11044 (org-delete-overlay org-read-date-overlay)
11045 (setq org-read-date-overlay nil)))))))
11047 (t ; Naked prompt only
11048 (unwind-protect
11049 (setq ans (read-string prompt default-input nil timestr))
11050 (when org-read-date-overlay
11051 (org-delete-overlay org-read-date-overlay)
11052 (setq org-read-date-overlay nil)))))
11054 (setq final (org-read-date-analyze ans def defdecode))
11056 (if to-time
11057 (apply 'encode-time final)
11058 (if (and (boundp 'org-time-was-given) org-time-was-given)
11059 (format "%04d-%02d-%02d %02d:%02d"
11060 (nth 5 final) (nth 4 final) (nth 3 final)
11061 (nth 2 final) (nth 1 final))
11062 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11063 (defvar def)
11064 (defvar defdecode)
11065 (defvar with-time)
11066 (defun org-read-date-display ()
11067 "Display the current date prompt interpretation in the minibuffer."
11068 (when org-read-date-display-live
11069 (when org-read-date-overlay
11070 (org-delete-overlay org-read-date-overlay))
11071 (let ((p (point)))
11072 (end-of-line 1)
11073 (while (not (equal (buffer-substring
11074 (max (point-min) (- (point) 4)) (point))
11075 " "))
11076 (insert " "))
11077 (goto-char p))
11078 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11079 " " (or org-ans1 org-ans2)))
11080 (org-end-time-was-given nil)
11081 (f (org-read-date-analyze ans def defdecode))
11082 (fmts (if org-dcst
11083 org-time-stamp-custom-formats
11084 org-time-stamp-formats))
11085 (fmt (if (or with-time
11086 (and (boundp 'org-time-was-given) org-time-was-given))
11087 (cdr fmts)
11088 (car fmts)))
11089 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11090 (when (and org-end-time-was-given
11091 (string-match org-plain-time-of-day-regexp txt))
11092 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11093 org-end-time-was-given
11094 (substring txt (match-end 0)))))
11095 (setq org-read-date-overlay
11096 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11097 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11099 (defun org-read-date-analyze (ans def defdecode)
11100 "Analyse the combined answer of the date prompt."
11101 ;; FIXME: cleanup and comment
11102 (let (delta deltan deltaw deltadef year month day
11103 hour minute second wday pm h2 m2 tl wday1
11104 iso-year iso-weekday iso-week iso-year iso-date)
11106 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11107 (setq ans "+0"))
11109 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11110 (setq ans (replace-match "" t t ans)
11111 deltan (car delta)
11112 deltaw (nth 1 delta)
11113 deltadef (nth 2 delta)))
11115 ;; Check if there is an iso week date in there
11116 ;; If yes, sore the info and postpone interpreting it until the rest
11117 ;; of the parsing is done
11118 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11119 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11120 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11121 iso-week (string-to-number (match-string 2 ans)))
11122 (setq ans (replace-match "" t t ans)))
11124 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11125 (when (string-match
11126 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11127 (setq year (if (match-end 2)
11128 (string-to-number (match-string 2 ans))
11129 (string-to-number (format-time-string "%Y")))
11130 month (string-to-number (match-string 3 ans))
11131 day (string-to-number (match-string 4 ans)))
11132 (if (< year 100) (setq year (+ 2000 year)))
11133 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11134 t nil ans)))
11135 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11136 ;; If there is a time with am/pm, and *no* time without it, we convert
11137 ;; so that matching will be successful.
11138 (loop for i from 1 to 2 do ; twice, for end time as well
11139 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11140 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11141 (setq hour (string-to-number (match-string 1 ans))
11142 minute (if (match-end 3)
11143 (string-to-number (match-string 3 ans))
11145 pm (equal ?p
11146 (string-to-char (downcase (match-string 4 ans)))))
11147 (if (and (= hour 12) (not pm))
11148 (setq hour 0)
11149 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11150 (setq ans (replace-match (format "%02d:%02d" hour minute)
11151 t t ans))))
11153 ;; Check if a time range is given as a duration
11154 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11155 (setq hour (string-to-number (match-string 1 ans))
11156 h2 (+ hour (string-to-number (match-string 3 ans)))
11157 minute (string-to-number (match-string 2 ans))
11158 m2 (+ minute (if (match-end 5) (string-to-number
11159 (match-string 5 ans))0)))
11160 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11161 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11162 t t ans)))
11164 ;; Check if there is a time range
11165 (when (boundp 'org-end-time-was-given)
11166 (setq org-time-was-given nil)
11167 (when (and (string-match org-plain-time-of-day-regexp ans)
11168 (match-end 8))
11169 (setq org-end-time-was-given (match-string 8 ans))
11170 (setq ans (concat (substring ans 0 (match-beginning 7))
11171 (substring ans (match-end 7))))))
11173 (setq tl (parse-time-string ans)
11174 day (or (nth 3 tl) (nth 3 defdecode))
11175 month (or (nth 4 tl)
11176 (if (and org-read-date-prefer-future
11177 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11178 (1+ (nth 4 defdecode))
11179 (nth 4 defdecode)))
11180 year (or (nth 5 tl)
11181 (if (and org-read-date-prefer-future
11182 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11183 (1+ (nth 5 defdecode))
11184 (nth 5 defdecode)))
11185 hour (or (nth 2 tl) (nth 2 defdecode))
11186 minute (or (nth 1 tl) (nth 1 defdecode))
11187 second (or (nth 0 tl) 0)
11188 wday (nth 6 tl))
11190 ;; Special date definitions below
11191 (cond
11192 (iso-week
11193 ;; There was an iso week
11194 (setq year (or iso-year year)
11195 day (or iso-weekday wday 1)
11196 wday nil ; to make sure that the trigger below does not match
11197 iso-date (calendar-gregorian-from-absolute
11198 (calendar-absolute-from-iso
11199 (list iso-week day year))))
11200 ; FIXME: Should we also push ISO weeks into the future?
11201 ; (when (and org-read-date-prefer-future
11202 ; (not iso-year)
11203 ; (< (calendar-absolute-from-gregorian iso-date)
11204 ; (time-to-days (current-time))))
11205 ; (setq year (1+ year)
11206 ; iso-date (calendar-gregorian-from-absolute
11207 ; (calendar-absolute-from-iso
11208 ; (list iso-week day year)))))
11209 (setq month (car iso-date)
11210 year (nth 2 iso-date)
11211 day (nth 1 iso-date)))
11212 (deltan
11213 (unless deltadef
11214 (let ((now (decode-time (current-time))))
11215 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11216 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11217 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11218 ((equal deltaw "m") (setq month (+ month deltan)))
11219 ((equal deltaw "y") (setq year (+ year deltan)))))
11220 ((and wday (not (nth 3 tl)))
11221 ;; Weekday was given, but no day, so pick that day in the week
11222 ;; on or after the derived date.
11223 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11224 (unless (equal wday wday1)
11225 (setq day (+ day (% (- wday wday1 -7) 7))))))
11226 (if (and (boundp 'org-time-was-given)
11227 (nth 2 tl))
11228 (setq org-time-was-given t))
11229 (if (< year 100) (setq year (+ 2000 year)))
11230 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11231 (list second minute hour day month year)))
11233 (defvar parse-time-weekdays)
11235 (defun org-read-date-get-relative (s today default)
11236 "Check string S for special relative date string.
11237 TODAY and DEFAULT are internal times, for today and for a default.
11238 Return shift list (N what def-flag)
11239 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11240 N is the number of WHATs to shift.
11241 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11242 the DEFAULT date rather than TODAY."
11243 (when (and
11244 (string-match
11245 (concat
11246 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11247 "\\([0-9]+\\)?"
11248 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11249 "\\([ \t]\\|$\\)") s)
11250 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11251 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11252 (string-to-char (substring (match-string 1 s) -1))
11253 ?+))
11254 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11255 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11256 (what (if (match-end 3) (match-string 3 s) "d"))
11257 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11258 (date (if rel default today))
11259 (wday (nth 6 (decode-time date)))
11260 delta)
11261 (if wday1
11262 (progn
11263 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11264 (if (= dir ?-) (setq delta (- delta 7)))
11265 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11266 (list delta "d" rel))
11267 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11269 (defun org-eval-in-calendar (form &optional keepdate)
11270 "Eval FORM in the calendar window and return to current window.
11271 Also, store the cursor date in variable org-ans2."
11272 (let ((sw (selected-window)))
11273 (select-window (get-buffer-window "*Calendar*"))
11274 (eval form)
11275 (when (and (not keepdate) (calendar-cursor-to-date))
11276 (let* ((date (calendar-cursor-to-date))
11277 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11278 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11279 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11280 (select-window sw)))
11282 (defun org-calendar-select ()
11283 "Return to `org-read-date' with the date currently selected.
11284 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11285 (interactive)
11286 (when (calendar-cursor-to-date)
11287 (let* ((date (calendar-cursor-to-date))
11288 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11289 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11290 (if (active-minibuffer-window) (exit-minibuffer))))
11292 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11293 "Insert a date stamp for the date given by the internal TIME.
11294 WITH-HM means, use the stamp format that includes the time of the day.
11295 INACTIVE means use square brackets instead of angular ones, so that the
11296 stamp will not contribute to the agenda.
11297 PRE and POST are optional strings to be inserted before and after the
11298 stamp.
11299 The command returns the inserted time stamp."
11300 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11301 stamp)
11302 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11303 (insert-before-markers (or pre ""))
11304 (insert-before-markers (setq stamp (format-time-string fmt time)))
11305 (when (listp extra)
11306 (setq extra (car extra))
11307 (if (and (stringp extra)
11308 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11309 (setq extra (format "-%02d:%02d"
11310 (string-to-number (match-string 1 extra))
11311 (string-to-number (match-string 2 extra))))
11312 (setq extra nil)))
11313 (when extra
11314 (backward-char 1)
11315 (insert-before-markers extra)
11316 (forward-char 1))
11317 (insert-before-markers (or post ""))
11318 (setq org-last-inserted-timestamp stamp)))
11320 (defun org-toggle-time-stamp-overlays ()
11321 "Toggle the use of custom time stamp formats."
11322 (interactive)
11323 (setq org-display-custom-times (not org-display-custom-times))
11324 (unless org-display-custom-times
11325 (let ((p (point-min)) (bmp (buffer-modified-p)))
11326 (while (setq p (next-single-property-change p 'display))
11327 (if (and (get-text-property p 'display)
11328 (eq (get-text-property p 'face) 'org-date))
11329 (remove-text-properties
11330 p (setq p (next-single-property-change p 'display))
11331 '(display t))))
11332 (set-buffer-modified-p bmp)))
11333 (if (featurep 'xemacs)
11334 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11335 (org-restart-font-lock)
11336 (setq org-table-may-need-update t)
11337 (if org-display-custom-times
11338 (message "Time stamps are overlayed with custom format")
11339 (message "Time stamp overlays removed")))
11341 (defun org-display-custom-time (beg end)
11342 "Overlay modified time stamp format over timestamp between BEG and END."
11343 (let* ((ts (buffer-substring beg end))
11344 t1 w1 with-hm tf time str w2 (off 0))
11345 (save-match-data
11346 (setq t1 (org-parse-time-string ts t))
11347 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11348 (setq off (- (match-end 0) (match-beginning 0)))))
11349 (setq end (- end off))
11350 (setq w1 (- end beg)
11351 with-hm (and (nth 1 t1) (nth 2 t1))
11352 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11353 time (org-fix-decoded-time t1)
11354 str (org-add-props
11355 (format-time-string
11356 (substring tf 1 -1) (apply 'encode-time time))
11357 nil 'mouse-face 'highlight)
11358 w2 (length str))
11359 (if (not (= w2 w1))
11360 (add-text-properties (1+ beg) (+ 2 beg)
11361 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11362 (if (featurep 'xemacs)
11363 (progn
11364 (put-text-property beg end 'invisible t)
11365 (put-text-property beg end 'end-glyph (make-glyph str)))
11366 (put-text-property beg end 'display str))))
11368 (defun org-translate-time (string)
11369 "Translate all timestamps in STRING to custom format.
11370 But do this only if the variable `org-display-custom-times' is set."
11371 (when org-display-custom-times
11372 (save-match-data
11373 (let* ((start 0)
11374 (re org-ts-regexp-both)
11375 t1 with-hm inactive tf time str beg end)
11376 (while (setq start (string-match re string start))
11377 (setq beg (match-beginning 0)
11378 end (match-end 0)
11379 t1 (save-match-data
11380 (org-parse-time-string (substring string beg end) t))
11381 with-hm (and (nth 1 t1) (nth 2 t1))
11382 inactive (equal (substring string beg (1+ beg)) "[")
11383 tf (funcall (if with-hm 'cdr 'car)
11384 org-time-stamp-custom-formats)
11385 time (org-fix-decoded-time t1)
11386 str (format-time-string
11387 (concat
11388 (if inactive "[" "<") (substring tf 1 -1)
11389 (if inactive "]" ">"))
11390 (apply 'encode-time time))
11391 string (replace-match str t t string)
11392 start (+ start (length str)))))))
11393 string)
11395 (defun org-fix-decoded-time (time)
11396 "Set 0 instead of nil for the first 6 elements of time.
11397 Don't touch the rest."
11398 (let ((n 0))
11399 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11401 (defun org-days-to-time (timestamp-string)
11402 "Difference between TIMESTAMP-STRING and now in days."
11403 (- (time-to-days (org-time-string-to-time timestamp-string))
11404 (time-to-days (current-time))))
11406 (defun org-deadline-close (timestamp-string &optional ndays)
11407 "Is the time in TIMESTAMP-STRING close to the current date?"
11408 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11409 (and (< (org-days-to-time timestamp-string) ndays)
11410 (not (org-entry-is-done-p))))
11412 (defun org-get-wdays (ts)
11413 "Get the deadline lead time appropriate for timestring TS."
11414 (cond
11415 ((<= org-deadline-warning-days 0)
11416 ;; 0 or negative, enforce this value no matter what
11417 (- org-deadline-warning-days))
11418 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11419 ;; lead time is specified.
11420 (floor (* (string-to-number (match-string 1 ts))
11421 (cdr (assoc (match-string 2 ts)
11422 '(("d" . 1) ("w" . 7)
11423 ("m" . 30.4) ("y" . 365.25)))))))
11424 ;; go for the default.
11425 (t org-deadline-warning-days)))
11427 (defun org-calendar-select-mouse (ev)
11428 "Return to `org-read-date' with the date currently selected.
11429 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11430 (interactive "e")
11431 (mouse-set-point ev)
11432 (when (calendar-cursor-to-date)
11433 (let* ((date (calendar-cursor-to-date))
11434 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11435 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11436 (if (active-minibuffer-window) (exit-minibuffer))))
11438 (defun org-check-deadlines (ndays)
11439 "Check if there are any deadlines due or past due.
11440 A deadline is considered due if it happens within `org-deadline-warning-days'
11441 days from today's date. If the deadline appears in an entry marked DONE,
11442 it is not shown. The prefix arg NDAYS can be used to test that many
11443 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11444 (interactive "P")
11445 (let* ((org-warn-days
11446 (cond
11447 ((equal ndays '(4)) 100000)
11448 (ndays (prefix-numeric-value ndays))
11449 (t (abs org-deadline-warning-days))))
11450 (case-fold-search nil)
11451 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11452 (callback
11453 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11455 (message "%d deadlines past-due or due within %d days"
11456 (org-occur regexp nil callback)
11457 org-warn-days)))
11459 (defun org-check-before-date (date)
11460 "Check if there are deadlines or scheduled entries before DATE."
11461 (interactive (list (org-read-date)))
11462 (let ((case-fold-search nil)
11463 (regexp (concat "\\<\\(" org-deadline-string
11464 "\\|" org-scheduled-string
11465 "\\) *<\\([^>]+\\)>"))
11466 (callback
11467 (lambda () (time-less-p
11468 (org-time-string-to-time (match-string 2))
11469 (org-time-string-to-time date)))))
11470 (message "%d entries before %s"
11471 (org-occur regexp nil callback) date)))
11473 (defun org-evaluate-time-range (&optional to-buffer)
11474 "Evaluate a time range by computing the difference between start and end.
11475 Normally the result is just printed in the echo area, but with prefix arg
11476 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11477 If the time range is actually in a table, the result is inserted into the
11478 next column.
11479 For time difference computation, a year is assumed to be exactly 365
11480 days in order to avoid rounding problems."
11481 (interactive "P")
11483 (org-clock-update-time-maybe)
11484 (save-excursion
11485 (unless (org-at-date-range-p t)
11486 (goto-char (point-at-bol))
11487 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11488 (if (not (org-at-date-range-p t))
11489 (error "Not at a time-stamp range, and none found in current line")))
11490 (let* ((ts1 (match-string 1))
11491 (ts2 (match-string 2))
11492 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11493 (match-end (match-end 0))
11494 (time1 (org-time-string-to-time ts1))
11495 (time2 (org-time-string-to-time ts2))
11496 (t1 (time-to-seconds time1))
11497 (t2 (time-to-seconds time2))
11498 (diff (abs (- t2 t1)))
11499 (negative (< (- t2 t1) 0))
11500 ;; (ys (floor (* 365 24 60 60)))
11501 (ds (* 24 60 60))
11502 (hs (* 60 60))
11503 (fy "%dy %dd %02d:%02d")
11504 (fy1 "%dy %dd")
11505 (fd "%dd %02d:%02d")
11506 (fd1 "%dd")
11507 (fh "%02d:%02d")
11508 y d h m align)
11509 (if havetime
11510 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11512 d (floor (/ diff ds)) diff (mod diff ds)
11513 h (floor (/ diff hs)) diff (mod diff hs)
11514 m (floor (/ diff 60)))
11515 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11517 d (floor (+ (/ diff ds) 0.5))
11518 h 0 m 0))
11519 (if (not to-buffer)
11520 (message "%s" (org-make-tdiff-string y d h m))
11521 (if (org-at-table-p)
11522 (progn
11523 (goto-char match-end)
11524 (setq align t)
11525 (and (looking-at " *|") (goto-char (match-end 0))))
11526 (goto-char match-end))
11527 (if (looking-at
11528 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11529 (replace-match ""))
11530 (if negative (insert " -"))
11531 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11532 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11533 (insert " " (format fh h m))))
11534 (if align (org-table-align))
11535 (message "Time difference inserted")))))
11537 (defun org-make-tdiff-string (y d h m)
11538 (let ((fmt "")
11539 (l nil))
11540 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11541 l (push y l)))
11542 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11543 l (push d l)))
11544 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11545 l (push h l)))
11546 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11547 l (push m l)))
11548 (apply 'format fmt (nreverse l))))
11550 (defun org-time-string-to-time (s)
11551 (apply 'encode-time (org-parse-time-string s)))
11553 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11554 "Convert a time stamp to an absolute day number.
11555 If there is a specifyer for a cyclic time stamp, get the closest date to
11556 DAYNR.
11557 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11558 (cond
11559 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11560 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11561 daynr
11562 (+ daynr 1000)))
11563 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11564 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11565 (time-to-days (current-time))) (match-string 0 s)
11566 prefer show-all))
11567 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11569 (defun org-days-to-iso-week (days)
11570 "Return the iso week number."
11571 (require 'cal-iso)
11572 (car (calendar-iso-from-absolute days)))
11574 (defun org-small-year-to-year (year)
11575 "Convert 2-digit years into 4-digit years.
11576 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11577 The year 2000 cannot be abbreviated. Any year larger than 99
11578 is returned unchanged."
11579 (if (< year 38)
11580 (setq year (+ 2000 year))
11581 (if (< year 100)
11582 (setq year (+ 1900 year))))
11583 year)
11585 (defun org-time-from-absolute (d)
11586 "Return the time corresponding to date D.
11587 D may be an absolute day number, or a calendar-type list (month day year)."
11588 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11589 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11591 (defun org-calendar-holiday ()
11592 "List of holidays, for Diary display in Org-mode."
11593 (require 'holidays)
11594 (let ((hl (funcall
11595 (if (fboundp 'calendar-check-holidays)
11596 'calendar-check-holidays 'check-calendar-holidays) date)))
11597 (if hl (mapconcat 'identity hl "; "))))
11599 (defun org-diary-sexp-entry (sexp entry date)
11600 "Process a SEXP diary ENTRY for DATE."
11601 (require 'diary-lib)
11602 (let ((result (if calendar-debug-sexp
11603 (let ((stack-trace-on-error t))
11604 (eval (car (read-from-string sexp))))
11605 (condition-case nil
11606 (eval (car (read-from-string sexp)))
11607 (error
11608 (beep)
11609 (message "Bad sexp at line %d in %s: %s"
11610 (org-current-line)
11611 (buffer-file-name) sexp)
11612 (sleep-for 2))))))
11613 (cond ((stringp result) result)
11614 ((and (consp result)
11615 (stringp (cdr result))) (cdr result))
11616 (result entry)
11617 (t nil))))
11619 (defun org-diary-to-ical-string (frombuf)
11620 "Get iCalendar entries from diary entries in buffer FROMBUF.
11621 This uses the icalendar.el library."
11622 (let* ((tmpdir (if (featurep 'xemacs)
11623 (temp-directory)
11624 temporary-file-directory))
11625 (tmpfile (make-temp-name
11626 (expand-file-name "orgics" tmpdir)))
11627 buf rtn b e)
11628 (save-excursion
11629 (set-buffer frombuf)
11630 (icalendar-export-region (point-min) (point-max) tmpfile)
11631 (setq buf (find-buffer-visiting tmpfile))
11632 (set-buffer buf)
11633 (goto-char (point-min))
11634 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11635 (setq b (match-beginning 0)))
11636 (goto-char (point-max))
11637 (if (re-search-backward "^END:VEVENT" nil t)
11638 (setq e (match-end 0)))
11639 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11640 (kill-buffer buf)
11641 (delete-file tmpfile)
11642 rtn))
11644 (defun org-closest-date (start current change prefer show-all)
11645 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11646 When PREFER is `past' return a date that is either CURRENT or past.
11647 When PREFER is `future', return a date that is either CURRENT or future.
11648 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11649 ;; Make the proper lists from the dates
11650 (catch 'exit
11651 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11652 dn dw sday cday n1 n2 n0
11653 d m y y1 y2 date1 date2 nmonths nm ny m2)
11655 (setq start (org-date-to-gregorian start)
11656 current (org-date-to-gregorian
11657 (if show-all
11658 current
11659 (time-to-days (current-time))))
11660 sday (calendar-absolute-from-gregorian start)
11661 cday (calendar-absolute-from-gregorian current))
11663 (if (<= cday sday) (throw 'exit sday))
11665 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11666 (setq dn (string-to-number (match-string 1 change))
11667 dw (cdr (assoc (match-string 2 change) a1)))
11668 (error "Invalid change specifyer: %s" change))
11669 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11670 (cond
11671 ((eq dw 'day)
11672 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11673 n2 (+ n1 dn)))
11674 ((eq dw 'year)
11675 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11676 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11677 (setq date1 (list m d y1)
11678 n1 (calendar-absolute-from-gregorian date1)
11679 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11680 n2 (calendar-absolute-from-gregorian date2)))
11681 ((eq dw 'month)
11682 ;; approx number of month between the two dates
11683 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11684 ;; How often does dn fit in there?
11685 (setq d (nth 1 start) m (car start) y (nth 2 start)
11686 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11687 m (+ m nm)
11688 ny (floor (/ m 12))
11689 y (+ y ny)
11690 m (- m (* ny 12)))
11691 (while (> m 12) (setq m (- m 12) y (1+ y)))
11692 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11693 (setq m2 (+ m dn) y2 y)
11694 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11695 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11696 (while (<= n2 cday)
11697 (setq n1 n2 m m2 y y2)
11698 (setq m2 (+ m dn) y2 y)
11699 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11700 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11701 ;; Make sure n1 is the earlier date
11702 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11703 (if show-all
11704 (cond
11705 ((eq prefer 'past) n1)
11706 ((eq prefer 'future) (if (= cday n1) n1 n2))
11707 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11708 (cond
11709 ((eq prefer 'past) n1)
11710 ((eq prefer 'future) (if (= cday n1) n1 n2))
11711 (t (if (= cday n1) n1 n2)))))))
11713 (defun org-date-to-gregorian (date)
11714 "Turn any specification of DATE into a gregorian date for the calendar."
11715 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11716 ((and (listp date) (= (length date) 3)) date)
11717 ((stringp date)
11718 (setq date (org-parse-time-string date))
11719 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11720 ((listp date)
11721 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11723 (defun org-parse-time-string (s &optional nodefault)
11724 "Parse the standard Org-mode time string.
11725 This should be a lot faster than the normal `parse-time-string'.
11726 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11727 hour and minute fields will be nil if not given."
11728 (if (string-match org-ts-regexp0 s)
11729 (list 0
11730 (if (or (match-beginning 8) (not nodefault))
11731 (string-to-number (or (match-string 8 s) "0")))
11732 (if (or (match-beginning 7) (not nodefault))
11733 (string-to-number (or (match-string 7 s) "0")))
11734 (string-to-number (match-string 4 s))
11735 (string-to-number (match-string 3 s))
11736 (string-to-number (match-string 2 s))
11737 nil nil nil)
11738 (make-list 9 0)))
11740 (defun org-timestamp-up (&optional arg)
11741 "Increase the date item at the cursor by one.
11742 If the cursor is on the year, change the year. If it is on the month or
11743 the day, change that.
11744 With prefix ARG, change by that many units."
11745 (interactive "p")
11746 (org-timestamp-change (prefix-numeric-value arg)))
11748 (defun org-timestamp-down (&optional arg)
11749 "Decrease the date item at the cursor by one.
11750 If the cursor is on the year, change the year. If it is on the month or
11751 the day, change that.
11752 With prefix ARG, change by that many units."
11753 (interactive "p")
11754 (org-timestamp-change (- (prefix-numeric-value arg))))
11756 (defun org-timestamp-up-day (&optional arg)
11757 "Increase the date in the time stamp by one day.
11758 With prefix ARG, change that many days."
11759 (interactive "p")
11760 (if (and (not (org-at-timestamp-p t))
11761 (org-on-heading-p))
11762 (org-todo 'up)
11763 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11765 (defun org-timestamp-down-day (&optional arg)
11766 "Decrease the date in the time stamp by one day.
11767 With prefix ARG, change that many days."
11768 (interactive "p")
11769 (if (and (not (org-at-timestamp-p t))
11770 (org-on-heading-p))
11771 (org-todo 'down)
11772 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11774 (defun org-at-timestamp-p (&optional inactive-ok)
11775 "Determine if the cursor is in or at a timestamp."
11776 (interactive)
11777 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11778 (pos (point))
11779 (ans (or (looking-at tsr)
11780 (save-excursion
11781 (skip-chars-backward "^[<\n\r\t")
11782 (if (> (point) (point-min)) (backward-char 1))
11783 (and (looking-at tsr)
11784 (> (- (match-end 0) pos) -1))))))
11785 (and ans
11786 (boundp 'org-ts-what)
11787 (setq org-ts-what
11788 (cond
11789 ((= pos (match-beginning 0)) 'bracket)
11790 ((= pos (1- (match-end 0))) 'bracket)
11791 ((org-pos-in-match-range pos 2) 'year)
11792 ((org-pos-in-match-range pos 3) 'month)
11793 ((org-pos-in-match-range pos 7) 'hour)
11794 ((org-pos-in-match-range pos 8) 'minute)
11795 ((or (org-pos-in-match-range pos 4)
11796 (org-pos-in-match-range pos 5)) 'day)
11797 ((and (> pos (or (match-end 8) (match-end 5)))
11798 (< pos (match-end 0)))
11799 (- pos (or (match-end 8) (match-end 5))))
11800 (t 'day))))
11801 ans))
11803 (defun org-toggle-timestamp-type ()
11804 "Toggle the type (<active> or [inactive]) of a time stamp."
11805 (interactive)
11806 (when (org-at-timestamp-p t)
11807 (let ((beg (match-beginning 0)) (end (match-end 0))
11808 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11809 (save-excursion
11810 (goto-char beg)
11811 (while (re-search-forward "[][<>]" end t)
11812 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11813 t t)))
11814 (message "Timestamp is now %sactive"
11815 (if (equal (char-after beg) ?<) "" "in")))))
11817 (defun org-timestamp-change (n &optional what)
11818 "Change the date in the time stamp at point.
11819 The date will be changed by N times WHAT. WHAT can be `day', `month',
11820 `year', `minute', `second'. If WHAT is not given, the cursor position
11821 in the timestamp determines what will be changed."
11822 (let ((pos (point))
11823 with-hm inactive
11824 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11825 org-ts-what
11826 extra rem
11827 ts time time0)
11828 (if (not (org-at-timestamp-p t))
11829 (error "Not at a timestamp"))
11830 (if (and (not what) (eq org-ts-what 'bracket))
11831 (org-toggle-timestamp-type)
11832 (if (and (not what) (not (eq org-ts-what 'day))
11833 org-display-custom-times
11834 (get-text-property (point) 'display)
11835 (not (get-text-property (1- (point)) 'display)))
11836 (setq org-ts-what 'day))
11837 (setq org-ts-what (or what org-ts-what)
11838 inactive (= (char-after (match-beginning 0)) ?\[)
11839 ts (match-string 0))
11840 (replace-match "")
11841 (if (string-match
11842 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11844 (setq extra (match-string 1 ts)))
11845 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11846 (setq with-hm t))
11847 (setq time0 (org-parse-time-string ts))
11848 (when (and (eq org-ts-what 'minute)
11849 (eq current-prefix-arg nil))
11850 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11851 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11852 (setcar (cdr time0) (+ (nth 1 time0)
11853 (if (> n 0) (- rem) (- dm rem))))))
11854 (setq time
11855 (encode-time (or (car time0) 0)
11856 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11857 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11858 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11859 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11860 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11861 (nthcdr 6 time0)))
11862 (when (integerp org-ts-what)
11863 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11864 (if (eq what 'calendar)
11865 (let ((cal-date (org-get-date-from-calendar)))
11866 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11867 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11868 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11869 (setcar time0 (or (car time0) 0))
11870 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11871 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11872 (setq time (apply 'encode-time time0))))
11873 (setq org-last-changed-timestamp
11874 (org-insert-time-stamp time with-hm inactive nil nil extra))
11875 (org-clock-update-time-maybe)
11876 (goto-char pos)
11877 ;; Try to recenter the calendar window, if any
11878 (if (and org-calendar-follow-timestamp-change
11879 (get-buffer-window "*Calendar*" t)
11880 (memq org-ts-what '(day month year)))
11881 (org-recenter-calendar (time-to-days time))))))
11883 (defun org-modify-ts-extra (s pos n dm)
11884 "Change the different parts of the lead-time and repeat fields in timestamp."
11885 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11886 ng h m new rem)
11887 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11888 (cond
11889 ((or (org-pos-in-match-range pos 2)
11890 (org-pos-in-match-range pos 3))
11891 (setq m (string-to-number (match-string 3 s))
11892 h (string-to-number (match-string 2 s)))
11893 (if (org-pos-in-match-range pos 2)
11894 (setq h (+ h n))
11895 (setq n (* dm (org-no-warnings (signum n))))
11896 (when (not (= 0 (setq rem (% m dm))))
11897 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11898 (setq m (+ m n)))
11899 (if (< m 0) (setq m (+ m 60) h (1- h)))
11900 (if (> m 59) (setq m (- m 60) h (1+ h)))
11901 (setq h (min 24 (max 0 h)))
11902 (setq ng 1 new (format "-%02d:%02d" h m)))
11903 ((org-pos-in-match-range pos 6)
11904 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11905 ((org-pos-in-match-range pos 5)
11906 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11908 ((org-pos-in-match-range pos 9)
11909 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11910 ((org-pos-in-match-range pos 8)
11911 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11913 (when ng
11914 (setq s (concat
11915 (substring s 0 (match-beginning ng))
11917 (substring s (match-end ng))))))
11920 (defun org-recenter-calendar (date)
11921 "If the calendar is visible, recenter it to DATE."
11922 (let* ((win (selected-window))
11923 (cwin (get-buffer-window "*Calendar*" t))
11924 (calendar-move-hook nil))
11925 (when cwin
11926 (select-window cwin)
11927 (calendar-goto-date (if (listp date) date
11928 (calendar-gregorian-from-absolute date)))
11929 (select-window win))))
11931 (defun org-goto-calendar (&optional arg)
11932 "Go to the Emacs calendar at the current date.
11933 If there is a time stamp in the current line, go to that date.
11934 A prefix ARG can be used to force the current date."
11935 (interactive "P")
11936 (let ((tsr org-ts-regexp) diff
11937 (calendar-move-hook nil)
11938 (calendar-view-holidays-initially-flag nil)
11939 (view-calendar-holidays-initially nil)
11940 (calendar-view-diary-initially-flag nil)
11941 (view-diary-entries-initially nil))
11942 (if (or (org-at-timestamp-p)
11943 (save-excursion
11944 (beginning-of-line 1)
11945 (looking-at (concat ".*" tsr))))
11946 (let ((d1 (time-to-days (current-time)))
11947 (d2 (time-to-days
11948 (org-time-string-to-time (match-string 1)))))
11949 (setq diff (- d2 d1))))
11950 (calendar)
11951 (calendar-goto-today)
11952 (if (and diff (not arg)) (calendar-forward-day diff))))
11954 (defun org-get-date-from-calendar ()
11955 "Return a list (month day year) of date at point in calendar."
11956 (with-current-buffer "*Calendar*"
11957 (save-match-data
11958 (calendar-cursor-to-date))))
11960 (defun org-date-from-calendar ()
11961 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11962 If there is already a time stamp at the cursor position, update it."
11963 (interactive)
11964 (if (org-at-timestamp-p t)
11965 (org-timestamp-change 0 'calendar)
11966 (let ((cal-date (org-get-date-from-calendar)))
11967 (org-insert-time-stamp
11968 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11970 (defun org-minutes-to-hh:mm-string (m)
11971 "Compute H:MM from a number of minutes."
11972 (let ((h (/ m 60)))
11973 (setq m (- m (* 60 h)))
11974 (format org-time-clocksum-format h m)))
11976 (defun org-hh:mm-string-to-minutes (s)
11977 "Convert a string H:MM to a number of minutes."
11978 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11979 (+ (* (string-to-number (match-string 1 s)) 60)
11980 (string-to-number (match-string 2 s)))
11983 ;;;; Agenda files
11985 ;;;###autoload
11986 (defun org-iswitchb (&optional arg)
11987 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11988 With a prefix argument, restrict available to files.
11989 With two prefix arguments, restrict available buffers to agenda files.
11991 Due to some yet unresolved reason, the global function
11992 `iswitchb-mode' needs to be active for this function to work."
11993 (interactive "P")
11994 (require 'iswitchb)
11995 (let ((enabled iswitchb-mode) blist)
11996 (or enabled (iswitchb-mode 1))
11997 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11998 ((equal arg '(16)) (org-buffer-list 'agenda))
11999 (t (org-buffer-list))))
12000 (unwind-protect
12001 (let ((iswitchb-make-buflist-hook
12002 (lambda ()
12003 (setq iswitchb-temp-buflist
12004 (mapcar 'buffer-name blist)))))
12005 (switch-to-buffer
12006 (iswitchb-read-buffer
12007 "Switch-to: " nil t))
12008 (or enabled (iswitchb-mode -1))))))
12010 ;;;###autoload
12011 (defun org-ido-switchb (&optional arg)
12012 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12013 With a prefix argument, restrict available to files.
12014 With two prefix arguments, restrict available buffers to agenda files."
12015 (interactive "P")
12016 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12017 ((equal arg '(16)) (org-buffer-list 'agenda))
12018 (t (org-buffer-list)))))
12019 (switch-to-buffer
12020 (org-ido-completing-read "Org buffer: "
12021 (mapcar 'buffer-name blist)
12022 nil t))))
12024 (defun org-buffer-list (&optional predicate exclude-tmp)
12025 "Return a list of Org buffers.
12026 PREDICATE can be `export', `files' or `agenda'.
12028 export restrict the list to Export buffers.
12029 files restrict the list to buffers visiting Org files.
12030 agenda restrict the list to buffers visiting agenda files.
12032 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12033 (let* ((bfn nil)
12034 (agenda-files (and (eq predicate 'agenda)
12035 (mapcar 'file-truename (org-agenda-files t))))
12036 (filter
12037 (cond
12038 ((eq predicate 'files)
12039 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12040 ((eq predicate 'export)
12041 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12042 ((eq predicate 'agenda)
12043 (lambda (b)
12044 (with-current-buffer b
12045 (and (eq major-mode 'org-mode)
12046 (setq bfn (buffer-file-name b))
12047 (member (file-truename bfn) agenda-files)))))
12048 (t (lambda (b) (with-current-buffer b
12049 (or (eq major-mode 'org-mode)
12050 (string-match "\*Org .*Export"
12051 (buffer-name b)))))))))
12052 (delq nil
12053 (mapcar
12054 (lambda(b)
12055 (if (and (funcall filter b)
12056 (or (not exclude-tmp)
12057 (not (string-match "tmp" (buffer-name b)))))
12059 nil))
12060 (buffer-list)))))
12062 (defun org-agenda-files (&optional unrestricted archives)
12063 "Get the list of agenda files.
12064 Optional UNRESTRICTED means return the full list even if a restriction
12065 is currently in place.
12066 When ARCHIVES is t, include all archive files hat are really being
12067 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12068 `org-agenda-archives-mode' is t."
12069 (let ((files
12070 (cond
12071 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12072 ((stringp org-agenda-files) (org-read-agenda-file-list))
12073 ((listp org-agenda-files) org-agenda-files)
12074 (t (error "Invalid value of `org-agenda-files'")))))
12075 (setq files (apply 'append
12076 (mapcar (lambda (f)
12077 (if (file-directory-p f)
12078 (directory-files
12079 f t org-agenda-file-regexp)
12080 (list f)))
12081 files)))
12082 (when org-agenda-skip-unavailable-files
12083 (setq files (delq nil
12084 (mapcar (function
12085 (lambda (file)
12086 (and (file-readable-p file) file)))
12087 files))))
12088 (when (or (eq archives t)
12089 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12090 (setq files (org-add-archive-files files)))
12091 files))
12093 (defun org-edit-agenda-file-list ()
12094 "Edit the list of agenda files.
12095 Depending on setup, this either uses customize to edit the variable
12096 `org-agenda-files', or it visits the file that is holding the list. In the
12097 latter case, the buffer is set up in a way that saving it automatically kills
12098 the buffer and restores the previous window configuration."
12099 (interactive)
12100 (if (stringp org-agenda-files)
12101 (let ((cw (current-window-configuration)))
12102 (find-file org-agenda-files)
12103 (org-set-local 'org-window-configuration cw)
12104 (org-add-hook 'after-save-hook
12105 (lambda ()
12106 (set-window-configuration
12107 (prog1 org-window-configuration
12108 (kill-buffer (current-buffer))))
12109 (org-install-agenda-files-menu)
12110 (message "New agenda file list installed"))
12111 nil 'local)
12112 (message "%s" (substitute-command-keys
12113 "Edit list and finish with \\[save-buffer]")))
12114 (customize-variable 'org-agenda-files)))
12116 (defun org-store-new-agenda-file-list (list)
12117 "Set new value for the agenda file list and save it correctly."
12118 (if (stringp org-agenda-files)
12119 (let ((f org-agenda-files) b)
12120 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12121 (with-temp-file f
12122 (insert (mapconcat 'identity list "\n") "\n")))
12123 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12124 (setq org-agenda-files list)
12125 (customize-save-variable 'org-agenda-files org-agenda-files))))
12127 (defun org-read-agenda-file-list ()
12128 "Read the list of agenda files from a file."
12129 (when (file-directory-p org-agenda-files)
12130 (error "`org-agenda-files' cannot be a single directory"))
12131 (when (stringp org-agenda-files)
12132 (with-temp-buffer
12133 (insert-file-contents org-agenda-files)
12134 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12137 ;;;###autoload
12138 (defun org-cycle-agenda-files ()
12139 "Cycle through the files in `org-agenda-files'.
12140 If the current buffer visits an agenda file, find the next one in the list.
12141 If the current buffer does not, find the first agenda file."
12142 (interactive)
12143 (let* ((fs (org-agenda-files t))
12144 (files (append fs (list (car fs))))
12145 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12146 file)
12147 (unless files (error "No agenda files"))
12148 (catch 'exit
12149 (while (setq file (pop files))
12150 (if (equal (file-truename file) tcf)
12151 (when (car files)
12152 (find-file (car files))
12153 (throw 'exit t))))
12154 (find-file (car fs)))
12155 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12157 (defun org-agenda-file-to-front (&optional to-end)
12158 "Move/add the current file to the top of the agenda file list.
12159 If the file is not present in the list, it is added to the front. If it is
12160 present, it is moved there. With optional argument TO-END, add/move to the
12161 end of the list."
12162 (interactive "P")
12163 (let ((org-agenda-skip-unavailable-files nil)
12164 (file-alist (mapcar (lambda (x)
12165 (cons (file-truename x) x))
12166 (org-agenda-files t)))
12167 (ctf (file-truename buffer-file-name))
12168 x had)
12169 (setq x (assoc ctf file-alist) had x)
12171 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12172 (if to-end
12173 (setq file-alist (append (delq x file-alist) (list x)))
12174 (setq file-alist (cons x (delq x file-alist))))
12175 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12176 (org-install-agenda-files-menu)
12177 (message "File %s to %s of agenda file list"
12178 (if had "moved" "added") (if to-end "end" "front"))))
12180 (defun org-remove-file (&optional file)
12181 "Remove current file from the list of files in variable `org-agenda-files'.
12182 These are the files which are being checked for agenda entries.
12183 Optional argument FILE means, use this file instead of the current."
12184 (interactive)
12185 (let* ((org-agenda-skip-unavailable-files nil)
12186 (file (or file buffer-file-name))
12187 (true-file (file-truename file))
12188 (afile (abbreviate-file-name file))
12189 (files (delq nil (mapcar
12190 (lambda (x)
12191 (if (equal true-file
12192 (file-truename x))
12193 nil x))
12194 (org-agenda-files t)))))
12195 (if (not (= (length files) (length (org-agenda-files t))))
12196 (progn
12197 (org-store-new-agenda-file-list files)
12198 (org-install-agenda-files-menu)
12199 (message "Removed file: %s" afile))
12200 (message "File was not in list: %s (not removed)" afile))))
12202 (defun org-file-menu-entry (file)
12203 (vector file (list 'find-file file) t))
12205 (defun org-check-agenda-file (file)
12206 "Make sure FILE exists. If not, ask user what to do."
12207 (when (not (file-exists-p file))
12208 (message "non-existent file %s. [R]emove from list or [A]bort?"
12209 (abbreviate-file-name file))
12210 (let ((r (downcase (read-char-exclusive))))
12211 (cond
12212 ((equal r ?r)
12213 (org-remove-file file)
12214 (throw 'nextfile t))
12215 (t (error "Abort"))))))
12217 (defun org-get-agenda-file-buffer (file)
12218 "Get a buffer visiting FILE. If the buffer needs to be created, add
12219 it to the list of buffers which might be released later."
12220 (let ((buf (org-find-base-buffer-visiting file)))
12221 (if buf
12222 buf ; just return it
12223 ;; Make a new buffer and remember it
12224 (setq buf (find-file-noselect file))
12225 (if buf (push buf org-agenda-new-buffers))
12226 buf)))
12228 (defun org-release-buffers (blist)
12229 "Release all buffers in list, asking the user for confirmation when needed.
12230 When a buffer is unmodified, it is just killed. When modified, it is saved
12231 \(if the user agrees) and then killed."
12232 (let (buf file)
12233 (while (setq buf (pop blist))
12234 (setq file (buffer-file-name buf))
12235 (when (and (buffer-modified-p buf)
12236 file
12237 (y-or-n-p (format "Save file %s? " file)))
12238 (with-current-buffer buf (save-buffer)))
12239 (kill-buffer buf))))
12241 (defun org-prepare-agenda-buffers (files)
12242 "Create buffers for all agenda files, protect archived trees and comments."
12243 (interactive)
12244 (let ((pa '(:org-archived t))
12245 (pc '(:org-comment t))
12246 (pall '(:org-archived t :org-comment t))
12247 (inhibit-read-only t)
12248 (rea (concat ":" org-archive-tag ":"))
12249 bmp file re)
12250 (save-excursion
12251 (save-restriction
12252 (while (setq file (pop files))
12253 (if (bufferp file)
12254 (set-buffer file)
12255 (org-check-agenda-file file)
12256 (set-buffer (org-get-agenda-file-buffer file)))
12257 (widen)
12258 (setq bmp (buffer-modified-p))
12259 (org-refresh-category-properties)
12260 (setq org-todo-keywords-for-agenda
12261 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12262 (setq org-done-keywords-for-agenda
12263 (append org-done-keywords-for-agenda org-done-keywords))
12264 (setq org-todo-keyword-alist-for-agenda
12265 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12266 (setq org-tag-alist-for-agenda
12267 (append org-tag-alist-for-agenda org-tag-alist))
12269 (save-excursion
12270 (remove-text-properties (point-min) (point-max) pall)
12271 (when org-agenda-skip-archived-trees
12272 (goto-char (point-min))
12273 (while (re-search-forward rea nil t)
12274 (if (org-on-heading-p t)
12275 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12276 (goto-char (point-min))
12277 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12278 (while (re-search-forward re nil t)
12279 (add-text-properties
12280 (match-beginning 0) (org-end-of-subtree t) pc)))
12281 (set-buffer-modified-p bmp))))
12282 (setq org-todo-keyword-alist-for-agenda
12283 (org-uniquify org-todo-keyword-alist-for-agenda)
12284 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12286 ;;;; Embedded LaTeX
12288 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12289 "Keymap for the minor `org-cdlatex-mode'.")
12291 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12292 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12293 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12294 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12295 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12297 (defvar org-cdlatex-texmathp-advice-is-done nil
12298 "Flag remembering if we have applied the advice to texmathp already.")
12300 (define-minor-mode org-cdlatex-mode
12301 "Toggle the minor `org-cdlatex-mode'.
12302 This mode supports entering LaTeX environment and math in LaTeX fragments
12303 in Org-mode.
12304 \\{org-cdlatex-mode-map}"
12305 nil " OCDL" nil
12306 (when org-cdlatex-mode (require 'cdlatex))
12307 (unless org-cdlatex-texmathp-advice-is-done
12308 (setq org-cdlatex-texmathp-advice-is-done t)
12309 (defadvice texmathp (around org-math-always-on activate)
12310 "Always return t in org-mode buffers.
12311 This is because we want to insert math symbols without dollars even outside
12312 the LaTeX math segments. If Orgmode thinks that point is actually inside
12313 an embedded LaTeX fragment, let texmathp do its job.
12314 \\[org-cdlatex-mode-map]"
12315 (interactive)
12316 (let (p)
12317 (cond
12318 ((not (org-mode-p)) ad-do-it)
12319 ((eq this-command 'cdlatex-math-symbol)
12320 (setq ad-return-value t
12321 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12323 (let ((p (org-inside-LaTeX-fragment-p)))
12324 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12325 (setq ad-return-value t
12326 texmathp-why '("Org-mode embedded math" . 0))
12327 (if p ad-do-it)))))))))
12329 (defun turn-on-org-cdlatex ()
12330 "Unconditionally turn on `org-cdlatex-mode'."
12331 (org-cdlatex-mode 1))
12333 (defun org-inside-LaTeX-fragment-p ()
12334 "Test if point is inside a LaTeX fragment.
12335 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12336 sequence appearing also before point.
12337 Even though the matchers for math are configurable, this function assumes
12338 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12339 delimiters are skipped when they have been removed by customization.
12340 The return value is nil, or a cons cell with the delimiter and
12341 and the position of this delimiter.
12343 This function does a reasonably good job, but can locally be fooled by
12344 for example currency specifications. For example it will assume being in
12345 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12346 fragments that are properly closed, but during editing, we have to live
12347 with the uncertainty caused by missing closing delimiters. This function
12348 looks only before point, not after."
12349 (catch 'exit
12350 (let ((pos (point))
12351 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12352 (lim (progn
12353 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12354 (point)))
12355 dd-on str (start 0) m re)
12356 (goto-char pos)
12357 (when dodollar
12358 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12359 re (nth 1 (assoc "$" org-latex-regexps)))
12360 (while (string-match re str start)
12361 (cond
12362 ((= (match-end 0) (length str))
12363 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12364 ((= (match-end 0) (- (length str) 5))
12365 (throw 'exit nil))
12366 (t (setq start (match-end 0))))))
12367 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12368 (goto-char pos)
12369 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12370 (and (match-beginning 2) (throw 'exit nil))
12371 ;; count $$
12372 (while (re-search-backward "\\$\\$" lim t)
12373 (setq dd-on (not dd-on)))
12374 (goto-char pos)
12375 (if dd-on (cons "$$" m))))))
12378 (defun org-try-cdlatex-tab ()
12379 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12380 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12381 - inside a LaTeX fragment, or
12382 - after the first word in a line, where an abbreviation expansion could
12383 insert a LaTeX environment."
12384 (when org-cdlatex-mode
12385 (cond
12386 ((save-excursion
12387 (skip-chars-backward "a-zA-Z0-9*")
12388 (skip-chars-backward " \t")
12389 (bolp))
12390 (cdlatex-tab) t)
12391 ((org-inside-LaTeX-fragment-p)
12392 (cdlatex-tab) t)
12393 (t nil))))
12395 (defun org-cdlatex-underscore-caret (&optional arg)
12396 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12397 Revert to the normal definition outside of these fragments."
12398 (interactive "P")
12399 (if (org-inside-LaTeX-fragment-p)
12400 (call-interactively 'cdlatex-sub-superscript)
12401 (let (org-cdlatex-mode)
12402 (call-interactively (key-binding (vector last-input-event))))))
12404 (defun org-cdlatex-math-modify (&optional arg)
12405 "Execute `cdlatex-math-modify' in LaTeX fragments.
12406 Revert to the normal definition outside of these fragments."
12407 (interactive "P")
12408 (if (org-inside-LaTeX-fragment-p)
12409 (call-interactively 'cdlatex-math-modify)
12410 (let (org-cdlatex-mode)
12411 (call-interactively (key-binding (vector last-input-event))))))
12413 (defvar org-latex-fragment-image-overlays nil
12414 "List of overlays carrying the images of latex fragments.")
12415 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12417 (defun org-remove-latex-fragment-image-overlays ()
12418 "Remove all overlays with LaTeX fragment images in current buffer."
12419 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12420 (setq org-latex-fragment-image-overlays nil))
12422 (defun org-preview-latex-fragment (&optional subtree)
12423 "Preview the LaTeX fragment at point, or all locally or globally.
12424 If the cursor is in a LaTeX fragment, create the image and overlay
12425 it over the source code. If there is no fragment at point, display
12426 all fragments in the current text, from one headline to the next. With
12427 prefix SUBTREE, display all fragments in the current subtree. With a
12428 double prefix `C-u C-u', or when the cursor is before the first headline,
12429 display all fragments in the buffer.
12430 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12431 (interactive "P")
12432 (org-remove-latex-fragment-image-overlays)
12433 (save-excursion
12434 (save-restriction
12435 (let (beg end at msg)
12436 (cond
12437 ((or (equal subtree '(16))
12438 (not (save-excursion
12439 (re-search-backward (concat "^" outline-regexp) nil t))))
12440 (setq beg (point-min) end (point-max)
12441 msg "Creating images for buffer...%s"))
12442 ((equal subtree '(4))
12443 (org-back-to-heading)
12444 (setq beg (point) end (org-end-of-subtree t)
12445 msg "Creating images for subtree...%s"))
12447 (if (setq at (org-inside-LaTeX-fragment-p))
12448 (goto-char (max (point-min) (- (cdr at) 2)))
12449 (org-back-to-heading))
12450 (setq beg (point) end (progn (outline-next-heading) (point))
12451 msg (if at "Creating image...%s"
12452 "Creating images for entry...%s"))))
12453 (message msg "")
12454 (narrow-to-region beg end)
12455 (goto-char beg)
12456 (org-format-latex
12457 (concat "ltxpng/" (file-name-sans-extension
12458 (file-name-nondirectory
12459 buffer-file-name)))
12460 default-directory 'overlays msg at 'forbuffer)
12461 (message msg "done. Use `C-c C-c' to remove images.")))))
12463 (defvar org-latex-regexps
12464 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12465 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12466 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12467 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12468 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12469 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12470 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12471 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12472 "Regular expressions for matching embedded LaTeX.")
12474 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12475 "Replace LaTeX fragments with links to an image, and produce images."
12476 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12477 (let* ((prefixnodir (file-name-nondirectory prefix))
12478 (absprefix (expand-file-name prefix dir))
12479 (todir (file-name-directory absprefix))
12480 (opt org-format-latex-options)
12481 (matchers (plist-get opt :matchers))
12482 (re-list org-latex-regexps)
12483 (cnt 0) txt link beg end re e checkdir
12484 m n block linkfile movefile ov)
12485 ;; Check if there are old images files with this prefix, and remove them
12486 (when (file-directory-p todir)
12487 (mapc 'delete-file
12488 (directory-files
12489 todir 'full
12490 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12491 ;; Check the different regular expressions
12492 (while (setq e (pop re-list))
12493 (setq m (car e) re (nth 1 e) n (nth 2 e)
12494 block (if (nth 3 e) "\n\n" ""))
12495 (when (member m matchers)
12496 (goto-char (point-min))
12497 (while (re-search-forward re nil t)
12498 (when (or (not at) (equal (cdr at) (match-beginning n)))
12499 (setq txt (match-string n)
12500 beg (match-beginning n) end (match-end n)
12501 cnt (1+ cnt)
12502 linkfile (format "%s_%04d.png" prefix cnt)
12503 movefile (format "%s_%04d.png" absprefix cnt)
12504 link (concat block "[[file:" linkfile "]]" block))
12505 (if msg (message msg cnt))
12506 (goto-char beg)
12507 (unless checkdir ; make sure the directory exists
12508 (setq checkdir t)
12509 (or (file-directory-p todir) (make-directory todir)))
12510 (org-create-formula-image
12511 txt movefile opt forbuffer)
12512 (if overlays
12513 (progn
12514 (setq ov (org-make-overlay beg end))
12515 (if (featurep 'xemacs)
12516 (progn
12517 (org-overlay-put ov 'invisible t)
12518 (org-overlay-put
12519 ov 'end-glyph
12520 (make-glyph (vector 'png :file movefile))))
12521 (org-overlay-put
12522 ov 'display
12523 (list 'image :type 'png :file movefile :ascent 'center)))
12524 (push ov org-latex-fragment-image-overlays)
12525 (goto-char end))
12526 (delete-region beg end)
12527 (insert link))))))))
12529 ;; This function borrows from Ganesh Swami's latex2png.el
12530 (defun org-create-formula-image (string tofile options buffer)
12531 (let* ((tmpdir (if (featurep 'xemacs)
12532 (temp-directory)
12533 temporary-file-directory))
12534 (texfilebase (make-temp-name
12535 (expand-file-name "orgtex" tmpdir)))
12536 (texfile (concat texfilebase ".tex"))
12537 (dvifile (concat texfilebase ".dvi"))
12538 (pngfile (concat texfilebase ".png"))
12539 (fnh (if (featurep 'xemacs)
12540 (font-height (get-face-font 'default))
12541 (face-attribute 'default :height nil)))
12542 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12543 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12544 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12545 "Black"))
12546 (bg (or (plist-get options (if buffer :background :html-background))
12547 "Transparent")))
12548 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12549 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12550 (with-temp-file texfile
12551 (insert org-format-latex-header
12552 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12553 (let ((dir default-directory))
12554 (condition-case nil
12555 (progn
12556 (cd tmpdir)
12557 (call-process "latex" nil nil nil texfile))
12558 (error nil))
12559 (cd dir))
12560 (if (not (file-exists-p dvifile))
12561 (progn (message "Failed to create dvi file from %s" texfile) nil)
12562 (condition-case nil
12563 (call-process "dvipng" nil nil nil
12564 "-E" "-fg" fg "-bg" bg
12565 "-D" dpi
12566 ;;"-x" scale "-y" scale
12567 "-T" "tight"
12568 "-o" pngfile
12569 dvifile)
12570 (error nil))
12571 (if (not (file-exists-p pngfile))
12572 (progn (message "Failed to create png file from %s" texfile) nil)
12573 ;; Use the requested file name and clean up
12574 (copy-file pngfile tofile 'replace)
12575 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12576 (delete-file (concat texfilebase e)))
12577 pngfile))))
12579 (defun org-dvipng-color (attr)
12580 "Return an rgb color specification for dvipng."
12581 (apply 'format "rgb %s %s %s"
12582 (mapcar 'org-normalize-color
12583 (color-values (face-attribute 'default attr nil)))))
12585 (defun org-normalize-color (value)
12586 "Return string to be used as color value for an RGB component."
12587 (format "%g" (/ value 65535.0)))
12589 ;;;; Key bindings
12591 ;; Make `C-c C-x' a prefix key
12592 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12594 ;; TAB key with modifiers
12595 (org-defkey org-mode-map "\C-i" 'org-cycle)
12596 (org-defkey org-mode-map [(tab)] 'org-cycle)
12597 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12598 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12599 (org-defkey org-mode-map "\M-\t" 'org-complete)
12600 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12601 ;; The following line is necessary under Suse GNU/Linux
12602 (unless (featurep 'xemacs)
12603 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12604 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12605 (define-key org-mode-map [backtab] 'org-shifttab)
12607 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12608 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12609 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12611 ;; Cursor keys with modifiers
12612 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12613 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12614 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12615 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12617 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12618 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12619 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12620 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12622 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12623 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12624 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12625 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12627 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12628 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12630 ;;; Extra keys for tty access.
12631 ;; We only set them when really needed because otherwise the
12632 ;; menus don't show the simple keys
12634 (when (or org-use-extra-keys
12635 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12636 (not window-system))
12637 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12638 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12639 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12640 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12641 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12642 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12643 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12644 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12645 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12646 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12647 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12648 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12649 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12650 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12651 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12652 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12653 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12654 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12655 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12656 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12657 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12658 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12660 ;; All the other keys
12662 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12663 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12664 (if (boundp 'narrow-map)
12665 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12666 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12667 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12668 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12669 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12670 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12671 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12672 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12673 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12674 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12675 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12676 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12677 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12678 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12679 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12680 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12681 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12682 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12683 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12684 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12685 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12686 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12687 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12688 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12689 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12690 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12691 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12692 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12693 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12694 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12695 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12696 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12697 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12698 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12699 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12700 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12701 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12702 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12703 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12704 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12705 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12706 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12707 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12708 (org-defkey org-mode-map "\C-c^" 'org-sort)
12709 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12710 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12711 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12712 (org-defkey org-mode-map "\C-m" 'org-return)
12713 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12714 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12715 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12716 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12717 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12718 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12719 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12720 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12721 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12722 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12723 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12724 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12725 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12726 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12727 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12728 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12729 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12731 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12732 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12733 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12734 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12736 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12737 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12738 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12739 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12740 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12741 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12742 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12743 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12744 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12745 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12746 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12747 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12749 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12750 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12751 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12752 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12754 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12756 (when (featurep 'xemacs)
12757 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12759 (defvar org-table-auto-blank-field) ; defined in org-table.el
12760 (defun org-self-insert-command (N)
12761 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12762 If the cursor is in a table looking at whitespace, the whitespace is
12763 overwritten, and the table is not marked as requiring realignment."
12764 (interactive "p")
12765 (if (and (org-table-p)
12766 (progn
12767 ;; check if we blank the field, and if that triggers align
12768 (and (featurep 'org-table) org-table-auto-blank-field
12769 (member last-command
12770 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12771 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12772 ;; got extra space, this field does not determine column width
12773 (let (org-table-may-need-update) (org-table-blank-field))
12774 ;; no extra space, this field may determine column width
12775 (org-table-blank-field)))
12777 (eq N 1)
12778 (looking-at "[^|\n]* |"))
12779 (let (org-table-may-need-update)
12780 (goto-char (1- (match-end 0)))
12781 (delete-backward-char 1)
12782 (goto-char (match-beginning 0))
12783 (self-insert-command N))
12784 (setq org-table-may-need-update t)
12785 (self-insert-command N)
12786 (org-fix-tags-on-the-fly)))
12788 (defun org-fix-tags-on-the-fly ()
12789 (when (and (equal (char-after (point-at-bol)) ?*)
12790 (org-on-heading-p))
12791 (org-align-tags-here org-tags-column)))
12793 (defun org-delete-backward-char (N)
12794 "Like `delete-backward-char', insert whitespace at field end in tables.
12795 When deleting backwards, in tables this function will insert whitespace in
12796 front of the next \"|\" separator, to keep the table aligned. The table will
12797 still be marked for re-alignment if the field did fill the entire column,
12798 because, in this case the deletion might narrow the column."
12799 (interactive "p")
12800 (if (and (org-table-p)
12801 (eq N 1)
12802 (string-match "|" (buffer-substring (point-at-bol) (point)))
12803 (looking-at ".*?|"))
12804 (let ((pos (point))
12805 (noalign (looking-at "[^|\n\r]* |"))
12806 (c org-table-may-need-update))
12807 (backward-delete-char N)
12808 (skip-chars-forward "^|")
12809 (insert " ")
12810 (goto-char (1- pos))
12811 ;; noalign: if there were two spaces at the end, this field
12812 ;; does not determine the width of the column.
12813 (if noalign (setq org-table-may-need-update c)))
12814 (backward-delete-char N)
12815 (org-fix-tags-on-the-fly)))
12817 (defun org-delete-char (N)
12818 "Like `delete-char', but insert whitespace at field end in tables.
12819 When deleting characters, in tables this function will insert whitespace in
12820 front of the next \"|\" separator, to keep the table aligned. The table will
12821 still be marked for re-alignment if the field did fill the entire column,
12822 because, in this case the deletion might narrow the column."
12823 (interactive "p")
12824 (if (and (org-table-p)
12825 (not (bolp))
12826 (not (= (char-after) ?|))
12827 (eq N 1))
12828 (if (looking-at ".*?|")
12829 (let ((pos (point))
12830 (noalign (looking-at "[^|\n\r]* |"))
12831 (c org-table-may-need-update))
12832 (replace-match (concat
12833 (substring (match-string 0) 1 -1)
12834 " |"))
12835 (goto-char pos)
12836 ;; noalign: if there were two spaces at the end, this field
12837 ;; does not determine the width of the column.
12838 (if noalign (setq org-table-may-need-update c)))
12839 (delete-char N))
12840 (delete-char N)
12841 (org-fix-tags-on-the-fly)))
12843 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12844 (put 'org-self-insert-command 'delete-selection t)
12845 (put 'orgtbl-self-insert-command 'delete-selection t)
12846 (put 'org-delete-char 'delete-selection 'supersede)
12847 (put 'org-delete-backward-char 'delete-selection 'supersede)
12849 ;; Make `flyspell-mode' delay after some commands
12850 (put 'org-self-insert-command 'flyspell-delayed t)
12851 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12852 (put 'org-delete-char 'flyspell-delayed t)
12853 (put 'org-delete-backward-char 'flyspell-delayed t)
12855 ;; Make pabbrev-mode expand after org-mode commands
12856 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12857 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12859 ;; How to do this: Measure non-white length of current string
12860 ;; If equal to column width, we should realign.
12862 (defun org-remap (map &rest commands)
12863 "In MAP, remap the functions given in COMMANDS.
12864 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12865 (let (new old)
12866 (while commands
12867 (setq old (pop commands) new (pop commands))
12868 (if (fboundp 'command-remapping)
12869 (org-defkey map (vector 'remap old) new)
12870 (substitute-key-definition old new map global-map)))))
12872 (when (eq org-enable-table-editor 'optimized)
12873 ;; If the user wants maximum table support, we need to hijack
12874 ;; some standard editing functions
12875 (org-remap org-mode-map
12876 'self-insert-command 'org-self-insert-command
12877 'delete-char 'org-delete-char
12878 'delete-backward-char 'org-delete-backward-char)
12879 (org-defkey org-mode-map "|" 'org-force-self-insert))
12881 (defun org-shiftcursor-error ()
12882 "Throw an error because Shift-Cursor command was applied in wrong context."
12883 (error "This command is active in special context like tables, headlines or timestamps"))
12885 (defun org-shifttab (&optional arg)
12886 "Global visibility cycling or move to previous table field.
12887 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12888 on context.
12889 See the individual commands for more information."
12890 (interactive "P")
12891 (cond
12892 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12893 ((integerp arg)
12894 (message "Content view to level: %d" arg)
12895 (org-content (prefix-numeric-value arg))
12896 (setq org-cycle-global-status 'overview))
12897 (t (call-interactively 'org-global-cycle))))
12899 (defun org-shiftmetaleft ()
12900 "Promote subtree or delete table column.
12901 Calls `org-promote-subtree', `org-outdent-item',
12902 or `org-table-delete-column', depending on context.
12903 See the individual commands for more information."
12904 (interactive)
12905 (cond
12906 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12907 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12908 ((org-at-item-p) (call-interactively 'org-outdent-item))
12909 (t (org-shiftcursor-error))))
12911 (defun org-shiftmetaright ()
12912 "Demote subtree or insert table column.
12913 Calls `org-demote-subtree', `org-indent-item',
12914 or `org-table-insert-column', depending on context.
12915 See the individual commands for more information."
12916 (interactive)
12917 (cond
12918 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12919 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12920 ((org-at-item-p) (call-interactively 'org-indent-item))
12921 (t (org-shiftcursor-error))))
12923 (defun org-shiftmetaup (&optional arg)
12924 "Move subtree up or kill table row.
12925 Calls `org-move-subtree-up' or `org-table-kill-row' or
12926 `org-move-item-up' depending on context. See the individual commands
12927 for more information."
12928 (interactive "P")
12929 (cond
12930 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12931 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12932 ((org-at-item-p) (call-interactively 'org-move-item-up))
12933 (t (org-shiftcursor-error))))
12934 (defun org-shiftmetadown (&optional arg)
12935 "Move subtree down or insert table row.
12936 Calls `org-move-subtree-down' or `org-table-insert-row' or
12937 `org-move-item-down', depending on context. See the individual
12938 commands for more information."
12939 (interactive "P")
12940 (cond
12941 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12942 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12943 ((org-at-item-p) (call-interactively 'org-move-item-down))
12944 (t (org-shiftcursor-error))))
12946 (defun org-metaleft (&optional arg)
12947 "Promote heading or move table column to left.
12948 Calls `org-do-promote' or `org-table-move-column', depending on context.
12949 With no specific context, calls the Emacs default `backward-word'.
12950 See the individual commands for more information."
12951 (interactive "P")
12952 (cond
12953 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12954 ((or (org-on-heading-p) (org-region-active-p))
12955 (call-interactively 'org-do-promote))
12956 ((org-at-item-p) (call-interactively 'org-outdent-item))
12957 (t (call-interactively 'backward-word))))
12959 (defun org-metaright (&optional arg)
12960 "Demote subtree or move table column to right.
12961 Calls `org-do-demote' or `org-table-move-column', depending on context.
12962 With no specific context, calls the Emacs default `forward-word'.
12963 See the individual commands for more information."
12964 (interactive "P")
12965 (cond
12966 ((org-at-table-p) (call-interactively 'org-table-move-column))
12967 ((or (org-on-heading-p) (org-region-active-p))
12968 (call-interactively 'org-do-demote))
12969 ((org-at-item-p) (call-interactively 'org-indent-item))
12970 (t (call-interactively 'forward-word))))
12972 (defun org-metaup (&optional arg)
12973 "Move subtree up or move table row up.
12974 Calls `org-move-subtree-up' or `org-table-move-row' or
12975 `org-move-item-up', depending on context. See the individual commands
12976 for more information."
12977 (interactive "P")
12978 (cond
12979 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12980 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12981 ((org-at-item-p) (call-interactively 'org-move-item-up))
12982 (t (transpose-lines 1) (beginning-of-line -1))))
12984 (defun org-metadown (&optional arg)
12985 "Move subtree down or move table row down.
12986 Calls `org-move-subtree-down' or `org-table-move-row' or
12987 `org-move-item-down', depending on context. See the individual
12988 commands for more information."
12989 (interactive "P")
12990 (cond
12991 ((org-at-table-p) (call-interactively 'org-table-move-row))
12992 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12993 ((org-at-item-p) (call-interactively 'org-move-item-down))
12994 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12996 (defun org-shiftup (&optional arg)
12997 "Increase item in timestamp or increase priority of current headline.
12998 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12999 depending on context. See the individual commands for more information."
13000 (interactive "P")
13001 (cond
13002 ((org-at-timestamp-p t)
13003 (call-interactively (if org-edit-timestamp-down-means-later
13004 'org-timestamp-down 'org-timestamp-up)))
13005 ((org-on-heading-p) (call-interactively 'org-priority-up))
13006 ((org-at-item-p) (call-interactively 'org-previous-item))
13007 ((org-clocktable-try-shift 'up arg))
13008 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
13010 (defun org-shiftdown (&optional arg)
13011 "Decrease item in timestamp or decrease priority of current headline.
13012 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13013 depending on context. See the individual commands for more information."
13014 (interactive "P")
13015 (cond
13016 ((org-at-timestamp-p t)
13017 (call-interactively (if org-edit-timestamp-down-means-later
13018 'org-timestamp-up 'org-timestamp-down)))
13019 ((org-on-heading-p) (call-interactively 'org-priority-down))
13020 ((org-clocktable-try-shift 'down arg))
13021 (t (call-interactively 'org-next-item))))
13023 (defun org-shiftright (&optional arg)
13024 "Cycle the thing at point or in the current line, depending on context.
13025 Depending on context, this does one of the following:
13027 - switch a timestamp at point one day into the future
13028 - on a headline, switch to the next TODO keyword.
13029 - on an item, switch entire list to the next bullet type
13030 - on a property line, switch to the next allowed value
13031 - on a clocktable definition line, move time block into the future"
13032 (interactive "P")
13033 (cond
13034 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13035 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13036 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13037 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13038 ((org-clocktable-try-shift 'right arg))
13039 (t (org-shiftcursor-error))))
13041 (defun org-shiftleft (&optional arg)
13042 "Cycle the thing at point or in the current line, depending on context.
13043 Depending on context, this does one of the following:
13045 - switch a timestamp at point one day into the past
13046 - on a headline, switch to the previous TODO keyword.
13047 - on an item, switch entire list to the previous bullet type
13048 - on a property line, switch to the previous allowed value
13049 - on a clocktable definition line, move time block into the past"
13050 (interactive "P")
13051 (cond
13052 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13053 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13054 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13055 ((org-at-property-p)
13056 (call-interactively 'org-property-previous-allowed-value))
13057 ((org-clocktable-try-shift 'left arg))
13058 (t (org-shiftcursor-error))))
13060 (defun org-shiftcontrolright ()
13061 "Switch to next TODO set."
13062 (interactive)
13063 (cond
13064 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13065 (t (org-shiftcursor-error))))
13067 (defun org-shiftcontrolleft ()
13068 "Switch to previous TODO set."
13069 (interactive)
13070 (cond
13071 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13072 (t (org-shiftcursor-error))))
13074 (defun org-ctrl-c-ret ()
13075 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13076 (interactive)
13077 (cond
13078 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13079 (t (call-interactively 'org-insert-heading))))
13081 (defun org-copy-special ()
13082 "Copy region in table or copy current subtree.
13083 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13084 See the individual commands for more information."
13085 (interactive)
13086 (call-interactively
13087 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13089 (defun org-cut-special ()
13090 "Cut region in table or cut current subtree.
13091 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13092 See the individual commands for more information."
13093 (interactive)
13094 (call-interactively
13095 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13097 (defun org-paste-special (arg)
13098 "Paste rectangular region into table, or past subtree relative to level.
13099 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13100 See the individual commands for more information."
13101 (interactive "P")
13102 (if (org-at-table-p)
13103 (org-table-paste-rectangle)
13104 (org-paste-subtree arg)))
13106 (defun org-edit-special ()
13107 "Call a special editor for the stuff at point.
13108 When at a table, call the formula editor with `org-table-edit-formulas'.
13109 When at the first line of an src example, call `org-edit-src-code'.
13110 When in an #+include line, visit the include file. Otherwise call
13111 `ffap' to visit the file at point."
13112 (interactive)
13113 (cond
13114 ((org-at-table-p)
13115 (call-interactively 'org-table-edit-formulas))
13116 ((save-excursion
13117 (beginning-of-line 1)
13118 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13119 (find-file (org-trim (match-string 1))))
13120 ((org-edit-src-code))
13121 ((org-edit-fixed-width-region))
13122 (t (call-interactively 'ffap))))
13124 (defun org-ctrl-c-ctrl-c (&optional arg)
13125 "Set tags in headline, or update according to changed information at point.
13127 This command does many different things, depending on context:
13129 - If the cursor is in a headline, prompt for tags and insert them
13130 into the current line, aligned to `org-tags-column'. When called
13131 with prefix arg, realign all tags in the current buffer.
13133 - If the cursor is in one of the special #+KEYWORD lines, this
13134 triggers scanning the buffer for these lines and updating the
13135 information.
13137 - If the cursor is inside a table, realign the table. This command
13138 works even if the automatic table editor has been turned off.
13140 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13141 the entire table.
13143 - If the cursor is at a footnote reference or definition, jump to
13144 the corresponding definition or references, respectively.
13146 - If the cursor is a the beginning of a dynamic block, update it.
13148 - If the cursor is inside a table created by the table.el package,
13149 activate that table.
13151 - If the current buffer is a remember buffer, close note and file
13152 it. A prefix argument of 1 files to the default location
13153 without further interaction. A prefix argument of 2 files to
13154 the currently clocking task.
13156 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13157 links in this buffer.
13159 - If the cursor is on a numbered item in a plain list, renumber the
13160 ordered list.
13162 - If the cursor is on a checkbox, toggle it."
13163 (interactive "P")
13164 (let ((org-enable-table-editor t))
13165 (cond
13166 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13167 org-occur-highlights
13168 org-latex-fragment-image-overlays)
13169 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13170 (org-remove-occur-highlights)
13171 (org-remove-latex-fragment-image-overlays)
13172 (message "Temporary highlights/overlays removed from current buffer"))
13173 ((and (local-variable-p 'org-finish-function (current-buffer))
13174 (fboundp org-finish-function))
13175 (funcall org-finish-function))
13176 ((org-at-property-p)
13177 (call-interactively 'org-property-action))
13178 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13179 ((org-on-heading-p) (call-interactively 'org-set-tags))
13180 ((org-at-table.el-p)
13181 (require 'table)
13182 (beginning-of-line 1)
13183 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13184 (call-interactively 'table-recognize-table))
13185 ((org-at-table-p)
13186 (org-table-maybe-eval-formula)
13187 (if arg
13188 (call-interactively 'org-table-recalculate)
13189 (org-table-maybe-recalculate-line))
13190 (call-interactively 'org-table-align))
13191 ((or (org-footnote-at-reference-p)
13192 (org-footnote-at-definition-p))
13193 (call-interactively 'org-footnote-action))
13194 ((org-at-item-checkbox-p)
13195 (call-interactively 'org-toggle-checkbox))
13196 ((org-at-item-p)
13197 (call-interactively 'org-maybe-renumber-ordered-list))
13198 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13199 ;; Dynamic block
13200 (beginning-of-line 1)
13201 (save-excursion (org-update-dblock)))
13202 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13203 (cond
13204 ((equal (match-string 1) "TBLFM")
13205 ;; Recalculate the table before this line
13206 (save-excursion
13207 (beginning-of-line 1)
13208 (skip-chars-backward " \r\n\t")
13209 (if (org-at-table-p)
13210 (org-call-with-arg 'org-table-recalculate t))))
13212 ; (org-set-regexps-and-options)
13213 ; (org-restart-font-lock)
13214 (let ((org-inhibit-startup t)) (org-mode-restart))
13215 (message "Local setup has been refreshed"))))
13216 (t (error "C-c C-c can do nothing useful at this location.")))))
13218 (defun org-mode-restart ()
13219 "Restart Org-mode, to scan again for special lines.
13220 Also updates the keyword regular expressions."
13221 (interactive)
13222 (org-mode)
13223 (message "Org-mode restarted"))
13225 (defun org-kill-note-or-show-branches ()
13226 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13227 (interactive)
13228 (if (not org-finish-function)
13229 (call-interactively 'show-branches)
13230 (let ((org-note-abort t))
13231 (funcall org-finish-function))))
13233 (defun org-return (&optional indent)
13234 "Goto next table row or insert a newline.
13235 Calls `org-table-next-row' or `newline', depending on context.
13236 See the individual commands for more information."
13237 (interactive)
13238 (cond
13239 ((bobp) (if indent (newline-and-indent) (newline)))
13240 ((and (org-at-heading-p)
13241 (looking-at
13242 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13243 (org-show-entry)
13244 (end-of-line 1)
13245 (newline))
13246 ((org-at-table-p)
13247 (org-table-justify-field-maybe)
13248 (call-interactively 'org-table-next-row))
13249 (t (if indent (newline-and-indent) (newline)))))
13251 (defun org-return-indent ()
13252 "Goto next table row or insert a newline and indent.
13253 Calls `org-table-next-row' or `newline-and-indent', depending on
13254 context. See the individual commands for more information."
13255 (interactive)
13256 (org-return t))
13258 (defun org-ctrl-c-star ()
13259 "Compute table, or change heading status of lines.
13260 Calls `org-table-recalculate' or `org-toggle-region-headings',
13261 depending on context. This will also turn a plain list item or a normal
13262 line into a subheading."
13263 (interactive)
13264 (cond
13265 ((org-at-table-p)
13266 (call-interactively 'org-table-recalculate))
13267 ((org-region-active-p)
13268 ;; Convert all lines in region to list items
13269 (call-interactively 'org-toggle-region-headings))
13270 ((org-on-heading-p)
13271 (org-toggle-region-headings (point-at-bol)
13272 (min (1+ (point-at-eol)) (point-max))))
13273 ((org-at-item-p)
13274 ;; Convert to heading
13275 (let ((level (save-match-data
13276 (save-excursion
13277 (condition-case nil
13278 (progn
13279 (org-back-to-heading t)
13280 (funcall outline-level))
13281 (error 0))))))
13282 (replace-match
13283 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13284 (t (org-toggle-region-headings (point-at-bol)
13285 (min (1+ (point-at-eol)) (point-max))))))
13287 (defun org-ctrl-c-minus ()
13288 "Insert separator line in table or modify bullet status of line.
13289 Also turns a plain line or a region of lines into list items.
13290 Calls `org-table-insert-hline', `org-toggle-region-items', or
13291 `org-cycle-list-bullet', depending on context."
13292 (interactive)
13293 (cond
13294 ((org-at-table-p)
13295 (call-interactively 'org-table-insert-hline))
13296 ((org-on-heading-p)
13297 ;; Convert to item
13298 (save-excursion
13299 (beginning-of-line 1)
13300 (if (looking-at "\\*+ ")
13301 (replace-match
13302 (concat (make-string
13303 (- (match-end 0) (point) (if org-odd-levels-only 2 1)) ?\ )
13304 "- ")))))
13305 ((org-region-active-p)
13306 ;; Convert all lines in region to list items
13307 (call-interactively 'org-toggle-region-items))
13308 ((org-in-item-p)
13309 (call-interactively 'org-cycle-list-bullet))
13310 (t (org-toggle-region-items (point-at-bol)
13311 (min (1+ (point-at-eol)) (point-max))))))
13313 (defun org-toggle-region-items (beg end)
13314 "Convert all lines in region to list items.
13315 If the first line is already an item, convert all list items in the region
13316 to normal lines."
13317 (interactive "r")
13318 (let (l2 l)
13319 (save-excursion
13320 (goto-char end)
13321 (setq l2 (org-current-line))
13322 (goto-char beg)
13323 (beginning-of-line 1)
13324 (setq l (1- (org-current-line)))
13325 (if (org-at-item-p)
13326 ;; We already have items, de-itemize
13327 (while (< (setq l (1+ l)) l2)
13328 (when (org-at-item-p)
13329 (goto-char (match-beginning 2))
13330 (delete-region (match-beginning 2) (match-end 2))
13331 (and (looking-at "[ \t]+") (replace-match "")))
13332 (beginning-of-line 2))
13333 (while (< (setq l (1+ l)) l2)
13334 (unless (org-at-item-p)
13335 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13336 (replace-match "\\1- \\2")))
13337 (beginning-of-line 2))))))
13339 (defun org-toggle-region-headings (beg end)
13340 "Convert all lines in region to list items.
13341 If the first line is already an item, convert all list items in the region
13342 to normal lines."
13343 (interactive "r")
13344 (let (l2 l)
13345 (save-excursion
13346 (goto-char end)
13347 (setq l2 (org-current-line))
13348 (goto-char beg)
13349 (beginning-of-line 1)
13350 (setq l (1- (org-current-line)))
13351 (if (org-on-heading-p)
13352 ;; We already have headlines, de-star them
13353 (while (< (setq l (1+ l)) l2)
13354 (when (org-on-heading-p t)
13355 (and (looking-at outline-regexp) (replace-match "")))
13356 (beginning-of-line 2))
13357 (let* ((stars (save-excursion
13358 (re-search-backward org-complex-heading-regexp nil t)
13359 (or (match-string 1) "*")))
13360 (add-stars (if org-odd-levels-only "**" "*"))
13361 (rpl (concat stars add-stars " \\2")))
13362 (while (< (setq l (1+ l)) l2)
13363 (unless (org-on-heading-p)
13364 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13365 (replace-match rpl)))
13366 (beginning-of-line 2)))))))
13368 (defun org-meta-return (&optional arg)
13369 "Insert a new heading or wrap a region in a table.
13370 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13371 See the individual commands for more information."
13372 (interactive "P")
13373 (cond
13374 ((org-at-table-p)
13375 (call-interactively 'org-table-wrap-region))
13376 (t (call-interactively 'org-insert-heading))))
13378 ;;; Menu entries
13380 ;; Define the Org-mode menus
13381 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13382 '("Tbl"
13383 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13384 ["Next Field" org-cycle (org-at-table-p)]
13385 ["Previous Field" org-shifttab (org-at-table-p)]
13386 ["Next Row" org-return (org-at-table-p)]
13387 "--"
13388 ["Blank Field" org-table-blank-field (org-at-table-p)]
13389 ["Edit Field" org-table-edit-field (org-at-table-p)]
13390 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13391 "--"
13392 ("Column"
13393 ["Move Column Left" org-metaleft (org-at-table-p)]
13394 ["Move Column Right" org-metaright (org-at-table-p)]
13395 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13396 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13397 ("Row"
13398 ["Move Row Up" org-metaup (org-at-table-p)]
13399 ["Move Row Down" org-metadown (org-at-table-p)]
13400 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13401 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13402 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13403 "--"
13404 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13405 ("Rectangle"
13406 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13407 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13408 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13409 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13410 "--"
13411 ("Calculate"
13412 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13413 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13414 ["Edit Formulas" org-edit-special (org-at-table-p)]
13415 "--"
13416 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13417 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13418 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13419 "--"
13420 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13421 "--"
13422 ["Sum Column/Rectangle" org-table-sum
13423 (or (org-at-table-p) (org-region-active-p))]
13424 ["Which Column?" org-table-current-column (org-at-table-p)])
13425 ["Debug Formulas"
13426 org-table-toggle-formula-debugger
13427 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13428 ["Show Col/Row Numbers"
13429 org-table-toggle-coordinate-overlays
13430 :style toggle
13431 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13432 "--"
13433 ["Create" org-table-create (and (not (org-at-table-p))
13434 org-enable-table-editor)]
13435 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13436 ["Import from File" org-table-import (not (org-at-table-p))]
13437 ["Export to File" org-table-export (org-at-table-p)]
13438 "--"
13439 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13441 (easy-menu-define org-org-menu org-mode-map "Org menu"
13442 '("Org"
13443 ("Show/Hide"
13444 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13445 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13446 ["Sparse Tree..." org-sparse-tree t]
13447 ["Reveal Context" org-reveal t]
13448 ["Show All" show-all t]
13449 "--"
13450 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13451 "--"
13452 ["New Heading" org-insert-heading t]
13453 ("Navigate Headings"
13454 ["Up" outline-up-heading t]
13455 ["Next" outline-next-visible-heading t]
13456 ["Previous" outline-previous-visible-heading t]
13457 ["Next Same Level" outline-forward-same-level t]
13458 ["Previous Same Level" outline-backward-same-level t]
13459 "--"
13460 ["Jump" org-goto t])
13461 ("Edit Structure"
13462 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13463 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13464 "--"
13465 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13466 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13467 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13468 "--"
13469 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13470 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13471 ["Demote Heading" org-metaright (not (org-at-table-p))]
13472 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13473 "--"
13474 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13475 "--"
13476 ["Convert to odd levels" org-convert-to-odd-levels t]
13477 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13478 ("Editing"
13479 ["Emphasis..." org-emphasize t]
13480 ["Edit Source Example" org-edit-special t]
13481 "--"
13482 ["Footnote new/jump" org-footnote-action t]
13483 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13484 ("Archive"
13485 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13486 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13487 ; :active t :keys "C-u C-c C-x C-a"]
13488 ["Sparse trees open ARCHIVE trees"
13489 (setq org-sparse-tree-open-archived-trees
13490 (not org-sparse-tree-open-archived-trees))
13491 :style toggle :selected org-sparse-tree-open-archived-trees]
13492 ["Cycling opens ARCHIVE trees"
13493 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13494 :style toggle :selected org-cycle-open-archived-trees]
13495 "--"
13496 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13497 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13498 ; ["Check and Move Children" (org-archive-subtree '(4))
13499 ; :active t :keys "C-u C-c C-x C-s"]
13501 "--"
13502 ("TODO Lists"
13503 ["TODO/DONE/-" org-todo t]
13504 ("Select keyword"
13505 ["Next keyword" org-shiftright (org-on-heading-p)]
13506 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13507 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13508 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13509 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13510 ["Show TODO Tree" org-show-todo-tree t]
13511 ["Global TODO list" org-todo-list t]
13512 "--"
13513 ["Set Priority" org-priority t]
13514 ["Priority Up" org-shiftup t]
13515 ["Priority Down" org-shiftdown t])
13516 ("TAGS and Properties"
13517 ["Set Tags" org-set-tags-command t]
13518 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13519 "--"
13520 ["Set property" org-set-property t]
13521 ["Column view of properties" org-columns t]
13522 ["Insert Column View DBlock" org-insert-columns-dblock t])
13523 ("Dates and Scheduling"
13524 ["Timestamp" org-time-stamp t]
13525 ["Timestamp (inactive)" org-time-stamp-inactive t]
13526 ("Change Date"
13527 ["1 Day Later" org-shiftright t]
13528 ["1 Day Earlier" org-shiftleft t]
13529 ["1 ... Later" org-shiftup t]
13530 ["1 ... Earlier" org-shiftdown t])
13531 ["Compute Time Range" org-evaluate-time-range t]
13532 ["Schedule Item" org-schedule t]
13533 ["Deadline" org-deadline t]
13534 "--"
13535 ["Custom time format" org-toggle-time-stamp-overlays
13536 :style radio :selected org-display-custom-times]
13537 "--"
13538 ["Goto Calendar" org-goto-calendar t]
13539 ["Date from Calendar" org-date-from-calendar t]
13540 "--"
13541 ["Start/Restart Timer" org-timer-start t]
13542 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13543 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13544 ["Insert Timer String" org-timer t]
13545 ["Insert Timer Item" org-timer-item t])
13546 ("Logging work"
13547 ["Clock in" org-clock-in t]
13548 ["Clock out" org-clock-out t]
13549 ["Clock cancel" org-clock-cancel t]
13550 ["Goto running clock" org-clock-goto t]
13551 ["Display times" org-clock-display t]
13552 ["Create clock table" org-clock-report t]
13553 "--"
13554 ["Record DONE time"
13555 (progn (setq org-log-done (not org-log-done))
13556 (message "Switching to %s will %s record a timestamp"
13557 (car org-done-keywords)
13558 (if org-log-done "automatically" "not")))
13559 :style toggle :selected org-log-done])
13560 "--"
13561 ["Agenda Command..." org-agenda t]
13562 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13563 ("File List for Agenda")
13564 ("Special views current file"
13565 ["TODO Tree" org-show-todo-tree t]
13566 ["Check Deadlines" org-check-deadlines t]
13567 ["Timeline" org-timeline t]
13568 ["Tags Tree" org-tags-sparse-tree t])
13569 "--"
13570 ("Hyperlinks"
13571 ["Store Link (Global)" org-store-link t]
13572 ["Insert Link" org-insert-link t]
13573 ["Follow Link" org-open-at-point t]
13574 "--"
13575 ["Next link" org-next-link t]
13576 ["Previous link" org-previous-link t]
13577 "--"
13578 ["Descriptive Links"
13579 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13580 :style radio
13581 :selected (member '(org-link) buffer-invisibility-spec)]
13582 ["Literal Links"
13583 (progn
13584 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13585 :style radio
13586 :selected (not (member '(org-link) buffer-invisibility-spec))])
13587 "--"
13588 ["Export/Publish..." org-export t]
13589 ("LaTeX"
13590 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13591 :selected org-cdlatex-mode]
13592 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13593 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13594 ["Modify math symbol" org-cdlatex-math-modify
13595 (org-inside-LaTeX-fragment-p)]
13596 ["Export LaTeX fragments as images"
13597 (if (featurep 'org-exp)
13598 (setq org-export-with-LaTeX-fragments
13599 (not org-export-with-LaTeX-fragments))
13600 (require 'org-exp))
13601 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13602 org-export-with-LaTeX-fragments)])
13603 "--"
13604 ("Documentation"
13605 ["Show Version" org-version t]
13606 ["Info Documentation" org-info t])
13607 ("Customize"
13608 ["Browse Org Group" org-customize t]
13609 "--"
13610 ["Expand This Menu" org-create-customize-menu
13611 (fboundp 'customize-menu-create)])
13612 "--"
13613 ["Refresh setup" org-mode-restart t]
13616 (defun org-info (&optional node)
13617 "Read documentation for Org-mode in the info system.
13618 With optional NODE, go directly to that node."
13619 (interactive)
13620 (info (format "(org)%s" (or node ""))))
13622 (defun org-install-agenda-files-menu ()
13623 (let ((bl (buffer-list)))
13624 (save-excursion
13625 (while bl
13626 (set-buffer (pop bl))
13627 (if (org-mode-p) (setq bl nil)))
13628 (when (org-mode-p)
13629 (easy-menu-change
13630 '("Org") "File List for Agenda"
13631 (append
13632 (list
13633 ["Edit File List" (org-edit-agenda-file-list) t]
13634 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13635 ["Remove Current File from List" org-remove-file t]
13636 ["Cycle through agenda files" org-cycle-agenda-files t]
13637 ["Occur in all agenda files" org-occur-in-agenda-files t]
13638 "--")
13639 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13641 ;;;; Documentation
13643 ;;;###autoload
13644 (defun org-require-autoloaded-modules ()
13645 (interactive)
13646 (mapc 'require
13647 '(org-agenda org-archive org-clock org-colview
13648 org-exp org-id org-export-latex org-publish
13649 org-remember org-table)))
13651 ;;;###autoload
13652 (defun org-customize ()
13653 "Call the customize function with org as argument."
13654 (interactive)
13655 (org-load-modules-maybe)
13656 (org-require-autoloaded-modules)
13657 (customize-browse 'org))
13659 (defun org-create-customize-menu ()
13660 "Create a full customization menu for Org-mode, insert it into the menu."
13661 (interactive)
13662 (org-load-modules-maybe)
13663 (org-require-autoloaded-modules)
13664 (if (fboundp 'customize-menu-create)
13665 (progn
13666 (easy-menu-change
13667 '("Org") "Customize"
13668 `(["Browse Org group" org-customize t]
13669 "--"
13670 ,(customize-menu-create 'org)
13671 ["Set" Custom-set t]
13672 ["Save" Custom-save t]
13673 ["Reset to Current" Custom-reset-current t]
13674 ["Reset to Saved" Custom-reset-saved t]
13675 ["Reset to Standard Settings" Custom-reset-standard t]))
13676 (message "\"Org\"-menu now contains full customization menu"))
13677 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13679 ;;;; Miscellaneous stuff
13681 ;;; Generally useful functions
13683 (defun org-find-text-property-in-string (prop s)
13684 "Return the first non-nil value of property PROP in string S."
13685 (or (get-text-property 0 prop s)
13686 (get-text-property (or (next-single-property-change 0 prop s) 0)
13687 prop s)))
13689 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13690 "Display the given MESSAGE as a warning."
13691 (if (fboundp 'display-warning)
13692 (display-warning 'org message
13693 (if (featurep 'xemacs)
13694 'warning
13695 :warning))
13696 (let ((buf (get-buffer-create "*Org warnings*")))
13697 (with-current-buffer buf
13698 (goto-char (point-max))
13699 (insert "Warning (Org): " message)
13700 (unless (bolp)
13701 (newline)))
13702 (display-buffer buf)
13703 (sit-for 0))))
13705 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13706 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13707 (if (and marker (marker-buffer marker)
13708 (buffer-live-p (marker-buffer marker)))
13709 (progn
13710 (switch-to-buffer (marker-buffer marker))
13711 (if (or (> marker (point-max)) (< marker (point-min)))
13712 (widen))
13713 (goto-char marker)
13714 (org-show-context 'org-goto))
13715 (if bookmark
13716 (bookmark-jump bookmark)
13717 (error "Cannot find location"))))
13719 (defun org-quote-csv-field (s)
13720 "Quote field for inclusion in CSV material."
13721 (if (string-match "[\",]" s)
13722 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13725 (defun org-plist-delete (plist property)
13726 "Delete PROPERTY from PLIST.
13727 This is in contrast to merely setting it to 0."
13728 (let (p)
13729 (while plist
13730 (if (not (eq property (car plist)))
13731 (setq p (plist-put p (car plist) (nth 1 plist))))
13732 (setq plist (cddr plist)))
13735 (defun org-force-self-insert (N)
13736 "Needed to enforce self-insert under remapping."
13737 (interactive "p")
13738 (self-insert-command N))
13740 (defun org-string-width (s)
13741 "Compute width of string, ignoring invisible characters.
13742 This ignores character with invisibility property `org-link', and also
13743 characters with property `org-cwidth', because these will become invisible
13744 upon the next fontification round."
13745 (let (b l)
13746 (when (or (eq t buffer-invisibility-spec)
13747 (assq 'org-link buffer-invisibility-spec))
13748 (while (setq b (text-property-any 0 (length s)
13749 'invisible 'org-link s))
13750 (setq s (concat (substring s 0 b)
13751 (substring s (or (next-single-property-change
13752 b 'invisible s) (length s)))))))
13753 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13754 (setq s (concat (substring s 0 b)
13755 (substring s (or (next-single-property-change
13756 b 'org-cwidth s) (length s))))))
13757 (setq l (string-width s) b -1)
13758 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13759 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13762 (defun org-get-indentation (&optional line)
13763 "Get the indentation of the current line, interpreting tabs.
13764 When LINE is given, assume it represents a line and compute its indentation."
13765 (if line
13766 (if (string-match "^ *" (org-remove-tabs line))
13767 (match-end 0))
13768 (save-excursion
13769 (beginning-of-line 1)
13770 (skip-chars-forward " \t")
13771 (current-column))))
13773 (defun org-remove-tabs (s &optional width)
13774 "Replace tabulators in S with spaces.
13775 Assumes that s is a single line, starting in column 0."
13776 (setq width (or width tab-width))
13777 (while (string-match "\t" s)
13778 (setq s (replace-match
13779 (make-string
13780 (- (* width (/ (+ (match-beginning 0) width) width))
13781 (match-beginning 0)) ?\ )
13782 t t s)))
13785 (defun org-fix-indentation (line ind)
13786 "Fix indentation in LINE.
13787 IND is a cons cell with target and minimum indentation.
13788 If the current indentation in LINE is smaller than the minimum,
13789 leave it alone. If it is larger than ind, set it to the target."
13790 (let* ((l (org-remove-tabs line))
13791 (i (org-get-indentation l))
13792 (i1 (car ind)) (i2 (cdr ind)))
13793 (if (>= i i2) (setq l (substring line i2)))
13794 (if (> i1 0)
13795 (concat (make-string i1 ?\ ) l)
13796 l)))
13798 (defun org-base-buffer (buffer)
13799 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13800 (if (not buffer)
13801 buffer
13802 (or (buffer-base-buffer buffer)
13803 buffer)))
13805 (defun org-trim (s)
13806 "Remove whitespace at beginning and end of string."
13807 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13808 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13811 (defun org-wrap (string &optional width lines)
13812 "Wrap string to either a number of lines, or a width in characters.
13813 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13814 that costs. If there is a word longer than WIDTH, the text is actually
13815 wrapped to the length of that word.
13816 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13817 many lines, whatever width that takes.
13818 The return value is a list of lines, without newlines at the end."
13819 (let* ((words (org-split-string string "[ \t\n]+"))
13820 (maxword (apply 'max (mapcar 'org-string-width words)))
13821 w ll)
13822 (cond (width
13823 (org-do-wrap words (max maxword width)))
13824 (lines
13825 (setq w maxword)
13826 (setq ll (org-do-wrap words maxword))
13827 (if (<= (length ll) lines)
13829 (setq ll words)
13830 (while (> (length ll) lines)
13831 (setq w (1+ w))
13832 (setq ll (org-do-wrap words w)))
13833 ll))
13834 (t (error "Cannot wrap this")))))
13836 (defun org-do-wrap (words width)
13837 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13838 (let (lines line)
13839 (while words
13840 (setq line (pop words))
13841 (while (and words (< (+ (length line) (length (car words))) width))
13842 (setq line (concat line " " (pop words))))
13843 (setq lines (push line lines)))
13844 (nreverse lines)))
13846 (defun org-split-string (string &optional separators)
13847 "Splits STRING into substrings at SEPARATORS.
13848 No empty strings are returned if there are matches at the beginning
13849 and end of string."
13850 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13851 (start 0)
13852 notfirst
13853 (list nil))
13854 (while (and (string-match rexp string
13855 (if (and notfirst
13856 (= start (match-beginning 0))
13857 (< start (length string)))
13858 (1+ start) start))
13859 (< (match-beginning 0) (length string)))
13860 (setq notfirst t)
13861 (or (eq (match-beginning 0) 0)
13862 (and (eq (match-beginning 0) (match-end 0))
13863 (eq (match-beginning 0) start))
13864 (setq list
13865 (cons (substring string start (match-beginning 0))
13866 list)))
13867 (setq start (match-end 0)))
13868 (or (eq start (length string))
13869 (setq list
13870 (cons (substring string start)
13871 list)))
13872 (nreverse list)))
13874 (defun org-context ()
13875 "Return a list of contexts of the current cursor position.
13876 If several contexts apply, all are returned.
13877 Each context entry is a list with a symbol naming the context, and
13878 two positions indicating start and end of the context. Possible
13879 contexts are:
13881 :headline anywhere in a headline
13882 :headline-stars on the leading stars in a headline
13883 :todo-keyword on a TODO keyword (including DONE) in a headline
13884 :tags on the TAGS in a headline
13885 :priority on the priority cookie in a headline
13886 :item on the first line of a plain list item
13887 :item-bullet on the bullet/number of a plain list item
13888 :checkbox on the checkbox in a plain list item
13889 :table in an org-mode table
13890 :table-special on a special filed in a table
13891 :table-table in a table.el table
13892 :link on a hyperlink
13893 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13894 :target on a <<target>>
13895 :radio-target on a <<<radio-target>>>
13896 :latex-fragment on a LaTeX fragment
13897 :latex-preview on a LaTeX fragment with overlayed preview image
13899 This function expects the position to be visible because it uses font-lock
13900 faces as a help to recognize the following contexts: :table-special, :link,
13901 and :keyword."
13902 (let* ((f (get-text-property (point) 'face))
13903 (faces (if (listp f) f (list f)))
13904 (p (point)) clist o)
13905 ;; First the large context
13906 (cond
13907 ((org-on-heading-p t)
13908 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13909 (when (progn
13910 (beginning-of-line 1)
13911 (looking-at org-todo-line-tags-regexp))
13912 (push (org-point-in-group p 1 :headline-stars) clist)
13913 (push (org-point-in-group p 2 :todo-keyword) clist)
13914 (push (org-point-in-group p 4 :tags) clist))
13915 (goto-char p)
13916 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13917 (if (looking-at "\\[#[A-Z0-9]\\]")
13918 (push (org-point-in-group p 0 :priority) clist)))
13920 ((org-at-item-p)
13921 (push (org-point-in-group p 2 :item-bullet) clist)
13922 (push (list :item (point-at-bol)
13923 (save-excursion (org-end-of-item) (point)))
13924 clist)
13925 (and (org-at-item-checkbox-p)
13926 (push (org-point-in-group p 0 :checkbox) clist)))
13928 ((org-at-table-p)
13929 (push (list :table (org-table-begin) (org-table-end)) clist)
13930 (if (memq 'org-formula faces)
13931 (push (list :table-special
13932 (previous-single-property-change p 'face)
13933 (next-single-property-change p 'face)) clist)))
13934 ((org-at-table-p 'any)
13935 (push (list :table-table) clist)))
13936 (goto-char p)
13938 ;; Now the small context
13939 (cond
13940 ((org-at-timestamp-p)
13941 (push (org-point-in-group p 0 :timestamp) clist))
13942 ((memq 'org-link faces)
13943 (push (list :link
13944 (previous-single-property-change p 'face)
13945 (next-single-property-change p 'face)) clist))
13946 ((memq 'org-special-keyword faces)
13947 (push (list :keyword
13948 (previous-single-property-change p 'face)
13949 (next-single-property-change p 'face)) clist))
13950 ((org-on-target-p)
13951 (push (org-point-in-group p 0 :target) clist)
13952 (goto-char (1- (match-beginning 0)))
13953 (if (looking-at org-radio-target-regexp)
13954 (push (org-point-in-group p 0 :radio-target) clist))
13955 (goto-char p))
13956 ((setq o (car (delq nil
13957 (mapcar
13958 (lambda (x)
13959 (if (memq x org-latex-fragment-image-overlays) x))
13960 (org-overlays-at (point))))))
13961 (push (list :latex-fragment
13962 (org-overlay-start o) (org-overlay-end o)) clist)
13963 (push (list :latex-preview
13964 (org-overlay-start o) (org-overlay-end o)) clist))
13965 ((org-inside-LaTeX-fragment-p)
13966 ;; FIXME: positions wrong.
13967 (push (list :latex-fragment (point) (point)) clist)))
13969 (setq clist (nreverse (delq nil clist)))
13970 clist))
13972 ;; FIXME: Compare with at-regexp-p Do we need both?
13973 (defun org-in-regexp (re &optional nlines visually)
13974 "Check if point is inside a match of regexp.
13975 Normally only the current line is checked, but you can include NLINES extra
13976 lines both before and after point into the search.
13977 If VISUALLY is set, require that the cursor is not after the match but
13978 really on, so that the block visually is on the match."
13979 (catch 'exit
13980 (let ((pos (point))
13981 (eol (point-at-eol (+ 1 (or nlines 0))))
13982 (inc (if visually 1 0)))
13983 (save-excursion
13984 (beginning-of-line (- 1 (or nlines 0)))
13985 (while (re-search-forward re eol t)
13986 (if (and (<= (match-beginning 0) pos)
13987 (>= (+ inc (match-end 0)) pos))
13988 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13990 (defun org-at-regexp-p (regexp)
13991 "Is point inside a match of REGEXP in the current line?"
13992 (catch 'exit
13993 (save-excursion
13994 (let ((pos (point)) (end (point-at-eol)))
13995 (beginning-of-line 1)
13996 (while (re-search-forward regexp end t)
13997 (if (and (<= (match-beginning 0) pos)
13998 (>= (match-end 0) pos))
13999 (throw 'exit t)))
14000 nil))))
14002 (defun org-occur-in-agenda-files (regexp &optional nlines)
14003 "Call `multi-occur' with buffers for all agenda files."
14004 (interactive "sOrg-files matching: \np")
14005 (let* ((files (org-agenda-files))
14006 (tnames (mapcar 'file-truename files))
14007 (extra org-agenda-text-search-extra-files)
14009 (when (eq (car extra) 'agenda-archives)
14010 (setq extra (cdr extra))
14011 (setq files (org-add-archive-files files)))
14012 (while (setq f (pop extra))
14013 (unless (member (file-truename f) tnames)
14014 (add-to-list 'files f 'append)
14015 (add-to-list 'tnames (file-truename f) 'append)))
14016 (multi-occur
14017 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14018 regexp)))
14020 (if (boundp 'occur-mode-find-occurrence-hook)
14021 ;; Emacs 23
14022 (add-hook 'occur-mode-find-occurrence-hook
14023 (lambda ()
14024 (when (org-mode-p)
14025 (org-reveal))))
14026 ;; Emacs 22
14027 (defadvice occur-mode-goto-occurrence
14028 (after org-occur-reveal activate)
14029 (and (org-mode-p) (org-reveal)))
14030 (defadvice occur-mode-goto-occurrence-other-window
14031 (after org-occur-reveal activate)
14032 (and (org-mode-p) (org-reveal)))
14033 (defadvice occur-mode-display-occurrence
14034 (after org-occur-reveal activate)
14035 (when (org-mode-p)
14036 (let ((pos (occur-mode-find-occurrence)))
14037 (with-current-buffer (marker-buffer pos)
14038 (save-excursion
14039 (goto-char pos)
14040 (org-reveal)))))))
14042 (defun org-uniquify (list)
14043 "Remove duplicate elements from LIST."
14044 (let (res)
14045 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14046 res))
14048 (defun org-delete-all (elts list)
14049 "Remove all elements in ELTS from LIST."
14050 (while elts
14051 (setq list (delete (pop elts) list)))
14052 list)
14054 (defun org-back-over-empty-lines ()
14055 "Move backwards over whitespace, to the beginning of the first empty line.
14056 Returns the number of empty lines passed."
14057 (let ((pos (point)))
14058 (skip-chars-backward " \t\n\r")
14059 (beginning-of-line 2)
14060 (goto-char (min (point) pos))
14061 (count-lines (point) pos)))
14063 (defun org-skip-whitespace ()
14064 (skip-chars-forward " \t\n\r"))
14066 (defun org-point-in-group (point group &optional context)
14067 "Check if POINT is in match-group GROUP.
14068 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14069 match. If the match group does ot exist or point is not inside it,
14070 return nil."
14071 (and (match-beginning group)
14072 (>= point (match-beginning group))
14073 (<= point (match-end group))
14074 (if context
14075 (list context (match-beginning group) (match-end group))
14076 t)))
14078 (defun org-switch-to-buffer-other-window (&rest args)
14079 "Switch to buffer in a second window on the current frame.
14080 In particular, do not allow pop-up frames."
14081 (let (pop-up-frames special-display-buffer-names special-display-regexps
14082 special-display-function)
14083 (apply 'switch-to-buffer-other-window args)))
14085 (defun org-combine-plists (&rest plists)
14086 "Create a single property list from all plists in PLISTS.
14087 The process starts by copying the first list, and then setting properties
14088 from the other lists. Settings in the last list are the most significant
14089 ones and overrule settings in the other lists."
14090 (let ((rtn (copy-sequence (pop plists)))
14091 p v ls)
14092 (while plists
14093 (setq ls (pop plists))
14094 (while ls
14095 (setq p (pop ls) v (pop ls))
14096 (setq rtn (plist-put rtn p v))))
14097 rtn))
14099 (defun org-move-line-down (arg)
14100 "Move the current line down. With prefix argument, move it past ARG lines."
14101 (interactive "p")
14102 (let ((col (current-column))
14103 beg end pos)
14104 (beginning-of-line 1) (setq beg (point))
14105 (beginning-of-line 2) (setq end (point))
14106 (beginning-of-line (+ 1 arg))
14107 (setq pos (move-marker (make-marker) (point)))
14108 (insert (delete-and-extract-region beg end))
14109 (goto-char pos)
14110 (org-move-to-column col)))
14112 (defun org-move-line-up (arg)
14113 "Move the current line up. With prefix argument, move it past ARG lines."
14114 (interactive "p")
14115 (let ((col (current-column))
14116 beg end pos)
14117 (beginning-of-line 1) (setq beg (point))
14118 (beginning-of-line 2) (setq end (point))
14119 (beginning-of-line (- arg))
14120 (setq pos (move-marker (make-marker) (point)))
14121 (insert (delete-and-extract-region beg end))
14122 (goto-char pos)
14123 (org-move-to-column col)))
14125 (defun org-replace-escapes (string table)
14126 "Replace %-escapes in STRING with values in TABLE.
14127 TABLE is an association list with keys like \"%a\" and string values.
14128 The sequences in STRING may contain normal field width and padding information,
14129 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14130 so values can contain further %-escapes if they are define later in TABLE."
14131 (let ((case-fold-search nil)
14132 e re rpl)
14133 (while (setq e (pop table))
14134 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14135 (while (string-match re string)
14136 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14137 (cdr e)))
14138 (setq string (replace-match rpl t t string))))
14139 string))
14142 (defun org-sublist (list start end)
14143 "Return a section of LIST, from START to END.
14144 Counting starts at 1."
14145 (let (rtn (c start))
14146 (setq list (nthcdr (1- start) list))
14147 (while (and list (<= c end))
14148 (push (pop list) rtn)
14149 (setq c (1+ c)))
14150 (nreverse rtn)))
14152 (defun org-find-base-buffer-visiting (file)
14153 "Like `find-buffer-visiting' but alway return the base buffer and
14154 not an indirect buffer."
14155 (let ((buf (find-buffer-visiting file)))
14156 (if buf
14157 (or (buffer-base-buffer buf) buf)
14158 nil)))
14160 (defun org-image-file-name-regexp ()
14161 "Return regexp matching the file names of images."
14162 (if (fboundp 'image-file-name-regexp)
14163 (image-file-name-regexp)
14164 (let ((image-file-name-extensions
14165 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14166 "xbm" "xpm" "pbm" "pgm" "ppm")))
14167 (concat "\\."
14168 (regexp-opt (nconc (mapcar 'upcase
14169 image-file-name-extensions)
14170 image-file-name-extensions)
14172 "\\'"))))
14174 (defun org-file-image-p (file)
14175 "Return non-nil if FILE is an image."
14176 (save-match-data
14177 (string-match (org-image-file-name-regexp) file)))
14179 (defun org-get-cursor-date ()
14180 "Return the date at cursor in as a time.
14181 This works in the calendar and in the agenda, anywhere else it just
14182 returns the current time."
14183 (let (date day defd)
14184 (cond
14185 ((eq major-mode 'calendar-mode)
14186 (setq date (calendar-cursor-to-date)
14187 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14188 ((eq major-mode 'org-agenda-mode)
14189 (setq day (get-text-property (point) 'day))
14190 (if day
14191 (setq date (calendar-gregorian-from-absolute day)
14192 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14193 (nth 2 date))))))
14194 (or defd (current-time))))
14196 (defvar org-agenda-action-marker (make-marker)
14197 "Marker pointing to the entry for the next agenda action.")
14199 (defun org-mark-entry-for-agenda-action ()
14200 "Mark the current entry as target of an agenda action.
14201 Agenda actions are actions executed from the agenda with the key `k',
14202 which make use of the date at the cursor."
14203 (interactive)
14204 (move-marker org-agenda-action-marker
14205 (save-excursion (org-back-to-heading t) (point))
14206 (current-buffer))
14207 (message
14208 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14210 ;;; Paragraph filling stuff.
14211 ;; We want this to be just right, so use the full arsenal.
14213 (defun org-indent-line-function ()
14214 "Indent line like previous, but further if previous was headline or item."
14215 (interactive)
14216 (let* ((pos (point))
14217 (itemp (org-at-item-p))
14218 column bpos bcol tpos tcol bullet btype bullet-type)
14219 ;; Find the previous relevant line
14220 (beginning-of-line 1)
14221 (cond
14222 ((looking-at "#") (setq column 0))
14223 ((looking-at "\\*+ ") (setq column 0))
14225 (beginning-of-line 0)
14226 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14227 (beginning-of-line 0))
14228 (cond
14229 ((looking-at "\\*+[ \t]+")
14230 (if (not org-adapt-indentation)
14231 (setq column 0)
14232 (goto-char (match-end 0))
14233 (setq column (current-column))))
14234 ((org-in-item-p)
14235 (org-beginning-of-item)
14236 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14237 (setq bpos (match-beginning 1) tpos (match-end 0)
14238 bcol (progn (goto-char bpos) (current-column))
14239 tcol (progn (goto-char tpos) (current-column))
14240 bullet (match-string 1)
14241 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14242 (if (> tcol (+ bcol org-description-max-indent))
14243 (setq tcol (+ bcol 5)))
14244 (if (not itemp)
14245 (setq column tcol)
14246 (goto-char pos)
14247 (beginning-of-line 1)
14248 (if (looking-at "\\S-")
14249 (progn
14250 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14251 (setq bullet (match-string 1)
14252 btype (if (string-match "[0-9]" bullet) "n" bullet))
14253 (setq column (if (equal btype bullet-type) bcol tcol)))
14254 (setq column (org-get-indentation)))))
14255 (t (setq column (org-get-indentation))))))
14256 (goto-char pos)
14257 (if (<= (current-column) (current-indentation))
14258 (org-indent-line-to column)
14259 (save-excursion (org-indent-line-to column)))
14260 (setq column (current-column))
14261 (beginning-of-line 1)
14262 (if (looking-at
14263 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14264 (replace-match (concat "\\1" (format org-property-format
14265 (match-string 2) (match-string 3)))
14266 t nil))
14267 (org-move-to-column column)))
14269 (defun org-set-autofill-regexps ()
14270 (interactive)
14271 ;; In the paragraph separator we include headlines, because filling
14272 ;; text in a line directly attached to a headline would otherwise
14273 ;; fill the headline as well.
14274 (org-set-local 'comment-start-skip "^#+[ \t]*")
14275 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14276 ;; The paragraph starter includes hand-formatted lists.
14277 (org-set-local 'paragraph-start
14278 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14279 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14280 ;; But only if the user has not turned off tables or fixed-width regions
14281 (org-set-local
14282 'auto-fill-inhibit-regexp
14283 (concat "\\*+ \\|#\\+"
14284 "\\|[ \t]*" org-keyword-time-regexp
14285 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14286 (concat
14287 "\\|[ \t]*["
14288 (if org-enable-table-editor "|" "")
14289 (if org-enable-fixed-width-editor ":" "")
14290 "]"))))
14291 ;; We use our own fill-paragraph function, to make sure that tables
14292 ;; and fixed-width regions are not wrapped. That function will pass
14293 ;; through to `fill-paragraph' when appropriate.
14294 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14295 ; Adaptive filling: To get full control, first make sure that
14296 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14297 (org-set-local 'adaptive-fill-regexp "\000")
14298 (org-set-local 'adaptive-fill-function
14299 'org-adaptive-fill-function)
14300 (org-set-local
14301 'align-mode-rules-list
14302 '((org-in-buffer-settings
14303 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14304 (modes . '(org-mode))))))
14306 (defun org-fill-paragraph (&optional justify)
14307 "Re-align a table, pass through to fill-paragraph if no table."
14308 (let ((table-p (org-at-table-p))
14309 (table.el-p (org-at-table.el-p)))
14310 (cond ((and (equal (char-after (point-at-bol)) ?*)
14311 (save-excursion (goto-char (point-at-bol))
14312 (looking-at outline-regexp)))
14313 t) ; skip headlines
14314 (table.el-p t) ; skip table.el tables
14315 (table-p (org-table-align) t) ; align org-mode tables
14316 (t nil)))) ; call paragraph-fill
14318 ;; For reference, this is the default value of adaptive-fill-regexp
14319 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14321 (defun org-adaptive-fill-function ()
14322 "Return a fill prefix for org-mode files.
14323 In particular, this makes sure hanging paragraphs for hand-formatted lists
14324 work correctly."
14325 (cond ((looking-at "#[ \t]+")
14326 (match-string 0))
14327 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14328 (save-excursion
14329 (if (> (match-end 1) (+ (match-beginning 1)
14330 org-description-max-indent))
14331 (goto-char (+ (match-beginning 1) 5))
14332 (goto-char (match-end 0)))
14333 (make-string (current-column) ?\ )))
14334 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14335 (save-excursion
14336 (goto-char (match-end 0))
14337 (make-string (current-column) ?\ )))
14338 (t nil)))
14340 ;;; Other stuff.
14342 (defun org-toggle-fixed-width-section (arg)
14343 "Toggle the fixed-width export.
14344 If there is no active region, the QUOTE keyword at the current headline is
14345 inserted or removed. When present, it causes the text between this headline
14346 and the next to be exported as fixed-width text, and unmodified.
14347 If there is an active region, this command adds or removes a colon as the
14348 first character of this line. If the first character of a line is a colon,
14349 this line is also exported in fixed-width font."
14350 (interactive "P")
14351 (let* ((cc 0)
14352 (regionp (org-region-active-p))
14353 (beg (if regionp (region-beginning) (point)))
14354 (end (if regionp (region-end)))
14355 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14356 (case-fold-search nil)
14357 (re "[ \t]*\\(:\\)")
14358 off)
14359 (if regionp
14360 (save-excursion
14361 (goto-char beg)
14362 (setq cc (current-column))
14363 (beginning-of-line 1)
14364 (setq off (looking-at re))
14365 (while (> nlines 0)
14366 (setq nlines (1- nlines))
14367 (beginning-of-line 1)
14368 (cond
14369 (arg
14370 (org-move-to-column cc t)
14371 (insert ":\n")
14372 (forward-line -1))
14373 ((and off (looking-at re))
14374 (replace-match "" t t nil 1))
14375 ((not off) (org-move-to-column cc t) (insert ":")))
14376 (forward-line 1)))
14377 (save-excursion
14378 (org-back-to-heading)
14379 (if (looking-at (concat outline-regexp
14380 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14381 (replace-match "" t t nil 1)
14382 (if (looking-at outline-regexp)
14383 (progn
14384 (goto-char (match-end 0))
14385 (insert org-quote-string " "))))))))
14387 ;;;; Functions extending outline functionality
14389 (defun org-beginning-of-line (&optional arg)
14390 "Go to the beginning of the current line. If that is invisible, continue
14391 to a visible line beginning. This makes the function of C-a more intuitive.
14392 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14393 first attempt, and only move to after the tags when the cursor is already
14394 beyond the end of the headline."
14395 (interactive "P")
14396 (let ((pos (point)) refpos)
14397 (beginning-of-line 1)
14398 (if (bobp)
14400 (backward-char 1)
14401 (if (org-invisible-p)
14402 (while (and (not (bobp)) (org-invisible-p))
14403 (backward-char 1)
14404 (beginning-of-line 1))
14405 (forward-char 1)))
14406 (when org-special-ctrl-a/e
14407 (cond
14408 ((and (looking-at org-complex-heading-regexp)
14409 (= (char-after (match-end 1)) ?\ ))
14410 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14411 (point-at-eol)))
14412 (goto-char
14413 (if (eq org-special-ctrl-a/e t)
14414 (cond ((> pos refpos) refpos)
14415 ((= pos (point)) refpos)
14416 (t (point)))
14417 (cond ((> pos (point)) (point))
14418 ((not (eq last-command this-command)) (point))
14419 (t refpos)))))
14420 ((org-at-item-p)
14421 (goto-char
14422 (if (eq org-special-ctrl-a/e t)
14423 (cond ((> pos (match-end 4)) (match-end 4))
14424 ((= pos (point)) (match-end 4))
14425 (t (point)))
14426 (cond ((> pos (point)) (point))
14427 ((not (eq last-command this-command)) (point))
14428 (t (match-end 4))))))))
14429 (org-no-warnings
14430 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14432 (defun org-end-of-line (&optional arg)
14433 "Go to the end of the line.
14434 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14435 first attempt, and only move to after the tags when the cursor is already
14436 beyond the end of the headline."
14437 (interactive "P")
14438 (if (or (not org-special-ctrl-a/e)
14439 (not (org-on-heading-p)))
14440 (end-of-line arg)
14441 (let ((pos (point)))
14442 (beginning-of-line 1)
14443 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14444 (if (eq org-special-ctrl-a/e t)
14445 (if (or (< pos (match-beginning 1))
14446 (= pos (match-end 0)))
14447 (goto-char (match-beginning 1))
14448 (goto-char (match-end 0)))
14449 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14450 (goto-char (match-end 0))
14451 (goto-char (match-beginning 1))))
14452 (end-of-line arg))))
14453 (org-no-warnings
14454 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14457 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14458 (define-key org-mode-map "\C-e" 'org-end-of-line)
14460 (defun org-kill-line (&optional arg)
14461 "Kill line, to tags or end of line."
14462 (interactive "P")
14463 (cond
14464 ((or (not org-special-ctrl-k)
14465 (bolp)
14466 (not (org-on-heading-p)))
14467 (call-interactively 'kill-line))
14468 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14469 (kill-region (point) (match-beginning 1))
14470 (org-set-tags nil t))
14471 (t (kill-region (point) (point-at-eol)))))
14473 (define-key org-mode-map "\C-k" 'org-kill-line)
14475 (defun org-yank (&optional arg)
14476 "Yank. If the kill is a subtree, treat it specially.
14477 This command will look at the current kill and check if is a single
14478 subtree, or a series of subtrees[1]. If it passes the test, and if the
14479 cursor is at the beginning of a line or after the stars of a currently
14480 empty headline, then the yank is handled specially. How exactly depends
14481 on the value of the following variables, both set by default.
14483 org-yank-folded-subtrees
14484 When set, the subtree(s) will be folded after insertion, but only
14485 if doing so would now swallow text after the yanked text.
14487 org-yank-adjusted-subtrees
14488 When set, the subtree will be promoted or demoted in order to
14489 fit into the local outline tree structure, which means that the level
14490 will be adjusted so that it becomes the smaller one of the two
14491 *visible* surrounding headings.
14493 Any prefix to this command will cause `yank' to be called directly with
14494 no special treatment. In particular, a simple `C-u' prefix will just
14495 plainly yank the text as it is.
14497 \[1] Basically, the test checks if the first non-white line is a heading
14498 and if there are no other headings with fewer stars."
14499 (interactive "P")
14500 (setq this-command 'yank)
14501 (if arg
14502 (call-interactively 'yank)
14503 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14504 (and (org-kill-is-subtree-p)
14505 (or (bolp)
14506 (and (looking-at "[ \t]*$")
14507 (string-match
14508 "\\`\\*+\\'"
14509 (buffer-substring (point-at-bol) (point)))))))
14510 swallowp)
14511 (cond
14512 ((and subtreep org-yank-folded-subtrees)
14513 (let ((beg (point))
14514 end)
14515 (if (and subtreep org-yank-adjusted-subtrees)
14516 (org-paste-subtree nil nil 'for-yank)
14517 (call-interactively 'yank))
14518 (setq end (point))
14519 (goto-char beg)
14520 (when (and (bolp) subtreep
14521 (not (setq swallowp
14522 (org-yank-folding-would-swallow-text beg end))))
14523 (or (looking-at outline-regexp)
14524 (re-search-forward (concat "^" outline-regexp) end t))
14525 (while (and (< (point) end) (looking-at outline-regexp))
14526 (hide-subtree)
14527 (org-cycle-show-empty-lines 'folded)
14528 (condition-case nil
14529 (outline-forward-same-level 1)
14530 (error (goto-char end)))))
14531 (when swallowp
14532 (message
14533 "Yanked text not folded because that would swallow text"))
14534 (goto-char end)
14535 (skip-chars-forward " \t\n\r")
14536 (beginning-of-line 1)
14537 (push-mark beg 'nomsg)))
14538 ((and subtreep org-yank-adjusted-subtrees)
14539 (let ((beg (point-at-bol)))
14540 (org-paste-subtree nil nil 'for-yank)
14541 (push-mark beg 'nomsg)))
14543 (call-interactively 'yank))))))
14545 (defun org-yank-folding-would-swallow-text (beg end)
14546 "Would hide-subtree at BEG swallow any text after END?"
14547 (let (level)
14548 (save-excursion
14549 (goto-char beg)
14550 (when (or (looking-at outline-regexp)
14551 (re-search-forward (concat "^" outline-regexp) end t))
14552 (setq level (org-outline-level)))
14553 (goto-char end)
14554 (skip-chars-forward " \t\r\n\v\f")
14555 (if (or (eobp)
14556 (and (bolp) (looking-at org-outline-regexp)
14557 (<= (org-outline-level) level)))
14558 nil ; Nothing would be swallowed
14559 t)))) ; something would swallow
14561 (define-key org-mode-map "\C-y" 'org-yank)
14563 (defun org-invisible-p ()
14564 "Check if point is at a character currently not visible."
14565 ;; Early versions of noutline don't have `outline-invisible-p'.
14566 (if (fboundp 'outline-invisible-p)
14567 (outline-invisible-p)
14568 (get-char-property (point) 'invisible)))
14570 (defun org-invisible-p2 ()
14571 "Check if point is at a character currently not visible."
14572 (save-excursion
14573 (if (and (eolp) (not (bobp))) (backward-char 1))
14574 ;; Early versions of noutline don't have `outline-invisible-p'.
14575 (if (fboundp 'outline-invisible-p)
14576 (outline-invisible-p)
14577 (get-char-property (point) 'invisible))))
14579 (defun org-back-to-heading (&optional invisible-ok)
14580 "Call `outline-back-to-heading', but provide a better error message."
14581 (condition-case nil
14582 (outline-back-to-heading invisible-ok)
14583 (error (error "Before first headline at position %d in buffer %s"
14584 (point) (current-buffer)))))
14586 (defun org-before-first-heading-p ()
14587 "Before first heading?"
14588 (save-excursion
14589 (null (re-search-backward "^\\*+ " nil t))))
14591 (defalias 'org-on-heading-p 'outline-on-heading-p)
14592 (defalias 'org-at-heading-p 'outline-on-heading-p)
14593 (defun org-at-heading-or-item-p ()
14594 (or (org-on-heading-p) (org-at-item-p)))
14596 (defun org-on-target-p ()
14597 (or (org-in-regexp org-radio-target-regexp)
14598 (org-in-regexp org-target-regexp)))
14600 (defun org-up-heading-all (arg)
14601 "Move to the heading line of which the present line is a subheading.
14602 This function considers both visible and invisible heading lines.
14603 With argument, move up ARG levels."
14604 (if (fboundp 'outline-up-heading-all)
14605 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14606 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14608 (defun org-up-heading-safe ()
14609 "Move to the heading line of which the present line is a subheading.
14610 This version will not throw an error. It will return the level of the
14611 headline found, or nil if no higher level is found."
14612 (let (start-level re)
14613 (org-back-to-heading t)
14614 (setq start-level (funcall outline-level))
14615 (if (equal start-level 1)
14617 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14618 (if (re-search-backward re nil t)
14619 (funcall outline-level)))))
14621 (defun org-first-sibling-p ()
14622 "Is this heading the first child of its parents?"
14623 (interactive)
14624 (let ((re (concat "^" outline-regexp))
14625 level l)
14626 (unless (org-at-heading-p t)
14627 (error "Not at a heading"))
14628 (setq level (funcall outline-level))
14629 (save-excursion
14630 (if (not (re-search-backward re nil t))
14632 (setq l (funcall outline-level))
14633 (< l level)))))
14635 (defun org-goto-sibling (&optional previous)
14636 "Goto the next sibling, even if it is invisible.
14637 When PREVIOUS is set, go to the previous sibling instead. Returns t
14638 when a sibling was found. When none is found, return nil and don't
14639 move point."
14640 (let ((fun (if previous 're-search-backward 're-search-forward))
14641 (pos (point))
14642 (re (concat "^" outline-regexp))
14643 level l)
14644 (when (condition-case nil (org-back-to-heading t) (error nil))
14645 (setq level (funcall outline-level))
14646 (catch 'exit
14647 (or previous (forward-char 1))
14648 (while (funcall fun re nil t)
14649 (setq l (funcall outline-level))
14650 (when (< l level) (goto-char pos) (throw 'exit nil))
14651 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14652 (goto-char pos)
14653 nil))))
14655 (defun org-show-siblings ()
14656 "Show all siblings of the current headline."
14657 (save-excursion
14658 (while (org-goto-sibling) (org-flag-heading nil)))
14659 (save-excursion
14660 (while (org-goto-sibling 'previous)
14661 (org-flag-heading nil))))
14663 (defun org-show-hidden-entry ()
14664 "Show an entry where even the heading is hidden."
14665 (save-excursion
14666 (org-show-entry)))
14668 (defun org-flag-heading (flag &optional entry)
14669 "Flag the current heading. FLAG non-nil means make invisible.
14670 When ENTRY is non-nil, show the entire entry."
14671 (save-excursion
14672 (org-back-to-heading t)
14673 ;; Check if we should show the entire entry
14674 (if entry
14675 (progn
14676 (org-show-entry)
14677 (save-excursion
14678 (and (outline-next-heading)
14679 (org-flag-heading nil))))
14680 (outline-flag-region (max (point-min) (1- (point)))
14681 (save-excursion (outline-end-of-heading) (point))
14682 flag))))
14684 (defun org-forward-same-level (arg)
14685 "Move forward to the ARG'th subheading at same level as this one.
14686 Stop at the first and last subheadings of a superior heading.
14687 This is like outline-forward-same-level, but invisible headings are ok."
14688 (interactive "p")
14689 (org-back-to-heading t)
14690 (while (> arg 0)
14691 (let ((point-to-move-to (save-excursion
14692 (org-get-next-sibling))))
14693 (if point-to-move-to
14694 (progn
14695 (goto-char point-to-move-to)
14696 (setq arg (1- arg)))
14697 (progn
14698 (setq arg 0)
14699 (error "No following same-level heading"))))))
14701 (defun org-get-next-sibling ()
14702 "Move to next heading of the same level, and return point.
14703 If there is no such heading, return nil.
14704 This is like outline-next-sibling, but invisible headings are ok."
14705 (let ((level (funcall outline-level)))
14706 (outline-next-heading)
14707 (while (and (not (eobp)) (> (funcall outline-level) level))
14708 (outline-next-heading))
14709 (if (or (eobp) (< (funcall outline-level) level))
14711 (point))))
14713 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14714 ;; This is an exact copy of the original function, but it uses
14715 ;; `org-back-to-heading', to make it work also in invisible
14716 ;; trees. And is uses an invisible-OK argument.
14717 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14718 (org-back-to-heading invisible-OK)
14719 (let ((first t)
14720 (level (funcall outline-level)))
14721 (while (and (not (eobp))
14722 (or first (> (funcall outline-level) level)))
14723 (setq first nil)
14724 (outline-next-heading))
14725 (unless to-heading
14726 (if (memq (preceding-char) '(?\n ?\^M))
14727 (progn
14728 ;; Go to end of line before heading
14729 (forward-char -1)
14730 (if (memq (preceding-char) '(?\n ?\^M))
14731 ;; leave blank line before heading
14732 (forward-char -1))))))
14733 (point))
14735 (defun org-show-subtree ()
14736 "Show everything after this heading at deeper levels."
14737 (outline-flag-region
14738 (point)
14739 (save-excursion
14740 (outline-end-of-subtree) (outline-next-heading) (point))
14741 nil))
14743 (defun org-show-entry ()
14744 "Show the body directly following this heading.
14745 Show the heading too, if it is currently invisible."
14746 (interactive)
14747 (save-excursion
14748 (condition-case nil
14749 (progn
14750 (org-back-to-heading t)
14751 (outline-flag-region
14752 (max (point-min) (1- (point)))
14753 (save-excursion
14754 (re-search-forward
14755 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14756 (or (match-beginning 1) (point-max)))
14757 nil))
14758 (error nil))))
14760 (defun org-make-options-regexp (kwds)
14761 "Make a regular expression for keyword lines."
14762 (concat
14764 "#?[ \t]*\\+\\("
14765 (mapconcat 'regexp-quote kwds "\\|")
14766 "\\):[ \t]*"
14767 "\\(.+\\)"))
14769 ;; Make isearch reveal the necessary context
14770 (defun org-isearch-end ()
14771 "Reveal context after isearch exits."
14772 (when isearch-success ; only if search was successful
14773 (if (featurep 'xemacs)
14774 ;; Under XEmacs, the hook is run in the correct place,
14775 ;; we directly show the context.
14776 (org-show-context 'isearch)
14777 ;; In Emacs the hook runs *before* restoring the overlays.
14778 ;; So we have to use a one-time post-command-hook to do this.
14779 ;; (Emacs 22 has a special variable, see function `org-mode')
14780 (unless (and (boundp 'isearch-mode-end-hook-quit)
14781 isearch-mode-end-hook-quit)
14782 ;; Only when the isearch was not quitted.
14783 (org-add-hook 'post-command-hook 'org-isearch-post-command
14784 'append 'local)))))
14786 (defun org-isearch-post-command ()
14787 "Remove self from hook, and show context."
14788 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14789 (org-show-context 'isearch))
14792 ;;;; Integration with and fixes for other packages
14794 ;;; Imenu support
14796 (defvar org-imenu-markers nil
14797 "All markers currently used by Imenu.")
14798 (make-variable-buffer-local 'org-imenu-markers)
14800 (defun org-imenu-new-marker (&optional pos)
14801 "Return a new marker for use by Imenu, and remember the marker."
14802 (let ((m (make-marker)))
14803 (move-marker m (or pos (point)))
14804 (push m org-imenu-markers)
14807 (defun org-imenu-get-tree ()
14808 "Produce the index for Imenu."
14809 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14810 (setq org-imenu-markers nil)
14811 (let* ((n org-imenu-depth)
14812 (re (concat "^" outline-regexp))
14813 (subs (make-vector (1+ n) nil))
14814 (last-level 0)
14815 m tree level head)
14816 (save-excursion
14817 (save-restriction
14818 (widen)
14819 (goto-char (point-max))
14820 (while (re-search-backward re nil t)
14821 (setq level (org-reduced-level (funcall outline-level)))
14822 (when (<= level n)
14823 (looking-at org-complex-heading-regexp)
14824 (setq head (org-link-display-format
14825 (org-match-string-no-properties 4))
14826 m (org-imenu-new-marker))
14827 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14828 (if (>= level last-level)
14829 (push (cons head m) (aref subs level))
14830 (push (cons head (aref subs (1+ level))) (aref subs level))
14831 (loop for i from (1+ level) to n do (aset subs i nil)))
14832 (setq last-level level)))))
14833 (aref subs 1)))
14835 (eval-after-load "imenu"
14836 '(progn
14837 (add-hook 'imenu-after-jump-hook
14838 (lambda ()
14839 (if (eq major-mode 'org-mode)
14840 (org-show-context 'org-goto))))))
14842 (defun org-link-display-format (link)
14843 "Replace a link with either the description, or the link target
14844 if no description is present"
14845 (save-match-data
14846 (if (string-match org-bracket-link-analytic-regexp link)
14847 (replace-match (or (match-string 5 link)
14848 (concat (match-string 1 link)
14849 (match-string 3 link)))
14850 nil nil link)
14851 link)))
14853 ;; Speedbar support
14855 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14856 "Overlay marking the agenda restriction line in speedbar.")
14857 (org-overlay-put org-speedbar-restriction-lock-overlay
14858 'face 'org-agenda-restriction-lock)
14859 (org-overlay-put org-speedbar-restriction-lock-overlay
14860 'help-echo "Agendas are currently limited to this item.")
14861 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14863 (defun org-speedbar-set-agenda-restriction ()
14864 "Restrict future agenda commands to the location at point in speedbar.
14865 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14866 (interactive)
14867 (require 'org-agenda)
14868 (let (p m tp np dir txt w)
14869 (cond
14870 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14871 'org-imenu t))
14872 (setq m (get-text-property p 'org-imenu-marker))
14873 (save-excursion
14874 (save-restriction
14875 (set-buffer (marker-buffer m))
14876 (goto-char m)
14877 (org-agenda-set-restriction-lock 'subtree))))
14878 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14879 'speedbar-function 'speedbar-find-file))
14880 (setq tp (previous-single-property-change
14881 (1+ p) 'speedbar-function)
14882 np (next-single-property-change
14883 tp 'speedbar-function)
14884 dir (speedbar-line-directory)
14885 txt (buffer-substring-no-properties (or tp (point-min))
14886 (or np (point-max))))
14887 (save-excursion
14888 (save-restriction
14889 (set-buffer (find-file-noselect
14890 (let ((default-directory dir))
14891 (expand-file-name txt))))
14892 (unless (org-mode-p)
14893 (error "Cannot restrict to non-Org-mode file"))
14894 (org-agenda-set-restriction-lock 'file))))
14895 (t (error "Don't know how to restrict Org-mode's agenda")))
14896 (org-move-overlay org-speedbar-restriction-lock-overlay
14897 (point-at-bol) (point-at-eol))
14898 (setq current-prefix-arg nil)
14899 (org-agenda-maybe-redo)))
14901 (eval-after-load "speedbar"
14902 '(progn
14903 (speedbar-add-supported-extension ".org")
14904 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14905 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14906 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14907 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14908 (add-hook 'speedbar-visiting-tag-hook
14909 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14912 ;;; Fixes and Hacks for problems with other packages
14914 ;; Make flyspell not check words in links, to not mess up our keymap
14915 (defun org-mode-flyspell-verify ()
14916 "Don't let flyspell put overlays at active buttons."
14917 (not (get-text-property (point) 'keymap)))
14919 ;; Make `bookmark-jump' show the jump location if it was hidden.
14920 (eval-after-load "bookmark"
14921 '(if (boundp 'bookmark-after-jump-hook)
14922 ;; We can use the hook
14923 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14924 ;; Hook not available, use advice
14925 (defadvice bookmark-jump (after org-make-visible activate)
14926 "Make the position visible."
14927 (org-bookmark-jump-unhide))))
14929 ;; Make sure saveplace show the location if it was hidden
14930 (eval-after-load "saveplace"
14931 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14932 "Make the position visible."
14933 (org-bookmark-jump-unhide)))
14935 (defun org-bookmark-jump-unhide ()
14936 "Unhide the current position, to show the bookmark location."
14937 (and (org-mode-p)
14938 (or (org-invisible-p)
14939 (save-excursion (goto-char (max (point-min) (1- (point))))
14940 (org-invisible-p)))
14941 (org-show-context 'bookmark-jump)))
14943 ;; Make session.el ignore our circular variable
14944 (eval-after-load "session"
14945 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14947 ;;;; Experimental code
14949 (defun org-closed-in-range ()
14950 "Sparse tree of items closed in a certain time range.
14951 Still experimental, may disappear in the future."
14952 (interactive)
14953 ;; Get the time interval from the user.
14954 (let* ((time1 (time-to-seconds
14955 (org-read-date nil 'to-time nil "Starting date: ")))
14956 (time2 (time-to-seconds
14957 (org-read-date nil 'to-time nil "End date:")))
14958 ;; callback function
14959 (callback (lambda ()
14960 (let ((time
14961 (time-to-seconds
14962 (apply 'encode-time
14963 (org-parse-time-string
14964 (match-string 1))))))
14965 ;; check if time in interval
14966 (and (>= time time1) (<= time time2))))))
14967 ;; make tree, check each match with the callback
14968 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14971 ;;;; Finish up
14973 (provide 'org)
14975 (run-hooks 'org-load-hook)
14977 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14979 ;;; org.el ends here