Export: New hooks for preprocessing
[org-mode.git] / lisp / org.el
blobdf90e0bc1843d8e979c87f586af88b3b10432f8b
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 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.16trans
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.16trans"
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 . nil)
693 (plain-list-item . nil))
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) (boolean))
700 (cons (const plain-list-item) (boolean))))
702 (defcustom org-insert-heading-hook nil
703 "Hook being run after inserting a new heading."
704 :group 'org-edit-structure
705 :type 'hook)
707 (defcustom org-enable-fixed-width-editor t
708 "Non-nil means, lines starting with \":\" are treated as fixed-width.
709 This currently only means, they are never auto-wrapped.
710 When nil, such lines will be treated like ordinary lines.
711 See also the QUOTE keyword."
712 :group 'org-edit-structure
713 :type 'boolean)
715 (defcustom org-edit-src-region-extra nil
716 "Additional regexps to identify regions for editing with `org-edit-src-code'.
717 For examples see the function `org-edit-src-find-region-and-lang'.
718 The regular expression identifying the begin marker should end with a newline,
719 and the regexp marking the end line should start with a newline, to make sure
720 there are kept outside the narrowed region."
721 :group 'org-edit-structure
722 :type '(repeat
723 (list
724 (regexp :tag "begin regexp")
725 (regexp :tag "end regexp")
726 (choice :tag "language"
727 (string :tag "specify")
728 (integer :tag "from match group")
729 (const :tag "from `lang' element")
730 (const :tag "from `style' element")))))
732 (defcustom org-edit-fixed-width-region-mode 'artist-mode
733 "The mode that should be used to edit fixed-width regions.
734 These are the regions where each line starts with a colon."
735 :group 'org-edit-structure
736 :type '(choice
737 (const artist-mode)
738 (const picture-mode)
739 (const fundamental-mode)
740 (function :tag "Other (specify)")))
742 (defcustom org-goto-auto-isearch t
743 "Non-nil means, typing characters in org-goto starts incremental search."
744 :group 'org-edit-structure
745 :type 'boolean)
747 (defgroup org-sparse-trees nil
748 "Options concerning sparse trees in Org-mode."
749 :tag "Org Sparse Trees"
750 :group 'org-structure)
752 (defcustom org-highlight-sparse-tree-matches t
753 "Non-nil means, highlight all matches that define a sparse tree.
754 The highlights will automatically disappear the next time the buffer is
755 changed by an edit command."
756 :group 'org-sparse-trees
757 :type 'boolean)
759 (defcustom org-remove-highlights-with-change t
760 "Non-nil means, any change to the buffer will remove temporary highlights.
761 Such highlights are created by `org-occur' and `org-clock-display'.
762 When nil, `C-c C-c needs to be used to get rid of the highlights.
763 The highlights created by `org-preview-latex-fragment' always need
764 `C-c C-c' to be removed."
765 :group 'org-sparse-trees
766 :group 'org-time
767 :type 'boolean)
770 (defcustom org-occur-hook '(org-first-headline-recenter)
771 "Hook that is run after `org-occur' has constructed a sparse tree.
772 This can be used to recenter the window to show as much of the structure
773 as possible."
774 :group 'org-sparse-trees
775 :type 'hook)
777 (defgroup org-imenu-and-speedbar nil
778 "Options concerning imenu and speedbar in Org-mode."
779 :tag "Org Imenu and Speedbar"
780 :group 'org-structure)
782 (defcustom org-imenu-depth 2
783 "The maximum level for Imenu access to Org-mode headlines.
784 This also applied for speedbar access."
785 :group 'org-imenu-and-speedbar
786 :type 'number)
788 (defgroup org-table nil
789 "Options concerning tables in Org-mode."
790 :tag "Org Table"
791 :group 'org)
793 (defcustom org-enable-table-editor 'optimized
794 "Non-nil means, lines starting with \"|\" are handled by the table editor.
795 When nil, such lines will be treated like ordinary lines.
797 When equal to the symbol `optimized', the table editor will be optimized to
798 do the following:
799 - Automatic overwrite mode in front of whitespace in table fields.
800 This makes the structure of the table stay in tact as long as the edited
801 field does not exceed the column width.
802 - Minimize the number of realigns. Normally, the table is aligned each time
803 TAB or RET are pressed to move to another field. With optimization this
804 happens only if changes to a field might have changed the column width.
805 Optimization requires replacing the functions `self-insert-command',
806 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
807 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
808 very good at guessing when a re-align will be necessary, but you can always
809 force one with \\[org-ctrl-c-ctrl-c].
811 If you would like to use the optimized version in Org-mode, but the
812 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
814 This variable can be used to turn on and off the table editor during a session,
815 but in order to toggle optimization, a restart is required.
817 See also the variable `org-table-auto-blank-field'."
818 :group 'org-table
819 :type '(choice
820 (const :tag "off" nil)
821 (const :tag "on" t)
822 (const :tag "on, optimized" optimized)))
824 (defcustom org-table-tab-recognizes-table.el t
825 "Non-nil means, TAB will automatically notice a table.el table.
826 When it sees such a table, it moves point into it and - if necessary -
827 calls `table-recognize-table'."
828 :group 'org-table-editing
829 :type 'boolean)
831 (defgroup org-link nil
832 "Options concerning links in Org-mode."
833 :tag "Org Link"
834 :group 'org)
836 (defvar org-link-abbrev-alist-local nil
837 "Buffer-local version of `org-link-abbrev-alist', which see.
838 The value of this is taken from the #+LINK lines.")
839 (make-variable-buffer-local 'org-link-abbrev-alist-local)
841 (defcustom org-link-abbrev-alist nil
842 "Alist of link abbreviations.
843 The car of each element is a string, to be replaced at the start of a link.
844 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
845 links in Org-mode buffers can have an optional tag after a double colon, e.g.
847 [[linkkey:tag][description]]
849 If REPLACE is a string, the tag will simply be appended to create the link.
850 If the string contains \"%s\", the tag will be inserted there. Alternatively,
851 the placeholder \"%h\" will cause a url-encoded version of the tag to
852 be inserted at that point (see the function `url-hexify-string').
854 REPLACE may also be a function that will be called with the tag as the
855 only argument to create the link, which should be returned as a string.
857 See the manual for examples."
858 :group 'org-link
859 :type '(repeat
860 (cons
861 (string :tag "Protocol")
862 (choice
863 (string :tag "Format")
864 (function)))))
866 (defcustom org-descriptive-links t
867 "Non-nil means, hide link part and only show description of bracket links.
868 Bracket links are like [[link][description]]. This variable sets the initial
869 state in new org-mode buffers. The setting can then be toggled on a
870 per-buffer basis from the Org->Hyperlinks menu."
871 :group 'org-link
872 :type 'boolean)
874 (defcustom org-link-file-path-type 'adaptive
875 "How the path name in file links should be stored.
876 Valid values are:
878 relative Relative to the current directory, i.e. the directory of the file
879 into which the link is being inserted.
880 absolute Absolute path, if possible with ~ for home directory.
881 noabbrev Absolute path, no abbreviation of home directory.
882 adaptive Use relative path for files in the current directory and sub-
883 directories of it. For other files, use an absolute path."
884 :group 'org-link
885 :type '(choice
886 (const relative)
887 (const absolute)
888 (const noabbrev)
889 (const adaptive)))
891 (defcustom org-activate-links '(bracket angle plain radio tag date)
892 "Types of links that should be activated in Org-mode files.
893 This is a list of symbols, each leading to the activation of a certain link
894 type. In principle, it does not hurt to turn on most link types - there may
895 be a small gain when turning off unused link types. The types are:
897 bracket The recommended [[link][description]] or [[link]] links with hiding.
898 angular Links in angular brackets that may contain whitespace like
899 <bbdb:Carsten Dominik>.
900 plain Plain links in normal text, no whitespace, like http://google.com.
901 radio Text that is matched by a radio target, see manual for details.
902 tag Tag settings in a headline (link to tag search).
903 date Time stamps (link to calendar).
905 Changing this variable requires a restart of Emacs to become effective."
906 :group 'org-link
907 :type '(set (const :tag "Double bracket links (new style)" bracket)
908 (const :tag "Angular bracket links (old style)" angular)
909 (const :tag "Plain text links" plain)
910 (const :tag "Radio target matches" radio)
911 (const :tag "Tags" tag)
912 (const :tag "Timestamps" date)))
914 (defcustom org-make-link-description-function nil
915 "Function to use to generate link descriptions from links. If
916 nil the link location will be used. This function must take two
917 parameters; the first is the link and the second the description
918 org-insert-link has generated, and should return the description
919 to use."
920 :group 'org-link
921 :type 'function)
923 (defgroup org-link-store nil
924 "Options concerning storing links in Org-mode."
925 :tag "Org Store Link"
926 :group 'org-link)
928 (defcustom org-email-link-description-format "Email %c: %.30s"
929 "Format of the description part of a link to an email or usenet message.
930 The following %-escapes will be replaced by corresponding information:
932 %F full \"From\" field
933 %f name, taken from \"From\" field, address if no name
934 %T full \"To\" field
935 %t first name in \"To\" field, address if no name
936 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
937 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
938 %s subject
939 %m message-id.
941 You may use normal field width specification between the % and the letter.
942 This is for example useful to limit the length of the subject.
944 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
945 :group 'org-link-store
946 :type 'string)
948 (defcustom org-from-is-user-regexp
949 (let (r1 r2)
950 (when (and user-mail-address (not (string= user-mail-address "")))
951 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
952 (when (and user-full-name (not (string= user-full-name "")))
953 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
954 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
955 "Regexp matched against the \"From:\" header of an email or usenet message.
956 It should match if the message is from the user him/herself."
957 :group 'org-link-store
958 :type 'regexp)
960 (defcustom org-link-to-org-use-id 'create-if-interactive
961 "Non-nil means, storing a link to an Org file will use entry IDs.
963 Note that before this variable is even considered, org-id must be loaded,
964 to please customize `org-modules' and turn it on.
966 The variable can have the following values:
968 t Create an ID if needed to make a link to the current entry.
970 create-if-interactive
971 If `org-store-link' is called directly (interactively, as a user
972 command), do create an ID to support the link. But when doing the
973 job for remember, only use the ID if it already exists. The
974 purpose of this setting is to avoid proliferation of unwanted
975 IDs, just because you happen to be in an Org file when you
976 call `org-remember' that automatically and preemptively
977 creates a link. If you do want to get an ID link in a remember
978 template to an entry not having an ID, create it first by
979 explicitly creating a link to it, using `C-c C-l' first.
981 use-existing
982 Use existing ID, do not create one.
984 nil Never use an ID to make a link, instead link using a text search for
985 the headline text."
986 :group 'org-link-store
987 :type '(choice
988 (const :tag "Create ID to make link" t)
989 (const :tag "Create if string link interactively"
990 'create-if-interactive)
991 (const :tag "Only use existing" 'use-existing)
992 (const :tag "Do not use ID to create link" nil)))
994 (defcustom org-context-in-file-links t
995 "Non-nil means, file links from `org-store-link' contain context.
996 A search string will be added to the file name with :: as separator and
997 used to find the context when the link is activated by the command
998 `org-open-at-point'.
999 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1000 negates this setting for the duration of the command."
1001 :group 'org-link-store
1002 :type 'boolean)
1004 (defcustom org-keep-stored-link-after-insertion nil
1005 "Non-nil means, keep link in list for entire session.
1007 The command `org-store-link' adds a link pointing to the current
1008 location to an internal list. These links accumulate during a session.
1009 The command `org-insert-link' can be used to insert links into any
1010 Org-mode file (offering completion for all stored links). When this
1011 option is nil, every link which has been inserted once using \\[org-insert-link]
1012 will be removed from the list, to make completing the unused links
1013 more efficient."
1014 :group 'org-link-store
1015 :type 'boolean)
1017 (defgroup org-link-follow nil
1018 "Options concerning following links in Org-mode."
1019 :tag "Org Follow Link"
1020 :group 'org-link)
1022 (defcustom org-link-translation-function nil
1023 "Function to translate links with different syntax to Org syntax.
1024 This can be used to translate links created for example by the Planner
1025 or emacs-wiki packages to Org syntax.
1026 The function must accept two parameters, a TYPE containing the link
1027 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1028 which is everything after the link protocol. It should return a cons
1029 with possibly modified values of type and path.
1030 Org contains a function for this, so if you set this variable to
1031 `org-translate-link-from-planner', you should be able follow many
1032 links created by planner."
1033 :group 'org-link-follow
1034 :type 'function)
1036 (defcustom org-follow-link-hook nil
1037 "Hook that is run after a link has been followed."
1038 :group 'org-link-follow
1039 :type 'hook)
1041 (defcustom org-tab-follows-link nil
1042 "Non-nil means, on links TAB will follow the link.
1043 Needs to be set before org.el is loaded."
1044 :group 'org-link-follow
1045 :type 'boolean)
1047 (defcustom org-return-follows-link nil
1048 "Non-nil means, on links RET will follow the link.
1049 Needs to be set before org.el is loaded."
1050 :group 'org-link-follow
1051 :type 'boolean)
1053 (defcustom org-mouse-1-follows-link
1054 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1055 "Non-nil means, mouse-1 on a link will follow the link.
1056 A longer mouse click will still set point. Does not work on XEmacs.
1057 Needs to be set before org.el is loaded."
1058 :group 'org-link-follow
1059 :type 'boolean)
1061 (defcustom org-mark-ring-length 4
1062 "Number of different positions to be recorded in the ring
1063 Changing this requires a restart of Emacs to work correctly."
1064 :group 'org-link-follow
1065 :type 'integer)
1067 (defcustom org-link-frame-setup
1068 '((vm . vm-visit-folder-other-frame)
1069 (gnus . gnus-other-frame)
1070 (file . find-file-other-window))
1071 "Setup the frame configuration for following links.
1072 When following a link with Emacs, it may often be useful to display
1073 this link in another window or frame. This variable can be used to
1074 set this up for the different types of links.
1075 For VM, use any of
1076 `vm-visit-folder'
1077 `vm-visit-folder-other-frame'
1078 For Gnus, use any of
1079 `gnus'
1080 `gnus-other-frame'
1081 `org-gnus-no-new-news'
1082 For FILE, use any of
1083 `find-file'
1084 `find-file-other-window'
1085 `find-file-other-frame'
1086 For the calendar, use the variable `calendar-setup'.
1087 For BBDB, it is currently only possible to display the matches in
1088 another window."
1089 :group 'org-link-follow
1090 :type '(list
1091 (cons (const vm)
1092 (choice
1093 (const vm-visit-folder)
1094 (const vm-visit-folder-other-window)
1095 (const vm-visit-folder-other-frame)))
1096 (cons (const gnus)
1097 (choice
1098 (const gnus)
1099 (const gnus-other-frame)
1100 (const org-gnus-no-new-news)))
1101 (cons (const file)
1102 (choice
1103 (const find-file)
1104 (const find-file-other-window)
1105 (const find-file-other-frame)))))
1107 (defcustom org-display-internal-link-with-indirect-buffer nil
1108 "Non-nil means, use indirect buffer to display infile links.
1109 Activating internal links (from one location in a file to another location
1110 in the same file) normally just jumps to the location. When the link is
1111 activated with a C-u prefix (or with mouse-3), the link is displayed in
1112 another window. When this option is set, the other window actually displays
1113 an indirect buffer clone of the current buffer, to avoid any visibility
1114 changes to the current buffer."
1115 :group 'org-link-follow
1116 :type 'boolean)
1118 (defcustom org-open-non-existing-files nil
1119 "Non-nil means, `org-open-file' will open non-existing files.
1120 When nil, an error will be generated."
1121 :group 'org-link-follow
1122 :type 'boolean)
1124 (defcustom org-open-directory-means-index-dot-org nil
1125 "Non-nil means, a link to a directory really means to index.org.
1126 When nil, following a directory link will run dired or open a finder/explorer
1127 window on that directory."
1128 :group 'org-link-follow
1129 :type 'boolean)
1131 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1132 "Function and arguments to call for following mailto links.
1133 This is a list with the first element being a lisp function, and the
1134 remaining elements being arguments to the function. In string arguments,
1135 %a will be replaced by the address, and %s will be replaced by the subject
1136 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1137 :group 'org-link-follow
1138 :type '(choice
1139 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1140 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1141 (const :tag "message-mail" (message-mail "%a" "%s"))
1142 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1144 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1145 "Non-nil means, ask for confirmation before executing shell links.
1146 Shell links can be dangerous: just think about a link
1148 [[shell:rm -rf ~/*][Google Search]]
1150 This link would show up in your Org-mode document as \"Google Search\",
1151 but really it would remove your entire home directory.
1152 Therefore we advise against setting this variable to nil.
1153 Just change it to `y-or-n-p' of you want to confirm with a
1154 single keystroke rather than having to type \"yes\"."
1155 :group 'org-link-follow
1156 :type '(choice
1157 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1158 (const :tag "with y-or-n (faster)" y-or-n-p)
1159 (const :tag "no confirmation (dangerous)" nil)))
1161 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1162 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1163 Elisp links can be dangerous: just think about a link
1165 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1167 This link would show up in your Org-mode document as \"Google Search\",
1168 but really it would remove your entire home directory.
1169 Therefore we advise against setting this variable to nil.
1170 Just change it to `y-or-n-p' of you want to confirm with a
1171 single keystroke rather than having to type \"yes\"."
1172 :group 'org-link-follow
1173 :type '(choice
1174 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1175 (const :tag "with y-or-n (faster)" y-or-n-p)
1176 (const :tag "no confirmation (dangerous)" nil)))
1178 (defconst org-file-apps-defaults-gnu
1179 '((remote . emacs)
1180 (system . mailcap)
1181 (t . mailcap))
1182 "Default file applications on a UNIX or GNU/Linux system.
1183 See `org-file-apps'.")
1185 (defconst org-file-apps-defaults-macosx
1186 '((remote . emacs)
1187 (t . "open %s")
1188 (system . "open %s")
1189 ("ps.gz" . "gv %s")
1190 ("eps.gz" . "gv %s")
1191 ("dvi" . "xdvi %s")
1192 ("fig" . "xfig %s"))
1193 "Default file applications on a MacOS X system.
1194 The system \"open\" is known as a default, but we use X11 applications
1195 for some files for which the OS does not have a good default.
1196 See `org-file-apps'.")
1198 (defconst org-file-apps-defaults-windowsnt
1199 (list
1200 '(remote . emacs)
1201 (cons t
1202 (list (if (featurep 'xemacs)
1203 'mswindows-shell-execute
1204 'w32-shell-execute)
1205 "open" 'file))
1206 (cons 'system
1207 (list (if (featurep 'xemacs)
1208 'mswindows-shell-execute
1209 'w32-shell-execute)
1210 "open" 'file)))
1211 "Default file applications on a Windows NT system.
1212 The system \"open\" is used for most files.
1213 See `org-file-apps'.")
1215 (defcustom org-file-apps
1217 (auto-mode . emacs)
1218 ("\\.x?html?\\'" . default)
1219 ("\\.pdf\\'" . default)
1221 "External applications for opening `file:path' items in a document.
1222 Org-mode uses system defaults for different file types, but
1223 you can use this variable to set the application for a given file
1224 extension. The entries in this list are cons cells where the car identifies
1225 files and the cdr the corresponding command. Possible values for the
1226 file identifier are
1227 \"regex\" Regular expression matched against the file name. For backward
1228 compatibility, this can also be a string with only alphanumeric
1229 characters, which is then interpreted as an extension.
1230 `directory' Matches a directory
1231 `remote' Matches a remote file, accessible through tramp or efs.
1232 Remote files most likely should be visited through Emacs
1233 because external applications cannot handle such paths.
1234 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1235 so all files Emacs knows how to handle. Using this with
1236 command `emacs' will open most files in Emacs. Beware that this
1237 will also open html files inside Emacs, unless you add
1238 (\"html\" . default) to the list as well.
1239 t Default for files not matched by any of the other options.
1240 `system' The system command to open files, like `open' on Windows
1241 and Mac OS X, and mailcap under GNU/Linux. This is the command
1242 that will be selected if you call `C-c C-o' with a double
1243 `C-u C-u' prefix.
1245 Possible values for the command are:
1246 `emacs' The file will be visited by the current Emacs process.
1247 `default' Use the default application for this file type, which is the
1248 association for t in the list, most likely in the system-specific
1249 part.
1250 This can be used to overrule an unwanted setting in the
1251 system-specific variable.
1252 `system' Use the system command for opening files, like \"open\".
1253 This command is specified by the entry whose car is `system'.
1254 Most likely, the system-specific version of this variable
1255 does define this command, but you can overrule/replace it
1256 here.
1257 string A command to be executed by a shell; %s will be replaced
1258 by the path to the file.
1259 sexp A Lisp form which will be evaluated. The file path will
1260 be available in the Lisp variable `file'.
1261 For more examples, see the system specific constants
1262 `org-file-apps-defaults-macosx'
1263 `org-file-apps-defaults-windowsnt'
1264 `org-file-apps-defaults-gnu'."
1265 :group 'org-link-follow
1266 :type '(repeat
1267 (cons (choice :value ""
1268 (string :tag "Extension")
1269 (const :tag "System command to open files" system)
1270 (const :tag "Default for unrecognized files" t)
1271 (const :tag "Remote file" remote)
1272 (const :tag "Links to a directory" directory)
1273 (const :tag "Any files that have Emacs modes"
1274 auto-mode))
1275 (choice :value ""
1276 (const :tag "Visit with Emacs" emacs)
1277 (const :tag "Use default" default)
1278 (const :tag "Use the system command" system)
1279 (string :tag "Command")
1280 (sexp :tag "Lisp form")))))
1282 (defgroup org-refile nil
1283 "Options concerning refiling entries in Org-mode."
1284 :tag "Org Refile"
1285 :group 'org)
1287 (defcustom org-directory "~/org"
1288 "Directory with org files.
1289 This directory will be used as default to prompt for org files.
1290 Used by the hooks for remember.el."
1291 :group 'org-refile
1292 :group 'org-remember
1293 :type 'directory)
1295 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1296 "Default target for storing notes.
1297 Used by the hooks for remember.el. This can be a string, or nil to mean
1298 the value of `remember-data-file'.
1299 You can set this on a per-template basis with the variable
1300 `org-remember-templates'."
1301 :group 'org-refile
1302 :group 'org-remember
1303 :type '(choice
1304 (const :tag "Default from remember-data-file" nil)
1305 file))
1307 (defcustom org-goto-interface 'outline
1308 "The default interface to be used for `org-goto'.
1309 Allowed values are:
1310 outline The interface shows an outline of the relevant file
1311 and the correct heading is found by moving through
1312 the outline or by searching with incremental search.
1313 outline-path-completion Headlines in the current buffer are offered via
1314 completion. This is the interface also used by
1315 the refile command."
1316 :group 'org-refile
1317 :type '(choice
1318 (const :tag "Outline" outline)
1319 (const :tag "Outline-path-completion" outline-path-completion)))
1321 (defcustom org-goto-max-level 5
1322 "Maximum level to be considered when running org-goto with refile interface."
1323 :group 'org-refile
1324 :type 'number)
1326 (defcustom org-reverse-note-order nil
1327 "Non-nil means, store new notes at the beginning of a file or entry.
1328 When nil, new notes will be filed to the end of a file or entry.
1329 This can also be a list with cons cells of regular expressions that
1330 are matched against file names, and values."
1331 :group 'org-remember
1332 :group 'org-refile
1333 :type '(choice
1334 (const :tag "Reverse always" t)
1335 (const :tag "Reverse never" nil)
1336 (repeat :tag "By file name regexp"
1337 (cons regexp boolean))))
1339 (defcustom org-refile-targets nil
1340 "Targets for refiling entries with \\[org-refile].
1341 This is list of cons cells. Each cell contains:
1342 - a specification of the files to be considered, either a list of files,
1343 or a symbol whose function or variable value will be used to retrieve
1344 a file name or a list of file names. If you use `org-agenda-files' for
1345 that, all agenda files will be scanned for targets. Nil means, consider
1346 headings in the current buffer.
1347 - A specification of how to select find candidate refile targets. This
1348 may be any of
1349 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1350 This tag has to be present in all target headlines, inheritance will
1351 not be considered.
1352 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1353 todo keyword.
1354 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1355 headlines that are refiling targets.
1356 - a cons cell (:level . N). Any headline of level N is considered a target.
1357 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1359 When this variable is nil, all top-level headlines in the current buffer
1360 are used, equivalent to the value `((nil . (:level . 1))'."
1361 :group 'org-refile
1362 :type '(repeat
1363 (cons
1364 (choice :value org-agenda-files
1365 (const :tag "All agenda files" org-agenda-files)
1366 (const :tag "Current buffer" nil)
1367 (function) (variable) (file))
1368 (choice :tag "Identify target headline by"
1369 (cons :tag "Specific tag" (const :value :tag) (string))
1370 (cons :tag "TODO keyword" (const :value :todo) (string))
1371 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1372 (cons :tag "Level number" (const :value :level) (integer))
1373 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1375 (defcustom org-refile-use-outline-path nil
1376 "Non-nil means, provide refile targets as paths.
1377 So a level 3 headline will be available as level1/level2/level3.
1378 When the value is `file', also include the file name (without directory)
1379 into the path. When `full-file-path', include the full file path."
1380 :group 'org-refile
1381 :type '(choice
1382 (const :tag "Not" nil)
1383 (const :tag "Yes" t)
1384 (const :tag "Start with file name" file)
1385 (const :tag "Start with full file path" full-file-path)))
1387 (defcustom org-outline-path-complete-in-steps t
1388 "Non-nil means, complete the outline path in hierarchical steps.
1389 When Org-mode uses the refile interface to select an outline path
1390 \(see variable `org-refile-use-outline-path'), the completion of
1391 the path can be done is a single go, or if can be done in steps down
1392 the headline hierarchy. Going in steps is probably the best if you
1393 do not use a special completion package like `ido' or `icicles'.
1394 However, when using these packages, going in one step can be very
1395 fast, while still showing the whole path to the entry."
1396 :group 'org-refile
1397 :type 'boolean)
1399 (defgroup org-todo nil
1400 "Options concerning TODO items in Org-mode."
1401 :tag "Org TODO"
1402 :group 'org)
1404 (defgroup org-progress nil
1405 "Options concerning Progress logging in Org-mode."
1406 :tag "Org Progress"
1407 :group 'org-time)
1409 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1410 "List of TODO entry keyword sequences and their interpretation.
1411 \\<org-mode-map>This is a list of sequences.
1413 Each sequence starts with a symbol, either `sequence' or `type',
1414 indicating if the keywords should be interpreted as a sequence of
1415 action steps, or as different types of TODO items. The first
1416 keywords are states requiring action - these states will select a headline
1417 for inclusion into the global TODO list Org-mode produces. If one of
1418 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1419 signify that no further action is necessary. If \"|\" is not found,
1420 the last keyword is treated as the only DONE state of the sequence.
1422 The command \\[org-todo] cycles an entry through these states, and one
1423 additional state where no keyword is present. For details about this
1424 cycling, see the manual.
1426 TODO keywords and interpretation can also be set on a per-file basis with
1427 the special #+SEQ_TODO and #+TYP_TODO lines.
1429 Each keyword can optionally specify a character for fast state selection
1430 \(in combination with the variable `org-use-fast-todo-selection')
1431 and specifiers for state change logging, using the same syntax
1432 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1433 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1434 indicates to record a time stamp each time this state is selected.
1436 Each keyword may also specify if a timestamp or a note should be
1437 recorded when entering or leaving the state, by adding additional
1438 characters in the parenthesis after the keyword. This looks like this:
1439 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1440 record only the time of the state change. With X and Y being either
1441 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1442 Y when leaving the state if and only if the *target* state does not
1443 define X. You may omit any of the fast-selection key or X or /Y,
1444 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1446 For backward compatibility, this variable may also be just a list
1447 of keywords - in this case the interpretation (sequence or type) will be
1448 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1449 :group 'org-todo
1450 :group 'org-keywords
1451 :type '(choice
1452 (repeat :tag "Old syntax, just keywords"
1453 (string :tag "Keyword"))
1454 (repeat :tag "New syntax"
1455 (cons
1456 (choice
1457 :tag "Interpretation"
1458 (const :tag "Sequence (cycling hits every state)" sequence)
1459 (const :tag "Type (cycling directly to DONE)" type))
1460 (repeat
1461 (string :tag "Keyword"))))))
1463 (defvar org-todo-keywords-1 nil
1464 "All TODO and DONE keywords active in a buffer.")
1465 (make-variable-buffer-local 'org-todo-keywords-1)
1466 (defvar org-todo-keywords-for-agenda nil)
1467 (defvar org-done-keywords-for-agenda nil)
1468 (defvar org-todo-keyword-alist-for-agenda nil)
1469 (defvar org-tag-alist-for-agenda nil)
1470 (defvar org-agenda-contributing-files nil)
1471 (defvar org-not-done-keywords nil)
1472 (make-variable-buffer-local 'org-not-done-keywords)
1473 (defvar org-done-keywords nil)
1474 (make-variable-buffer-local 'org-done-keywords)
1475 (defvar org-todo-heads nil)
1476 (make-variable-buffer-local 'org-todo-heads)
1477 (defvar org-todo-sets nil)
1478 (make-variable-buffer-local 'org-todo-sets)
1479 (defvar org-todo-log-states nil)
1480 (make-variable-buffer-local 'org-todo-log-states)
1481 (defvar org-todo-kwd-alist nil)
1482 (make-variable-buffer-local 'org-todo-kwd-alist)
1483 (defvar org-todo-key-alist nil)
1484 (make-variable-buffer-local 'org-todo-key-alist)
1485 (defvar org-todo-key-trigger nil)
1486 (make-variable-buffer-local 'org-todo-key-trigger)
1488 (defcustom org-todo-interpretation 'sequence
1489 "Controls how TODO keywords are interpreted.
1490 This variable is in principle obsolete and is only used for
1491 backward compatibility, if the interpretation of todo keywords is
1492 not given already in `org-todo-keywords'. See that variable for
1493 more information."
1494 :group 'org-todo
1495 :group 'org-keywords
1496 :type '(choice (const sequence)
1497 (const type)))
1499 (defcustom org-use-fast-todo-selection 'prefix
1500 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1501 This variable describes if and under what circumstances the cycling
1502 mechanism for TODO keywords will be replaced by a single-key, direct
1503 selection scheme.
1505 When nil, fast selection is never used.
1507 When the symbol `prefix', it will be used when `org-todo' is called with
1508 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1509 in an agenda buffer.
1511 When t, fast selection is used by default. In this case, the prefix
1512 argument forces cycling instead.
1514 In all cases, the special interface is only used if access keys have actually
1515 been assigned by the user, i.e. if keywords in the configuration are followed
1516 by a letter in parenthesis, like TODO(t)."
1517 :group 'org-todo
1518 :type '(choice
1519 (const :tag "Never" nil)
1520 (const :tag "By default" t)
1521 (const :tag "Only with C-u C-c C-t" prefix)))
1523 (defcustom org-provide-todo-statistics t
1524 "Non-nil means, update todo statistics after insert and toggle.
1525 When this is set, todo statistics is updated in the parent of the current
1526 entry each time a todo state is changed."
1527 :group 'org-todo
1528 :type 'boolean)
1530 (defcustom org-after-todo-state-change-hook nil
1531 "Hook which is run after the state of a TODO item was changed.
1532 The new state (a string with a TODO keyword, or nil) is available in the
1533 Lisp variable `state'."
1534 :group 'org-todo
1535 :type 'hook)
1537 (defcustom org-todo-state-tags-triggers nil
1538 "Tag changes that should be triggered by TODO state changes.
1539 This is a list. Each entry is
1541 (state-change (tag . flag) .......)
1543 State-change can be a string with a state, and empty string to indicate the
1544 state that has no TODO keyword, or it can be one of the symbols `todo'
1545 or `done', meaning any not-done or done state, respectively."
1546 :group 'org-todo
1547 :group 'org-tags
1548 :type '(repeat
1549 (cons (choice :tag "When changing to"
1550 (const :tag "Not-done state" todo)
1551 (const :tag "Done state" done)
1552 (string :tag "State"))
1553 (repeat
1554 (cons :tag "Tag action"
1555 (string :tag "Tag")
1556 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1558 (defcustom org-log-done nil
1559 "Information to record when a task moves to the DONE state.
1561 Possible values are:
1563 nil Don't add anything, just change the keyword
1564 time Add a time stamp to the task
1565 note Prompt a closing note and add it with template `org-log-note-headings'
1567 This option can also be set with on a per-file-basis with
1569 #+STARTUP: nologdone
1570 #+STARTUP: logdone
1571 #+STARTUP: lognotedone
1573 You can have local logging settings for a subtree by setting the LOGGING
1574 property to one or more of these keywords."
1575 :group 'org-todo
1576 :group 'org-progress
1577 :type '(choice
1578 (const :tag "No logging" nil)
1579 (const :tag "Record CLOSED timestamp" time)
1580 (const :tag "Record CLOSED timestamp with closing note." note)))
1582 ;; Normalize old uses of org-log-done.
1583 (cond
1584 ((eq org-log-done t) (setq org-log-done 'time))
1585 ((and (listp org-log-done) (memq 'done org-log-done))
1586 (setq org-log-done 'note)))
1588 (defcustom org-log-note-clock-out nil
1589 "Non-nil means, record a note when clocking out of an item.
1590 This can also be configured on a per-file basis by adding one of
1591 the following lines anywhere in the buffer:
1593 #+STARTUP: lognoteclock-out
1594 #+STARTUP: nolognoteclock-out"
1595 :group 'org-todo
1596 :group 'org-progress
1597 :type 'boolean)
1599 (defcustom org-log-done-with-time t
1600 "Non-nil means, the CLOSED time stamp will contain date and time.
1601 When nil, only the date will be recorded."
1602 :group 'org-progress
1603 :type 'boolean)
1605 (defcustom org-log-note-headings
1606 '((done . "CLOSING NOTE %t")
1607 (state . "State %-12s %t")
1608 (note . "Note taken on %t")
1609 (clock-out . ""))
1610 "Headings for notes added to entries.
1611 The value is an alist, with the car being a symbol indicating the note
1612 context, and the cdr is the heading to be used. The heading may also be the
1613 empty string.
1614 %t in the heading will be replaced by a time stamp.
1615 %s will be replaced by the new TODO state, in double quotes.
1616 %u will be replaced by the user name.
1617 %U will be replaced by the full user name."
1618 :group 'org-todo
1619 :group 'org-progress
1620 :type '(list :greedy t
1621 (cons (const :tag "Heading when closing an item" done) string)
1622 (cons (const :tag
1623 "Heading when changing todo state (todo sequence only)"
1624 state) string)
1625 (cons (const :tag "Heading when just taking a note" note) string)
1626 (cons (const :tag "Heading when clocking out" clock-out) string)))
1628 (unless (assq 'note org-log-note-headings)
1629 (push '(note . "%t") org-log-note-headings))
1631 (defcustom org-log-state-notes-insert-after-drawers nil
1632 "Non-nil means, insert state change notes after any drawers in entry.
1633 Only the drawers that *immediately* follow the headline and the
1634 deadline/scheduled line are skipped.
1635 When nil, insert notes right after the heading and perhaps the line
1636 with deadline/scheduling if present."
1637 :group 'org-todo
1638 :group 'org-progress
1639 :type 'boolean)
1641 (defcustom org-log-states-order-reversed t
1642 "Non-nil means, the latest state change note will be directly after heading.
1643 When nil, the notes will be orderer according to time."
1644 :group 'org-todo
1645 :group 'org-progress
1646 :type 'boolean)
1648 (defcustom org-log-repeat 'time
1649 "Non-nil means, record moving through the DONE state when triggering repeat.
1650 An auto-repeating tasks is immediately switched back to TODO when marked
1651 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1652 the TODO keyword definition, or recording a closing note by setting
1653 `org-log-done', there will be no record of the task moving through DONE.
1654 This variable forces taking a note anyway. Possible values are:
1656 nil Don't force a record
1657 time Record a time stamp
1658 note Record a note
1660 This option can also be set with on a per-file-basis with
1662 #+STARTUP: logrepeat
1663 #+STARTUP: lognoterepeat
1664 #+STARTUP: nologrepeat
1666 You can have local logging settings for a subtree by setting the LOGGING
1667 property to one or more of these keywords."
1668 :group 'org-todo
1669 :group 'org-progress
1670 :type '(choice
1671 (const :tag "Don't force a record" nil)
1672 (const :tag "Force recording the DONE state" time)
1673 (const :tag "Force recording a note with the DONE state" note)))
1676 (defgroup org-priorities nil
1677 "Priorities in Org-mode."
1678 :tag "Org Priorities"
1679 :group 'org-todo)
1681 (defcustom org-highest-priority ?A
1682 "The highest priority of TODO items. A character like ?A, ?B etc.
1683 Must have a smaller ASCII number than `org-lowest-priority'."
1684 :group 'org-priorities
1685 :type 'character)
1687 (defcustom org-lowest-priority ?C
1688 "The lowest priority of TODO items. A character like ?A, ?B etc.
1689 Must have a larger ASCII number than `org-highest-priority'."
1690 :group 'org-priorities
1691 :type 'character)
1693 (defcustom org-default-priority ?B
1694 "The default priority of TODO items.
1695 This is the priority an item get if no explicit priority is given."
1696 :group 'org-priorities
1697 :type 'character)
1699 (defcustom org-priority-start-cycle-with-default t
1700 "Non-nil means, start with default priority when starting to cycle.
1701 When this is nil, the first step in the cycle will be (depending on the
1702 command used) one higher or lower that the default priority."
1703 :group 'org-priorities
1704 :type 'boolean)
1706 (defgroup org-time nil
1707 "Options concerning time stamps and deadlines in Org-mode."
1708 :tag "Org Time"
1709 :group 'org)
1711 (defcustom org-insert-labeled-timestamps-at-point nil
1712 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1713 When nil, these labeled time stamps are forces into the second line of an
1714 entry, just after the headline. When scheduling from the global TODO list,
1715 the time stamp will always be forced into the second line."
1716 :group 'org-time
1717 :type 'boolean)
1719 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1720 "Formats for `format-time-string' which are used for time stamps.
1721 It is not recommended to change this constant.")
1723 (defcustom org-time-stamp-rounding-minutes '(0 5)
1724 "Number of minutes to round time stamps to.
1725 These are two values, the first applies when first creating a time stamp.
1726 The second applies when changing it with the commands `S-up' and `S-down'.
1727 When changing the time stamp, this means that it will change in steps
1728 of N minutes, as given by the second value.
1730 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1731 numbers should be factors of 60, so for example 5, 10, 15.
1733 When this is larger than 1, you can still force an exact time-stamp by using
1734 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1735 and by using a prefix arg to `S-up/down' to specify the exact number
1736 of minutes to shift."
1737 :group 'org-time
1738 :get '(lambda (var) ; Make sure all entries have 5 elements
1739 (if (integerp (default-value var))
1740 (list (default-value var) 5)
1741 (default-value var)))
1742 :type '(list
1743 (integer :tag "when inserting times")
1744 (integer :tag "when modifying times")))
1746 ;; Normalize old customizations of this variable.
1747 (when (integerp org-time-stamp-rounding-minutes)
1748 (setq org-time-stamp-rounding-minutes
1749 (list org-time-stamp-rounding-minutes
1750 org-time-stamp-rounding-minutes)))
1752 (defcustom org-display-custom-times nil
1753 "Non-nil means, overlay custom formats over all time stamps.
1754 The formats are defined through the variable `org-time-stamp-custom-formats'.
1755 To turn this on on a per-file basis, insert anywhere in the file:
1756 #+STARTUP: customtime"
1757 :group 'org-time
1758 :set 'set-default
1759 :type 'sexp)
1760 (make-variable-buffer-local 'org-display-custom-times)
1762 (defcustom org-time-stamp-custom-formats
1763 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1764 "Custom formats for time stamps. See `format-time-string' for the syntax.
1765 These are overlayed over the default ISO format if the variable
1766 `org-display-custom-times' is set. Time like %H:%M should be at the
1767 end of the second format."
1768 :group 'org-time
1769 :type 'sexp)
1771 (defun org-time-stamp-format (&optional long inactive)
1772 "Get the right format for a time string."
1773 (let ((f (if long (cdr org-time-stamp-formats)
1774 (car org-time-stamp-formats))))
1775 (if inactive
1776 (concat "[" (substring f 1 -1) "]")
1777 f)))
1779 (defcustom org-time-clocksum-format "%d:%02d"
1780 "The format string used when creating CLOCKSUM lines, or when
1781 org-mode generates a time duration."
1782 :group 'org-time
1783 :type 'string)
1785 (defcustom org-deadline-warning-days 14
1786 "No. of days before expiration during which a deadline becomes active.
1787 This variable governs the display in sparse trees and in the agenda.
1788 When 0 or negative, it means use this number (the absolute value of it)
1789 even if a deadline has a different individual lead time specified."
1790 :group 'org-time
1791 :group 'org-agenda-daily/weekly
1792 :type 'number)
1794 (defcustom org-read-date-prefer-future t
1795 "Non-nil means, assume future for incomplete date input from user.
1796 This affects the following situations:
1797 1. The user gives a day, but no month.
1798 For example, if today is the 15th, and you enter \"3\", Org-mode will
1799 read this as the third of *next* month. However, if you enter \"17\",
1800 it will be considered as *this* month.
1801 2. The user gives a month but not a year.
1802 For example, if it is april and you enter \"feb 2\", this will be read
1803 as feb 2, *next* year. \"May 5\", however, will be this year.
1805 Currently this does not work for ISO week specifications.
1807 When this option is nil, the current month and year will always be used
1808 as defaults."
1809 :group 'org-time
1810 :type 'boolean)
1812 (defcustom org-read-date-display-live t
1813 "Non-nil means, display current interpretation of date prompt live.
1814 This display will be in an overlay, in the minibuffer."
1815 :group 'org-time
1816 :type 'boolean)
1818 (defcustom org-read-date-popup-calendar t
1819 "Non-nil means, pop up a calendar when prompting for a date.
1820 In the calendar, the date can be selected with mouse-1. However, the
1821 minibuffer will also be active, and you can simply enter the date as well.
1822 When nil, only the minibuffer will be available."
1823 :group 'org-time
1824 :type 'boolean)
1825 (if (fboundp 'defvaralias)
1826 (defvaralias 'org-popup-calendar-for-date-prompt
1827 'org-read-date-popup-calendar))
1829 (defcustom org-extend-today-until 0
1830 "The hour when your day really ends. Must be an integer.
1831 This has influence for the following applications:
1832 - When switching the agenda to \"today\". It it is still earlier than
1833 the time given here, the day recognized as TODAY is actually yesterday.
1834 - When a date is read from the user and it is still before the time given
1835 here, the current date and time will be assumed to be yesterday, 23:59.
1836 Also, timestamps inserted in remember templates follow this rule.
1838 IMPORTANT: This is a feature whose implementation is and likely will
1839 remain incomplete. Really, it is only here because past midnight seems to
1840 be the favorite working time of John Wiegley :-)"
1841 :group 'org-time
1842 :type 'number)
1844 (defcustom org-edit-timestamp-down-means-later nil
1845 "Non-nil means, S-down will increase the time in a time stamp.
1846 When nil, S-up will increase."
1847 :group 'org-time
1848 :type 'boolean)
1850 (defcustom org-calendar-follow-timestamp-change t
1851 "Non-nil means, make the calendar window follow timestamp changes.
1852 When a timestamp is modified and the calendar window is visible, it will be
1853 moved to the new date."
1854 :group 'org-time
1855 :type 'boolean)
1857 (defgroup org-tags nil
1858 "Options concerning tags in Org-mode."
1859 :tag "Org Tags"
1860 :group 'org)
1862 (defcustom org-tag-alist nil
1863 "List of tags allowed in Org-mode files.
1864 When this list is nil, Org-mode will base TAG input on what is already in the
1865 buffer.
1866 The value of this variable is an alist, the car of each entry must be a
1867 keyword as a string, the cdr may be a character that is used to select
1868 that tag through the fast-tag-selection interface.
1869 See the manual for details."
1870 :group 'org-tags
1871 :type '(repeat
1872 (choice
1873 (cons (string :tag "Tag name")
1874 (character :tag "Access char"))
1875 (const :tag "Start radio group" (:startgroup))
1876 (const :tag "End radio group" (:endgroup)))))
1878 (defvar org-file-tags nil
1879 "List of tags that can be inherited by all entries in the file.
1880 The tags will be inherited if the variable `org-use-tag-inheritance'
1881 says they should be.
1882 This variable is populated from #+TAG lines.")
1884 (defcustom org-use-fast-tag-selection 'auto
1885 "Non-nil means, use fast tag selection scheme.
1886 This is a special interface to select and deselect tags with single keys.
1887 When nil, fast selection is never used.
1888 When the symbol `auto', fast selection is used if and only if selection
1889 characters for tags have been configured, either through the variable
1890 `org-tag-alist' or through a #+TAGS line in the buffer.
1891 When t, fast selection is always used and selection keys are assigned
1892 automatically if necessary."
1893 :group 'org-tags
1894 :type '(choice
1895 (const :tag "Always" t)
1896 (const :tag "Never" nil)
1897 (const :tag "When selection characters are configured" 'auto)))
1899 (defcustom org-fast-tag-selection-single-key nil
1900 "Non-nil means, fast tag selection exits after first change.
1901 When nil, you have to press RET to exit it.
1902 During fast tag selection, you can toggle this flag with `C-c'.
1903 This variable can also have the value `expert'. In this case, the window
1904 displaying the tags menu is not even shown, until you press C-c again."
1905 :group 'org-tags
1906 :type '(choice
1907 (const :tag "No" nil)
1908 (const :tag "Yes" t)
1909 (const :tag "Expert" expert)))
1911 (defvar org-fast-tag-selection-include-todo nil
1912 "Non-nil means, fast tags selection interface will also offer TODO states.
1913 This is an undocumented feature, you should not rely on it.")
1915 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1916 "The column to which tags should be indented in a headline.
1917 If this number is positive, it specifies the column. If it is negative,
1918 it means that the tags should be flushright to that column. For example,
1919 -80 works well for a normal 80 character screen."
1920 :group 'org-tags
1921 :type 'integer)
1923 (defcustom org-auto-align-tags t
1924 "Non-nil means, realign tags after pro/demotion of TODO state change.
1925 These operations change the length of a headline and therefore shift
1926 the tags around. With this options turned on, after each such operation
1927 the tags are again aligned to `org-tags-column'."
1928 :group 'org-tags
1929 :type 'boolean)
1931 (defcustom org-use-tag-inheritance t
1932 "Non-nil means, tags in levels apply also for sublevels.
1933 When nil, only the tags directly given in a specific line apply there.
1934 This may also be a list of tags that should be inherited, or a regexp that
1935 matches tags that should be inherited. Additional control is possible
1936 with the variable `org-tags-exclude-from-inheritance' which gives an
1937 explicit list of tags to be excluded from inheritance., even if the value of
1938 `org-use-tag-inheritance' would select it for inheritance.
1940 If this option is t, a match early-on in a tree can lead to a large
1941 number of matches in the subtree when constructing the agenda or creating
1942 a sparse tree. If you only want to see the first match in a tree during
1943 a search, check out the variable `org-tags-match-list-sublevels'."
1944 :group 'org-tags
1945 :type '(choice
1946 (const :tag "Not" nil)
1947 (const :tag "Always" t)
1948 (repeat :tag "Specific tags" (string :tag "Tag"))
1949 (regexp :tag "Tags matched by regexp")))
1951 (defcustom org-tags-exclude-from-inheritance nil
1952 "List of tags that should never be inherited.
1953 This is a way to exclude a few tags from inheritance. For way to do
1954 the opposite, to actively allow inheritance for selected tags,
1955 see the variable `org-use-tag-inheritance'."
1956 :group 'org-tags
1957 :type '(repeat (string :tag "Tag")))
1959 (defun org-tag-inherit-p (tag)
1960 "Check if TAG is one that should be inherited."
1961 (cond
1962 ((member tag org-tags-exclude-from-inheritance) nil)
1963 ((eq org-use-tag-inheritance t) t)
1964 ((not org-use-tag-inheritance) nil)
1965 ((stringp org-use-tag-inheritance)
1966 (string-match org-use-tag-inheritance tag))
1967 ((listp org-use-tag-inheritance)
1968 (member tag org-use-tag-inheritance))
1969 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1971 (defcustom org-tags-match-list-sublevels t
1972 "Non-nil means list also sublevels of headlines matching tag search.
1973 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1974 the sublevels of a headline matching a tag search often also match
1975 the same search. Listing all of them can create very long lists.
1976 Setting this variable to nil causes subtrees of a match to be skipped.
1977 This option is off by default, because inheritance in on. If you turn
1978 inheritance off, you very likely want to turn this option on.
1980 As a special case, if the tag search is restricted to TODO items, the
1981 value of this variable is ignored and sublevels are always checked, to
1982 make sure all corresponding TODO items find their way into the list.
1984 This variable is semi-obsolete and probably should always be true. It
1985 is better to limit inheritance to certain tags using the variables
1986 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
1987 :group 'org-tags
1988 :type 'boolean)
1990 (defvar org-tags-history nil
1991 "History of minibuffer reads for tags.")
1992 (defvar org-last-tags-completion-table nil
1993 "The last used completion table for tags.")
1994 (defvar org-after-tags-change-hook nil
1995 "Hook that is run after the tags in a line have changed.")
1997 (defgroup org-properties nil
1998 "Options concerning properties in Org-mode."
1999 :tag "Org Properties"
2000 :group 'org)
2002 (defcustom org-property-format "%-10s %s"
2003 "How property key/value pairs should be formatted by `indent-line'.
2004 When `indent-line' hits a property definition, it will format the line
2005 according to this format, mainly to make sure that the values are
2006 lined-up with respect to each other."
2007 :group 'org-properties
2008 :type 'string)
2010 (defcustom org-use-property-inheritance nil
2011 "Non-nil means, properties apply also for sublevels.
2013 This setting is chiefly used during property searches. Turning it on can
2014 cause significant overhead when doing a search, which is why it is not
2015 on by default.
2017 When nil, only the properties directly given in the current entry count.
2018 When t, every property is inherited. The value may also be a list of
2019 properties that should have inheritance, or a regular expression matching
2020 properties that should be inherited.
2022 However, note that some special properties use inheritance under special
2023 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2024 and the properties ending in \"_ALL\" when they are used as descriptor
2025 for valid values of a property.
2027 Note for programmers:
2028 When querying an entry with `org-entry-get', you can control if inheritance
2029 should be used. By default, `org-entry-get' looks only at the local
2030 properties. You can request inheritance by setting the inherit argument
2031 to t (to force inheritance) or to `selective' (to respect the setting
2032 in this variable)."
2033 :group 'org-properties
2034 :type '(choice
2035 (const :tag "Not" nil)
2036 (const :tag "Always" t)
2037 (repeat :tag "Specific properties" (string :tag "Property"))
2038 (regexp :tag "Properties matched by regexp")))
2040 (defun org-property-inherit-p (property)
2041 "Check if PROPERTY is one that should be inherited."
2042 (cond
2043 ((eq org-use-property-inheritance t) t)
2044 ((not org-use-property-inheritance) nil)
2045 ((stringp org-use-property-inheritance)
2046 (string-match org-use-property-inheritance property))
2047 ((listp org-use-property-inheritance)
2048 (member property org-use-property-inheritance))
2049 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2051 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2052 "The default column format, if no other format has been defined.
2053 This variable can be set on the per-file basis by inserting a line
2055 #+COLUMNS: %25ITEM ....."
2056 :group 'org-properties
2057 :type 'string)
2059 (defcustom org-columns-ellipses ".."
2060 "The ellipses to be used when a field in column view is truncated.
2061 When this is the empty string, as many characters as possible are shown,
2062 but then there will be no visual indication that the field has been truncated.
2063 When this is a string of length N, the last N characters of a truncated
2064 field are replaced by this string. If the column is narrower than the
2065 ellipses string, only part of the ellipses string will be shown."
2066 :group 'org-properties
2067 :type 'string)
2069 (defcustom org-columns-modify-value-for-display-function nil
2070 "Function that modifies values for display in column view.
2071 For example, it can be used to cut out a certain part from a time stamp.
2072 The function must take 2 arguments:
2074 column-title The title of the column (*not* the property name)
2075 value The value that should be modified.
2077 The function should return the value that should be displayed,
2078 or nil if the normal value should be used."
2079 :group 'org-properties
2080 :type 'function)
2082 (defcustom org-effort-property "Effort"
2083 "The property that is being used to keep track of effort estimates.
2084 Effort estimates given in this property need to have the format H:MM."
2085 :group 'org-properties
2086 :group 'org-progress
2087 :type '(string :tag "Property"))
2089 (defconst org-global-properties-fixed
2090 '(("VISIBILITY_ALL" . "folded children content all"))
2091 "List of property/value pairs that can be inherited by any entry.
2092 These are fixed values, for the preset properties.")
2095 (defcustom org-global-properties nil
2096 "List of property/value pairs that can be inherited by any entry.
2097 You can set buffer-local values for the same purpose in the variable
2098 `org-file-properties' this by adding lines like
2100 #+PROPERTY: NAME VALUE"
2101 :group 'org-properties
2102 :type '(repeat
2103 (cons (string :tag "Property")
2104 (string :tag "Value"))))
2106 (defvar org-file-properties nil
2107 "List of property/value pairs that can be inherited by any entry.
2108 Valid for the current buffer.
2109 This variable is populated from #+PROPERTY lines.")
2110 (make-variable-buffer-local 'org-file-properties)
2112 (defgroup org-agenda nil
2113 "Options concerning agenda views in Org-mode."
2114 :tag "Org Agenda"
2115 :group 'org)
2117 (defvar org-category nil
2118 "Variable used by org files to set a category for agenda display.
2119 Such files should use a file variable to set it, for example
2121 # -*- mode: org; org-category: \"ELisp\"
2123 or contain a special line
2125 #+CATEGORY: ELisp
2127 If the file does not specify a category, then file's base name
2128 is used instead.")
2129 (make-variable-buffer-local 'org-category)
2130 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2132 (defcustom org-agenda-files nil
2133 "The files to be used for agenda display.
2134 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2135 \\[org-remove-file]. You can also use customize to edit the list.
2137 If an entry is a directory, all files in that directory that are matched by
2138 `org-agenda-file-regexp' will be part of the file list.
2140 If the value of the variable is not a list but a single file name, then
2141 the list of agenda files is actually stored and maintained in that file, one
2142 agenda file per line."
2143 :group 'org-agenda
2144 :type '(choice
2145 (repeat :tag "List of files and directories" file)
2146 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2148 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2149 "Regular expression to match files for `org-agenda-files'.
2150 If any element in the list in that variable contains a directory instead
2151 of a normal file, all files in that directory that are matched by this
2152 regular expression will be included."
2153 :group 'org-agenda
2154 :type 'regexp)
2156 (defcustom org-agenda-text-search-extra-files nil
2157 "List of extra files to be searched by text search commands.
2158 These files will be search in addition to the agenda files by the
2159 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2160 Note that these files will only be searched for text search commands,
2161 not for the other agenda views like todo lists, tag searches or the weekly
2162 agenda. This variable is intended to list notes and possibly archive files
2163 that should also be searched by these two commands.
2164 In fact, if the first element in the list is the symbol `agenda-archives',
2165 than all archive files of all agenda files will be added to the search
2166 scope."
2167 :group 'org-agenda
2168 :type '(set :greedy t
2169 (const :tag "Agenda Archives" agenda-archives)
2170 (repeat :inline t (file))))
2172 (if (fboundp 'defvaralias)
2173 (defvaralias 'org-agenda-multi-occur-extra-files
2174 'org-agenda-text-search-extra-files))
2176 (defcustom org-agenda-skip-unavailable-files nil
2177 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2178 A nil value means to remove them, after a query, from the list."
2179 :group 'org-agenda
2180 :type 'boolean)
2182 (defcustom org-calendar-to-agenda-key [?c]
2183 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2184 The command `org-calendar-goto-agenda' will be bound to this key. The
2185 default is the character `c' because then `c' can be used to switch back and
2186 forth between agenda and calendar."
2187 :group 'org-agenda
2188 :type 'sexp)
2190 (defcustom org-calendar-agenda-action-key [?k]
2191 "The key to be installed in `calendar-mode-map' for agenda-action.
2192 The command `org-agenda-action' will be bound to this key. The
2193 default is the character `k' because we use the same key in the agenda."
2194 :group 'org-agenda
2195 :type 'sexp)
2197 (eval-after-load "calendar"
2198 '(progn
2199 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2200 'org-calendar-goto-agenda)
2201 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2202 'org-agenda-action)))
2204 (defgroup org-latex nil
2205 "Options for embedding LaTeX code into Org-mode."
2206 :tag "Org LaTeX"
2207 :group 'org)
2209 (defcustom org-format-latex-options
2210 '(:foreground default :background default :scale 1.0
2211 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2212 :matchers ("begin" "$" "$$" "\\(" "\\["))
2213 "Options for creating images from LaTeX fragments.
2214 This is a property list with the following properties:
2215 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2216 `default' means use the foreground of the default face.
2217 :background the background color, or \"Transparent\".
2218 `default' means use the background of the default face.
2219 :scale a scaling factor for the size of the images.
2220 :html-foreground, :html-background, :html-scale
2221 the same numbers for HTML export.
2222 :matchers a list indicating which matchers should be used to
2223 find LaTeX fragments. Valid members of this list are:
2224 \"begin\" find environments
2225 \"$\" find math expressions surrounded by $...$
2226 \"$$\" find math expressions surrounded by $$....$$
2227 \"\\(\" find math expressions surrounded by \\(...\\)
2228 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2229 :group 'org-latex
2230 :type 'plist)
2232 (defcustom org-format-latex-header "\\documentclass{article}
2233 \\usepackage{fullpage} % do not remove
2234 \\usepackage{amssymb}
2235 \\usepackage[usenames]{color}
2236 \\usepackage{amsmath}
2237 \\usepackage{latexsym}
2238 \\usepackage[mathscr]{eucal}
2239 \\pagestyle{empty} % do not remove"
2240 "The document header used for processing LaTeX fragments."
2241 :group 'org-latex
2242 :type 'string)
2245 (defgroup org-font-lock nil
2246 "Font-lock settings for highlighting in Org-mode."
2247 :tag "Org Font Lock"
2248 :group 'org)
2250 (defcustom org-level-color-stars-only nil
2251 "Non-nil means fontify only the stars in each headline.
2252 When nil, the entire headline is fontified.
2253 Changing it requires restart of `font-lock-mode' to become effective
2254 also in regions already fontified."
2255 :group 'org-font-lock
2256 :type 'boolean)
2258 (defcustom org-hide-leading-stars nil
2259 "Non-nil means, hide the first N-1 stars in a headline.
2260 This works by using the face `org-hide' for these stars. This
2261 face is white for a light background, and black for a dark
2262 background. You may have to customize the face `org-hide' to
2263 make this work.
2264 Changing it requires restart of `font-lock-mode' to become effective
2265 also in regions already fontified.
2266 You may also set this on a per-file basis by adding one of the following
2267 lines to the buffer:
2269 #+STARTUP: hidestars
2270 #+STARTUP: showstars"
2271 :group 'org-font-lock
2272 :type 'boolean)
2274 (defcustom org-fontify-done-headline nil
2275 "Non-nil means, change the face of a headline if it is marked DONE.
2276 Normally, only the TODO/DONE keyword indicates the state of a headline.
2277 When this is non-nil, the headline after the keyword is set to the
2278 `org-headline-done' as an additional indication."
2279 :group 'org-font-lock
2280 :type 'boolean)
2282 (defcustom org-fontify-emphasized-text t
2283 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2284 Changing this variable requires a restart of Emacs to take effect."
2285 :group 'org-font-lock
2286 :type 'boolean)
2288 (defcustom org-highlight-latex-fragments-and-specials nil
2289 "Non-nil means, fontify what is treated specially by the exporters."
2290 :group 'org-font-lock
2291 :type 'boolean)
2293 (defcustom org-hide-emphasis-markers nil
2294 "Non-nil mean font-lock should hide the emphasis marker characters."
2295 :group 'org-font-lock
2296 :type 'boolean)
2298 (defvar org-emph-re nil
2299 "Regular expression for matching emphasis.")
2300 (defvar org-verbatim-re nil
2301 "Regular expression for matching verbatim text.")
2302 (defvar org-emphasis-regexp-components) ; defined just below
2303 (defvar org-emphasis-alist) ; defined just below
2304 (defun org-set-emph-re (var val)
2305 "Set variable and compute the emphasis regular expression."
2306 (set var val)
2307 (when (and (boundp 'org-emphasis-alist)
2308 (boundp 'org-emphasis-regexp-components)
2309 org-emphasis-alist org-emphasis-regexp-components)
2310 (let* ((e org-emphasis-regexp-components)
2311 (pre (car e))
2312 (post (nth 1 e))
2313 (border (nth 2 e))
2314 (body (nth 3 e))
2315 (nl (nth 4 e))
2316 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2317 (body1 (concat body "*?"))
2318 (markers (mapconcat 'car org-emphasis-alist ""))
2319 (vmarkers (mapconcat
2320 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2321 org-emphasis-alist "")))
2322 ;; make sure special characters appear at the right position in the class
2323 (if (string-match "\\^" markers)
2324 (setq markers (concat (replace-match "" t t markers) "^")))
2325 (if (string-match "-" markers)
2326 (setq markers (concat (replace-match "" t t markers) "-")))
2327 (if (string-match "\\^" vmarkers)
2328 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2329 (if (string-match "-" vmarkers)
2330 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2331 (if (> nl 0)
2332 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2333 (int-to-string nl) "\\}")))
2334 ;; Make the regexp
2335 (setq org-emph-re
2336 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2337 "\\("
2338 "\\([" markers "]\\)"
2339 "\\("
2340 "[^" border "]\\|"
2341 "[^" border (if (and nil stacked) markers) "]"
2342 body1
2343 "[^" border (if (and nil stacked) markers) "]"
2344 "\\)"
2345 "\\3\\)"
2346 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2347 (setq org-verbatim-re
2348 (concat "\\([" pre "]\\|^\\)"
2349 "\\("
2350 "\\([" vmarkers "]\\)"
2351 "\\("
2352 "[^" border "]\\|"
2353 "[^" border "]"
2354 body1
2355 "[^" border "]"
2356 "\\)"
2357 "\\3\\)"
2358 "\\([" post "]\\|$\\)")))))
2360 (defcustom org-emphasis-regexp-components
2361 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2362 "Components used to build the regular expression for emphasis.
2363 This is a list with 6 entries. Terminology: In an emphasis string
2364 like \" *strong word* \", we call the initial space PREMATCH, the final
2365 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2366 and \"trong wor\" is the body. The different components in this variable
2367 specify what is allowed/forbidden in each part:
2369 pre Chars allowed as prematch. Beginning of line will be allowed too.
2370 post Chars allowed as postmatch. End of line will be allowed too.
2371 border The chars *forbidden* as border characters.
2372 body-regexp A regexp like \".\" to match a body character. Don't use
2373 non-shy groups here, and don't allow newline here.
2374 newline The maximum number of newlines allowed in an emphasis exp.
2376 Use customize to modify this, or restart Emacs after changing it."
2377 :group 'org-font-lock
2378 :set 'org-set-emph-re
2379 :type '(list
2380 (sexp :tag "Allowed chars in pre ")
2381 (sexp :tag "Allowed chars in post ")
2382 (sexp :tag "Forbidden chars in border ")
2383 (sexp :tag "Regexp for body ")
2384 (integer :tag "number of newlines allowed")
2385 (option (boolean :tag "Please ignore this button"))))
2387 (defcustom org-emphasis-alist
2388 `(("*" bold "<b>" "</b>")
2389 ("/" italic "<i>" "</i>")
2390 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2391 ("=" org-code "<code>" "</code>" verbatim)
2392 ("~" org-verbatim "<code>" "</code>" verbatim)
2393 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2394 "<del>" "</del>")
2396 "Special syntax for emphasized text.
2397 Text starting and ending with a special character will be emphasized, for
2398 example *bold*, _underlined_ and /italic/. This variable sets the marker
2399 characters, the face to be used by font-lock for highlighting in Org-mode
2400 Emacs buffers, and the HTML tags to be used for this.
2401 Use customize to modify this, or restart Emacs after changing it."
2402 :group 'org-font-lock
2403 :set 'org-set-emph-re
2404 :type '(repeat
2405 (list
2406 (string :tag "Marker character")
2407 (choice
2408 (face :tag "Font-lock-face")
2409 (plist :tag "Face property list"))
2410 (string :tag "HTML start tag")
2411 (string :tag "HTML end tag")
2412 (option (const verbatim)))))
2414 ;;; Miscellaneous options
2416 (defgroup org-completion nil
2417 "Completion in Org-mode."
2418 :tag "Org Completion"
2419 :group 'org)
2421 (defcustom org-completion-use-ido nil
2422 "Non-nil means, use ido completion wherever possible.
2423 Note that `ido-mode' must be active for this variable to be relevant.
2424 If you decide to turn this variable on, you might well want to turn off
2425 `org-outline-path-complete-in-steps'."
2426 :group 'org-completion
2427 :type 'boolean)
2429 (defcustom org-completion-fallback-command 'hippie-expand
2430 "The expansion command called by \\[org-complete] in normal context.
2431 Normal means, no org-mode-specific context."
2432 :group 'org-completion
2433 :type 'function)
2435 ;;; Functions and variables from ther packages
2436 ;; Declared here to avoid compiler warnings
2438 ;; XEmacs only
2439 (defvar outline-mode-menu-heading)
2440 (defvar outline-mode-menu-show)
2441 (defvar outline-mode-menu-hide)
2442 (defvar zmacs-regions) ; XEmacs regions
2444 ;; Emacs only
2445 (defvar mark-active)
2447 ;; Various packages
2448 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2449 (declare-function calendar-forward-day "cal-move" (arg))
2450 (declare-function calendar-goto-date "cal-move" (date))
2451 (declare-function calendar-goto-today "cal-move" ())
2452 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2453 (defvar calc-embedded-close-formula)
2454 (defvar calc-embedded-open-formula)
2455 (declare-function cdlatex-tab "ext:cdlatex" ())
2456 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2457 (defvar font-lock-unfontify-region-function)
2458 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2459 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2460 (defvar iswitchb-temp-buflist)
2461 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2462 (declare-function org-agenda-skip "org-agenda" ())
2463 (declare-function org-format-agenda-item "org-agenda"
2464 (extra txt &optional category tags dotime noprefix remove-re))
2465 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2466 (declare-function org-agenda-change-all-lines "org-agenda"
2467 (newhead hdmarker &optional fixface just-this))
2468 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2469 (declare-function org-agenda-maybe-redo "org-agenda" ())
2470 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2471 (beg end))
2472 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2473 (declare-function parse-time-string "parse-time" (string))
2474 (declare-function remember "remember" (&optional initial))
2475 (declare-function remember-buffer-desc "remember" ())
2476 (declare-function remember-finalize "remember" ())
2477 (defvar remember-save-after-remembering)
2478 (defvar remember-data-file)
2479 (defvar remember-register)
2480 (defvar remember-buffer)
2481 (defvar remember-handler-functions)
2482 (defvar remember-annotation-functions)
2483 (defvar texmathp-why)
2484 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2485 (declare-function table--at-cell-p "table" (position &optional object at-column))
2487 (defvar w3m-current-url)
2488 (defvar w3m-current-title)
2490 (defvar org-latex-regexps)
2492 ;;; Autoload and prepare some org modules
2494 ;; Some table stuff that needs to be defined here, because it is used
2495 ;; by the functions setting up org-mode or checking for table context.
2497 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2498 "Detects an org-type or table-type table.")
2499 (defconst org-table-line-regexp "^[ \t]*|"
2500 "Detects an org-type table line.")
2501 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2502 "Detects an org-type table line.")
2503 (defconst org-table-hline-regexp "^[ \t]*|-"
2504 "Detects an org-type table hline.")
2505 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2506 "Detects a table-type table hline.")
2507 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2508 "Searching from within a table (any type) this finds the first line
2509 outside the table.")
2511 ;; Autoload the functions in org-table.el that are needed by functions here.
2513 (eval-and-compile
2514 (org-autoload "org-table"
2515 '(org-table-align org-table-begin org-table-blank-field
2516 org-table-convert org-table-convert-region org-table-copy-down
2517 org-table-copy-region org-table-create
2518 org-table-create-or-convert-from-region
2519 org-table-create-with-table.el org-table-current-dline
2520 org-table-cut-region org-table-delete-column org-table-edit-field
2521 org-table-edit-formulas org-table-end org-table-eval-formula
2522 org-table-export org-table-field-info
2523 org-table-get-stored-formulas org-table-goto-column
2524 org-table-hline-and-move org-table-import org-table-insert-column
2525 org-table-insert-hline org-table-insert-row org-table-iterate
2526 org-table-justify-field-maybe org-table-kill-row
2527 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2528 org-table-move-column org-table-move-column-left
2529 org-table-move-column-right org-table-move-row
2530 org-table-move-row-down org-table-move-row-up
2531 org-table-next-field org-table-next-row org-table-paste-rectangle
2532 org-table-previous-field org-table-recalculate
2533 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2534 org-table-toggle-coordinate-overlays
2535 org-table-toggle-formula-debugger org-table-wrap-region
2536 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2538 (defun org-at-table-p (&optional table-type)
2539 "Return t if the cursor is inside an org-type table.
2540 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2541 (if org-enable-table-editor
2542 (save-excursion
2543 (beginning-of-line 1)
2544 (looking-at (if table-type org-table-any-line-regexp
2545 org-table-line-regexp)))
2546 nil))
2547 (defsubst org-table-p () (org-at-table-p))
2549 (defun org-at-table.el-p ()
2550 "Return t if and only if we are at a table.el table."
2551 (and (org-at-table-p 'any)
2552 (save-excursion
2553 (goto-char (org-table-begin 'any))
2554 (looking-at org-table1-hline-regexp))))
2555 (defun org-table-recognize-table.el ()
2556 "If there is a table.el table nearby, recognize it and move into it."
2557 (if org-table-tab-recognizes-table.el
2558 (if (org-at-table.el-p)
2559 (progn
2560 (beginning-of-line 1)
2561 (if (looking-at org-table-dataline-regexp)
2563 (if (looking-at org-table1-hline-regexp)
2564 (progn
2565 (beginning-of-line 2)
2566 (if (looking-at org-table-any-border-regexp)
2567 (beginning-of-line -1)))))
2568 (if (re-search-forward "|" (org-table-end t) t)
2569 (progn
2570 (require 'table)
2571 (if (table--at-cell-p (point))
2573 (message "recognizing table.el table...")
2574 (table-recognize-table)
2575 (message "recognizing table.el table...done")))
2576 (error "This should not happen..."))
2578 nil)
2579 nil))
2581 (defun org-at-table-hline-p ()
2582 "Return t if the cursor is inside a hline in a table."
2583 (if org-enable-table-editor
2584 (save-excursion
2585 (beginning-of-line 1)
2586 (looking-at org-table-hline-regexp))
2587 nil))
2589 (defvar org-table-clean-did-remove-column nil)
2591 (defun org-table-map-tables (function)
2592 "Apply FUNCTION to the start of all tables in the buffer."
2593 (save-excursion
2594 (save-restriction
2595 (widen)
2596 (goto-char (point-min))
2597 (while (re-search-forward org-table-any-line-regexp nil t)
2598 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2599 (beginning-of-line 1)
2600 (if (looking-at org-table-line-regexp)
2601 (save-excursion (funcall function)))
2602 (re-search-forward org-table-any-border-regexp nil 1))))
2603 (message "Mapping tables: done"))
2605 ;; Declare and autoload functions from org-exp.el
2607 (declare-function org-default-export-plist "org-exp")
2608 (declare-function org-infile-export-plist "org-exp")
2609 (declare-function org-get-current-options "org-exp")
2610 (eval-and-compile
2611 (org-autoload "org-exp"
2612 '(org-export org-export-as-ascii org-export-visible
2613 org-insert-export-options-template org-export-as-html-and-open
2614 org-export-as-html-batch org-export-as-html-to-buffer
2615 org-replace-region-by-html org-export-region-as-html
2616 org-export-as-html org-export-icalendar-this-file
2617 org-export-icalendar-all-agenda-files
2618 org-table-clean-before-export
2619 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2621 ;; Declare and autoload functions from org-agenda.el
2623 (eval-and-compile
2624 (org-autoload "org-agenda"
2625 '(org-agenda org-agenda-list org-search-view
2626 org-todo-list org-tags-view org-agenda-list-stuck-projects
2627 org-diary org-agenda-to-appt)))
2629 ;; Autoload org-remember
2631 (eval-and-compile
2632 (org-autoload "org-remember"
2633 '(org-remember-insinuate org-remember-annotation
2634 org-remember-apply-template org-remember org-remember-handler)))
2636 ;; Autoload org-clock.el
2639 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2640 (beg end))
2641 (declare-function org-update-mode-line "org-clock" ())
2642 (defvar org-clock-start-time)
2643 (defvar org-clock-marker (make-marker)
2644 "Marker recording the last clock-in.")
2646 (eval-and-compile
2647 (org-autoload
2648 "org-clock"
2649 '(org-clock-in org-clock-out org-clock-cancel
2650 org-clock-goto org-clock-sum org-clock-display
2651 org-remove-clock-overlays org-clock-report
2652 org-clocktable-shift org-dblock-write:clocktable
2653 org-get-clocktable)))
2655 (defun org-clock-update-time-maybe ()
2656 "If this is a CLOCK line, update it and return t.
2657 Otherwise, return nil."
2658 (interactive)
2659 (save-excursion
2660 (beginning-of-line 1)
2661 (skip-chars-forward " \t")
2662 (when (looking-at org-clock-string)
2663 (let ((re (concat "[ \t]*" org-clock-string
2664 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2665 "\\([ \t]*=>.*\\)?\\)?"))
2666 ts te h m s neg)
2667 (cond
2668 ((not (looking-at re))
2669 nil)
2670 ((not (match-end 2))
2671 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2672 (> org-clock-marker (point))
2673 (<= org-clock-marker (point-at-eol)))
2674 ;; The clock is running here
2675 (setq org-clock-start-time
2676 (apply 'encode-time
2677 (org-parse-time-string (match-string 1))))
2678 (org-update-mode-line)))
2680 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2681 (end-of-line 1)
2682 (setq ts (match-string 1)
2683 te (match-string 3))
2684 (setq s (- (time-to-seconds
2685 (apply 'encode-time (org-parse-time-string te)))
2686 (time-to-seconds
2687 (apply 'encode-time (org-parse-time-string ts))))
2688 neg (< s 0)
2689 s (abs s)
2690 h (floor (/ s 3600))
2691 s (- s (* 3600 h))
2692 m (floor (/ s 60))
2693 s (- s (* 60 s)))
2694 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2695 t))))))
2697 (defun org-check-running-clock ()
2698 "Check if the current buffer contains the running clock.
2699 If yes, offer to stop it and to save the buffer with the changes."
2700 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2701 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2702 (buffer-name))))
2703 (org-clock-out)
2704 (when (y-or-n-p "Save changed buffer?")
2705 (save-buffer))))
2707 (defun org-clocktable-try-shift (dir n)
2708 "Check if this line starts a clock table, if yes, shift the time block."
2709 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2710 (org-clocktable-shift dir n)))
2712 ;; Autoload org-timer.el
2714 ;(declare-function org-timer "org-timer")
2716 (eval-and-compile
2717 (org-autoload
2718 "org-timer"
2719 '(org-timer-start org-timer org-timer-item
2720 org-timer-change-times-in-region)))
2723 ;; Autoload archiving code
2724 ;; The stuff that is needed for cycling and tags has to be defined here.
2726 (defgroup org-archive nil
2727 "Options concerning archiving in Org-mode."
2728 :tag "Org Archive"
2729 :group 'org-structure)
2731 (defcustom org-archive-location "%s_archive::"
2732 "The location where subtrees should be archived.
2734 The value of this variable is a string, consisting of two parts,
2735 separated by a double-colon. The first part is a filename and
2736 the second part is a headline.
2738 When the filename is omitted, archiving happens in the same file.
2739 %s in the filename will be replaced by the current file
2740 name (without the directory part). Archiving to a different file
2741 is useful to keep archived entries from contributing to the
2742 Org-mode Agenda.
2744 The archived entries will be filed as subtrees of the specified
2745 headline. When the headline is omitted, the subtrees are simply
2746 filed away at the end of the file, as top-level entries.
2748 Here are a few examples:
2749 \"%s_archive::\"
2750 If the current file is Projects.org, archive in file
2751 Projects.org_archive, as top-level trees. This is the default.
2753 \"::* Archived Tasks\"
2754 Archive in the current file, under the top-level headline
2755 \"* Archived Tasks\".
2757 \"~/org/archive.org::\"
2758 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2760 \"basement::** Finished Tasks\"
2761 Archive in file ./basement (relative path), as level 3 trees
2762 below the level 2 heading \"** Finished Tasks\".
2764 You may set this option on a per-file basis by adding to the buffer a
2765 line like
2767 #+ARCHIVE: basement::** Finished Tasks
2769 You may also define it locally for a subtree by setting an ARCHIVE property
2770 in the entry. If such a property is found in an entry, or anywhere up
2771 the hierarchy, it will be used."
2772 :group 'org-archive
2773 :type 'string)
2775 (defcustom org-archive-tag "ARCHIVE"
2776 "The tag that marks a subtree as archived.
2777 An archived subtree does not open during visibility cycling, and does
2778 not contribute to the agenda listings.
2779 After changing this, font-lock must be restarted in the relevant buffers to
2780 get the proper fontification."
2781 :group 'org-archive
2782 :group 'org-keywords
2783 :type 'string)
2785 (defcustom org-agenda-skip-archived-trees t
2786 "Non-nil means, the agenda will skip any items located in archived trees.
2787 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2788 variable is no longer recommended, you should leave it at the value t.
2789 Instead, use the key `v' to cycle the archives-mode in the agenda."
2790 :group 'org-archive
2791 :group 'org-agenda-skip
2792 :type 'boolean)
2794 (defcustom org-cycle-open-archived-trees nil
2795 "Non-nil means, `org-cycle' will open archived trees.
2796 An archived tree is a tree marked with the tag ARCHIVE.
2797 When nil, archived trees will stay folded. You can still open them with
2798 normal outline commands like `show-all', but not with the cycling commands."
2799 :group 'org-archive
2800 :group 'org-cycle
2801 :type 'boolean)
2803 (defcustom org-sparse-tree-open-archived-trees nil
2804 "Non-nil means sparse tree construction shows matches in archived trees.
2805 When nil, matches in these trees are highlighted, but the trees are kept in
2806 collapsed state."
2807 :group 'org-archive
2808 :group 'org-sparse-trees
2809 :type 'boolean)
2811 (defun org-cycle-hide-archived-subtrees (state)
2812 "Re-hide all archived subtrees after a visibility state change."
2813 (when (and (not org-cycle-open-archived-trees)
2814 (not (memq state '(overview folded))))
2815 (save-excursion
2816 (let* ((globalp (memq state '(contents all)))
2817 (beg (if globalp (point-min) (point)))
2818 (end (if globalp (point-max) (org-end-of-subtree t))))
2819 (org-hide-archived-subtrees beg end)
2820 (goto-char beg)
2821 (if (looking-at (concat ".*:" org-archive-tag ":"))
2822 (message "%s" (substitute-command-keys
2823 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2825 (defun org-force-cycle-archived ()
2826 "Cycle subtree even if it is archived."
2827 (interactive)
2828 (setq this-command 'org-cycle)
2829 (let ((org-cycle-open-archived-trees t))
2830 (call-interactively 'org-cycle)))
2832 (defun org-hide-archived-subtrees (beg end)
2833 "Re-hide all archived subtrees after a visibility state change."
2834 (save-excursion
2835 (let* ((re (concat ":" org-archive-tag ":")))
2836 (goto-char beg)
2837 (while (re-search-forward re end t)
2838 (and (org-on-heading-p) (hide-subtree))
2839 (org-end-of-subtree t)))))
2841 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2843 (eval-and-compile
2844 (org-autoload "org-archive"
2845 '(org-add-archive-files org-archive-subtree
2846 org-archive-to-archive-sibling org-toggle-archive-tag)))
2848 ;; Autoload Column View Code
2850 (declare-function org-columns-number-to-string "org-colview")
2851 (declare-function org-columns-get-format-and-top-level "org-colview")
2852 (declare-function org-columns-compute "org-colview")
2854 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2855 '(org-columns-number-to-string org-columns-get-format-and-top-level
2856 org-columns-compute org-agenda-columns org-columns-remove-overlays
2857 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2859 ;; Autoload ID code
2861 (declare-function org-id-store-link "org-id")
2862 (org-autoload "org-id"
2863 '(org-id-get-create org-id-new org-id-copy org-id-get
2864 org-id-get-with-outline-path-completion
2865 org-id-get-with-outline-drilling
2866 org-id-goto org-id-find org-id-store-link))
2868 ;;; Variables for pre-computed regular expressions, all buffer local
2870 (defvar org-drawer-regexp nil
2871 "Matches first line of a hidden block.")
2872 (make-variable-buffer-local 'org-drawer-regexp)
2873 (defvar org-todo-regexp nil
2874 "Matches any of the TODO state keywords.")
2875 (make-variable-buffer-local 'org-todo-regexp)
2876 (defvar org-not-done-regexp nil
2877 "Matches any of the TODO state keywords except the last one.")
2878 (make-variable-buffer-local 'org-not-done-regexp)
2879 (defvar org-todo-line-regexp nil
2880 "Matches a headline and puts TODO state into group 2 if present.")
2881 (make-variable-buffer-local 'org-todo-line-regexp)
2882 (defvar org-complex-heading-regexp nil
2883 "Matches a headline and puts everything into groups:
2884 group 1: the stars
2885 group 2: The todo keyword, maybe
2886 group 3: Priority cookie
2887 group 4: True headline
2888 group 5: Tags")
2889 (make-variable-buffer-local 'org-complex-heading-regexp)
2890 (defvar org-todo-line-tags-regexp nil
2891 "Matches a headline and puts TODO state into group 2 if present.
2892 Also put tags into group 4 if tags are present.")
2893 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2894 (defvar org-nl-done-regexp nil
2895 "Matches newline followed by a headline with the DONE keyword.")
2896 (make-variable-buffer-local 'org-nl-done-regexp)
2897 (defvar org-looking-at-done-regexp nil
2898 "Matches the DONE keyword a point.")
2899 (make-variable-buffer-local 'org-looking-at-done-regexp)
2900 (defvar org-ds-keyword-length 12
2901 "Maximum length of the Deadline and SCHEDULED keywords.")
2902 (make-variable-buffer-local 'org-ds-keyword-length)
2903 (defvar org-deadline-regexp nil
2904 "Matches the DEADLINE keyword.")
2905 (make-variable-buffer-local 'org-deadline-regexp)
2906 (defvar org-deadline-time-regexp nil
2907 "Matches the DEADLINE keyword together with a time stamp.")
2908 (make-variable-buffer-local 'org-deadline-time-regexp)
2909 (defvar org-deadline-line-regexp nil
2910 "Matches the DEADLINE keyword and the rest of the line.")
2911 (make-variable-buffer-local 'org-deadline-line-regexp)
2912 (defvar org-scheduled-regexp nil
2913 "Matches the SCHEDULED keyword.")
2914 (make-variable-buffer-local 'org-scheduled-regexp)
2915 (defvar org-scheduled-time-regexp nil
2916 "Matches the SCHEDULED keyword together with a time stamp.")
2917 (make-variable-buffer-local 'org-scheduled-time-regexp)
2918 (defvar org-closed-time-regexp nil
2919 "Matches the CLOSED keyword together with a time stamp.")
2920 (make-variable-buffer-local 'org-closed-time-regexp)
2922 (defvar org-keyword-time-regexp nil
2923 "Matches any of the 4 keywords, together with the time stamp.")
2924 (make-variable-buffer-local 'org-keyword-time-regexp)
2925 (defvar org-keyword-time-not-clock-regexp nil
2926 "Matches any of the 3 keywords, together with the time stamp.")
2927 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2928 (defvar org-maybe-keyword-time-regexp nil
2929 "Matches a timestamp, possibly preceeded by a keyword.")
2930 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2931 (defvar org-planning-or-clock-line-re nil
2932 "Matches a line with planning or clock info.")
2933 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2935 (defconst org-plain-time-of-day-regexp
2936 (concat
2937 "\\(\\<[012]?[0-9]"
2938 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2939 "\\(--?"
2940 "\\(\\<[012]?[0-9]"
2941 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2942 "\\)?")
2943 "Regular expression to match a plain time or time range.
2944 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2945 groups carry important information:
2946 0 the full match
2947 1 the first time, range or not
2948 8 the second time, if it is a range.")
2950 (defconst org-plain-time-extension-regexp
2951 (concat
2952 "\\(\\<[012]?[0-9]"
2953 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2954 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2955 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2956 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2957 groups carry important information:
2958 0 the full match
2959 7 hours of duration
2960 9 minutes of duration")
2962 (defconst org-stamp-time-of-day-regexp
2963 (concat
2964 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2965 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2966 "\\(--?"
2967 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2968 "Regular expression to match a timestamp time or time range.
2969 After a match, the following groups carry important information:
2970 0 the full match
2971 1 date plus weekday, for backreferencing to make sure both times on same day
2972 2 the first time, range or not
2973 4 the second time, if it is a range.")
2975 (defconst org-startup-options
2976 '(("fold" org-startup-folded t)
2977 ("overview" org-startup-folded t)
2978 ("nofold" org-startup-folded nil)
2979 ("showall" org-startup-folded nil)
2980 ("content" org-startup-folded content)
2981 ("hidestars" org-hide-leading-stars t)
2982 ("showstars" org-hide-leading-stars nil)
2983 ("odd" org-odd-levels-only t)
2984 ("oddeven" org-odd-levels-only nil)
2985 ("align" org-startup-align-all-tables t)
2986 ("noalign" org-startup-align-all-tables nil)
2987 ("customtime" org-display-custom-times t)
2988 ("logdone" org-log-done time)
2989 ("lognotedone" org-log-done note)
2990 ("nologdone" org-log-done nil)
2991 ("lognoteclock-out" org-log-note-clock-out t)
2992 ("nolognoteclock-out" org-log-note-clock-out nil)
2993 ("logrepeat" org-log-repeat state)
2994 ("lognoterepeat" org-log-repeat note)
2995 ("nologrepeat" org-log-repeat nil)
2996 ("fninline" org-footnote-define-inline t)
2997 ("nofninline" org-footnote-define-inline nil)
2998 ("constcgs" constants-unit-system cgs)
2999 ("constSI" constants-unit-system SI))
3000 "Variable associated with STARTUP options for org-mode.
3001 Each element is a list of three items: The startup options as written
3002 in the #+STARTUP line, the corresponding variable, and the value to
3003 set this variable to if the option is found. An optional forth element PUSH
3004 means to push this value onto the list in the variable.")
3006 (defun org-set-regexps-and-options ()
3007 "Precompute regular expressions for current buffer."
3008 (when (org-mode-p)
3009 (org-set-local 'org-todo-kwd-alist nil)
3010 (org-set-local 'org-todo-key-alist nil)
3011 (org-set-local 'org-todo-key-trigger nil)
3012 (org-set-local 'org-todo-keywords-1 nil)
3013 (org-set-local 'org-done-keywords nil)
3014 (org-set-local 'org-todo-heads nil)
3015 (org-set-local 'org-todo-sets nil)
3016 (org-set-local 'org-todo-log-states nil)
3017 (org-set-local 'org-file-properties nil)
3018 (org-set-local 'org-file-tags nil)
3019 (let ((re (org-make-options-regexp
3020 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3021 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3022 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3023 (splitre "[ \t]+")
3024 kwds kws0 kwsa key log value cat arch tags const links hw dws
3025 tail sep kws1 prio props ftags drawers
3026 ext-setup-or-nil setup-contents (start 0))
3027 (save-excursion
3028 (save-restriction
3029 (widen)
3030 (goto-char (point-min))
3031 (while (or (and ext-setup-or-nil
3032 (string-match re ext-setup-or-nil start)
3033 (setq start (match-end 0)))
3034 (and (setq ext-setup-or-nil nil start 0)
3035 (re-search-forward re nil t)))
3036 (setq key (upcase (match-string 1 ext-setup-or-nil))
3037 value (org-match-string-no-properties 2 ext-setup-or-nil))
3038 (cond
3039 ((equal key "CATEGORY")
3040 (if (string-match "[ \t]+$" value)
3041 (setq value (replace-match "" t t value)))
3042 (setq cat value))
3043 ((member key '("SEQ_TODO" "TODO"))
3044 (push (cons 'sequence (org-split-string value splitre)) kwds))
3045 ((equal key "TYP_TODO")
3046 (push (cons 'type (org-split-string value splitre)) kwds))
3047 ((equal key "TAGS")
3048 (setq tags (append tags (org-split-string value splitre))))
3049 ((equal key "COLUMNS")
3050 (org-set-local 'org-columns-default-format value))
3051 ((equal key "LINK")
3052 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3053 (push (cons (match-string 1 value)
3054 (org-trim (match-string 2 value)))
3055 links)))
3056 ((equal key "PRIORITIES")
3057 (setq prio (org-split-string value " +")))
3058 ((equal key "PROPERTY")
3059 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3060 (push (cons (match-string 1 value) (match-string 2 value))
3061 props)))
3062 ((equal key "FILETAGS")
3063 (when (string-match "\\S-" value)
3064 (setq ftags
3065 (append
3066 ftags
3067 (apply 'append
3068 (mapcar (lambda (x) (org-split-string x ":"))
3069 (org-split-string value)))))))
3070 ((equal key "DRAWERS")
3071 (setq drawers (org-split-string value splitre)))
3072 ((equal key "CONSTANTS")
3073 (setq const (append const (org-split-string value splitre))))
3074 ((equal key "STARTUP")
3075 (let ((opts (org-split-string value splitre))
3076 l var val)
3077 (while (setq l (pop opts))
3078 (when (setq l (assoc l org-startup-options))
3079 (setq var (nth 1 l) val (nth 2 l))
3080 (if (not (nth 3 l))
3081 (set (make-local-variable var) val)
3082 (if (not (listp (symbol-value var)))
3083 (set (make-local-variable var) nil))
3084 (set (make-local-variable var) (symbol-value var))
3085 (add-to-list var val))))))
3086 ((equal key "ARCHIVE")
3087 (string-match " *$" value)
3088 (setq arch (replace-match "" t t value))
3089 (remove-text-properties 0 (length arch)
3090 '(face t fontified t) arch))
3091 ((equal key "SETUPFILE")
3092 (setq setup-contents (org-file-contents
3093 (expand-file-name
3094 (org-remove-double-quotes value))
3095 'noerror))
3096 (if (not ext-setup-or-nil)
3097 (setq ext-setup-or-nil setup-contents start 0)
3098 (setq ext-setup-or-nil
3099 (concat (substring ext-setup-or-nil 0 start)
3100 "\n" setup-contents "\n"
3101 (substring ext-setup-or-nil start)))))
3102 ))))
3103 (when cat
3104 (org-set-local 'org-category (intern cat))
3105 (push (cons "CATEGORY" cat) props))
3106 (when prio
3107 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3108 (setq prio (mapcar 'string-to-char prio))
3109 (org-set-local 'org-highest-priority (nth 0 prio))
3110 (org-set-local 'org-lowest-priority (nth 1 prio))
3111 (org-set-local 'org-default-priority (nth 2 prio)))
3112 (and props (org-set-local 'org-file-properties (nreverse props)))
3113 (and ftags (org-set-local 'org-file-tags ftags))
3114 (and drawers (org-set-local 'org-drawers drawers))
3115 (and arch (org-set-local 'org-archive-location arch))
3116 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3117 ;; Process the TODO keywords
3118 (unless kwds
3119 ;; Use the global values as if they had been given locally.
3120 (setq kwds (default-value 'org-todo-keywords))
3121 (if (stringp (car kwds))
3122 (setq kwds (list (cons org-todo-interpretation
3123 (default-value 'org-todo-keywords)))))
3124 (setq kwds (reverse kwds)))
3125 (setq kwds (nreverse kwds))
3126 (let (inter kws kw)
3127 (while (setq kws (pop kwds))
3128 (setq inter (pop kws) sep (member "|" kws)
3129 kws0 (delete "|" (copy-sequence kws))
3130 kwsa nil
3131 kws1 (mapcar
3132 (lambda (x)
3133 ;; 1 2
3134 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3135 (progn
3136 (setq kw (match-string 1 x)
3137 key (and (match-end 2) (match-string 2 x))
3138 log (org-extract-log-state-settings x))
3139 (push (cons kw (and key (string-to-char key))) kwsa)
3140 (and log (push log org-todo-log-states))
3142 (error "Invalid TODO keyword %s" x)))
3143 kws0)
3144 kwsa (if kwsa (append '((:startgroup))
3145 (nreverse kwsa)
3146 '((:endgroup))))
3147 hw (car kws1)
3148 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3149 tail (list inter hw (car dws) (org-last dws)))
3150 (add-to-list 'org-todo-heads hw 'append)
3151 (push kws1 org-todo-sets)
3152 (setq org-done-keywords (append org-done-keywords dws nil))
3153 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3154 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3155 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3156 (setq org-todo-sets (nreverse org-todo-sets)
3157 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3158 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3159 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3160 ;; Process the constants
3161 (when const
3162 (let (e cst)
3163 (while (setq e (pop const))
3164 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3165 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3166 (setq org-table-formula-constants-local cst)))
3168 ;; Process the tags.
3169 (when tags
3170 (let (e tgs)
3171 (while (setq e (pop tags))
3172 (cond
3173 ((equal e "{") (push '(:startgroup) tgs))
3174 ((equal e "}") (push '(:endgroup) tgs))
3175 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3176 (push (cons (match-string 1 e)
3177 (string-to-char (match-string 2 e)))
3178 tgs))
3179 (t (push (list e) tgs))))
3180 (org-set-local 'org-tag-alist nil)
3181 (while (setq e (pop tgs))
3182 (or (and (stringp (car e))
3183 (assoc (car e) org-tag-alist))
3184 (push e org-tag-alist)))))
3186 ;; Compute the regular expressions and other local variables
3187 (if (not org-done-keywords)
3188 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3189 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3190 (length org-scheduled-string)
3191 (length org-clock-string)
3192 (length org-closed-string)))
3193 org-drawer-regexp
3194 (concat "^[ \t]*:\\("
3195 (mapconcat 'regexp-quote org-drawers "\\|")
3196 "\\):[ \t]*$")
3197 org-not-done-keywords
3198 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3199 org-todo-regexp
3200 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3201 "\\|") "\\)\\>")
3202 org-not-done-regexp
3203 (concat "\\<\\("
3204 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3205 "\\)\\>")
3206 org-todo-line-regexp
3207 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3208 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3209 "\\)\\>\\)?[ \t]*\\(.*\\)")
3210 org-complex-heading-regexp
3211 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3212 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3213 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3214 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3215 org-nl-done-regexp
3216 (concat "\n\\*+[ \t]+"
3217 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3218 "\\)" "\\>")
3219 org-todo-line-tags-regexp
3220 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3221 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3222 (org-re
3223 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3224 org-looking-at-done-regexp
3225 (concat "^" "\\(?:"
3226 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3227 "\\>")
3228 org-deadline-regexp (concat "\\<" org-deadline-string)
3229 org-deadline-time-regexp
3230 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3231 org-deadline-line-regexp
3232 (concat "\\<\\(" org-deadline-string "\\).*")
3233 org-scheduled-regexp
3234 (concat "\\<" org-scheduled-string)
3235 org-scheduled-time-regexp
3236 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3237 org-closed-time-regexp
3238 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3239 org-keyword-time-regexp
3240 (concat "\\<\\(" org-scheduled-string
3241 "\\|" org-deadline-string
3242 "\\|" org-closed-string
3243 "\\|" org-clock-string "\\)"
3244 " *[[<]\\([^]>]+\\)[]>]")
3245 org-keyword-time-not-clock-regexp
3246 (concat "\\<\\(" org-scheduled-string
3247 "\\|" org-deadline-string
3248 "\\|" org-closed-string
3249 "\\)"
3250 " *[[<]\\([^]>]+\\)[]>]")
3251 org-maybe-keyword-time-regexp
3252 (concat "\\(\\<\\(" org-scheduled-string
3253 "\\|" org-deadline-string
3254 "\\|" org-closed-string
3255 "\\|" org-clock-string "\\)\\)?"
3256 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3257 org-planning-or-clock-line-re
3258 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3259 "\\|" org-deadline-string
3260 "\\|" org-closed-string "\\|" org-clock-string
3261 "\\)\\>\\)")
3263 (org-compute-latex-and-specials-regexp)
3264 (org-set-font-lock-defaults))))
3266 (defun org-file-contents (file &optional noerror)
3267 "Return the contents of FILE, as a string."
3268 (if (or (not file)
3269 (not (file-readable-p file)))
3270 (if noerror
3271 (progn
3272 (message "Cannot read file %s" file)
3273 (ding) (sit-for 2)
3275 (error "Cannot read file %s" file))
3276 (with-temp-buffer
3277 (insert-file-contents file)
3278 (buffer-string))))
3280 (defun org-extract-log-state-settings (x)
3281 "Extract the log state setting from a TODO keyword string.
3282 This will extract info from a string like \"WAIT(w@/!)\"."
3283 (let (kw key log1 log2)
3284 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3285 (setq kw (match-string 1 x)
3286 key (and (match-end 2) (match-string 2 x))
3287 log1 (and (match-end 3) (match-string 3 x))
3288 log2 (and (match-end 4) (match-string 4 x)))
3289 (and (or log1 log2)
3290 (list kw
3291 (and log1 (if (equal log1 "!") 'time 'note))
3292 (and log2 (if (equal log2 "!") 'time 'note)))))))
3294 (defun org-remove-keyword-keys (list)
3295 "Remove a pair of parenthesis at the end of each string in LIST."
3296 (mapcar (lambda (x)
3297 (if (string-match "(.*)$" x)
3298 (substring x 0 (match-beginning 0))
3300 list))
3302 ;; FIXME: this could be done much better, using second characters etc.
3303 (defun org-assign-fast-keys (alist)
3304 "Assign fast keys to a keyword-key alist.
3305 Respect keys that are already there."
3306 (let (new e k c c1 c2 (char ?a))
3307 (while (setq e (pop alist))
3308 (cond
3309 ((equal e '(:startgroup)) (push e new))
3310 ((equal e '(:endgroup)) (push e new))
3312 (setq k (car e) c2 nil)
3313 (if (cdr e)
3314 (setq c (cdr e))
3315 ;; automatically assign a character.
3316 (setq c1 (string-to-char
3317 (downcase (substring
3318 k (if (= (string-to-char k) ?@) 1 0)))))
3319 (if (or (rassoc c1 new) (rassoc c1 alist))
3320 (while (or (rassoc char new) (rassoc char alist))
3321 (setq char (1+ char)))
3322 (setq c2 c1))
3323 (setq c (or c2 char)))
3324 (push (cons k c) new))))
3325 (nreverse new)))
3327 ;;; Some variables used in various places
3329 (defvar org-window-configuration nil
3330 "Used in various places to store a window configuration.")
3331 (defvar org-finish-function nil
3332 "Function to be called when `C-c C-c' is used.
3333 This is for getting out of special buffers like remember.")
3336 ;; FIXME: Occasionally check by commenting these, to make sure
3337 ;; no other functions uses these, forgetting to let-bind them.
3338 (defvar entry)
3339 (defvar state)
3340 (defvar last-state)
3341 (defvar date)
3342 (defvar description)
3344 ;; Defined somewhere in this file, but used before definition.
3345 (defvar org-html-entities)
3346 (defvar org-struct-menu)
3347 (defvar org-org-menu)
3348 (defvar org-tbl-menu)
3349 (defvar org-agenda-keymap)
3351 ;;;; Define the Org-mode
3353 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3354 (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."))
3357 ;; We use a before-change function to check if a table might need
3358 ;; an update.
3359 (defvar org-table-may-need-update t
3360 "Indicates that a table might need an update.
3361 This variable is set by `org-before-change-function'.
3362 `org-table-align' sets it back to nil.")
3363 (defun org-before-change-function (beg end)
3364 "Every change indicates that a table might need an update."
3365 (setq org-table-may-need-update t))
3366 (defvar org-mode-map)
3367 (defvar org-mode-hook nil)
3368 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3369 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3370 (defvar org-table-buffer-is-an nil)
3371 (defconst org-outline-regexp "\\*+ ")
3373 ;;;###autoload
3374 (define-derived-mode org-mode outline-mode "Org"
3375 "Outline-based notes management and organizer, alias
3376 \"Carsten's outline-mode for keeping track of everything.\"
3378 Org-mode develops organizational tasks around a NOTES file which
3379 contains information about projects as plain text. Org-mode is
3380 implemented on top of outline-mode, which is ideal to keep the content
3381 of large files well structured. It supports ToDo items, deadlines and
3382 time stamps, which magically appear in the diary listing of the Emacs
3383 calendar. Tables are easily created with a built-in table editor.
3384 Plain text URL-like links connect to websites, emails (VM), Usenet
3385 messages (Gnus), BBDB entries, and any files related to the project.
3386 For printing and sharing of notes, an Org-mode file (or a part of it)
3387 can be exported as a structured ASCII or HTML file.
3389 The following commands are available:
3391 \\{org-mode-map}"
3393 ;; Get rid of Outline menus, they are not needed
3394 ;; Need to do this here because define-derived-mode sets up
3395 ;; the keymap so late. Still, it is a waste to call this each time
3396 ;; we switch another buffer into org-mode.
3397 (if (featurep 'xemacs)
3398 (when (boundp 'outline-mode-menu-heading)
3399 ;; Assume this is Greg's port, it used easymenu
3400 (easy-menu-remove outline-mode-menu-heading)
3401 (easy-menu-remove outline-mode-menu-show)
3402 (easy-menu-remove outline-mode-menu-hide))
3403 (define-key org-mode-map [menu-bar headings] 'undefined)
3404 (define-key org-mode-map [menu-bar hide] 'undefined)
3405 (define-key org-mode-map [menu-bar show] 'undefined))
3407 (org-load-modules-maybe)
3408 (easy-menu-add org-org-menu)
3409 (easy-menu-add org-tbl-menu)
3410 (org-install-agenda-files-menu)
3411 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3412 (org-add-to-invisibility-spec '(org-cwidth))
3413 (when (featurep 'xemacs)
3414 (org-set-local 'line-move-ignore-invisible t))
3415 (org-set-local 'outline-regexp org-outline-regexp)
3416 (org-set-local 'outline-level 'org-outline-level)
3417 (when (and org-ellipsis
3418 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3419 (fboundp 'make-glyph-code))
3420 (unless org-display-table
3421 (setq org-display-table (make-display-table)))
3422 (set-display-table-slot
3423 org-display-table 4
3424 (vconcat (mapcar
3425 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3426 org-ellipsis)))
3427 (if (stringp org-ellipsis) org-ellipsis "..."))))
3428 (setq buffer-display-table org-display-table))
3429 (org-set-regexps-and-options)
3430 (when (and org-tag-faces (not org-tags-special-faces-re))
3431 ;; tag faces set outside customize.... force initialization.
3432 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3433 ;; Calc embedded
3434 (org-set-local 'calc-embedded-open-mode "# ")
3435 (modify-syntax-entry ?# "<")
3436 (modify-syntax-entry ?@ "w")
3437 (if org-startup-truncated (setq truncate-lines t))
3438 (org-set-local 'font-lock-unfontify-region-function
3439 'org-unfontify-region)
3440 ;; Activate before-change-function
3441 (org-set-local 'org-table-may-need-update t)
3442 (org-add-hook 'before-change-functions 'org-before-change-function nil
3443 'local)
3444 ;; Check for running clock before killing a buffer
3445 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3446 ;; Paragraphs and auto-filling
3447 (org-set-autofill-regexps)
3448 (setq indent-line-function 'org-indent-line-function)
3449 (org-update-radio-target-regexp)
3451 ;; Comment characters
3452 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3453 (org-set-local 'comment-padding " ")
3455 ;; Align options lines
3456 (org-set-local
3457 'align-mode-rules-list
3458 '((org-in-buffer-settings
3459 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3460 (modes . '(org-mode)))))
3462 ;; Imenu
3463 (org-set-local 'imenu-create-index-function
3464 'org-imenu-get-tree)
3466 ;; Make isearch reveal context
3467 (if (or (featurep 'xemacs)
3468 (not (boundp 'outline-isearch-open-invisible-function)))
3469 ;; Emacs 21 and XEmacs make use of the hook
3470 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3471 ;; Emacs 22 deals with this through a special variable
3472 (org-set-local 'outline-isearch-open-invisible-function
3473 (lambda (&rest ignore) (org-show-context 'isearch))))
3475 ;; If empty file that did not turn on org-mode automatically, make it to.
3476 (if (and org-insert-mode-line-in-empty-file
3477 (interactive-p)
3478 (= (point-min) (point-max)))
3479 (insert "# -*- mode: org -*-\n\n"))
3481 (unless org-inhibit-startup
3482 (when org-startup-align-all-tables
3483 (let ((bmp (buffer-modified-p)))
3484 (org-table-map-tables 'org-table-align)
3485 (set-buffer-modified-p bmp)))
3486 (org-set-startup-visibility)))
3488 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3490 (defun org-current-time ()
3491 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3492 (if (> (car org-time-stamp-rounding-minutes) 1)
3493 (let ((r (car org-time-stamp-rounding-minutes))
3494 (time (decode-time)))
3495 (apply 'encode-time
3496 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3497 (nthcdr 2 time))))
3498 (current-time)))
3500 ;;;; Font-Lock stuff, including the activators
3502 (defvar org-mouse-map (make-sparse-keymap))
3503 (org-defkey org-mouse-map
3504 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3505 (org-defkey org-mouse-map
3506 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3507 (when org-mouse-1-follows-link
3508 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3509 (when org-tab-follows-link
3510 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3511 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3512 (when org-return-follows-link
3513 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3514 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3516 (require 'font-lock)
3518 (defconst org-non-link-chars "]\t\n\r<>")
3519 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3520 "shell" "elisp"))
3521 (defvar org-link-types-re nil
3522 "Matches a link that has a url-like prefix like \"http:\"")
3523 (defvar org-link-re-with-space nil
3524 "Matches a link with spaces, optional angular brackets around it.")
3525 (defvar org-link-re-with-space2 nil
3526 "Matches a link with spaces, optional angular brackets around it.")
3527 (defvar org-link-re-with-space3 nil
3528 "Matches a link with spaces, only for internal part in bracket links.")
3529 (defvar org-angle-link-re nil
3530 "Matches link with angular brackets, spaces are allowed.")
3531 (defvar org-plain-link-re nil
3532 "Matches plain link, without spaces.")
3533 (defvar org-bracket-link-regexp nil
3534 "Matches a link in double brackets.")
3535 (defvar org-bracket-link-analytic-regexp nil
3536 "Regular expression used to analyze links.
3537 Here is what the match groups contain after a match:
3538 1: http:
3539 2: http
3540 3: path
3541 4: [desc]
3542 5: desc")
3543 (defvar org-bracket-link-analytic-regexp++ nil
3544 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3545 (defvar org-any-link-re nil
3546 "Regular expression matching any link.")
3548 (defun org-make-link-regexps ()
3549 "Update the link regular expressions.
3550 This should be called after the variable `org-link-types' has changed."
3551 (setq org-link-types-re
3552 (concat
3553 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3554 org-link-re-with-space
3555 (concat
3556 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3557 "\\([^" org-non-link-chars " ]"
3558 "[^" org-non-link-chars "]*"
3559 "[^" org-non-link-chars " ]\\)>?")
3560 org-link-re-with-space2
3561 (concat
3562 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3563 "\\([^" org-non-link-chars " ]"
3564 "[^\t\n\r]*"
3565 "[^" org-non-link-chars " ]\\)>?")
3566 org-link-re-with-space3
3567 (concat
3568 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3569 "\\([^" org-non-link-chars " ]"
3570 "[^\t\n\r]*\\)")
3571 org-angle-link-re
3572 (concat
3573 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3574 "\\([^" org-non-link-chars " ]"
3575 "[^" org-non-link-chars "]*"
3576 "\\)>")
3577 org-plain-link-re
3578 (concat
3579 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3580 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3581 org-bracket-link-regexp
3582 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3583 org-bracket-link-analytic-regexp
3584 (concat
3585 "\\[\\["
3586 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3587 "\\([^]]+\\)"
3588 "\\]"
3589 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3590 "\\]")
3591 org-bracket-link-analytic-regexp++
3592 (concat
3593 "\\[\\["
3594 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3595 "\\([^]]+\\)"
3596 "\\]"
3597 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3598 "\\]")
3599 org-any-link-re
3600 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3601 org-angle-link-re "\\)\\|\\("
3602 org-plain-link-re "\\)")))
3604 (org-make-link-regexps)
3606 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3607 "Regular expression for fast time stamp matching.")
3608 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3609 "Regular expression for fast time stamp matching.")
3610 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3611 "Regular expression matching time strings for analysis.
3612 This one does not require the space after the date, so it can be used
3613 on a string that terminates immediately after the date.")
3614 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3615 "Regular expression matching time strings for analysis.")
3616 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3617 "Regular expression matching time stamps, with groups.")
3618 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3619 "Regular expression matching time stamps (also [..]), with groups.")
3620 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3621 "Regular expression matching a time stamp range.")
3622 (defconst org-tr-regexp-both
3623 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3624 "Regular expression matching a time stamp range.")
3625 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3626 org-ts-regexp "\\)?")
3627 "Regular expression matching a time stamp or time stamp range.")
3628 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3629 org-ts-regexp-both "\\)?")
3630 "Regular expression matching a time stamp or time stamp range.
3631 The time stamps may be either active or inactive.")
3633 (defvar org-emph-face nil)
3635 (defun org-do-emphasis-faces (limit)
3636 "Run through the buffer and add overlays to links."
3637 (let (rtn)
3638 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3639 (if (not (= (char-after (match-beginning 3))
3640 (char-after (match-beginning 4))))
3641 (progn
3642 (setq rtn t)
3643 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3644 'face
3645 (nth 1 (assoc (match-string 3)
3646 org-emphasis-alist)))
3647 (add-text-properties (match-beginning 2) (match-end 2)
3648 '(font-lock-multiline t))
3649 (when org-hide-emphasis-markers
3650 (add-text-properties (match-end 4) (match-beginning 5)
3651 '(invisible org-link))
3652 (add-text-properties (match-beginning 3) (match-end 3)
3653 '(invisible org-link)))))
3654 (backward-char 1))
3655 rtn))
3657 (defun org-emphasize (&optional char)
3658 "Insert or change an emphasis, i.e. a font like bold or italic.
3659 If there is an active region, change that region to a new emphasis.
3660 If there is no region, just insert the marker characters and position
3661 the cursor between them.
3662 CHAR should be either the marker character, or the first character of the
3663 HTML tag associated with that emphasis. If CHAR is a space, the means
3664 to remove the emphasis of the selected region.
3665 If char is not given (for example in an interactive call) it
3666 will be prompted for."
3667 (interactive)
3668 (let ((eal org-emphasis-alist) e det
3669 (erc org-emphasis-regexp-components)
3670 (prompt "")
3671 (string "") beg end move tag c s)
3672 (if (org-region-active-p)
3673 (setq beg (region-beginning) end (region-end)
3674 string (buffer-substring beg end))
3675 (setq move t))
3677 (while (setq e (pop eal))
3678 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3679 c (aref tag 0))
3680 (push (cons c (string-to-char (car e))) det)
3681 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3682 (substring tag 1)))))
3683 (setq det (nreverse det))
3684 (unless char
3685 (message "%s" (concat "Emphasis marker or tag:" prompt))
3686 (setq char (read-char-exclusive)))
3687 (setq char (or (cdr (assoc char det)) char))
3688 (if (equal char ?\ )
3689 (setq s "" move nil)
3690 (unless (assoc (char-to-string char) org-emphasis-alist)
3691 (error "No such emphasis marker: \"%c\"" char))
3692 (setq s (char-to-string char)))
3693 (while (and (> (length string) 1)
3694 (equal (substring string 0 1) (substring string -1))
3695 (assoc (substring string 0 1) org-emphasis-alist))
3696 (setq string (substring string 1 -1)))
3697 (setq string (concat s string s))
3698 (if beg (delete-region beg end))
3699 (unless (or (bolp)
3700 (string-match (concat "[" (nth 0 erc) "\n]")
3701 (char-to-string (char-before (point)))))
3702 (insert " "))
3703 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3704 (char-to-string (char-after (point))))
3705 (insert " ") (backward-char 1))
3706 (insert string)
3707 (and move (backward-char 1))))
3709 (defconst org-nonsticky-props
3710 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3713 (defun org-activate-plain-links (limit)
3714 "Run through the buffer and add overlays to links."
3715 (catch 'exit
3716 (let (f)
3717 (while (re-search-forward org-plain-link-re limit t)
3718 (setq f (get-text-property (match-beginning 0) 'face))
3719 (if (or (eq f 'org-tag)
3720 (and (listp f) (memq 'org-tag f)))
3722 (add-text-properties (match-beginning 0) (match-end 0)
3723 (list 'mouse-face 'highlight
3724 'rear-nonsticky org-nonsticky-props
3725 'keymap org-mouse-map
3727 (throw 'exit t))))))
3729 (defun org-activate-code (limit)
3730 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3731 (progn
3732 (remove-text-properties (match-beginning 0) (match-end 0)
3733 '(display t invisible t intangible t))
3734 t)))
3736 (defun org-activate-angle-links (limit)
3737 "Run through the buffer and add overlays to links."
3738 (if (re-search-forward org-angle-link-re limit t)
3739 (progn
3740 (add-text-properties (match-beginning 0) (match-end 0)
3741 (list 'mouse-face 'highlight
3742 'rear-nonsticky org-nonsticky-props
3743 'keymap org-mouse-map
3745 t)))
3747 (defun org-activate-bracket-links (limit)
3748 "Run through the buffer and add overlays to bracketed links."
3749 (if (re-search-forward org-bracket-link-regexp limit t)
3750 (let* ((help (concat "LINK: "
3751 (org-match-string-no-properties 1)))
3752 ;; FIXME: above we should remove the escapes.
3753 ;; but that requires another match, protecting match data,
3754 ;; a lot of overhead for font-lock.
3755 (ip (org-maybe-intangible
3756 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3757 'keymap org-mouse-map 'mouse-face 'highlight
3758 'font-lock-multiline t 'help-echo help)))
3759 (vp (list 'rear-nonsticky org-nonsticky-props
3760 'keymap org-mouse-map 'mouse-face 'highlight
3761 ' font-lock-multiline t 'help-echo help)))
3762 ;; We need to remove the invisible property here. Table narrowing
3763 ;; may have made some of this invisible.
3764 (remove-text-properties (match-beginning 0) (match-end 0)
3765 '(invisible nil))
3766 (if (match-end 3)
3767 (progn
3768 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3769 (add-text-properties (match-beginning 3) (match-end 3) vp)
3770 (add-text-properties (match-end 3) (match-end 0) ip))
3771 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3772 (add-text-properties (match-beginning 1) (match-end 1) vp)
3773 (add-text-properties (match-end 1) (match-end 0) ip))
3774 t)))
3776 (defun org-activate-dates (limit)
3777 "Run through the buffer and add overlays to dates."
3778 (if (re-search-forward org-tsr-regexp-both limit t)
3779 (progn
3780 (add-text-properties (match-beginning 0) (match-end 0)
3781 (list 'mouse-face 'highlight
3782 'rear-nonsticky org-nonsticky-props
3783 'keymap org-mouse-map))
3784 (when org-display-custom-times
3785 (if (match-end 3)
3786 (org-display-custom-time (match-beginning 3) (match-end 3)))
3787 (org-display-custom-time (match-beginning 1) (match-end 1)))
3788 t)))
3790 (defvar org-target-link-regexp nil
3791 "Regular expression matching radio targets in plain text.")
3792 (make-variable-buffer-local 'org-target-link-regexp)
3793 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3794 "Regular expression matching a link target.")
3795 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3796 "Regular expression matching a radio target.")
3797 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3798 "Regular expression matching any target.")
3800 (defun org-activate-target-links (limit)
3801 "Run through the buffer and add overlays to target matches."
3802 (when org-target-link-regexp
3803 (let ((case-fold-search t))
3804 (if (re-search-forward org-target-link-regexp limit t)
3805 (progn
3806 (add-text-properties (match-beginning 0) (match-end 0)
3807 (list 'mouse-face 'highlight
3808 'rear-nonsticky org-nonsticky-props
3809 'keymap org-mouse-map
3810 'help-echo "Radio target link"
3811 'org-linked-text t))
3812 t)))))
3814 (defun org-update-radio-target-regexp ()
3815 "Find all radio targets in this file and update the regular expression."
3816 (interactive)
3817 (when (memq 'radio org-activate-links)
3818 (setq org-target-link-regexp
3819 (org-make-target-link-regexp (org-all-targets 'radio)))
3820 (org-restart-font-lock)))
3822 (defun org-hide-wide-columns (limit)
3823 (let (s e)
3824 (setq s (text-property-any (point) (or limit (point-max))
3825 'org-cwidth t))
3826 (when s
3827 (setq e (next-single-property-change s 'org-cwidth))
3828 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3829 (goto-char e)
3830 t)))
3832 (defvar org-latex-and-specials-regexp nil
3833 "Regular expression for highlighting export special stuff.")
3834 (defvar org-match-substring-regexp)
3835 (defvar org-match-substring-with-braces-regexp)
3836 (defvar org-export-html-special-string-regexps)
3838 (defun org-compute-latex-and-specials-regexp ()
3839 "Compute regular expression for stuff treated specially by exporters."
3840 (if (not org-highlight-latex-fragments-and-specials)
3841 (org-set-local 'org-latex-and-specials-regexp nil)
3842 (require 'org-exp)
3843 (let*
3844 ((matchers (plist-get org-format-latex-options :matchers))
3845 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3846 org-latex-regexps)))
3847 (options (org-combine-plists (org-default-export-plist)
3848 (org-infile-export-plist)))
3849 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3850 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3851 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3852 (org-export-html-expand (plist-get options :expand-quoted-html))
3853 (org-export-with-special-strings (plist-get options :special-strings))
3854 (re-sub
3855 (cond
3856 ((equal org-export-with-sub-superscripts '{})
3857 (list org-match-substring-with-braces-regexp))
3858 (org-export-with-sub-superscripts
3859 (list org-match-substring-regexp))
3860 (t nil)))
3861 (re-latex
3862 (if org-export-with-LaTeX-fragments
3863 (mapcar (lambda (x) (nth 1 x)) latexs)))
3864 (re-macros
3865 (if org-export-with-TeX-macros
3866 (list (concat "\\\\"
3867 (regexp-opt
3868 (append (mapcar 'car org-html-entities)
3869 (if (boundp 'org-latex-entities)
3870 org-latex-entities nil))
3871 'words))) ; FIXME
3873 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3874 (re-special (if org-export-with-special-strings
3875 (mapcar (lambda (x) (car x))
3876 org-export-html-special-string-regexps)))
3877 (re-rest
3878 (delq nil
3879 (list
3880 (if org-export-html-expand "@<[^>\n]+>")
3881 ))))
3882 (org-set-local
3883 'org-latex-and-specials-regexp
3884 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3885 re-rest) "\\|")))))
3887 (defun org-do-latex-and-special-faces (limit)
3888 "Run through the buffer and add overlays to links."
3889 (when org-latex-and-specials-regexp
3890 (let (rtn d)
3891 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3892 limit t))
3893 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3894 'face))
3895 '(org-code org-verbatim underline)))
3896 (progn
3897 (setq rtn t
3898 d (cond ((member (char-after (1+ (match-beginning 0)))
3899 '(?_ ?^)) 1)
3900 (t 0)))
3901 (font-lock-prepend-text-property
3902 (+ d (match-beginning 0)) (match-end 0)
3903 'face 'org-latex-and-export-specials)
3904 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3905 '(font-lock-multiline t)))))
3906 rtn)))
3908 (defun org-restart-font-lock ()
3909 "Restart font-lock-mode, to force refontification."
3910 (when (and (boundp 'font-lock-mode) font-lock-mode)
3911 (font-lock-mode -1)
3912 (font-lock-mode 1)))
3914 (defun org-all-targets (&optional radio)
3915 "Return a list of all targets in this file.
3916 With optional argument RADIO, only find radio targets."
3917 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3918 rtn)
3919 (save-excursion
3920 (goto-char (point-min))
3921 (while (re-search-forward re nil t)
3922 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3923 rtn)))
3925 (defun org-make-target-link-regexp (targets)
3926 "Make regular expression matching all strings in TARGETS.
3927 The regular expression finds the targets also if there is a line break
3928 between words."
3929 (and targets
3930 (concat
3931 "\\<\\("
3932 (mapconcat
3933 (lambda (x)
3934 (while (string-match " +" x)
3935 (setq x (replace-match "\\s-+" t t x)))
3937 targets
3938 "\\|")
3939 "\\)\\>")))
3941 (defun org-activate-tags (limit)
3942 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3943 (progn
3944 (add-text-properties (match-beginning 1) (match-end 1)
3945 (list 'mouse-face 'highlight
3946 'rear-nonsticky org-nonsticky-props
3947 'keymap org-mouse-map))
3948 t)))
3950 (defun org-outline-level ()
3951 (save-excursion
3952 (looking-at outline-regexp)
3953 (if (match-beginning 1)
3954 (+ (org-get-string-indentation (match-string 1)) 1000)
3955 (1- (- (match-end 0) (match-beginning 0))))))
3957 (defvar org-font-lock-keywords nil)
3959 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3960 "Regular expression matching a property line.")
3962 (defvar org-font-lock-hook nil
3963 "Functions to be called for special font lock stuff.")
3965 (defun org-font-lock-hook (limit)
3966 (run-hook-with-args 'org-font-lock-hook limit))
3968 (defun org-set-font-lock-defaults ()
3969 (let* ((em org-fontify-emphasized-text)
3970 (lk org-activate-links)
3971 (org-font-lock-extra-keywords
3972 (list
3973 ;; Call the hook
3974 '(org-font-lock-hook)
3975 ;; Headlines
3976 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3977 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3978 ;; Table lines
3979 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3980 (1 'org-table t))
3981 ;; Table internals
3982 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3983 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3984 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3985 ;; Drawers
3986 (list org-drawer-regexp '(0 'org-special-keyword t))
3987 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3988 ;; Properties
3989 (list org-property-re
3990 '(1 'org-special-keyword t)
3991 '(3 'org-property-value t))
3992 (if org-format-transports-properties-p
3993 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3994 ;; Links
3995 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3996 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3997 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3998 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3999 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4000 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4001 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4002 '(org-hide-wide-columns (0 nil append))
4003 ;; TODO lines
4004 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4005 '(1 (org-get-todo-face 1) t))
4006 ;; DONE
4007 (if org-fontify-done-headline
4008 (list (concat "^[*]+ +\\<\\("
4009 (mapconcat 'regexp-quote org-done-keywords "\\|")
4010 "\\)\\(.*\\)")
4011 '(2 'org-headline-done t))
4012 nil)
4013 ;; Priorities
4014 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4015 ;; Tags
4016 '(org-font-lock-add-tag-faces)
4017 ;; Special keywords
4018 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4019 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4020 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4021 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4022 ;; Emphasis
4023 (if em
4024 (if (featurep 'xemacs)
4025 '(org-do-emphasis-faces (0 nil append))
4026 '(org-do-emphasis-faces)))
4027 ;; Checkboxes
4028 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4029 2 'bold prepend)
4030 (if org-provide-checkbox-statistics
4031 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4032 (0 (org-get-checkbox-statistics-face) t)))
4033 ;; Description list items
4034 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4035 2 'bold prepend)
4036 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4037 '(1 'org-archived prepend))
4038 ;; Specials
4039 '(org-do-latex-and-special-faces)
4040 ;; Code
4041 '(org-activate-code (1 'org-code t))
4042 ;; COMMENT
4043 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4044 "\\|" org-quote-string "\\)\\>")
4045 '(1 'org-special-keyword t))
4046 '("^#.*" (0 'font-lock-comment-face t))
4048 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4049 ;; Now set the full font-lock-keywords
4050 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4051 (org-set-local 'font-lock-defaults
4052 '(org-font-lock-keywords t nil nil backward-paragraph))
4053 (kill-local-variable 'font-lock-keywords) nil))
4055 (defvar org-m nil)
4056 (defvar org-l nil)
4057 (defvar org-f nil)
4058 (defun org-get-level-face (n)
4059 "Get the right face for match N in font-lock matching of headlines."
4060 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4061 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4062 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4063 (cond
4064 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4065 ((eq n 2) org-f)
4066 (t (if org-level-color-stars-only nil org-f))))
4068 (defun org-get-todo-face (kwd)
4069 "Get the right face for a TODO keyword KWD.
4070 If KWD is a number, get the corresponding match group."
4071 (if (numberp kwd) (setq kwd (match-string kwd)))
4072 (or (cdr (assoc kwd org-todo-keyword-faces))
4073 (and (member kwd org-done-keywords) 'org-done)
4074 'org-todo))
4076 (defun org-font-lock-add-tag-faces (limit)
4077 "Add the special tag faces."
4078 (when (and org-tag-faces org-tags-special-faces-re)
4079 (while (re-search-forward org-tags-special-faces-re limit t)
4080 (add-text-properties (match-beginning 1) (match-end 1)
4081 (list 'face (org-get-tag-face 1)
4082 'font-lock-fontified t))
4083 (backward-char 1))))
4085 (defun org-get-tag-face (kwd)
4086 "Get the right face for a TODO keyword KWD.
4087 If KWD is a number, get the corresponding match group."
4088 (if (numberp kwd) (setq kwd (match-string kwd)))
4089 (or (cdr (assoc kwd org-tag-faces))
4090 'org-tag))
4092 (defun org-unfontify-region (beg end &optional maybe_loudly)
4093 "Remove fontification and activation overlays from links."
4094 (font-lock-default-unfontify-region beg end)
4095 (let* ((buffer-undo-list t)
4096 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4097 (inhibit-modification-hooks t)
4098 deactivate-mark buffer-file-name buffer-file-truename)
4099 (remove-text-properties beg end
4100 '(mouse-face t keymap t org-linked-text t
4101 invisible t intangible t))))
4103 ;;;; Visibility cycling, including org-goto and indirect buffer
4105 ;;; Cycling
4107 (defvar org-cycle-global-status nil)
4108 (make-variable-buffer-local 'org-cycle-global-status)
4109 (defvar org-cycle-subtree-status nil)
4110 (make-variable-buffer-local 'org-cycle-subtree-status)
4112 ;;;###autoload
4113 (defun org-cycle (&optional arg)
4114 "Visibility cycling for Org-mode.
4116 - When this function is called with a prefix argument, rotate the entire
4117 buffer through 3 states (global cycling)
4118 1. OVERVIEW: Show only top-level headlines.
4119 2. CONTENTS: Show all headlines of all levels, but no body text.
4120 3. SHOW ALL: Show everything.
4121 When called with two C-u C-u prefixes, switch to the startup visibility,
4122 determined by the variable `org-startup-folded', and by any VISIBILITY
4123 properties in the buffer.
4124 When called with three C-u C-u C-u prefixed, show the entire buffer,
4125 including drawers.
4127 - When point is at the beginning of a headline, rotate the subtree started
4128 by this line through 3 different states (local cycling)
4129 1. FOLDED: Only the main headline is shown.
4130 2. CHILDREN: The main headline and the direct children are shown.
4131 From this state, you can move to one of the children
4132 and zoom in further.
4133 3. SUBTREE: Show the entire subtree, including body text.
4135 - When there is a numeric prefix, go up to a heading with level ARG, do
4136 a `show-subtree' and return to the previous cursor position. If ARG
4137 is negative, go up that many levels.
4139 - When point is not at the beginning of a headline, execute the global
4140 binding for TAB, which is re-indenting the line. See the option
4141 `org-cycle-emulate-tab' for details.
4143 - Special case: if point is at the beginning of the buffer and there is
4144 no headline in line 1, this function will act as if called with prefix arg.
4145 But only if also the variable `org-cycle-global-at-bob' is t."
4146 (interactive "P")
4147 (org-load-modules-maybe)
4148 (let* ((outline-regexp
4149 (if (and (org-mode-p) org-cycle-include-plain-lists)
4150 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4151 outline-regexp))
4152 (bob-special (and org-cycle-global-at-bob (bobp)
4153 (not (looking-at outline-regexp))))
4154 (org-cycle-hook
4155 (if bob-special
4156 (delq 'org-optimize-window-after-visibility-change
4157 (copy-sequence org-cycle-hook))
4158 org-cycle-hook))
4159 (pos (point)))
4161 (if (or bob-special (equal arg '(4)))
4162 ;; special case: use global cycling
4163 (setq arg t))
4165 (cond
4167 ((equal arg '(16))
4168 (org-set-startup-visibility)
4169 (message "Startup visibility, plus VISIBILITY properties"))
4171 ((equal arg '(64))
4172 (show-all)
4173 (message "Entire buffer visible, including drawers"))
4175 ((org-at-table-p 'any)
4176 ;; Enter the table or move to the next field in the table
4177 (or (org-table-recognize-table.el)
4178 (progn
4179 (if arg (org-table-edit-field t)
4180 (org-table-justify-field-maybe)
4181 (call-interactively 'org-table-next-field)))))
4183 ((eq arg t) ;; Global cycling
4185 (cond
4186 ((and (eq last-command this-command)
4187 (eq org-cycle-global-status 'overview))
4188 ;; We just created the overview - now do table of contents
4189 ;; This can be slow in very large buffers, so indicate action
4190 (message "CONTENTS...")
4191 (org-content)
4192 (message "CONTENTS...done")
4193 (setq org-cycle-global-status 'contents)
4194 (run-hook-with-args 'org-cycle-hook 'contents))
4196 ((and (eq last-command this-command)
4197 (eq org-cycle-global-status 'contents))
4198 ;; We just showed the table of contents - now show everything
4199 (show-all)
4200 (message "SHOW ALL")
4201 (setq org-cycle-global-status 'all)
4202 (run-hook-with-args 'org-cycle-hook 'all))
4205 ;; Default action: go to overview
4206 (org-overview)
4207 (message "OVERVIEW")
4208 (setq org-cycle-global-status 'overview)
4209 (run-hook-with-args 'org-cycle-hook 'overview))))
4211 ((and org-drawers org-drawer-regexp
4212 (save-excursion
4213 (beginning-of-line 1)
4214 (looking-at org-drawer-regexp)))
4215 ;; Toggle block visibility
4216 (org-flag-drawer
4217 (not (get-char-property (match-end 0) 'invisible))))
4219 ((integerp arg)
4220 ;; Show-subtree, ARG levels up from here.
4221 (save-excursion
4222 (org-back-to-heading)
4223 (outline-up-heading (if (< arg 0) (- arg)
4224 (- (funcall outline-level) arg)))
4225 (org-show-subtree)))
4227 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4228 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4229 ;; At a heading: rotate between three different views
4230 (org-back-to-heading)
4231 (let ((goal-column 0) eoh eol eos)
4232 ;; First, some boundaries
4233 (save-excursion
4234 (org-back-to-heading)
4235 (save-excursion
4236 (beginning-of-line 2)
4237 (while (and (not (eobp)) ;; this is like `next-line'
4238 (get-char-property (1- (point)) 'invisible))
4239 (beginning-of-line 2)) (setq eol (point)))
4240 (outline-end-of-heading) (setq eoh (point))
4241 (org-end-of-subtree t)
4242 (unless (eobp)
4243 (skip-chars-forward " \t\n")
4244 (beginning-of-line 1) ; in case this is an item
4246 (setq eos (1- (point))))
4247 ;; Find out what to do next and set `this-command'
4248 (cond
4249 ((= eos eoh)
4250 ;; Nothing is hidden behind this heading
4251 (message "EMPTY ENTRY")
4252 (setq org-cycle-subtree-status nil)
4253 (save-excursion
4254 (goto-char eos)
4255 (outline-next-heading)
4256 (if (org-invisible-p) (org-flag-heading nil))))
4257 ((or (>= eol eos)
4258 (not (string-match "\\S-" (buffer-substring eol eos))))
4259 ;; Entire subtree is hidden in one line: open it
4260 (org-show-entry)
4261 (show-children)
4262 (message "CHILDREN")
4263 (save-excursion
4264 (goto-char eos)
4265 (outline-next-heading)
4266 (if (org-invisible-p) (org-flag-heading nil)))
4267 (setq org-cycle-subtree-status 'children)
4268 (run-hook-with-args 'org-cycle-hook 'children))
4269 ((and (eq last-command this-command)
4270 (eq org-cycle-subtree-status 'children))
4271 ;; We just showed the children, now show everything.
4272 (org-show-subtree)
4273 (message "SUBTREE")
4274 (setq org-cycle-subtree-status 'subtree)
4275 (run-hook-with-args 'org-cycle-hook 'subtree))
4277 ;; Default action: hide the subtree.
4278 (hide-subtree)
4279 (message "FOLDED")
4280 (setq org-cycle-subtree-status 'folded)
4281 (run-hook-with-args 'org-cycle-hook 'folded)))))
4283 ;; TAB emulation and template completion
4284 (buffer-read-only (org-back-to-heading))
4286 ((org-try-structure-completion))
4288 ((org-try-cdlatex-tab))
4290 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4291 (or (not (bolp))
4292 (not (looking-at outline-regexp))))
4293 (call-interactively (global-key-binding "\t")))
4295 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4296 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4297 (or (and (eq org-cycle-emulate-tab 'white)
4298 (= (match-end 0) (point-at-eol)))
4299 (and (eq org-cycle-emulate-tab 'whitestart)
4300 (>= (match-end 0) pos))))
4302 (eq org-cycle-emulate-tab t))
4303 (call-interactively (global-key-binding "\t")))
4305 (t (save-excursion
4306 (org-back-to-heading)
4307 (org-cycle))))))
4309 ;;;###autoload
4310 (defun org-global-cycle (&optional arg)
4311 "Cycle the global visibility. For details see `org-cycle'.
4312 With C-u prefix arg, switch to startup visibility.
4313 With a numeric prefix, show all headlines up to that level."
4314 (interactive "P")
4315 (let ((org-cycle-include-plain-lists
4316 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4317 (cond
4318 ((integerp arg)
4319 (show-all)
4320 (hide-sublevels arg)
4321 (setq org-cycle-global-status 'contents))
4322 ((equal arg '(4))
4323 (org-set-startup-visibility)
4324 (message "Startup visibility, plus VISIBILITY properties."))
4326 (org-cycle '(4))))))
4328 (defun org-set-startup-visibility ()
4329 "Set the visibility required by startup options and properties."
4330 (cond
4331 ((eq org-startup-folded t)
4332 (org-cycle '(4)))
4333 ((eq org-startup-folded 'content)
4334 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4335 (org-cycle '(4)) (org-cycle '(4)))))
4336 (org-set-visibility-according-to-property 'no-cleanup)
4337 (org-cycle-hide-archived-subtrees 'all)
4338 (org-cycle-hide-drawers 'all)
4339 (org-cycle-show-empty-lines 'all))
4341 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4342 "Switch subtree visibilities according to :VISIBILITY: property."
4343 (interactive)
4344 (let (state)
4345 (save-excursion
4346 (goto-char (point-min))
4347 (while (re-search-forward
4348 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4349 nil t)
4350 (setq state (match-string 1))
4351 (save-excursion
4352 (org-back-to-heading t)
4353 (hide-subtree)
4354 (org-reveal)
4355 (cond
4356 ((equal state '("fold" "folded"))
4357 (hide-subtree))
4358 ((equal state "children")
4359 (org-show-hidden-entry)
4360 (show-children))
4361 ((equal state "content")
4362 (save-excursion
4363 (save-restriction
4364 (org-narrow-to-subtree)
4365 (org-content))))
4366 ((member state '("all" "showall"))
4367 (show-subtree)))))
4368 (unless no-cleanup
4369 (org-cycle-hide-archived-subtrees 'all)
4370 (org-cycle-hide-drawers 'all)
4371 (org-cycle-show-empty-lines 'all)))))
4373 (defun org-overview ()
4374 "Switch to overview mode, showing only top-level headlines.
4375 Really, this shows all headlines with level equal or greater than the level
4376 of the first headline in the buffer. This is important, because if the
4377 first headline is not level one, then (hide-sublevels 1) gives confusing
4378 results."
4379 (interactive)
4380 (let ((level (save-excursion
4381 (goto-char (point-min))
4382 (if (re-search-forward (concat "^" outline-regexp) nil t)
4383 (progn
4384 (goto-char (match-beginning 0))
4385 (funcall outline-level))))))
4386 (and level (hide-sublevels level))))
4388 (defun org-content (&optional arg)
4389 "Show all headlines in the buffer, like a table of contents.
4390 With numerical argument N, show content up to level N."
4391 (interactive "P")
4392 (save-excursion
4393 ;; Visit all headings and show their offspring
4394 (and (integerp arg) (org-overview))
4395 (goto-char (point-max))
4396 (catch 'exit
4397 (while (and (progn (condition-case nil
4398 (outline-previous-visible-heading 1)
4399 (error (goto-char (point-min))))
4401 (looking-at outline-regexp))
4402 (if (integerp arg)
4403 (show-children (1- arg))
4404 (show-branches))
4405 (if (bobp) (throw 'exit nil))))))
4408 (defun org-optimize-window-after-visibility-change (state)
4409 "Adjust the window after a change in outline visibility.
4410 This function is the default value of the hook `org-cycle-hook'."
4411 (when (get-buffer-window (current-buffer))
4412 (cond
4413 ; ((eq state 'overview) (org-first-headline-recenter 1))
4414 ; ((eq state 'overview) (org-beginning-of-line))
4415 ((eq state 'content) nil)
4416 ((eq state 'all) nil)
4417 ((eq state 'folded) nil)
4418 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4419 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4421 (defun org-compact-display-after-subtree-move ()
4422 (let (beg end)
4423 (save-excursion
4424 (if (org-up-heading-safe)
4425 (progn
4426 (hide-subtree)
4427 (show-entry)
4428 (show-children)
4429 (org-cycle-show-empty-lines 'children)
4430 (org-cycle-hide-drawers 'children))
4431 (org-overview)))))
4433 (defun org-cycle-show-empty-lines (state)
4434 "Show empty lines above all visible headlines.
4435 The region to be covered depends on STATE when called through
4436 `org-cycle-hook'. Lisp program can use t for STATE to get the
4437 entire buffer covered. Note that an empty line is only shown if there
4438 are at least `org-cycle-separator-lines' empty lines before the headline."
4439 (when (> org-cycle-separator-lines 0)
4440 (save-excursion
4441 (let* ((n org-cycle-separator-lines)
4442 (re (cond
4443 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4444 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4445 (t (let ((ns (number-to-string (- n 2))))
4446 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4447 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4448 beg end)
4449 (cond
4450 ((memq state '(overview contents t))
4451 (setq beg (point-min) end (point-max)))
4452 ((memq state '(children folded))
4453 (setq beg (point) end (progn (org-end-of-subtree t t)
4454 (beginning-of-line 2)
4455 (point)))))
4456 (when beg
4457 (goto-char beg)
4458 (while (re-search-forward re end t)
4459 (if (not (get-char-property (match-end 1) 'invisible))
4460 (outline-flag-region
4461 (match-beginning 1) (match-end 1) nil)))))))
4462 ;; Never hide empty lines at the end of the file.
4463 (save-excursion
4464 (goto-char (point-max))
4465 (outline-previous-heading)
4466 (outline-end-of-heading)
4467 (if (and (looking-at "[ \t\n]+")
4468 (= (match-end 0) (point-max)))
4469 (outline-flag-region (point) (match-end 0) nil))))
4471 (defun org-show-empty-lines-in-parent ()
4472 "Move to the parent and re-show empty lines before visible headlines."
4473 (save-excursion
4474 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4475 (org-cycle-show-empty-lines context))))
4477 (defun org-cycle-hide-drawers (state)
4478 "Re-hide all drawers after a visibility state change."
4479 (when (and (org-mode-p)
4480 (not (memq state '(overview folded))))
4481 (save-excursion
4482 (let* ((globalp (memq state '(contents all)))
4483 (beg (if globalp (point-min) (point)))
4484 (end (if globalp (point-max) (org-end-of-subtree t))))
4485 (goto-char beg)
4486 (while (re-search-forward org-drawer-regexp end t)
4487 (org-flag-drawer t))))))
4489 (defun org-flag-drawer (flag)
4490 (save-excursion
4491 (beginning-of-line 1)
4492 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4493 (let ((b (match-end 0))
4494 (outline-regexp org-outline-regexp))
4495 (if (re-search-forward
4496 "^[ \t]*:END:"
4497 (save-excursion (outline-next-heading) (point)) t)
4498 (outline-flag-region b (point-at-eol) flag)
4499 (error ":END: line missing"))))))
4501 (defun org-subtree-end-visible-p ()
4502 "Is the end of the current subtree visible?"
4503 (pos-visible-in-window-p
4504 (save-excursion (org-end-of-subtree t) (point))))
4506 (defun org-first-headline-recenter (&optional N)
4507 "Move cursor to the first headline and recenter the headline.
4508 Optional argument N means, put the headline into the Nth line of the window."
4509 (goto-char (point-min))
4510 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4511 (beginning-of-line)
4512 (recenter (prefix-numeric-value N))))
4514 ;;; Org-goto
4516 (defvar org-goto-window-configuration nil)
4517 (defvar org-goto-marker nil)
4518 (defvar org-goto-map
4519 (let ((map (make-sparse-keymap)))
4520 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4521 (while (setq cmd (pop cmds))
4522 (substitute-key-definition cmd cmd map global-map)))
4523 (suppress-keymap map)
4524 (org-defkey map "\C-m" 'org-goto-ret)
4525 (org-defkey map [(return)] 'org-goto-ret)
4526 (org-defkey map [(left)] 'org-goto-left)
4527 (org-defkey map [(right)] 'org-goto-right)
4528 (org-defkey map [(control ?g)] 'org-goto-quit)
4529 (org-defkey map "\C-i" 'org-cycle)
4530 (org-defkey map [(tab)] 'org-cycle)
4531 (org-defkey map [(down)] 'outline-next-visible-heading)
4532 (org-defkey map [(up)] 'outline-previous-visible-heading)
4533 (if org-goto-auto-isearch
4534 (if (fboundp 'define-key-after)
4535 (define-key-after map [t] 'org-goto-local-auto-isearch)
4536 nil)
4537 (org-defkey map "q" 'org-goto-quit)
4538 (org-defkey map "n" 'outline-next-visible-heading)
4539 (org-defkey map "p" 'outline-previous-visible-heading)
4540 (org-defkey map "f" 'outline-forward-same-level)
4541 (org-defkey map "b" 'outline-backward-same-level)
4542 (org-defkey map "u" 'outline-up-heading))
4543 (org-defkey map "/" 'org-occur)
4544 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4545 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4546 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4547 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4548 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4549 map))
4551 (defconst org-goto-help
4552 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4553 RET=jump to location [Q]uit and return to previous location
4554 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4556 (defvar org-goto-start-pos) ; dynamically scoped parameter
4558 ;; FIXME: Docstring doe not mention both interfaces
4559 (defun org-goto (&optional alternative-interface)
4560 "Look up a different location in the current file, keeping current visibility.
4562 When you want look-up or go to a different location in a document, the
4563 fastest way is often to fold the entire buffer and then dive into the tree.
4564 This method has the disadvantage, that the previous location will be folded,
4565 which may not be what you want.
4567 This command works around this by showing a copy of the current buffer
4568 in an indirect buffer, in overview mode. You can dive into the tree in
4569 that copy, use org-occur and incremental search to find a location.
4570 When pressing RET or `Q', the command returns to the original buffer in
4571 which the visibility is still unchanged. After RET is will also jump to
4572 the location selected in the indirect buffer and expose the
4573 the headline hierarchy above."
4574 (interactive "P")
4575 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4576 (org-refile-use-outline-path t)
4577 (interface
4578 (if (not alternative-interface)
4579 org-goto-interface
4580 (if (eq org-goto-interface 'outline)
4581 'outline-path-completion
4582 'outline)))
4583 (org-goto-start-pos (point))
4584 (selected-point
4585 (if (eq interface 'outline)
4586 (car (org-get-location (current-buffer) org-goto-help))
4587 (nth 3 (org-refile-get-location "Goto: ")))))
4588 (if selected-point
4589 (progn
4590 (org-mark-ring-push org-goto-start-pos)
4591 (goto-char selected-point)
4592 (if (or (org-invisible-p) (org-invisible-p2))
4593 (org-show-context 'org-goto)))
4594 (message "Quit"))))
4596 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4597 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4598 (defvar org-goto-local-auto-isearch-map) ; defined below
4600 (defun org-get-location (buf help)
4601 "Let the user select a location in the Org-mode buffer BUF.
4602 This function uses a recursive edit. It returns the selected position
4603 or nil."
4604 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4605 (isearch-hide-immediately nil)
4606 (isearch-search-fun-function
4607 (lambda () 'org-goto-local-search-headings))
4608 (org-goto-selected-point org-goto-exit-command))
4609 (save-excursion
4610 (save-window-excursion
4611 (delete-other-windows)
4612 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4613 (switch-to-buffer
4614 (condition-case nil
4615 (make-indirect-buffer (current-buffer) "*org-goto*")
4616 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4617 (with-output-to-temp-buffer "*Help*"
4618 (princ help))
4619 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4620 (setq buffer-read-only nil)
4621 (let ((org-startup-truncated t)
4622 (org-startup-folded nil)
4623 (org-startup-align-all-tables nil))
4624 (org-mode)
4625 (org-overview))
4626 (setq buffer-read-only t)
4627 (if (and (boundp 'org-goto-start-pos)
4628 (integer-or-marker-p org-goto-start-pos))
4629 (let ((org-show-hierarchy-above t)
4630 (org-show-siblings t)
4631 (org-show-following-heading t))
4632 (goto-char org-goto-start-pos)
4633 (and (org-invisible-p) (org-show-context)))
4634 (goto-char (point-min)))
4635 (org-beginning-of-line)
4636 (message "Select location and press RET")
4637 (use-local-map org-goto-map)
4638 (recursive-edit)
4640 (kill-buffer "*org-goto*")
4641 (cons org-goto-selected-point org-goto-exit-command)))
4643 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4644 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4645 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4646 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4648 (defun org-goto-local-search-headings (string bound noerror)
4649 "Search and make sure that any matches are in headlines."
4650 (catch 'return
4651 (while (if isearch-forward
4652 (search-forward string bound noerror)
4653 (search-backward string bound noerror))
4654 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4655 (and (member :headline context)
4656 (not (member :tags context))))
4657 (throw 'return (point))))))
4659 (defun org-goto-local-auto-isearch ()
4660 "Start isearch."
4661 (interactive)
4662 (goto-char (point-min))
4663 (let ((keys (this-command-keys)))
4664 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4665 (isearch-mode t)
4666 (isearch-process-search-char (string-to-char keys)))))
4668 (defun org-goto-ret (&optional arg)
4669 "Finish `org-goto' by going to the new location."
4670 (interactive "P")
4671 (setq org-goto-selected-point (point)
4672 org-goto-exit-command 'return)
4673 (throw 'exit nil))
4675 (defun org-goto-left ()
4676 "Finish `org-goto' by going to the new location."
4677 (interactive)
4678 (if (org-on-heading-p)
4679 (progn
4680 (beginning-of-line 1)
4681 (setq org-goto-selected-point (point)
4682 org-goto-exit-command 'left)
4683 (throw 'exit nil))
4684 (error "Not on a heading")))
4686 (defun org-goto-right ()
4687 "Finish `org-goto' by going to the new location."
4688 (interactive)
4689 (if (org-on-heading-p)
4690 (progn
4691 (setq org-goto-selected-point (point)
4692 org-goto-exit-command 'right)
4693 (throw 'exit nil))
4694 (error "Not on a heading")))
4696 (defun org-goto-quit ()
4697 "Finish `org-goto' without cursor motion."
4698 (interactive)
4699 (setq org-goto-selected-point nil)
4700 (setq org-goto-exit-command 'quit)
4701 (throw 'exit nil))
4703 ;;; Indirect buffer display of subtrees
4705 (defvar org-indirect-dedicated-frame nil
4706 "This is the frame being used for indirect tree display.")
4707 (defvar org-last-indirect-buffer nil)
4709 (defun org-tree-to-indirect-buffer (&optional arg)
4710 "Create indirect buffer and narrow it to current subtree.
4711 With numerical prefix ARG, go up to this level and then take that tree.
4712 If ARG is negative, go up that many levels.
4713 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4714 indirect buffer previously made with this command, to avoid proliferation of
4715 indirect buffers. However, when you call the command with a `C-u' prefix, or
4716 when `org-indirect-buffer-display' is `new-frame', the last buffer
4717 is kept so that you can work with several indirect buffers at the same time.
4718 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4719 requests that a new frame be made for the new buffer, so that the dedicated
4720 frame is not changed."
4721 (interactive "P")
4722 (let ((cbuf (current-buffer))
4723 (cwin (selected-window))
4724 (pos (point))
4725 beg end level heading ibuf)
4726 (save-excursion
4727 (org-back-to-heading t)
4728 (when (numberp arg)
4729 (setq level (org-outline-level))
4730 (if (< arg 0) (setq arg (+ level arg)))
4731 (while (> (setq level (org-outline-level)) arg)
4732 (outline-up-heading 1 t)))
4733 (setq beg (point)
4734 heading (org-get-heading))
4735 (org-end-of-subtree t) (setq end (point)))
4736 (if (and (buffer-live-p org-last-indirect-buffer)
4737 (not (eq org-indirect-buffer-display 'new-frame))
4738 (not arg))
4739 (kill-buffer org-last-indirect-buffer))
4740 (setq ibuf (org-get-indirect-buffer cbuf)
4741 org-last-indirect-buffer ibuf)
4742 (cond
4743 ((or (eq org-indirect-buffer-display 'new-frame)
4744 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4745 (select-frame (make-frame))
4746 (delete-other-windows)
4747 (switch-to-buffer ibuf)
4748 (org-set-frame-title heading))
4749 ((eq org-indirect-buffer-display 'dedicated-frame)
4750 (raise-frame
4751 (select-frame (or (and org-indirect-dedicated-frame
4752 (frame-live-p org-indirect-dedicated-frame)
4753 org-indirect-dedicated-frame)
4754 (setq org-indirect-dedicated-frame (make-frame)))))
4755 (delete-other-windows)
4756 (switch-to-buffer ibuf)
4757 (org-set-frame-title (concat "Indirect: " heading)))
4758 ((eq org-indirect-buffer-display 'current-window)
4759 (switch-to-buffer ibuf))
4760 ((eq org-indirect-buffer-display 'other-window)
4761 (pop-to-buffer ibuf))
4762 (t (error "Invalid value.")))
4763 (if (featurep 'xemacs)
4764 (save-excursion (org-mode) (turn-on-font-lock)))
4765 (narrow-to-region beg end)
4766 (show-all)
4767 (goto-char pos)
4768 (and (window-live-p cwin) (select-window cwin))))
4770 (defun org-get-indirect-buffer (&optional buffer)
4771 (setq buffer (or buffer (current-buffer)))
4772 (let ((n 1) (base (buffer-name buffer)) bname)
4773 (while (buffer-live-p
4774 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4775 (setq n (1+ n)))
4776 (condition-case nil
4777 (make-indirect-buffer buffer bname 'clone)
4778 (error (make-indirect-buffer buffer bname)))))
4780 (defun org-set-frame-title (title)
4781 "Set the title of the current frame to the string TITLE."
4782 ;; FIXME: how to name a single frame in XEmacs???
4783 (unless (featurep 'xemacs)
4784 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4786 ;;;; Structure editing
4788 ;;; Inserting headlines
4790 (defun org-insert-heading (&optional force-heading)
4791 "Insert a new heading or item with same depth at point.
4792 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4793 If point is at the beginning of a headline, insert a sibling before the
4794 current headline. If point is not at the beginning, do not split the line,
4795 but create the new headline after the current line."
4796 (interactive "P")
4797 (if (= (buffer-size) 0)
4798 (insert "\n* ")
4799 (when (or force-heading (not (org-insert-item)))
4800 (let* ((head (save-excursion
4801 (condition-case nil
4802 (progn
4803 (org-back-to-heading)
4804 (match-string 0))
4805 (error "*"))))
4806 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4807 pos hide-previous previous-pos)
4808 (cond
4809 ((and (org-on-heading-p) (bolp)
4810 (or (bobp)
4811 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4812 ;; insert before the current line
4813 (open-line (if blank 2 1)))
4814 ((and (bolp)
4815 (or (bobp)
4816 (save-excursion
4817 (backward-char 1) (not (org-invisible-p)))))
4818 ;; insert right here
4819 nil)
4821 ;; somewhere in the line
4822 (save-excursion
4823 (setq previous-pos (point-at-bol))
4824 (end-of-line)
4825 (setq hide-previous (org-invisible-p)))
4826 (and org-insert-heading-respect-content (org-show-subtree))
4827 (let ((split
4828 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4829 (save-excursion
4830 (let ((p (point)))
4831 (goto-char (point-at-bol))
4832 (and (looking-at org-complex-heading-regexp)
4833 (> p (match-beginning 4)))))))
4834 tags pos)
4835 (cond
4836 (org-insert-heading-respect-content
4837 (org-end-of-subtree nil t)
4838 (or (bolp) (newline))
4839 (open-line 1))
4840 ((org-on-heading-p)
4841 (when hide-previous
4842 (show-children)
4843 (org-show-entry))
4844 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4845 (setq tags (and (match-end 2) (match-string 2)))
4846 (and (match-end 1)
4847 (delete-region (match-beginning 1) (match-end 1)))
4848 (setq pos (point-at-bol))
4849 (or split (end-of-line 1))
4850 (delete-horizontal-space)
4851 (newline (if blank 2 1))
4852 (when tags
4853 (save-excursion
4854 (goto-char pos)
4855 (end-of-line 1)
4856 (insert " " tags)
4857 (org-set-tags nil 'align))))
4859 (or split (end-of-line 1))
4860 (newline (if blank 2 1)))))))
4861 (insert head) (just-one-space)
4862 (setq pos (point))
4863 (end-of-line 1)
4864 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4865 (when (and org-insert-heading-respect-content hide-previous)
4866 (save-excursion
4867 (goto-char previous-pos)
4868 (hide-subtree)))
4869 (run-hooks 'org-insert-heading-hook)))))
4871 (defun org-get-heading (&optional no-tags)
4872 "Return the heading of the current entry, without the stars."
4873 (save-excursion
4874 (org-back-to-heading t)
4875 (if (looking-at
4876 (if no-tags
4877 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4878 "\\*+[ \t]+\\([^\r\n]*\\)"))
4879 (match-string 1) "")))
4881 (defun org-insert-heading-after-current ()
4882 "Insert a new heading with same level as current, after current subtree."
4883 (interactive)
4884 (org-back-to-heading)
4885 (org-insert-heading)
4886 (org-move-subtree-down)
4887 (end-of-line 1))
4889 (defun org-insert-heading-respect-content ()
4890 (interactive)
4891 (let ((org-insert-heading-respect-content t))
4892 (org-insert-heading t)))
4894 (defun org-insert-todo-heading-respect-content (&optional force-state)
4895 (interactive "P")
4896 (let ((org-insert-heading-respect-content t))
4897 (org-insert-todo-heading force-state t)))
4899 (defun org-insert-todo-heading (arg &optional force-heading)
4900 "Insert a new heading with the same level and TODO state as current heading.
4901 If the heading has no TODO state, or if the state is DONE, use the first
4902 state (TODO by default). Also with prefix arg, force first state."
4903 (interactive "P")
4904 (when (or force-heading (not (org-insert-item 'checkbox)))
4905 (org-insert-heading force-heading)
4906 (save-excursion
4907 (org-back-to-heading)
4908 (outline-previous-heading)
4909 (looking-at org-todo-line-regexp))
4910 (if (or arg
4911 (not (match-beginning 2))
4912 (member (match-string 2) org-done-keywords))
4913 (insert (car org-todo-keywords-1) " ")
4914 (insert (match-string 2) " "))
4915 (when org-provide-todo-statistics
4916 (org-update-parent-todo-statistics))))
4918 (defun org-insert-subheading (arg)
4919 "Insert a new subheading and demote it.
4920 Works for outline headings and for plain lists alike."
4921 (interactive "P")
4922 (org-insert-heading arg)
4923 (cond
4924 ((org-on-heading-p) (org-do-demote))
4925 ((org-at-item-p) (org-indent-item 1))))
4927 (defun org-insert-todo-subheading (arg)
4928 "Insert a new subheading with TODO keyword or checkbox and demote it.
4929 Works for outline headings and for plain lists alike."
4930 (interactive "P")
4931 (org-insert-todo-heading arg)
4932 (cond
4933 ((org-on-heading-p) (org-do-demote))
4934 ((org-at-item-p) (org-indent-item 1))))
4936 ;;; Promotion and Demotion
4938 (defun org-promote-subtree ()
4939 "Promote the entire subtree.
4940 See also `org-promote'."
4941 (interactive)
4942 (save-excursion
4943 (org-map-tree 'org-promote))
4944 (org-fix-position-after-promote))
4946 (defun org-demote-subtree ()
4947 "Demote the entire subtree. See `org-demote'.
4948 See also `org-promote'."
4949 (interactive)
4950 (save-excursion
4951 (org-map-tree 'org-demote))
4952 (org-fix-position-after-promote))
4955 (defun org-do-promote ()
4956 "Promote the current heading higher up the tree.
4957 If the region is active in `transient-mark-mode', promote all headings
4958 in the region."
4959 (interactive)
4960 (save-excursion
4961 (if (org-region-active-p)
4962 (org-map-region 'org-promote (region-beginning) (region-end))
4963 (org-promote)))
4964 (org-fix-position-after-promote))
4966 (defun org-do-demote ()
4967 "Demote the current heading lower down the tree.
4968 If the region is active in `transient-mark-mode', demote all headings
4969 in the region."
4970 (interactive)
4971 (save-excursion
4972 (if (org-region-active-p)
4973 (org-map-region 'org-demote (region-beginning) (region-end))
4974 (org-demote)))
4975 (org-fix-position-after-promote))
4977 (defun org-fix-position-after-promote ()
4978 "Make sure that after pro/demotion cursor position is right."
4979 (let ((pos (point)))
4980 (when (save-excursion
4981 (beginning-of-line 1)
4982 (looking-at org-todo-line-regexp)
4983 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4984 (cond ((eobp) (insert " "))
4985 ((eolp) (insert " "))
4986 ((equal (char-after) ?\ ) (forward-char 1))))))
4988 (defun org-reduced-level (l)
4989 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4991 (defun org-get-valid-level (level &optional change)
4992 "Rectify a level change under the influence of `org-odd-levels-only'
4993 LEVEL is a current level, CHANGE is by how much the level should be
4994 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4995 even level numbers will become the next higher odd number."
4996 (if org-odd-levels-only
4997 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4998 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4999 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5000 (max 1 (+ level change))))
5002 (if (boundp 'define-obsolete-function-alias)
5003 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5004 (define-obsolete-function-alias 'org-get-legal-level
5005 'org-get-valid-level)
5006 (define-obsolete-function-alias 'org-get-legal-level
5007 'org-get-valid-level "23.1")))
5009 (defun org-promote ()
5010 "Promote the current heading higher up the tree.
5011 If the region is active in `transient-mark-mode', promote all headings
5012 in the region."
5013 (org-back-to-heading t)
5014 (let* ((level (save-match-data (funcall outline-level)))
5015 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5016 (diff (abs (- level (length up-head) -1))))
5017 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5018 (replace-match up-head nil t)
5019 ;; Fixup tag positioning
5020 (and org-auto-align-tags (org-set-tags nil t))
5021 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5023 (defun org-demote ()
5024 "Demote the current heading lower down the tree.
5025 If the region is active in `transient-mark-mode', demote all headings
5026 in the region."
5027 (org-back-to-heading t)
5028 (let* ((level (save-match-data (funcall outline-level)))
5029 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5030 (diff (abs (- level (length down-head) -1))))
5031 (replace-match down-head nil t)
5032 ;; Fixup tag positioning
5033 (and org-auto-align-tags (org-set-tags nil t))
5034 (if org-adapt-indentation (org-fixup-indentation diff))))
5036 (defun org-map-tree (fun)
5037 "Call FUN for every heading underneath the current one."
5038 (org-back-to-heading)
5039 (let ((level (funcall outline-level)))
5040 (save-excursion
5041 (funcall fun)
5042 (while (and (progn
5043 (outline-next-heading)
5044 (> (funcall outline-level) level))
5045 (not (eobp)))
5046 (funcall fun)))))
5048 (defun org-map-region (fun beg end)
5049 "Call FUN for every heading between BEG and END."
5050 (let ((org-ignore-region t))
5051 (save-excursion
5052 (setq end (copy-marker end))
5053 (goto-char beg)
5054 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5055 (< (point) end))
5056 (funcall fun))
5057 (while (and (progn
5058 (outline-next-heading)
5059 (< (point) end))
5060 (not (eobp)))
5061 (funcall fun)))))
5063 (defun org-fixup-indentation (diff)
5064 "Change the indentation in the current entry by DIFF
5065 However, if any line in the current entry has no indentation, or if it
5066 would end up with no indentation after the change, nothing at all is done."
5067 (save-excursion
5068 (let ((end (save-excursion (outline-next-heading)
5069 (point-marker)))
5070 (prohibit (if (> diff 0)
5071 "^\\S-"
5072 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5073 col)
5074 (unless (save-excursion (end-of-line 1)
5075 (re-search-forward prohibit end t))
5076 (while (and (< (point) end)
5077 (re-search-forward "^[ \t]+" end t))
5078 (goto-char (match-end 0))
5079 (setq col (current-column))
5080 (if (< diff 0) (replace-match ""))
5081 (org-indent-to-column (+ diff col))))
5082 (move-marker end nil))))
5084 (defun org-convert-to-odd-levels ()
5085 "Convert an org-mode file with all levels allowed to one with odd levels.
5086 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5087 level 5 etc."
5088 (interactive)
5089 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5090 (let ((org-odd-levels-only nil) n)
5091 (save-excursion
5092 (goto-char (point-min))
5093 (while (re-search-forward "^\\*\\*+ " nil t)
5094 (setq n (- (length (match-string 0)) 2))
5095 (while (>= (setq n (1- n)) 0)
5096 (org-demote))
5097 (end-of-line 1))))))
5100 (defun org-convert-to-oddeven-levels ()
5101 "Convert an org-mode file with only odd levels to one with odd and even levels.
5102 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5103 section with an even level, conversion would destroy the structure of the file. An error
5104 is signaled in this case."
5105 (interactive)
5106 (goto-char (point-min))
5107 ;; First check if there are no even levels
5108 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5109 (org-show-context t)
5110 (error "Not all levels are odd in this file. Conversion not possible."))
5111 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5112 (let ((org-odd-levels-only nil) n)
5113 (save-excursion
5114 (goto-char (point-min))
5115 (while (re-search-forward "^\\*\\*+ " nil t)
5116 (setq n (/ (1- (length (match-string 0))) 2))
5117 (while (>= (setq n (1- n)) 0)
5118 (org-promote))
5119 (end-of-line 1))))))
5121 (defun org-tr-level (n)
5122 "Make N odd if required."
5123 (if org-odd-levels-only (1+ (/ n 2)) n))
5125 ;;; Vertical tree motion, cutting and pasting of subtrees
5127 (defun org-move-subtree-up (&optional arg)
5128 "Move the current subtree up past ARG headlines of the same level."
5129 (interactive "p")
5130 (org-move-subtree-down (- (prefix-numeric-value arg))))
5132 (defun org-move-subtree-down (&optional arg)
5133 "Move the current subtree down past ARG headlines of the same level."
5134 (interactive "p")
5135 (setq arg (prefix-numeric-value arg))
5136 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5137 'outline-get-last-sibling))
5138 (ins-point (make-marker))
5139 (cnt (abs arg))
5140 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5141 ;; Select the tree
5142 (org-back-to-heading)
5143 (setq beg0 (point))
5144 (save-excursion
5145 (setq ne-beg (org-back-over-empty-lines))
5146 (setq beg (point)))
5147 (save-match-data
5148 (save-excursion (outline-end-of-heading)
5149 (setq folded (org-invisible-p)))
5150 (outline-end-of-subtree))
5151 (outline-next-heading)
5152 (setq ne-end (org-back-over-empty-lines))
5153 (setq end (point))
5154 (goto-char beg0)
5155 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5156 ;; include less whitespace
5157 (save-excursion
5158 (goto-char beg)
5159 (forward-line (- ne-beg ne-end))
5160 (setq beg (point))))
5161 ;; Find insertion point, with error handling
5162 (while (> cnt 0)
5163 (or (and (funcall movfunc) (looking-at outline-regexp))
5164 (progn (goto-char beg0)
5165 (error "Cannot move past superior level or buffer limit")))
5166 (setq cnt (1- cnt)))
5167 (if (> arg 0)
5168 ;; Moving forward - still need to move over subtree
5169 (progn (org-end-of-subtree t t)
5170 (save-excursion
5171 (org-back-over-empty-lines)
5172 (or (bolp) (newline)))))
5173 (setq ne-ins (org-back-over-empty-lines))
5174 (move-marker ins-point (point))
5175 (setq txt (buffer-substring beg end))
5176 (org-save-markers-in-region beg end)
5177 (delete-region beg end)
5178 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5179 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5180 (let ((bbb (point)))
5181 (insert-before-markers txt)
5182 (org-reinstall-markers-in-region bbb)
5183 (move-marker ins-point bbb))
5184 (or (bolp) (insert "\n"))
5185 (setq ins-end (point))
5186 (goto-char ins-point)
5187 (org-skip-whitespace)
5188 (when (and (< arg 0)
5189 (org-first-sibling-p)
5190 (> ne-ins ne-beg))
5191 ;; Move whitespace back to beginning
5192 (save-excursion
5193 (goto-char ins-end)
5194 (let ((kill-whole-line t))
5195 (kill-line (- ne-ins ne-beg)) (point)))
5196 (insert (make-string (- ne-ins ne-beg) ?\n)))
5197 (move-marker ins-point nil)
5198 (org-compact-display-after-subtree-move)
5199 (org-show-empty-lines-in-parent)
5200 (unless folded
5201 (org-show-entry)
5202 (show-children)
5203 (org-cycle-hide-drawers 'children))))
5205 (defvar org-subtree-clip ""
5206 "Clipboard for cut and paste of subtrees.
5207 This is actually only a copy of the kill, because we use the normal kill
5208 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5210 (defvar org-subtree-clip-folded nil
5211 "Was the last copied subtree folded?
5212 This is used to fold the tree back after pasting.")
5214 (defun org-cut-subtree (&optional n)
5215 "Cut the current subtree into the clipboard.
5216 With prefix arg N, cut this many sequential subtrees.
5217 This is a short-hand for marking the subtree and then cutting it."
5218 (interactive "p")
5219 (org-copy-subtree n 'cut))
5221 (defun org-copy-subtree (&optional n cut force-store-markers)
5222 "Cut the current subtree into the clipboard.
5223 With prefix arg N, cut this many sequential subtrees.
5224 This is a short-hand for marking the subtree and then copying it.
5225 If CUT is non-nil, actually cut the subtree.
5226 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5227 of some markers in the region, even if CUT is non-nil. This is
5228 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5229 (interactive "p")
5230 (let (beg end folded (beg0 (point)))
5231 (if (interactive-p)
5232 (org-back-to-heading nil) ; take what looks like a subtree
5233 (org-back-to-heading t)) ; take what is really there
5234 (org-back-over-empty-lines)
5235 (setq beg (point))
5236 (skip-chars-forward " \t\r\n")
5237 (save-match-data
5238 (save-excursion (outline-end-of-heading)
5239 (setq folded (org-invisible-p)))
5240 (condition-case nil
5241 (outline-forward-same-level (1- n))
5242 (error nil))
5243 (org-end-of-subtree t t))
5244 (org-back-over-empty-lines)
5245 (setq end (point))
5246 (goto-char beg0)
5247 (when (> end beg)
5248 (setq org-subtree-clip-folded folded)
5249 (when (or cut force-store-markers)
5250 (org-save-markers-in-region beg end))
5251 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5252 (setq org-subtree-clip (current-kill 0))
5253 (message "%s: Subtree(s) with %d characters"
5254 (if cut "Cut" "Copied")
5255 (length org-subtree-clip)))))
5257 (defun org-paste-subtree (&optional level tree for-yank)
5258 "Paste the clipboard as a subtree, with modification of headline level.
5259 The entire subtree is promoted or demoted in order to match a new headline
5260 level.
5262 If the cursor is at the beginning of a headline, the same level as
5263 that headline is used to paste the tree
5265 If not, the new level is derived from the *visible* headings
5266 before and after the insertion point, and taken to be the inferior headline
5267 level of the two. So if the previous visible heading is level 3 and the
5268 next is level 4 (or vice versa), level 4 will be used for insertion.
5269 This makes sure that the subtree remains an independent subtree and does
5270 not swallow low level entries.
5272 You can also force a different level, either by using a numeric prefix
5273 argument, or by inserting the heading marker by hand. For example, if the
5274 cursor is after \"*****\", then the tree will be shifted to level 5.
5276 If optional TREE is given, use this text instead of the kill ring.
5278 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5279 move back over whitespace before inserting, and move point to the end of
5280 the inserted text when done."
5281 (interactive "P")
5282 (unless (org-kill-is-subtree-p tree)
5283 (error "%s"
5284 (substitute-command-keys
5285 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5286 (let* ((visp (not (org-invisible-p)))
5287 (txt (or tree (and kill-ring (current-kill 0))))
5288 (^re (concat "^\\(" outline-regexp "\\)"))
5289 (re (concat "\\(" outline-regexp "\\)"))
5290 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5292 (old-level (if (string-match ^re txt)
5293 (- (match-end 0) (match-beginning 0) 1)
5294 -1))
5295 (force-level (cond (level (prefix-numeric-value level))
5296 ((and (looking-at "[ \t]*$")
5297 (string-match
5298 ^re_ (buffer-substring
5299 (point-at-bol) (point))))
5300 (- (match-end 1) (match-beginning 1)))
5301 ((and (bolp)
5302 (looking-at org-outline-regexp))
5303 (- (match-end 0) (point) 1))
5304 (t nil)))
5305 (previous-level (save-excursion
5306 (condition-case nil
5307 (progn
5308 (outline-previous-visible-heading 1)
5309 (if (looking-at re)
5310 (- (match-end 0) (match-beginning 0) 1)
5312 (error 1))))
5313 (next-level (save-excursion
5314 (condition-case nil
5315 (progn
5316 (or (looking-at outline-regexp)
5317 (outline-next-visible-heading 1))
5318 (if (looking-at re)
5319 (- (match-end 0) (match-beginning 0) 1)
5321 (error 1))))
5322 (new-level (or force-level (max previous-level next-level)))
5323 (shift (if (or (= old-level -1)
5324 (= new-level -1)
5325 (= old-level new-level))
5327 (- new-level old-level)))
5328 (delta (if (> shift 0) -1 1))
5329 (func (if (> shift 0) 'org-demote 'org-promote))
5330 (org-odd-levels-only nil)
5331 beg end newend)
5332 ;; Remove the forced level indicator
5333 (if force-level
5334 (delete-region (point-at-bol) (point)))
5335 ;; Paste
5336 (beginning-of-line 1)
5337 (unless for-yank (org-back-over-empty-lines))
5338 (setq beg (point))
5339 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5340 (insert-before-markers txt)
5341 (unless (string-match "\n\\'" txt) (insert "\n"))
5342 (setq newend (point))
5343 (org-reinstall-markers-in-region beg)
5344 (setq end (point))
5345 (goto-char beg)
5346 (skip-chars-forward " \t\n\r")
5347 (setq beg (point))
5348 (if (and (org-invisible-p) visp)
5349 (save-excursion (outline-show-heading)))
5350 ;; Shift if necessary
5351 (unless (= shift 0)
5352 (save-restriction
5353 (narrow-to-region beg end)
5354 (while (not (= shift 0))
5355 (org-map-region func (point-min) (point-max))
5356 (setq shift (+ delta shift)))
5357 (goto-char (point-min))
5358 (setq newend (point-max))))
5359 (when (or (interactive-p) for-yank)
5360 (message "Clipboard pasted as level %d subtree" new-level))
5361 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5362 kill-ring
5363 (eq org-subtree-clip (current-kill 0))
5364 org-subtree-clip-folded)
5365 ;; The tree was folded before it was killed/copied
5366 (hide-subtree))
5367 (and for-yank (goto-char newend))))
5369 (defun org-kill-is-subtree-p (&optional txt)
5370 "Check if the current kill is an outline subtree, or a set of trees.
5371 Returns nil if kill does not start with a headline, or if the first
5372 headline level is not the largest headline level in the tree.
5373 So this will actually accept several entries of equal levels as well,
5374 which is OK for `org-paste-subtree'.
5375 If optional TXT is given, check this string instead of the current kill."
5376 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5377 (start-level (and kill
5378 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5379 org-outline-regexp "\\)")
5380 kill)
5381 (- (match-end 2) (match-beginning 2) 1)))
5382 (re (concat "^" org-outline-regexp))
5383 (start (1+ (or (match-beginning 2) -1))))
5384 (if (not start-level)
5385 (progn
5386 nil) ;; does not even start with a heading
5387 (catch 'exit
5388 (while (setq start (string-match re kill (1+ start)))
5389 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5390 (throw 'exit nil)))
5391 t))))
5393 (defvar org-markers-to-move nil
5394 "Markers that should be moved with a cut-and-paste operation.
5395 Those markers are stored together with their positions relative to
5396 the start of the region.")
5398 (defun org-save-markers-in-region (beg end)
5399 "Check markers in region.
5400 If these markers are between BEG and END, record their position relative
5401 to BEG, so that after moving the block of text, we can put the markers back
5402 into place.
5403 This function gets called just before an entry or tree gets cut from the
5404 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5405 called immediately, to move the markers with the entries."
5406 (setq org-markers-to-move nil)
5407 (when (featurep 'org-clock)
5408 (org-clock-save-markers-for-cut-and-paste beg end))
5409 (when (featurep 'org-agenda)
5410 (org-agenda-save-markers-for-cut-and-paste beg end)))
5412 (defun org-check-and-save-marker (marker beg end)
5413 "Check if MARKER is between BEG and END.
5414 If yes, remember the marker and the distance to BEG."
5415 (when (and (marker-buffer marker)
5416 (equal (marker-buffer marker) (current-buffer)))
5417 (if (and (>= marker beg) (< marker end))
5418 (push (cons marker (- marker beg)) org-markers-to-move))))
5420 (defun org-reinstall-markers-in-region (beg)
5421 "Move all remembered markers to their position relative to BEG."
5422 (mapc (lambda (x)
5423 (move-marker (car x) (+ beg (cdr x))))
5424 org-markers-to-move)
5425 (setq org-markers-to-move nil))
5427 (defun org-narrow-to-subtree ()
5428 "Narrow buffer to the current subtree."
5429 (interactive)
5430 (save-excursion
5431 (save-match-data
5432 (narrow-to-region
5433 (progn (org-back-to-heading) (point))
5434 (progn (org-end-of-subtree t) (point))))))
5437 ;;; Outline Sorting
5439 (defun org-sort (with-case)
5440 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5441 Optional argument WITH-CASE means sort case-sensitively."
5442 (interactive "P")
5443 (if (org-at-table-p)
5444 (org-call-with-arg 'org-table-sort-lines with-case)
5445 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5447 (defun org-sort-remove-invisible (s)
5448 (remove-text-properties 0 (length s) org-rm-props s)
5449 (while (string-match org-bracket-link-regexp s)
5450 (setq s (replace-match (if (match-end 2)
5451 (match-string 3 s)
5452 (match-string 1 s)) t t s)))
5455 (defvar org-priority-regexp) ; defined later in the file
5457 (defun org-sort-entries-or-items
5458 (&optional with-case sorting-type getkey-func compare-func property)
5459 "Sort entries on a certain level of an outline tree.
5460 If there is an active region, the entries in the region are sorted.
5461 Else, if the cursor is before the first entry, sort the top-level items.
5462 Else, the children of the entry at point are sorted.
5464 Sorting can be alphabetically, numerically, and by date/time as given by
5465 the first time stamp in the entry. The command prompts for the sorting
5466 type unless it has been given to the function through the SORTING-TYPE
5467 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5468 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5469 called with point at the beginning of the record. It must return either
5470 a string or a number that should serve as the sorting key for that record.
5472 Comparing entries ignores case by default. However, with an optional argument
5473 WITH-CASE, the sorting considers case as well."
5474 (interactive "P")
5475 (let ((case-func (if with-case 'identity 'downcase))
5476 start beg end stars re re2
5477 txt what tmp plain-list-p)
5478 ;; Find beginning and end of region to sort
5479 (cond
5480 ((org-region-active-p)
5481 ;; we will sort the region
5482 (setq end (region-end)
5483 what "region")
5484 (goto-char (region-beginning))
5485 (if (not (org-on-heading-p)) (outline-next-heading))
5486 (setq start (point)))
5487 ((org-at-item-p)
5488 ;; we will sort this plain list
5489 (org-beginning-of-item-list) (setq start (point))
5490 (org-end-of-item-list) (setq end (point))
5491 (goto-char start)
5492 (setq plain-list-p t
5493 what "plain list"))
5494 ((or (org-on-heading-p)
5495 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5496 ;; we will sort the children of the current headline
5497 (org-back-to-heading)
5498 (setq start (point)
5499 end (progn (org-end-of-subtree t t)
5500 (org-back-over-empty-lines)
5501 (point))
5502 what "children")
5503 (goto-char start)
5504 (show-subtree)
5505 (outline-next-heading))
5507 ;; we will sort the top-level entries in this file
5508 (goto-char (point-min))
5509 (or (org-on-heading-p) (outline-next-heading))
5510 (setq start (point) end (point-max) what "top-level")
5511 (goto-char start)
5512 (show-all)))
5514 (setq beg (point))
5515 (if (>= beg end) (error "Nothing to sort"))
5517 (unless plain-list-p
5518 (looking-at "\\(\\*+\\)")
5519 (setq stars (match-string 1)
5520 re (concat "^" (regexp-quote stars) " +")
5521 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5522 txt (buffer-substring beg end))
5523 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5524 (if (and (not (equal stars "*")) (string-match re2 txt))
5525 (error "Region to sort contains a level above the first entry")))
5527 (unless sorting-type
5528 (message
5529 (if plain-list-p
5530 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5531 "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:")
5532 what)
5533 (setq sorting-type (read-char-exclusive))
5535 (and (= (downcase sorting-type) ?f)
5536 (setq getkey-func
5537 (org-ido-completing-read "Sort using function: "
5538 obarray 'fboundp t nil nil))
5539 (setq getkey-func (intern getkey-func)))
5541 (and (= (downcase sorting-type) ?r)
5542 (setq property
5543 (org-ido-completing-read "Property: "
5544 (mapcar 'list (org-buffer-property-keys t))
5545 nil t))))
5547 (message "Sorting entries...")
5549 (save-restriction
5550 (narrow-to-region start end)
5552 (let ((dcst (downcase sorting-type))
5553 (now (current-time)))
5554 (sort-subr
5555 (/= dcst sorting-type)
5556 ;; This function moves to the beginning character of the "record" to
5557 ;; be sorted.
5558 (if plain-list-p
5559 (lambda nil
5560 (if (org-at-item-p) t (goto-char (point-max))))
5561 (lambda nil
5562 (if (re-search-forward re nil t)
5563 (goto-char (match-beginning 0))
5564 (goto-char (point-max)))))
5565 ;; This function moves to the last character of the "record" being
5566 ;; sorted.
5567 (if plain-list-p
5568 'org-end-of-item
5569 (lambda nil
5570 (save-match-data
5571 (condition-case nil
5572 (outline-forward-same-level 1)
5573 (error
5574 (goto-char (point-max)))))))
5576 ;; This function returns the value that gets sorted against.
5577 (if plain-list-p
5578 (lambda nil
5579 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5580 (cond
5581 ((= dcst ?n)
5582 (string-to-number (buffer-substring (match-end 0)
5583 (point-at-eol))))
5584 ((= dcst ?a)
5585 (buffer-substring (match-end 0) (point-at-eol)))
5586 ((= dcst ?t)
5587 (if (re-search-forward org-ts-regexp
5588 (point-at-eol) t)
5589 (org-time-string-to-time (match-string 0))
5590 now))
5591 ((= dcst ?f)
5592 (if getkey-func
5593 (progn
5594 (setq tmp (funcall getkey-func))
5595 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5596 tmp)
5597 (error "Invalid key function `%s'" getkey-func)))
5598 (t (error "Invalid sorting type `%c'" sorting-type)))))
5599 (lambda nil
5600 (cond
5601 ((= dcst ?n)
5602 (if (looking-at org-complex-heading-regexp)
5603 (string-to-number (match-string 4))
5604 nil))
5605 ((= dcst ?a)
5606 (if (looking-at org-complex-heading-regexp)
5607 (funcall case-func (match-string 4))
5608 nil))
5609 ((= dcst ?t)
5610 (if (re-search-forward org-ts-regexp
5611 (save-excursion
5612 (forward-line 2)
5613 (point)) t)
5614 (org-time-string-to-time (match-string 0))
5615 now))
5616 ((= dcst ?p)
5617 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5618 (string-to-char (match-string 2))
5619 org-default-priority))
5620 ((= dcst ?r)
5621 (or (org-entry-get nil property) ""))
5622 ((= dcst ?o)
5623 (if (looking-at org-complex-heading-regexp)
5624 (- 9999 (length (member (match-string 2)
5625 org-todo-keywords-1)))))
5626 ((= dcst ?f)
5627 (if getkey-func
5628 (progn
5629 (setq tmp (funcall getkey-func))
5630 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5631 tmp)
5632 (error "Invalid key function `%s'" getkey-func)))
5633 (t (error "Invalid sorting type `%c'" sorting-type)))))
5635 (cond
5636 ((= dcst ?a) 'string<)
5637 ((= dcst ?t) 'time-less-p)
5638 ((= dcst ?f) compare-func)
5639 (t nil)))))
5640 (message "Sorting entries...done")))
5642 (defun org-do-sort (table what &optional with-case sorting-type)
5643 "Sort TABLE of WHAT according to SORTING-TYPE.
5644 The user will be prompted for the SORTING-TYPE if the call to this
5645 function does not specify it. WHAT is only for the prompt, to indicate
5646 what is being sorted. The sorting key will be extracted from
5647 the car of the elements of the table.
5648 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5649 (unless sorting-type
5650 (message
5651 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5652 what)
5653 (setq sorting-type (read-char-exclusive)))
5654 (let ((dcst (downcase sorting-type))
5655 extractfun comparefun)
5656 ;; Define the appropriate functions
5657 (cond
5658 ((= dcst ?n)
5659 (setq extractfun 'string-to-number
5660 comparefun (if (= dcst sorting-type) '< '>)))
5661 ((= dcst ?a)
5662 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5663 (lambda(x) (downcase (org-sort-remove-invisible x))))
5664 comparefun (if (= dcst sorting-type)
5665 'string<
5666 (lambda (a b) (and (not (string< a b))
5667 (not (string= a b)))))))
5668 ((= dcst ?t)
5669 (setq extractfun
5670 (lambda (x)
5671 (if (string-match org-ts-regexp x)
5672 (time-to-seconds
5673 (org-time-string-to-time (match-string 0 x)))
5675 comparefun (if (= dcst sorting-type) '< '>)))
5676 (t (error "Invalid sorting type `%c'" sorting-type)))
5678 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5679 table)
5680 (lambda (a b) (funcall comparefun (car a) (car b))))))
5682 ;;; Editing source examples
5684 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5685 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5686 (defvar org-edit-src-force-single-line nil)
5687 (defvar org-edit-src-from-org-mode nil)
5688 (defvar org-edit-src-picture nil)
5690 (define-minor-mode org-exit-edit-mode
5691 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5693 (defun org-edit-src-code ()
5694 "Edit the source code example at point.
5695 An indirect buffer is created, and that buffer is then narrowed to the
5696 example at point and switched to the correct language mode. When done,
5697 exit by killing the buffer with \\[org-edit-src-exit]."
5698 (interactive)
5699 (let ((line (org-current-line))
5700 (case-fold-search t)
5701 (msg (substitute-command-keys
5702 "Edit, then exit with C-c ' (C-c and single quote)"))
5703 (info (org-edit-src-find-region-and-lang))
5704 (org-mode-p (eq major-mode 'org-mode))
5705 beg end lang lang-f single)
5706 (if (not info)
5708 (setq beg (nth 0 info)
5709 end (nth 1 info)
5710 lang (nth 2 info)
5711 single (nth 3 info)
5712 lang-f (intern (concat lang "-mode")))
5713 (unless (functionp lang-f)
5714 (error "No such language mode: %s" lang-f))
5715 (goto-line line)
5716 (if (get-buffer "*Org Edit Src Example*")
5717 (kill-buffer "*Org Edit Src Example*"))
5718 (switch-to-buffer (make-indirect-buffer (current-buffer)
5719 "*Org Edit Src Example*"))
5720 (narrow-to-region beg end)
5721 (remove-text-properties beg end '(display nil invisible nil
5722 intangible nil))
5723 (let ((org-inhibit-startup t))
5724 (funcall lang-f))
5725 (set (make-local-variable 'org-edit-src-force-single-line) single)
5726 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5727 (when org-mode-p
5728 (goto-char (point-min))
5729 (while (re-search-forward "^," nil t)
5730 (replace-match "")))
5731 (goto-line line)
5732 (org-exit-edit-mode)
5733 (org-set-local 'header-line-format msg)
5734 (message "%s" msg)
5735 t)))
5737 (defun org-edit-fixed-width-region ()
5738 "Edit the fixed-width ascii drawing at point.
5739 This must be a region where each line starts with a colon followed by
5740 a space character.
5741 An indirect buffer is created, and that buffer is then narrowed to the
5742 example at point and switched to artist-mode. When done,
5743 exit by killing the buffer with \\[org-edit-src-exit]."
5744 (interactive)
5745 (let ((line (org-current-line))
5746 (case-fold-search t)
5747 (msg (substitute-command-keys
5748 "Edit, then exit with C-c ' (C-c and single quote)"))
5749 (org-mode-p (eq major-mode 'org-mode))
5750 beg end lang lang-f)
5751 (beginning-of-line 1)
5752 (if (looking-at "[ \t]*[^:\n \t]")
5754 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5755 (setq beg (point) end beg)
5756 (save-excursion
5757 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5758 (setq beg (point-at-bol 2))
5759 (setq beg (point))))
5760 (save-excursion
5761 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5762 (setq end (1- (match-beginning 0)))
5763 (setq end (point))))
5764 (goto-line line))
5765 (if (get-buffer "*Org Edit Picture*")
5766 (kill-buffer "*Org Edit Picture*"))
5767 (switch-to-buffer (make-indirect-buffer (current-buffer)
5768 "*Org Edit Picture*"))
5769 (narrow-to-region beg end)
5770 (remove-text-properties beg end '(display nil invisible nil
5771 intangible nil))
5772 (when (fboundp 'font-lock-unfontify-region)
5773 (font-lock-unfontify-region (point-min) (point-max)))
5774 (cond
5775 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5776 (fundamental-mode)
5777 (artist-mode 1))
5778 (t (funcall org-edit-fixed-width-region-mode)))
5779 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5780 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5781 (set (make-local-variable 'org-edit-src-picture) t)
5782 (goto-char (point-min))
5783 (while (re-search-forward "^[ \t]*: ?" nil t)
5784 (replace-match ""))
5785 (goto-line line)
5786 (org-exit-edit-mode)
5787 (org-set-local 'header-line-format msg)
5788 (message "%s" msg)
5789 t)))
5792 (defun org-edit-src-find-region-and-lang ()
5793 "Find the region and language for a local edit.
5794 Return a list with beginning and end of the region, a string representing
5795 the language, a switch telling of the content should be in a single line."
5796 (let ((re-list
5797 (append
5798 org-edit-src-region-extra
5800 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5801 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5802 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5803 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5804 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5805 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5806 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5807 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5808 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5809 ("^#\\+html:" "\n" "html" single-line)
5810 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5811 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5812 ("^#\\+latex:" "\n" "latex" single-line)
5813 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5814 ("^#\\+ascii:" "\n" "ascii" single-line)
5816 (pos (point))
5817 re re1 re2 single beg end lang)
5818 (catch 'exit
5819 (while (setq entry (pop re-list))
5820 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5821 single (nth 3 entry))
5822 (save-excursion
5823 (if (or (looking-at re1)
5824 (re-search-backward re1 nil t))
5825 (progn
5826 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5827 (if (and (re-search-forward re2 nil t)
5828 (>= (match-end 0) pos))
5829 (throw 'exit (list beg (match-beginning 0) lang single))))
5830 (if (or (looking-at re2)
5831 (re-search-forward re2 nil t))
5832 (progn
5833 (setq end (match-beginning 0))
5834 (if (and (re-search-backward re1 nil t)
5835 (<= (match-beginning 0) pos))
5836 (throw 'exit
5837 (list (match-end 0) end
5838 (org-edit-src-get-lang lang) single)))))))))))
5840 (defun org-edit-src-get-lang (lang)
5841 "Extract the src language."
5842 (let ((m (match-string 0)))
5843 (cond
5844 ((stringp lang) lang)
5845 ((integerp lang) (match-string lang))
5846 ((and (eq lang 'lang)
5847 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5848 (match-string 1 m))
5849 ((and (eq lang 'style)
5850 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5851 (match-string 1 m))
5852 (t "fundamental"))))
5854 (defun org-edit-src-exit ()
5855 "Exit special edit and protect problematic lines."
5856 (interactive)
5857 (unless (buffer-base-buffer (current-buffer))
5858 (error "This is not an indirect buffer, something is wrong..."))
5859 (unless (> (point-min) 1)
5860 (error "This buffer is not narrowed, something is wrong..."))
5861 (goto-char (point-min))
5862 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5863 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5864 (when (org-bound-and-true-p org-edit-src-force-single-line)
5865 (goto-char (point-min))
5866 (while (re-search-forward "\n" nil t)
5867 (replace-match " "))
5868 (goto-char (point-min))
5869 (if (looking-at "\\s-*") (replace-match " "))
5870 (if (re-search-forward "\\s-+\\'" nil t)
5871 (replace-match "")))
5872 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5873 (goto-char (point-min))
5874 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5875 (replace-match ",\\1"))
5876 (when font-lock-mode
5877 (font-lock-unfontify-region (point-min) (point-max)))
5878 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5879 (when (org-bound-and-true-p org-edit-src-picture)
5880 (untabify (point-min) (point-max))
5881 (goto-char (point-min))
5882 (while (re-search-forward "^" nil t)
5883 (replace-match ": "))
5884 (when font-lock-mode
5885 (font-lock-unfontify-region (point-min) (point-max)))
5886 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5887 (kill-buffer (current-buffer))
5888 (and (org-mode-p) (org-restart-font-lock)))
5891 ;;; The orgstruct minor mode
5893 ;; Define a minor mode which can be used in other modes in order to
5894 ;; integrate the org-mode structure editing commands.
5896 ;; This is really a hack, because the org-mode structure commands use
5897 ;; keys which normally belong to the major mode. Here is how it
5898 ;; works: The minor mode defines all the keys necessary to operate the
5899 ;; structure commands, but wraps the commands into a function which
5900 ;; tests if the cursor is currently at a headline or a plain list
5901 ;; item. If that is the case, the structure command is used,
5902 ;; temporarily setting many Org-mode variables like regular
5903 ;; expressions for filling etc. However, when any of those keys is
5904 ;; used at a different location, function uses `key-binding' to look
5905 ;; up if the key has an associated command in another currently active
5906 ;; keymap (minor modes, major mode, global), and executes that
5907 ;; command. There might be problems if any of the keys is otherwise
5908 ;; used as a prefix key.
5910 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5911 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5912 ;; addresses this by checking explicitly for both bindings.
5914 (defvar orgstruct-mode-map (make-sparse-keymap)
5915 "Keymap for the minor `orgstruct-mode'.")
5917 (defvar org-local-vars nil
5918 "List of local variables, for use by `orgstruct-mode'")
5920 ;;;###autoload
5921 (define-minor-mode orgstruct-mode
5922 "Toggle the minor more `orgstruct-mode'.
5923 This mode is for using Org-mode structure commands in other modes.
5924 The following key behave as if Org-mode was active, if the cursor
5925 is on a headline, or on a plain list item (both in the definition
5926 of Org-mode).
5928 M-up Move entry/item up
5929 M-down Move entry/item down
5930 M-left Promote
5931 M-right Demote
5932 M-S-up Move entry/item up
5933 M-S-down Move entry/item down
5934 M-S-left Promote subtree
5935 M-S-right Demote subtree
5936 M-q Fill paragraph and items like in Org-mode
5937 C-c ^ Sort entries
5938 C-c - Cycle list bullet
5939 TAB Cycle item visibility
5940 M-RET Insert new heading/item
5941 S-M-RET Insert new TODO heading / Checkbox item
5942 C-c C-c Set tags / toggle checkbox"
5943 nil " OrgStruct" nil
5944 (org-load-modules-maybe)
5945 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5947 ;;;###autoload
5948 (defun turn-on-orgstruct ()
5949 "Unconditionally turn on `orgstruct-mode'."
5950 (orgstruct-mode 1))
5952 ;;;###autoload
5953 (defun turn-on-orgstruct++ ()
5954 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5955 In addition to setting orgstruct-mode, this also exports all indentation and
5956 autofilling variables from org-mode into the buffer. Note that turning
5957 off orgstruct-mode will *not* remove these additional settings."
5958 (orgstruct-mode 1)
5959 (let (var val)
5960 (mapc
5961 (lambda (x)
5962 (when (string-match
5963 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5964 (symbol-name (car x)))
5965 (setq var (car x) val (nth 1 x))
5966 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5967 org-local-vars)))
5969 (defun orgstruct-error ()
5970 "Error when there is no default binding for a structure key."
5971 (interactive)
5972 (error "This key has no function outside structure elements"))
5974 (defun orgstruct-setup ()
5975 "Setup orgstruct keymaps."
5976 (let ((nfunc 0)
5977 (bindings
5978 (list
5979 '([(meta up)] org-metaup)
5980 '([(meta down)] org-metadown)
5981 '([(meta left)] org-metaleft)
5982 '([(meta right)] org-metaright)
5983 '([(meta shift up)] org-shiftmetaup)
5984 '([(meta shift down)] org-shiftmetadown)
5985 '([(meta shift left)] org-shiftmetaleft)
5986 '([(meta shift right)] org-shiftmetaright)
5987 '([(shift up)] org-shiftup)
5988 '([(shift down)] org-shiftdown)
5989 '([(shift left)] org-shiftleft)
5990 '([(shift right)] org-shiftright)
5991 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5992 '("\M-q" fill-paragraph)
5993 '("\C-c^" org-sort)
5994 '("\C-c-" org-cycle-list-bullet)))
5995 elt key fun cmd)
5996 (while (setq elt (pop bindings))
5997 (setq nfunc (1+ nfunc))
5998 (setq key (org-key (car elt))
5999 fun (nth 1 elt)
6000 cmd (orgstruct-make-binding fun nfunc key))
6001 (org-defkey orgstruct-mode-map key cmd))
6003 ;; Special treatment needed for TAB and RET
6004 (org-defkey orgstruct-mode-map [(tab)]
6005 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6006 (org-defkey orgstruct-mode-map "\C-i"
6007 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6009 (org-defkey orgstruct-mode-map "\M-\C-m"
6010 (orgstruct-make-binding 'org-insert-heading 105
6011 "\M-\C-m" [(meta return)]))
6012 (org-defkey orgstruct-mode-map [(meta return)]
6013 (orgstruct-make-binding 'org-insert-heading 106
6014 [(meta return)] "\M-\C-m"))
6016 (org-defkey orgstruct-mode-map [(shift meta return)]
6017 (orgstruct-make-binding 'org-insert-todo-heading 107
6018 [(meta return)] "\M-\C-m"))
6020 (unless org-local-vars
6021 (setq org-local-vars (org-get-local-variables)))
6025 (defun orgstruct-make-binding (fun n &rest keys)
6026 "Create a function for binding in the structure minor mode.
6027 FUN is the command to call inside a table. N is used to create a unique
6028 command name. KEYS are keys that should be checked in for a command
6029 to execute outside of tables."
6030 (eval
6031 (list 'defun
6032 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6033 '(arg)
6034 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6035 "Outside of structure, run the binding of `"
6036 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6037 "'.")
6038 '(interactive "p")
6039 (list 'if
6040 '(org-context-p 'headline 'item)
6041 (list 'org-run-like-in-org-mode (list 'quote fun))
6042 (list 'let '(orgstruct-mode)
6043 (list 'call-interactively
6044 (append '(or)
6045 (mapcar (lambda (k)
6046 (list 'key-binding k))
6047 keys)
6048 '('orgstruct-error))))))))
6050 (defun org-context-p (&rest contexts)
6051 "Check if local context is any of CONTEXTS.
6052 Possible values in the list of contexts are `table', `headline', and `item'."
6053 (let ((pos (point)))
6054 (goto-char (point-at-bol))
6055 (prog1 (or (and (memq 'table contexts)
6056 (looking-at "[ \t]*|"))
6057 (and (memq 'headline contexts)
6058 ;;????????? (looking-at "\\*+"))
6059 (looking-at outline-regexp))
6060 (and (memq 'item contexts)
6061 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6062 (goto-char pos))))
6064 (defun org-get-local-variables ()
6065 "Return a list of all local variables in an org-mode buffer."
6066 (let (varlist)
6067 (with-current-buffer (get-buffer-create "*Org tmp*")
6068 (erase-buffer)
6069 (org-mode)
6070 (setq varlist (buffer-local-variables)))
6071 (kill-buffer "*Org tmp*")
6072 (delq nil
6073 (mapcar
6074 (lambda (x)
6075 (setq x
6076 (if (symbolp x)
6077 (list x)
6078 (list (car x) (list 'quote (cdr x)))))
6079 (if (string-match
6080 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6081 (symbol-name (car x)))
6082 x nil))
6083 varlist))))
6085 ;;;###autoload
6086 (defun org-run-like-in-org-mode (cmd)
6087 (org-load-modules-maybe)
6088 (unless org-local-vars
6089 (setq org-local-vars (org-get-local-variables)))
6090 (eval (list 'let org-local-vars
6091 (list 'call-interactively (list 'quote cmd)))))
6093 ;;;; Archiving
6095 (defun org-get-category (&optional pos)
6096 "Get the category applying to position POS."
6097 (get-text-property (or pos (point)) 'org-category))
6099 (defun org-refresh-category-properties ()
6100 "Refresh category text properties in the buffer."
6101 (let ((def-cat (cond
6102 ((null org-category)
6103 (if buffer-file-name
6104 (file-name-sans-extension
6105 (file-name-nondirectory buffer-file-name))
6106 "???"))
6107 ((symbolp org-category) (symbol-name org-category))
6108 (t org-category)))
6109 beg end cat pos optionp)
6110 (org-unmodified
6111 (save-excursion
6112 (save-restriction
6113 (widen)
6114 (goto-char (point-min))
6115 (put-text-property (point) (point-max) 'org-category def-cat)
6116 (while (re-search-forward
6117 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6118 (setq pos (match-end 0)
6119 optionp (equal (char-after (match-beginning 0)) ?#)
6120 cat (org-trim (match-string 2)))
6121 (if optionp
6122 (setq beg (point-at-bol) end (point-max))
6123 (org-back-to-heading t)
6124 (setq beg (point) end (org-end-of-subtree t t)))
6125 (put-text-property beg end 'org-category cat)
6126 (goto-char pos)))))))
6129 ;;;; Link Stuff
6131 ;;; Link abbreviations
6133 (defun org-link-expand-abbrev (link)
6134 "Apply replacements as defined in `org-link-abbrev-alist."
6135 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6136 (let* ((key (match-string 1 link))
6137 (as (or (assoc key org-link-abbrev-alist-local)
6138 (assoc key org-link-abbrev-alist)))
6139 (tag (and (match-end 2) (match-string 3 link)))
6140 rpl)
6141 (if (not as)
6142 link
6143 (setq rpl (cdr as))
6144 (cond
6145 ((symbolp rpl) (funcall rpl tag))
6146 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6147 ((string-match "%h" rpl)
6148 (replace-match (url-hexify-string (or tag "")) t t rpl))
6149 (t (concat rpl tag)))))
6150 link))
6152 ;;; Storing and inserting links
6154 (defvar org-insert-link-history nil
6155 "Minibuffer history for links inserted with `org-insert-link'.")
6157 (defvar org-stored-links nil
6158 "Contains the links stored with `org-store-link'.")
6160 (defvar org-store-link-plist nil
6161 "Plist with info about the most recently link created with `org-store-link'.")
6163 (defvar org-link-protocols nil
6164 "Link protocols added to Org-mode using `org-add-link-type'.")
6166 (defvar org-store-link-functions nil
6167 "List of functions that are called to create and store a link.
6168 Each function will be called in turn until one returns a non-nil
6169 value. Each function should check if it is responsible for creating
6170 this link (for example by looking at the major mode).
6171 If not, it must exit and return nil.
6172 If yes, it should return a non-nil value after a calling
6173 `org-store-link-props' with a list of properties and values.
6174 Special properties are:
6176 :type The link prefix. like \"http\". This must be given.
6177 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6178 This is obligatory as well.
6179 :description Optional default description for the second pair
6180 of brackets in an Org-mode link. The user can still change
6181 this when inserting this link into an Org-mode buffer.
6183 In addition to these, any additional properties can be specified
6184 and then used in remember templates.")
6186 (defun org-add-link-type (type &optional follow export)
6187 "Add TYPE to the list of `org-link-types'.
6188 Re-compute all regular expressions depending on `org-link-types'
6190 FOLLOW and EXPORT are two functions.
6192 FOLLOW should take the link path as the single argument and do whatever
6193 is necessary to follow the link, for example find a file or display
6194 a mail message.
6196 EXPORT should format the link path for export to one of the export formats.
6197 It should be a function accepting three arguments:
6199 path the path of the link, the text after the prefix (like \"http:\")
6200 desc the description of the link, if any, nil if there was no description
6201 format the export format, a symbol like `html' or `latex'.
6203 The function may use the FORMAT information to return different values
6204 depending on the format. The return value will be put literally into
6205 the exported file.
6206 Org-mode has a built-in default for exporting links. If you are happy with
6207 this default, there is no need to define an export function for the link
6208 type. For a simple example of an export function, see `org-bbdb.el'."
6209 (add-to-list 'org-link-types type t)
6210 (org-make-link-regexps)
6211 (if (assoc type org-link-protocols)
6212 (setcdr (assoc type org-link-protocols) (list follow export))
6213 (push (list type follow export) org-link-protocols)))
6215 ;;;###autoload
6216 (defun org-store-link (arg)
6217 "\\<org-mode-map>Store an org-link to the current location.
6218 This link is added to `org-stored-links' and can later be inserted
6219 into an org-buffer with \\[org-insert-link].
6221 For some link types, a prefix arg is interpreted:
6222 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6223 For file links, arg negates `org-context-in-file-links'."
6224 (interactive "P")
6225 (org-load-modules-maybe)
6226 (setq org-store-link-plist nil) ; reset
6227 (let (link cpltxt desc description search txt)
6228 (cond
6230 ((run-hook-with-args-until-success 'org-store-link-functions)
6231 (setq link (plist-get org-store-link-plist :link)
6232 desc (or (plist-get org-store-link-plist :description) link)))
6234 ((equal (buffer-name) "*Org Edit Src Example*")
6235 (let (label gc)
6236 (while (or (not label)
6237 (save-excursion
6238 (save-restriction
6239 (widen)
6240 (goto-char (point-min))
6241 (re-search-forward (concat "((" label "))") nil t))))
6242 (when label (message "Label exists already") (sit-for 2))
6243 (setq label (read-string "Code line label: " label)))
6244 (end-of-line 1)
6245 (setq link (format "((%s))" label))
6246 (setq gc (- 79 (length link)))
6247 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6248 (insert link)
6249 (setq desc nil)))
6251 ((eq major-mode 'calendar-mode)
6252 (let ((cd (calendar-cursor-to-date)))
6253 (setq link
6254 (format-time-string
6255 (car org-time-stamp-formats)
6256 (apply 'encode-time
6257 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6258 nil nil nil))))
6259 (org-store-link-props :type "calendar" :date cd)))
6261 ((eq major-mode 'w3-mode)
6262 (setq cpltxt (url-view-url t)
6263 link (org-make-link cpltxt))
6264 (org-store-link-props :type "w3" :url (url-view-url t)))
6266 ((eq major-mode 'w3m-mode)
6267 (setq cpltxt (or w3m-current-title w3m-current-url)
6268 link (org-make-link w3m-current-url))
6269 (org-store-link-props :type "w3m" :url (url-view-url t)))
6271 ((setq search (run-hook-with-args-until-success
6272 'org-create-file-search-functions))
6273 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6274 "::" search))
6275 (setq cpltxt (or description link)))
6277 ((eq major-mode 'image-mode)
6278 (setq cpltxt (concat "file:"
6279 (abbreviate-file-name buffer-file-name))
6280 link (org-make-link cpltxt))
6281 (org-store-link-props :type "image" :file buffer-file-name))
6283 ((eq major-mode 'dired-mode)
6284 ;; link to the file in the current line
6285 (setq cpltxt (concat "file:"
6286 (abbreviate-file-name
6287 (expand-file-name
6288 (dired-get-filename nil t))))
6289 link (org-make-link cpltxt)))
6291 ((and buffer-file-name (org-mode-p))
6292 (cond
6293 ((org-in-regexp "<<\\(.*?\\)>>")
6294 (setq cpltxt
6295 (concat "file:"
6296 (abbreviate-file-name buffer-file-name)
6297 "::" (match-string 1))
6298 link (org-make-link cpltxt)))
6299 ((and (featurep 'org-id)
6300 (or (eq org-link-to-org-use-id t)
6301 (and (eq org-link-to-org-use-id 'create-if-interactive)
6302 (interactive-p))
6303 (and org-link-to-org-use-id
6304 (condition-case nil
6305 (org-entry-get nil "ID")
6306 (error nil)))))
6307 ;; We can make a link using the ID.
6308 (setq link (condition-case nil
6309 (prog1 (org-id-store-link)
6310 (setq desc (plist-get org-store-link-plist
6311 :description)))
6312 (error
6313 ;; probably before first headline, link to file only
6314 (concat "file:"
6315 (abbreviate-file-name buffer-file-name))))))
6317 ;; Just link to current headline
6318 (setq cpltxt (concat "file:"
6319 (abbreviate-file-name buffer-file-name)))
6320 ;; Add a context search string
6321 (when (org-xor org-context-in-file-links arg)
6322 (setq txt (cond
6323 ((org-on-heading-p) nil)
6324 ((org-region-active-p)
6325 (buffer-substring (region-beginning) (region-end)))
6326 (t nil)))
6327 (when (or (null txt) (string-match "\\S-" txt))
6328 (setq cpltxt
6329 (concat cpltxt "::"
6330 (condition-case nil
6331 (org-make-org-heading-search-string txt)
6332 (error "")))
6333 desc "NONE")))
6334 (if (string-match "::\\'" cpltxt)
6335 (setq cpltxt (substring cpltxt 0 -2)))
6336 (setq link (org-make-link cpltxt)))))
6338 ((buffer-file-name (buffer-base-buffer))
6339 ;; Just link to this file here.
6340 (setq cpltxt (concat "file:"
6341 (abbreviate-file-name
6342 (buffer-file-name (buffer-base-buffer)))))
6343 ;; Add a context string
6344 (when (org-xor org-context-in-file-links arg)
6345 (setq txt (if (org-region-active-p)
6346 (buffer-substring (region-beginning) (region-end))
6347 (buffer-substring (point-at-bol) (point-at-eol))))
6348 ;; Only use search option if there is some text.
6349 (when (string-match "\\S-" txt)
6350 (setq cpltxt
6351 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6352 desc "NONE")))
6353 (setq link (org-make-link cpltxt)))
6355 ((interactive-p)
6356 (error "Cannot link to a buffer which is not visiting a file"))
6358 (t (setq link nil)))
6360 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6361 (setq link (or link cpltxt)
6362 desc (or desc cpltxt))
6363 (if (equal desc "NONE") (setq desc nil))
6365 (if (and (interactive-p) link)
6366 (progn
6367 (setq org-stored-links
6368 (cons (list link desc) org-stored-links))
6369 (message "Stored: %s" (or desc link)))
6370 (and link (org-make-link-string link desc)))))
6372 (defun org-store-link-props (&rest plist)
6373 "Store link properties, extract names and addresses."
6374 (let (x adr)
6375 (when (setq x (plist-get plist :from))
6376 (setq adr (mail-extract-address-components x))
6377 (setq plist (plist-put plist :fromname (car adr)))
6378 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6379 (when (setq x (plist-get plist :to))
6380 (setq adr (mail-extract-address-components x))
6381 (setq plist (plist-put plist :toname (car adr)))
6382 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6383 (let ((from (plist-get plist :from))
6384 (to (plist-get plist :to)))
6385 (when (and from to org-from-is-user-regexp)
6386 (setq plist
6387 (plist-put plist :fromto
6388 (if (string-match org-from-is-user-regexp from)
6389 (concat "to %t")
6390 (concat "from %f"))))))
6391 (setq org-store-link-plist plist))
6393 (defun org-add-link-props (&rest plist)
6394 "Add these properties to the link property list."
6395 (let (key value)
6396 (while plist
6397 (setq key (pop plist) value (pop plist))
6398 (setq org-store-link-plist
6399 (plist-put org-store-link-plist key value)))))
6401 (defun org-email-link-description (&optional fmt)
6402 "Return the description part of an email link.
6403 This takes information from `org-store-link-plist' and formats it
6404 according to FMT (default from `org-email-link-description-format')."
6405 (setq fmt (or fmt org-email-link-description-format))
6406 (let* ((p org-store-link-plist)
6407 (to (plist-get p :toaddress))
6408 (from (plist-get p :fromaddress))
6409 (table
6410 (list
6411 (cons "%c" (plist-get p :fromto))
6412 (cons "%F" (plist-get p :from))
6413 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6414 (cons "%T" (plist-get p :to))
6415 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6416 (cons "%s" (plist-get p :subject))
6417 (cons "%m" (plist-get p :message-id)))))
6418 (when (string-match "%c" fmt)
6419 ;; Check if the user wrote this message
6420 (if (and org-from-is-user-regexp from to
6421 (save-match-data (string-match org-from-is-user-regexp from)))
6422 (setq fmt (replace-match "to %t" t t fmt))
6423 (setq fmt (replace-match "from %f" t t fmt))))
6424 (org-replace-escapes fmt table)))
6426 (defun org-make-org-heading-search-string (&optional string heading)
6427 "Make search string for STRING or current headline."
6428 (interactive)
6429 (let ((s (or string (org-get-heading))))
6430 (unless (and string (not heading))
6431 ;; We are using a headline, clean up garbage in there.
6432 (if (string-match org-todo-regexp s)
6433 (setq s (replace-match "" t t s)))
6434 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6435 (setq s (replace-match "" t t s)))
6436 (setq s (org-trim s))
6437 (if (string-match (concat "^\\(" org-quote-string "\\|"
6438 org-comment-string "\\)") s)
6439 (setq s (replace-match "" t t s)))
6440 (while (string-match org-ts-regexp s)
6441 (setq s (replace-match "" t t s))))
6442 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6443 (setq s (replace-match " " t t s)))
6444 (or string (setq s (concat "*" s))) ; Add * for headlines
6445 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6447 (defun org-make-link (&rest strings)
6448 "Concatenate STRINGS."
6449 (apply 'concat strings))
6451 (defun org-make-link-string (link &optional description)
6452 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6453 (unless (string-match "\\S-" link)
6454 (error "Empty link"))
6455 (when (stringp description)
6456 ;; Remove brackets from the description, they are fatal.
6457 (while (string-match "\\[" description)
6458 (setq description (replace-match "{" t t description)))
6459 (while (string-match "\\]" description)
6460 (setq description (replace-match "}" t t description))))
6461 (when (equal (org-link-escape link) description)
6462 ;; No description needed, it is identical
6463 (setq description nil))
6464 (when (and (not description)
6465 (not (equal link (org-link-escape link))))
6466 (setq description (org-extract-attributes link)))
6467 (concat "[[" (org-link-escape link) "]"
6468 (if description (concat "[" description "]") "")
6469 "]"))
6471 (defconst org-link-escape-chars
6472 '((?\ . "%20")
6473 (?\[ . "%5B")
6474 (?\] . "%5D")
6475 (?\340 . "%E0") ; `a
6476 (?\342 . "%E2") ; ^a
6477 (?\347 . "%E7") ; ,c
6478 (?\350 . "%E8") ; `e
6479 (?\351 . "%E9") ; 'e
6480 (?\352 . "%EA") ; ^e
6481 (?\356 . "%EE") ; ^i
6482 (?\364 . "%F4") ; ^o
6483 (?\371 . "%F9") ; `u
6484 (?\373 . "%FB") ; ^u
6485 (?\; . "%3B")
6486 (?? . "%3F")
6487 (?= . "%3D")
6488 (?+ . "%2B")
6490 "Association list of escapes for some characters problematic in links.
6491 This is the list that is used for internal purposes.")
6493 (defconst org-link-escape-chars-browser
6494 '((?\ . "%20")) ; 32 for the SPC char
6495 "Association list of escapes for some characters problematic in links.
6496 This is the list that is used before handing over to the browser.")
6498 (defun org-link-escape (text &optional table)
6499 "Escape characters in TEXT that are problematic for links."
6500 (setq table (or table org-link-escape-chars))
6501 (when text
6502 (let ((re (mapconcat (lambda (x) (regexp-quote
6503 (char-to-string (car x))))
6504 table "\\|")))
6505 (while (string-match re text)
6506 (setq text
6507 (replace-match
6508 (cdr (assoc (string-to-char (match-string 0 text))
6509 table))
6510 t t text)))
6511 text)))
6513 (defun org-link-unescape (text &optional table)
6514 "Reverse the action of `org-link-escape'."
6515 (setq table (or table org-link-escape-chars))
6516 (when text
6517 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6518 table "\\|")))
6519 (while (string-match re text)
6520 (setq text
6521 (replace-match
6522 (char-to-string (car (rassoc (match-string 0 text) table)))
6523 t t text)))
6524 text)))
6526 (defun org-xor (a b)
6527 "Exclusive or."
6528 (if a (not b) b))
6530 (defun org-get-header (header)
6531 "Find a header field in the current buffer."
6532 (save-excursion
6533 (goto-char (point-min))
6534 (let ((case-fold-search t) s)
6535 (cond
6536 ((eq header 'from)
6537 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6538 (setq s (match-string 1)))
6539 (while (string-match "\"" s)
6540 (setq s (replace-match "" t t s)))
6541 (if (string-match "[<(].*" s)
6542 (setq s (replace-match "" t t s))))
6543 ((eq header 'message-id)
6544 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6545 (setq s (match-string 1))))
6546 ((eq header 'subject)
6547 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6548 (setq s (match-string 1)))))
6549 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6550 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6551 s)))
6554 (defun org-fixup-message-id-for-http (s)
6555 "Replace special characters in a message id, so it can be used in an http query."
6556 (while (string-match "<" s)
6557 (setq s (replace-match "%3C" t t s)))
6558 (while (string-match ">" s)
6559 (setq s (replace-match "%3E" t t s)))
6560 (while (string-match "@" s)
6561 (setq s (replace-match "%40" t t s)))
6564 ;;;###autoload
6565 (defun org-insert-link-global ()
6566 "Insert a link like Org-mode does.
6567 This command can be called in any mode to insert a link in Org-mode syntax."
6568 (interactive)
6569 (org-load-modules-maybe)
6570 (org-run-like-in-org-mode 'org-insert-link))
6572 (defun org-insert-link (&optional complete-file link-location)
6573 "Insert a link. At the prompt, enter the link.
6575 Completion can be used to insert any of the link protocol prefixes like
6576 http or ftp in use.
6578 The history can be used to select a link previously stored with
6579 `org-store-link'. When the empty string is entered (i.e. if you just
6580 press RET at the prompt), the link defaults to the most recently
6581 stored link. As SPC triggers completion in the minibuffer, you need to
6582 use M-SPC or C-q SPC to force the insertion of a space character.
6584 You will also be prompted for a description, and if one is given, it will
6585 be displayed in the buffer instead of the link.
6587 If there is already a link at point, this command will allow you to edit link
6588 and description parts.
6590 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6591 be selected using completion. The path to the file will be relative to the
6592 current directory if the file is in the current directory or a subdirectory.
6593 Otherwise, the link will be the absolute path as completed in the minibuffer
6594 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6595 option `org-link-file-path-type'.
6597 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6598 the current directory or below.
6600 With three \\[universal-argument] prefixes, negate the meaning of
6601 `org-keep-stored-link-after-insertion'.
6603 If `org-make-link-description-function' is non-nil, this function will be
6604 called with the link target, and the result will be the default
6605 link description.
6607 If the LINK-LOCATION parameter is non-nil, this value will be
6608 used as the link location instead of reading one interactively."
6609 (interactive "P")
6610 (let* ((wcf (current-window-configuration))
6611 (region (if (org-region-active-p)
6612 (buffer-substring (region-beginning) (region-end))))
6613 (remove (and region (list (region-beginning) (region-end))))
6614 (desc region)
6615 tmphist ; byte-compile incorrectly complains about this
6616 (link link-location)
6617 entry file)
6618 (cond
6619 (link-location) ; specified by arg, just use it.
6620 ((org-in-regexp org-bracket-link-regexp 1)
6621 ;; We do have a link at point, and we are going to edit it.
6622 (setq remove (list (match-beginning 0) (match-end 0)))
6623 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6624 (setq link (read-string "Link: "
6625 (org-link-unescape
6626 (org-match-string-no-properties 1)))))
6627 ((or (org-in-regexp org-angle-link-re)
6628 (org-in-regexp org-plain-link-re))
6629 ;; Convert to bracket link
6630 (setq remove (list (match-beginning 0) (match-end 0))
6631 link (read-string "Link: "
6632 (org-remove-angle-brackets (match-string 0)))))
6633 ((member complete-file '((4) (16)))
6634 ;; Completing read for file names.
6635 (setq file (read-file-name "File: "))
6636 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6637 (pwd1 (file-name-as-directory (abbreviate-file-name
6638 (expand-file-name ".")))))
6639 (cond
6640 ((equal complete-file '(16))
6641 (setq link (org-make-link
6642 "file:"
6643 (abbreviate-file-name (expand-file-name file)))))
6644 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6645 (setq link (org-make-link "file:" (match-string 1 file))))
6646 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6647 (expand-file-name file))
6648 (setq link (org-make-link
6649 "file:" (match-string 1 (expand-file-name file)))))
6650 (t (setq link (org-make-link "file:" file))))))
6652 ;; Read link, with completion for stored links.
6653 (with-output-to-temp-buffer "*Org Links*"
6654 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6655 (when org-stored-links
6656 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6657 (princ (mapconcat
6658 (lambda (x)
6659 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6660 (reverse org-stored-links) "\n"))))
6661 (let ((cw (selected-window)))
6662 (select-window (get-buffer-window "*Org Links*"))
6663 (setq truncate-lines t)
6664 (org-fit-window-to-buffer)
6665 (select-window cw))
6666 ;; Fake a link history, containing the stored links.
6667 (setq tmphist (append (mapcar 'car org-stored-links)
6668 org-insert-link-history))
6669 (unwind-protect
6670 (setq link
6671 (let ((org-completion-use-ido nil))
6672 (org-completing-read
6673 "Link: "
6674 (append
6675 (mapcar (lambda (x) (list (concat (car x) ":")))
6676 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6677 (mapcar (lambda (x) (list (concat x ":")))
6678 org-link-types))
6679 nil nil nil
6680 'tmphist
6681 (or (car (car org-stored-links))))))
6682 (set-window-configuration wcf)
6683 (kill-buffer "*Org Links*"))
6684 (setq entry (assoc link org-stored-links))
6685 (or entry (push link org-insert-link-history))
6686 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6687 (not org-keep-stored-link-after-insertion))
6688 (setq org-stored-links (delq (assoc link org-stored-links)
6689 org-stored-links)))
6690 (setq desc (or desc (nth 1 entry)))))
6692 (if (string-match org-plain-link-re link)
6693 ;; URL-like link, normalize the use of angular brackets.
6694 (setq link (org-make-link (org-remove-angle-brackets link))))
6696 ;; Check if we are linking to the current file with a search option
6697 ;; If yes, simplify the link by using only the search option.
6698 (when (and buffer-file-name
6699 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6700 (let* ((path (match-string 1 link))
6701 (case-fold-search nil)
6702 (search (match-string 2 link)))
6703 (save-match-data
6704 (if (equal (file-truename buffer-file-name) (file-truename path))
6705 ;; We are linking to this same file, with a search option
6706 (setq link search)))))
6708 ;; Check if we can/should use a relative path. If yes, simplify the link
6709 (when (string-match "^file:\\(.*\\)" link)
6710 (let* ((path (match-string 1 link))
6711 (origpath path)
6712 (case-fold-search nil))
6713 (cond
6714 ((or (eq org-link-file-path-type 'absolute)
6715 (equal complete-file '(16)))
6716 (setq path (abbreviate-file-name (expand-file-name path))))
6717 ((eq org-link-file-path-type 'noabbrev)
6718 (setq path (expand-file-name path)))
6719 ((eq org-link-file-path-type 'relative)
6720 (setq path (file-relative-name path)))
6722 (save-match-data
6723 (if (string-match (concat "^" (regexp-quote
6724 (file-name-as-directory
6725 (expand-file-name "."))))
6726 (expand-file-name path))
6727 ;; We are linking a file with relative path name.
6728 (setq path (substring (expand-file-name path)
6729 (match-end 0)))
6730 (setq path (abbreviate-file-name (expand-file-name path)))))))
6731 (setq link (concat "file:" path))
6732 (if (equal desc origpath)
6733 (setq desc path))))
6735 (if org-make-link-description-function
6736 (setq desc (funcall org-make-link-description-function link desc)))
6738 (setq desc (read-string "Description: " desc))
6739 (unless (string-match "\\S-" desc) (setq desc nil))
6740 (if remove (apply 'delete-region remove))
6741 (insert (org-make-link-string link desc))))
6743 (defun org-completing-read (&rest args)
6744 "Completing-read with SPACE being a normal character."
6745 (let ((minibuffer-local-completion-map
6746 (copy-keymap minibuffer-local-completion-map)))
6747 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6748 (apply 'org-ido-completing-read args)))
6750 (defun org-ido-completing-read (&rest args)
6751 "Completing-read using `ido-mode' speedups if available"
6752 (if (and org-completion-use-ido
6753 (fboundp 'ido-completing-read)
6754 (boundp 'ido-mode) ido-mode
6755 (listp (second args)))
6756 (apply 'ido-completing-read (concat (car args)) (cdr args))
6757 (apply 'completing-read args)))
6759 (defun org-extract-attributes (s)
6760 "Extract the attributes cookie from a string and set as text property."
6761 (let (a attr (start 0) key value)
6762 (save-match-data
6763 (when (string-match "{{\\([^}]+\\)}}$" s)
6764 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6765 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6766 (setq key (match-string 1 a) value (match-string 2 a)
6767 start (match-end 0)
6768 attr (plist-put attr (intern key) value))))
6769 (org-add-props s nil 'org-attr attr))
6772 (defun org-attributes-to-string (plist)
6773 "Format a property list into an HTML attribute list."
6774 (let ((s "") key value)
6775 (while plist
6776 (setq key (pop plist) value (pop plist))
6777 (and value
6778 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6781 ;;; Opening/following a link
6783 (defvar org-link-search-failed nil)
6785 (defun org-next-link ()
6786 "Move forward to the next link.
6787 If the link is in hidden text, expose it."
6788 (interactive)
6789 (when (and org-link-search-failed (eq this-command last-command))
6790 (goto-char (point-min))
6791 (message "Link search wrapped back to beginning of buffer"))
6792 (setq org-link-search-failed nil)
6793 (let* ((pos (point))
6794 (ct (org-context))
6795 (a (assoc :link ct)))
6796 (if a (goto-char (nth 2 a)))
6797 (if (re-search-forward org-any-link-re nil t)
6798 (progn
6799 (goto-char (match-beginning 0))
6800 (if (org-invisible-p) (org-show-context)))
6801 (goto-char pos)
6802 (setq org-link-search-failed t)
6803 (error "No further link found"))))
6805 (defun org-previous-link ()
6806 "Move backward to the previous link.
6807 If the link is in hidden text, expose it."
6808 (interactive)
6809 (when (and org-link-search-failed (eq this-command last-command))
6810 (goto-char (point-max))
6811 (message "Link search wrapped back to end of buffer"))
6812 (setq org-link-search-failed nil)
6813 (let* ((pos (point))
6814 (ct (org-context))
6815 (a (assoc :link ct)))
6816 (if a (goto-char (nth 1 a)))
6817 (if (re-search-backward org-any-link-re nil t)
6818 (progn
6819 (goto-char (match-beginning 0))
6820 (if (org-invisible-p) (org-show-context)))
6821 (goto-char pos)
6822 (setq org-link-search-failed t)
6823 (error "No further link found"))))
6825 (defun org-translate-link (s)
6826 "Translate a link string if a translation function has been defined."
6827 (if (and org-link-translation-function
6828 (fboundp org-link-translation-function)
6829 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6830 (progn
6831 (setq s (funcall org-link-translation-function
6832 (match-string 1) (match-string 2)))
6833 (concat (car s) ":" (cdr s)))
6836 (defun org-translate-link-from-planner (type path)
6837 "Translate a link from Emacs Planner syntax so that Org can follow it.
6838 This is still an experimental function, your mileage may vary."
6839 (cond
6840 ((member type '("http" "https" "news" "ftp"))
6841 ;; standard Internet links are the same.
6842 nil)
6843 ((and (equal type "irc") (string-match "^//" path))
6844 ;; Planner has two / at the beginning of an irc link, we have 1.
6845 ;; We should have zero, actually....
6846 (setq path (substring path 1)))
6847 ((and (equal type "lisp") (string-match "^/" path))
6848 ;; Planner has a slash, we do not.
6849 (setq type "elisp" path (substring path 1)))
6850 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6851 ;; A typical message link. Planner has the id after the fina slash,
6852 ;; we separate it with a hash mark
6853 (setq path (concat (match-string 1 path) "#"
6854 (org-remove-angle-brackets (match-string 2 path)))))
6856 (cons type path))
6858 (defun org-find-file-at-mouse (ev)
6859 "Open file link or URL at mouse."
6860 (interactive "e")
6861 (mouse-set-point ev)
6862 (org-open-at-point 'in-emacs))
6864 (defun org-open-at-mouse (ev)
6865 "Open file link or URL at mouse."
6866 (interactive "e")
6867 (mouse-set-point ev)
6868 (if (eq major-mode 'org-agenda-mode)
6869 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6870 (org-open-at-point))
6872 (defvar org-window-config-before-follow-link nil
6873 "The window configuration before following a link.
6874 This is saved in case the need arises to restore it.")
6876 (defvar org-open-link-marker (make-marker)
6877 "Marker pointing to the location where `org-open-at-point; was called.")
6879 ;;;###autoload
6880 (defun org-open-at-point-global ()
6881 "Follow a link like Org-mode does.
6882 This command can be called in any mode to follow a link that has
6883 Org-mode syntax."
6884 (interactive)
6885 (org-run-like-in-org-mode 'org-open-at-point))
6887 ;;;###autoload
6888 (defun org-open-link-from-string (s &optional arg)
6889 "Open a link in the string S, as if it was in Org-mode."
6890 (interactive "sLink: \nP")
6891 (with-temp-buffer
6892 (let ((org-inhibit-startup t))
6893 (org-mode)
6894 (insert s)
6895 (goto-char (point-min))
6896 (org-open-at-point arg))))
6898 (defun org-open-at-point (&optional in-emacs)
6899 "Open link at or after point.
6900 If there is no link at point, this function will search forward up to
6901 the end of the current subtree.
6902 Normally, files will be opened by an appropriate application. If the
6903 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6904 With a double prefix argument, try to open outside of Emacs, in the
6905 application the system uses for this file type."
6906 (interactive "P")
6907 (org-load-modules-maybe)
6908 (move-marker org-open-link-marker (point))
6909 (setq org-window-config-before-follow-link (current-window-configuration))
6910 (org-remove-occur-highlights nil nil t)
6911 (if (org-at-timestamp-p t)
6912 (org-follow-timestamp-link)
6913 (let (type path link line search (pos (point)))
6914 (catch 'match
6915 (save-excursion
6916 (skip-chars-forward "^]\n\r")
6917 (when (org-in-regexp org-bracket-link-regexp)
6918 (setq link (org-extract-attributes
6919 (org-link-unescape (org-match-string-no-properties 1))))
6920 (while (string-match " *\n *" link)
6921 (setq link (replace-match " " t t link)))
6922 (setq link (org-link-expand-abbrev link))
6923 (cond
6924 ((or (file-name-absolute-p link)
6925 (string-match "^\\.\\.?/" link))
6926 (setq type "file" path link))
6927 ((string-match org-link-re-with-space3 link)
6928 (setq type (match-string 1 link) path (match-string 2 link)))
6929 (t (setq type "thisfile" path link)))
6930 (throw 'match t)))
6932 (when (get-text-property (point) 'org-linked-text)
6933 (setq type "thisfile"
6934 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6935 (1+ (point)) (point))
6936 path (buffer-substring
6937 (previous-single-property-change pos 'org-linked-text)
6938 (next-single-property-change pos 'org-linked-text)))
6939 (throw 'match t))
6941 (save-excursion
6942 (when (or (org-in-regexp org-angle-link-re)
6943 (org-in-regexp org-plain-link-re))
6944 (setq type (match-string 1) path (match-string 2))
6945 (throw 'match t)))
6946 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6947 (setq type "tree-match"
6948 path (match-string 1))
6949 (throw 'match t))
6950 (save-excursion
6951 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6952 (setq type "tags"
6953 path (match-string 1))
6954 (while (string-match ":" path)
6955 (setq path (replace-match "+" t t path)))
6956 (throw 'match t))))
6957 (unless path
6958 (error "No link found"))
6959 ;; Remove any trailing spaces in path
6960 (if (string-match " +\\'" path)
6961 (setq path (replace-match "" t t path)))
6962 (if (and org-link-translation-function
6963 (fboundp org-link-translation-function))
6964 ;; Check if we need to translate the link
6965 (let ((tmp (funcall org-link-translation-function type path)))
6966 (setq type (car tmp) path (cdr tmp))))
6968 (cond
6970 ((assoc type org-link-protocols)
6971 (funcall (nth 1 (assoc type org-link-protocols)) path))
6973 ((equal type "mailto")
6974 (let ((cmd (car org-link-mailto-program))
6975 (args (cdr org-link-mailto-program)) args1
6976 (address path) (subject "") a)
6977 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6978 (setq address (match-string 1 path)
6979 subject (org-link-escape (match-string 2 path))))
6980 (while args
6981 (cond
6982 ((not (stringp (car args))) (push (pop args) args1))
6983 (t (setq a (pop args))
6984 (if (string-match "%a" a)
6985 (setq a (replace-match address t t a)))
6986 (if (string-match "%s" a)
6987 (setq a (replace-match subject t t a)))
6988 (push a args1))))
6989 (apply cmd (nreverse args1))))
6991 ((member type '("http" "https" "ftp" "news"))
6992 (browse-url (concat type ":" (org-link-escape
6993 path org-link-escape-chars-browser))))
6995 ((member type '("message"))
6996 (browse-url (concat type ":" path)))
6998 ((string= type "tags")
6999 (org-tags-view in-emacs path))
7000 ((string= type "thisfile")
7001 (if in-emacs
7002 (switch-to-buffer-other-window
7003 (org-get-buffer-for-internal-link (current-buffer)))
7004 (org-mark-ring-push))
7005 (let ((cmd `(org-link-search
7006 ,path
7007 ,(cond ((equal in-emacs '(4)) 'occur)
7008 ((equal in-emacs '(16)) 'org-occur)
7009 (t nil))
7010 ,pos)))
7011 (condition-case nil (eval cmd)
7012 (error (progn (widen) (eval cmd))))))
7014 ((string= type "tree-match")
7015 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7017 ((string= type "file")
7018 (if (string-match "::\\([0-9]+\\)\\'" path)
7019 (setq line (string-to-number (match-string 1 path))
7020 path (substring path 0 (match-beginning 0)))
7021 (if (string-match "::\\(.+\\)\\'" path)
7022 (setq search (match-string 1 path)
7023 path (substring path 0 (match-beginning 0)))))
7024 (if (string-match "[*?{]" (file-name-nondirectory path))
7025 (dired path)
7026 (org-open-file path in-emacs line search)))
7028 ((string= type "news")
7029 (require 'org-gnus)
7030 (org-gnus-follow-link path))
7032 ((string= type "shell")
7033 (let ((cmd path))
7034 (if (or (not org-confirm-shell-link-function)
7035 (funcall org-confirm-shell-link-function
7036 (format "Execute \"%s\" in shell? "
7037 (org-add-props cmd nil
7038 'face 'org-warning))))
7039 (progn
7040 (message "Executing %s" cmd)
7041 (shell-command cmd))
7042 (error "Abort"))))
7044 ((string= type "elisp")
7045 (let ((cmd path))
7046 (if (or (not org-confirm-elisp-link-function)
7047 (funcall org-confirm-elisp-link-function
7048 (format "Execute \"%s\" as elisp? "
7049 (org-add-props cmd nil
7050 'face 'org-warning))))
7051 (message "%s => %s" cmd
7052 (if (equal (string-to-char cmd) ?\()
7053 (eval (read cmd))
7054 (call-interactively (read cmd))))
7055 (error "Abort"))))
7058 (browse-url-at-point)))))
7059 (move-marker org-open-link-marker nil)
7060 (run-hook-with-args 'org-follow-link-hook))
7062 ;;;; Time estimates
7064 (defun org-get-effort (&optional pom)
7065 "Get the effort estimate for the current entry."
7066 (org-entry-get pom org-effort-property))
7068 ;;; File search
7070 (defvar org-create-file-search-functions nil
7071 "List of functions to construct the right search string for a file link.
7072 These functions are called in turn with point at the location to
7073 which the link should point.
7075 A function in the hook should first test if it would like to
7076 handle this file type, for example by checking the major-mode or
7077 the file extension. If it decides not to handle this file, it
7078 should just return nil to give other functions a chance. If it
7079 does handle the file, it must return the search string to be used
7080 when following the link. The search string will be part of the
7081 file link, given after a double colon, and `org-open-at-point'
7082 will automatically search for it. If special measures must be
7083 taken to make the search successful, another function should be
7084 added to the companion hook `org-execute-file-search-functions',
7085 which see.
7087 A function in this hook may also use `setq' to set the variable
7088 `description' to provide a suggestion for the descriptive text to
7089 be used for this link when it gets inserted into an Org-mode
7090 buffer with \\[org-insert-link].")
7092 (defvar org-execute-file-search-functions nil
7093 "List of functions to execute a file search triggered by a link.
7095 Functions added to this hook must accept a single argument, the
7096 search string that was part of the file link, the part after the
7097 double colon. The function must first check if it would like to
7098 handle this search, for example by checking the major-mode or the
7099 file extension. If it decides not to handle this search, it
7100 should just return nil to give other functions a chance. If it
7101 does handle the search, it must return a non-nil value to keep
7102 other functions from trying.
7104 Each function can access the current prefix argument through the
7105 variable `current-prefix-argument'. Note that a single prefix is
7106 used to force opening a link in Emacs, so it may be good to only
7107 use a numeric or double prefix to guide the search function.
7109 In case this is needed, a function in this hook can also restore
7110 the window configuration before `org-open-at-point' was called using:
7112 (set-window-configuration org-window-config-before-follow-link)")
7114 (defun org-link-search (s &optional type avoid-pos)
7115 "Search for a link search option.
7116 If S is surrounded by forward slashes, it is interpreted as a
7117 regular expression. In org-mode files, this will create an `org-occur'
7118 sparse tree. In ordinary files, `occur' will be used to list matches.
7119 If the current buffer is in `dired-mode', grep will be used to search
7120 in all files. If AVOID-POS is given, ignore matches near that position."
7121 (let ((case-fold-search t)
7122 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7123 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7124 (append '(("") (" ") ("\t") ("\n"))
7125 org-emphasis-alist)
7126 "\\|") "\\)"))
7127 (pos (point))
7128 (pre nil) (post nil)
7129 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7130 (cond
7131 ;; First check if there are any special
7132 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7133 ;; Now try the builtin stuff
7134 ((save-excursion
7135 (goto-char (point-min))
7136 (and
7137 (re-search-forward
7138 (concat "<<" (regexp-quote s0) ">>") nil t)
7139 (setq type 'dedicated
7140 pos (match-beginning 0))))
7141 ;; There is an exact target for this
7142 (goto-char pos))
7143 ((and (string-match "^((.*))$" s0)
7144 (save-excursion
7145 (goto-char (point-min))
7146 (and
7147 (re-search-forward (concat "[^[]" (regexp-quote s0)) nil t)
7148 (setq type 'dedicated
7149 pos (1+ (match-beginning 0))))))
7150 ;; There is a coderef target for this
7151 (goto-char pos))
7152 ((string-match "^/\\(.*\\)/$" s)
7153 ;; A regular expression
7154 (cond
7155 ((org-mode-p)
7156 (org-occur (match-string 1 s)))
7157 ;;((eq major-mode 'dired-mode)
7158 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7159 (t (org-do-occur (match-string 1 s)))))
7161 ;; A normal search strings
7162 (when (equal (string-to-char s) ?*)
7163 ;; Anchor on headlines, post may include tags.
7164 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7165 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7166 s (substring s 1)))
7167 (remove-text-properties
7168 0 (length s)
7169 '(face nil mouse-face nil keymap nil fontified nil) s)
7170 ;; Make a series of regular expressions to find a match
7171 (setq words (org-split-string s "[ \n\r\t]+")
7173 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7174 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7175 "\\)" markers)
7176 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7177 re2a (concat "[ \t\r\n]" re2a_)
7178 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7179 re4 (concat "[^a-zA-Z_]" re4_)
7181 re1 (concat pre re2 post)
7182 re3 (concat pre (if pre re4_ re4) post)
7183 re5 (concat pre ".*" re4)
7184 re2 (concat pre re2)
7185 re2a (concat pre (if pre re2a_ re2a))
7186 re4 (concat pre (if pre re4_ re4))
7187 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7188 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7189 re5 "\\)"
7191 (cond
7192 ((eq type 'org-occur) (org-occur reall))
7193 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7194 (t (goto-char (point-min))
7195 (setq type 'fuzzy)
7196 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7197 (org-search-not-self 1 re1 nil t)
7198 (org-search-not-self 1 re2 nil t)
7199 (org-search-not-self 1 re2a nil t)
7200 (org-search-not-self 1 re3 nil t)
7201 (org-search-not-self 1 re4 nil t)
7202 (org-search-not-self 1 re5 nil t)
7204 (goto-char (match-beginning 1))
7205 (goto-char pos)
7206 (error "No match")))))
7208 ;; Normal string-search
7209 (goto-char (point-min))
7210 (if (search-forward s nil t)
7211 (goto-char (match-beginning 0))
7212 (error "No match"))))
7213 (and (org-mode-p) (org-show-context 'link-search))
7214 type))
7216 (defun org-search-not-self (group &rest args)
7217 "Execute `re-search-forward', but only accept matches that do not
7218 enclose the position of `org-open-link-marker'."
7219 (let ((m org-open-link-marker))
7220 (catch 'exit
7221 (while (apply 're-search-forward args)
7222 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7223 (goto-char (match-end group))
7224 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7225 (> (match-beginning 0) (marker-position m))
7226 (< (match-end 0) (marker-position m)))
7227 (save-match-data
7228 (or (not (org-in-regexp
7229 org-bracket-link-analytic-regexp 1))
7230 (not (match-end 4)) ; no description
7231 (and (<= (match-beginning 4) (point))
7232 (>= (match-end 4) (point))))))
7233 (throw 'exit (point))))))))
7235 (defun org-get-buffer-for-internal-link (buffer)
7236 "Return a buffer to be used for displaying the link target of internal links."
7237 (cond
7238 ((not org-display-internal-link-with-indirect-buffer)
7239 buffer)
7240 ((string-match "(Clone)$" (buffer-name buffer))
7241 (message "Buffer is already a clone, not making another one")
7242 ;; we also do not modify visibility in this case
7243 buffer)
7244 (t ; make a new indirect buffer for displaying the link
7245 (let* ((bn (buffer-name buffer))
7246 (ibn (concat bn "(Clone)"))
7247 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7248 (with-current-buffer ib (org-overview))
7249 ib))))
7251 (defun org-do-occur (regexp &optional cleanup)
7252 "Call the Emacs command `occur'.
7253 If CLEANUP is non-nil, remove the printout of the regular expression
7254 in the *Occur* buffer. This is useful if the regex is long and not useful
7255 to read."
7256 (occur regexp)
7257 (when cleanup
7258 (let ((cwin (selected-window)) win beg end)
7259 (when (setq win (get-buffer-window "*Occur*"))
7260 (select-window win))
7261 (goto-char (point-min))
7262 (when (re-search-forward "match[a-z]+" nil t)
7263 (setq beg (match-end 0))
7264 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7265 (setq end (1- (match-beginning 0)))))
7266 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7267 (goto-char (point-min))
7268 (select-window cwin))))
7270 ;;; The mark ring for links jumps
7272 (defvar org-mark-ring nil
7273 "Mark ring for positions before jumps in Org-mode.")
7274 (defvar org-mark-ring-last-goto nil
7275 "Last position in the mark ring used to go back.")
7276 ;; Fill and close the ring
7277 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7278 (loop for i from 1 to org-mark-ring-length do
7279 (push (make-marker) org-mark-ring))
7280 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7281 org-mark-ring)
7283 (defun org-mark-ring-push (&optional pos buffer)
7284 "Put the current position or POS into the mark ring and rotate it."
7285 (interactive)
7286 (setq pos (or pos (point)))
7287 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7288 (move-marker (car org-mark-ring)
7289 (or pos (point))
7290 (or buffer (current-buffer)))
7291 (message "%s"
7292 (substitute-command-keys
7293 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7295 (defun org-mark-ring-goto (&optional n)
7296 "Jump to the previous position in the mark ring.
7297 With prefix arg N, jump back that many stored positions. When
7298 called several times in succession, walk through the entire ring.
7299 Org-mode commands jumping to a different position in the current file,
7300 or to another Org-mode file, automatically push the old position
7301 onto the ring."
7302 (interactive "p")
7303 (let (p m)
7304 (if (eq last-command this-command)
7305 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7306 (setq p org-mark-ring))
7307 (setq org-mark-ring-last-goto p)
7308 (setq m (car p))
7309 (switch-to-buffer (marker-buffer m))
7310 (goto-char m)
7311 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7313 (defun org-remove-angle-brackets (s)
7314 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7315 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7317 (defun org-add-angle-brackets (s)
7318 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7319 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7321 (defun org-remove-double-quotes (s)
7322 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7323 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7326 ;;; Following specific links
7328 (defun org-follow-timestamp-link ()
7329 (cond
7330 ((org-at-date-range-p t)
7331 (let ((org-agenda-start-on-weekday)
7332 (t1 (match-string 1))
7333 (t2 (match-string 2)))
7334 (setq t1 (time-to-days (org-time-string-to-time t1))
7335 t2 (time-to-days (org-time-string-to-time t2)))
7336 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7337 ((org-at-timestamp-p t)
7338 (org-agenda-list nil (time-to-days (org-time-string-to-time
7339 (substring (match-string 1) 0 10)))
7341 (t (error "This should not happen"))))
7344 ;;; Following file links
7345 (defvar org-wait nil)
7346 (defun org-open-file (path &optional in-emacs line search)
7347 "Open the file at PATH.
7348 First, this expands any special file name abbreviations. Then the
7349 configuration variable `org-file-apps' is checked if it contains an
7350 entry for this file type, and if yes, the corresponding command is launched.
7352 If no application is found, Emacs simply visits the file.
7354 With optional prefix argument IN-EMACS, Emacs will visit the file.
7355 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7356 and o use an external application to visit the file.
7358 Optional LINE specifies a line to go to, optional SEARCH a string to
7359 search for. If LINE or SEARCH is given, the file will always be
7360 opened in Emacs.
7361 If the file does not exist, an error is thrown."
7362 (setq in-emacs (or in-emacs line search))
7363 (let* ((file (if (equal path "")
7364 buffer-file-name
7365 (substitute-in-file-name (expand-file-name path))))
7366 (apps (append org-file-apps (org-default-apps)))
7367 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7368 (dirp (if remp nil (file-directory-p file)))
7369 (file (if (and dirp org-open-directory-means-index-dot-org)
7370 (concat (file-name-as-directory file) "index.org")
7371 file))
7372 (a-m-a-p (assq 'auto-mode apps))
7373 (dfile (downcase file))
7374 (old-buffer (current-buffer))
7375 (old-pos (point))
7376 (old-mode major-mode)
7377 ext cmd)
7378 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7379 (setq ext (match-string 1 dfile))
7380 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7381 (setq ext (match-string 1 dfile))))
7382 (cond
7383 ((equal in-emacs '(16))
7384 (setq cmd (cdr (assoc 'system apps))))
7385 (in-emacs (setq cmd 'emacs))
7387 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7388 (and dirp (cdr (assoc 'directory apps)))
7389 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7390 'string-match)
7391 (cdr (assoc ext apps))
7392 (cdr (assoc t apps))))))
7393 (when (eq cmd 'system)
7394 (setq cmd (cdr (assoc 'system apps))))
7395 (when (eq cmd 'default)
7396 (setq cmd (cdr (assoc t apps))))
7397 (when (eq cmd 'mailcap)
7398 (require 'mailcap)
7399 (mailcap-parse-mailcaps)
7400 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7401 (command (mailcap-mime-info mime-type)))
7402 (if (stringp command)
7403 (setq cmd command)
7404 (setq cmd 'emacs))))
7405 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7406 (not (file-exists-p file))
7407 (not org-open-non-existing-files))
7408 (error "No such file: %s" file))
7409 (cond
7410 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7411 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7412 (while (string-match "['\"]%s['\"]" cmd)
7413 (setq cmd (replace-match "%s" t t cmd)))
7414 (while (string-match "%s" cmd)
7415 (setq cmd (replace-match
7416 (save-match-data
7417 (shell-quote-argument
7418 (convert-standard-filename file)))
7419 t t cmd)))
7420 (save-window-excursion
7421 (start-process-shell-command cmd nil cmd)
7422 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7424 ((or (stringp cmd)
7425 (eq cmd 'emacs))
7426 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7427 (widen)
7428 (if line (goto-line line)
7429 (if search (org-link-search search))))
7430 ((consp cmd)
7431 (let ((file (convert-standard-filename file)))
7432 (eval cmd)))
7433 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7434 (and (org-mode-p) (eq old-mode 'org-mode)
7435 (or (not (equal old-buffer (current-buffer)))
7436 (not (equal old-pos (point))))
7437 (org-mark-ring-push old-pos old-buffer))))
7439 (defun org-default-apps ()
7440 "Return the default applications for this operating system."
7441 (cond
7442 ((eq system-type 'darwin)
7443 org-file-apps-defaults-macosx)
7444 ((eq system-type 'windows-nt)
7445 org-file-apps-defaults-windowsnt)
7446 (t org-file-apps-defaults-gnu)))
7448 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7449 "Convert extensions to regular expressions in the cars of LIST.
7450 Also, weed out any non-string entries, because the return value is used
7451 only for regexp matching.
7452 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7453 point to the symbol `emacs', indicating that the file should
7454 be opened in Emacs."
7455 (append
7456 (delq nil
7457 (mapcar (lambda (x)
7458 (if (not (stringp (car x)))
7460 (if (string-match "\\W" (car x))
7462 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7463 list))
7464 (if add-auto-mode
7465 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7467 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7468 (defun org-file-remote-p (file)
7469 "Test whether FILE specifies a location on a remote system.
7470 Return non-nil if the location is indeed remote.
7472 For example, the filename \"/user@host:/foo\" specifies a location
7473 on the system \"/user@host:\"."
7474 (cond ((fboundp 'file-remote-p)
7475 (file-remote-p file))
7476 ((fboundp 'tramp-handle-file-remote-p)
7477 (tramp-handle-file-remote-p file))
7478 ((and (boundp 'ange-ftp-name-format)
7479 (string-match (car ange-ftp-name-format) file))
7481 (t nil)))
7484 ;;;; Refiling
7486 (defun org-get-org-file ()
7487 "Read a filename, with default directory `org-directory'."
7488 (let ((default (or org-default-notes-file remember-data-file)))
7489 (read-file-name (format "File name [%s]: " default)
7490 (file-name-as-directory org-directory)
7491 default)))
7493 (defun org-notes-order-reversed-p ()
7494 "Check if the current file should receive notes in reversed order."
7495 (cond
7496 ((not org-reverse-note-order) nil)
7497 ((eq t org-reverse-note-order) t)
7498 ((not (listp org-reverse-note-order)) nil)
7499 (t (catch 'exit
7500 (let ((all org-reverse-note-order)
7501 entry)
7502 (while (setq entry (pop all))
7503 (if (string-match (car entry) buffer-file-name)
7504 (throw 'exit (cdr entry))))
7505 nil)))))
7507 (defvar org-refile-target-table nil
7508 "The list of refile targets, created by `org-refile'.")
7510 (defvar org-agenda-new-buffers nil
7511 "Buffers created to visit agenda files.")
7513 (defun org-get-refile-targets (&optional default-buffer)
7514 "Produce a table with refile targets."
7515 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7516 targets txt re files f desc descre fast-path-p level)
7517 (message "Getting targets...")
7518 (with-current-buffer (or default-buffer (current-buffer))
7519 (while (setq entry (pop entries))
7520 (setq files (car entry) desc (cdr entry))
7521 (setq fast-path-p nil)
7522 (cond
7523 ((null files) (setq files (list (current-buffer))))
7524 ((eq files 'org-agenda-files)
7525 (setq files (org-agenda-files 'unrestricted)))
7526 ((and (symbolp files) (fboundp files))
7527 (setq files (funcall files)))
7528 ((and (symbolp files) (boundp files))
7529 (setq files (symbol-value files))))
7530 (if (stringp files) (setq files (list files)))
7531 (cond
7532 ((eq (car desc) :tag)
7533 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7534 ((eq (car desc) :todo)
7535 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7536 ((eq (car desc) :regexp)
7537 (setq descre (cdr desc)))
7538 ((eq (car desc) :level)
7539 (setq descre (concat "^\\*\\{" (number-to-string
7540 (if org-odd-levels-only
7541 (1- (* 2 (cdr desc)))
7542 (cdr desc)))
7543 "\\}[ \t]")))
7544 ((eq (car desc) :maxlevel)
7545 (setq fast-path-p t)
7546 (setq descre (concat "^\\*\\{1," (number-to-string
7547 (if org-odd-levels-only
7548 (1- (* 2 (cdr desc)))
7549 (cdr desc)))
7550 "\\}[ \t]")))
7551 (t (error "Bad refiling target description %s" desc)))
7552 (while (setq f (pop files))
7553 (save-excursion
7554 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7555 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7556 (setq f (expand-file-name f))
7557 (save-excursion
7558 (save-restriction
7559 (widen)
7560 (goto-char (point-min))
7561 (while (re-search-forward descre nil t)
7562 (goto-char (point-at-bol))
7563 (when (looking-at org-complex-heading-regexp)
7564 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7565 txt (org-link-display-format (match-string 4))
7566 re (concat "^" (regexp-quote
7567 (buffer-substring (match-beginning 1)
7568 (match-end 4)))))
7569 (if (match-end 5) (setq re (concat re "[ \t]+"
7570 (regexp-quote
7571 (match-string 5)))))
7572 (setq re (concat re "[ \t]*$"))
7573 (when org-refile-use-outline-path
7574 (setq txt (mapconcat 'org-protect-slash
7575 (append
7576 (if (eq org-refile-use-outline-path 'file)
7577 (list (file-name-nondirectory
7578 (buffer-file-name (buffer-base-buffer))))
7579 (if (eq org-refile-use-outline-path 'full-file-path)
7580 (list (buffer-file-name (buffer-base-buffer)))))
7581 (org-get-outline-path fast-path-p level txt)
7582 (list txt))
7583 "/")))
7584 (push (list txt f re (point)) targets))
7585 (goto-char (point-at-eol))))))))
7586 (message "Getting targets...done")
7587 (nreverse targets))))
7589 (defun org-protect-slash (s)
7590 (while (string-match "/" s)
7591 (setq s (replace-match "\\" t t s)))
7594 (defvar org-olpa (make-vector 20 nil))
7596 (defun org-get-outline-path (&optional fastp level heading)
7597 "Return the outline path to the current entry, as a list."
7598 (if fastp
7599 (progn
7600 (if (> level 19)
7601 (error "Outline path failure, more than 19 levels."))
7602 (loop for i from level upto 19 do
7603 (aset org-olpa i nil))
7604 (prog1
7605 (delq nil (append org-olpa nil))
7606 (aset org-olpa level heading)))
7607 (let (rtn)
7608 (save-excursion
7609 (while (org-up-heading-safe)
7610 (when (looking-at org-complex-heading-regexp)
7611 (push (org-match-string-no-properties 4) rtn)))
7612 rtn))))
7614 (defvar org-refile-history nil
7615 "History for refiling operations.")
7617 (defun org-refile (&optional goto default-buffer)
7618 "Move the entry at point to another heading.
7619 The list of target headings is compiled using the information in
7620 `org-refile-targets', which see. This list is created before each use
7621 and will therefore always be up-to-date.
7623 At the target location, the entry is filed as a subitem of the target heading.
7624 Depending on `org-reverse-note-order', the new subitem will either be the
7625 first or the last subitem.
7627 If there is an active region, all entries in that region will be moved.
7628 However, the region must fulfil the requirement that the first heading
7629 is the first one sets the top-level of the moved text - at most siblings
7630 below it are allowed.
7632 With prefix arg GOTO, the command will only visit the target location,
7633 not actually move anything.
7634 With a double prefix `C-u C-u', go to the location where the last refiling
7635 operation has put the subtree."
7636 (interactive "P")
7637 (let* ((cbuf (current-buffer))
7638 (regionp (org-region-active-p))
7639 (region-start (and regionp (region-beginning)))
7640 (region-end (and regionp (region-end)))
7641 (region-length (and regionp (- region-end region-start)))
7642 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7643 pos it nbuf file re level reversed)
7644 (when regionp (goto-char region-start)
7645 (unless (org-kill-is-subtree-p
7646 (buffer-substring region-start region-end))
7647 (error "The region is not a (sequence of) subtree(s)")))
7648 (if (equal goto '(16))
7649 (org-refile-goto-last-stored)
7650 (when (setq it (org-refile-get-location
7651 (if goto "Goto: " "Refile to: ") default-buffer))
7652 (setq file (nth 1 it)
7653 re (nth 2 it)
7654 pos (nth 3 it))
7655 (if (and (equal (buffer-file-name) file)
7656 (if regionp
7657 (and (>= pos region-start)
7658 (<= pos region-end))
7659 (and (>= pos (point))
7660 (< pos (save-excursion
7661 (org-end-of-subtree t t))))))
7662 (error "Cannot refile to position inside the tree or region"))
7664 (setq nbuf (or (find-buffer-visiting file)
7665 (find-file-noselect file)))
7666 (if goto
7667 (progn
7668 (switch-to-buffer nbuf)
7669 (goto-char pos)
7670 (org-show-context 'org-goto))
7671 (if regionp
7672 (progn
7673 (kill-new (buffer-substring region-start region-end))
7674 (org-save-markers-in-region region-start region-end))
7675 (org-copy-subtree 1 nil t))
7676 (save-excursion
7677 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7678 (find-file-noselect file))))
7679 (setq reversed (org-notes-order-reversed-p))
7680 (save-excursion
7681 (save-restriction
7682 (widen)
7683 (goto-char pos)
7684 (looking-at outline-regexp)
7685 (setq level (org-get-valid-level (funcall outline-level) 1))
7686 (goto-char
7687 (if reversed
7688 (or (outline-next-heading) (point-max))
7689 (or (save-excursion (outline-get-next-sibling))
7690 (org-end-of-subtree t t)
7691 (point-max))))
7692 (if (not (bolp)) (newline))
7693 (bookmark-set "org-refile-last-stored")
7694 (org-paste-subtree level))))
7695 (if regionp
7696 (delete-region (point) (+ (point) region-length))
7697 (org-cut-subtree))
7698 (setq org-markers-to-move nil)
7699 (message "Refiled to \"%s\"" (car it)))))))
7701 (defun org-refile-goto-last-stored ()
7702 "Go to the location where the last refile was stored."
7703 (interactive)
7704 (bookmark-jump "org-refile-last-stored")
7705 (message "This is the location of the last refile"))
7707 (defun org-refile-get-location (&optional prompt default-buffer)
7708 "Prompt the user for a refile location, using PROMPT."
7709 (let ((org-refile-targets org-refile-targets)
7710 (org-refile-use-outline-path org-refile-use-outline-path))
7711 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7712 (unless org-refile-target-table
7713 (error "No refile targets"))
7714 (let* ((cbuf (current-buffer))
7715 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7716 (cfunc (if (and org-refile-use-outline-path
7717 org-outline-path-complete-in-steps)
7718 'org-olpath-completing-read
7719 'org-ido-completing-read))
7720 (extra (if org-refile-use-outline-path "/" ""))
7721 (filename (and cfn (expand-file-name cfn)))
7722 (tbl (mapcar
7723 (lambda (x)
7724 (if (not (equal filename (nth 1 x)))
7725 (cons (concat (car x) extra " ("
7726 (file-name-nondirectory (nth 1 x)) ")")
7727 (cdr x))
7728 (cons (concat (car x) extra) (cdr x))))
7729 org-refile-target-table))
7730 (completion-ignore-case t))
7731 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7732 tbl)))
7734 (defun org-olpath-completing-read (prompt collection &rest args)
7735 "Read an outline path like a file name."
7736 (let ((thetable collection))
7737 (apply
7738 'org-ido-completing-read prompt
7739 (lambda (string predicate &optional flag)
7740 (let (rtn r s f (l (length string)))
7741 (cond
7742 ((eq flag nil)
7743 ;; try completion
7744 (try-completion string thetable))
7745 ((eq flag t)
7746 ;; all-completions
7747 (setq rtn (all-completions string thetable predicate))
7748 (mapcar
7749 (lambda (x)
7750 (setq r (substring x l))
7751 (if (string-match " ([^)]*)$" x)
7752 (setq f (match-string 0 x))
7753 (setq f ""))
7754 (if (string-match "/" r)
7755 (concat string (substring r 0 (match-end 0)) f)
7757 rtn))
7758 ((eq flag 'lambda)
7759 ;; exact match?
7760 (assoc string thetable)))
7762 args)))
7764 ;;;; Dynamic blocks
7766 (defun org-find-dblock (name)
7767 "Find the first dynamic block with name NAME in the buffer.
7768 If not found, stay at current position and return nil."
7769 (let (pos)
7770 (save-excursion
7771 (goto-char (point-min))
7772 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7773 nil t)
7774 (match-beginning 0))))
7775 (if pos (goto-char pos))
7776 pos))
7778 (defconst org-dblock-start-re
7779 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7780 "Matches the startline of a dynamic block, with parameters.")
7782 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7783 "Matches the end of a dynamic block.")
7785 (defun org-create-dblock (plist)
7786 "Create a dynamic block section, with parameters taken from PLIST.
7787 PLIST must contain a :name entry which is used as name of the block."
7788 (unless (bolp) (newline))
7789 (let ((name (plist-get plist :name)))
7790 (insert "#+BEGIN: " name)
7791 (while plist
7792 (if (eq (car plist) :name)
7793 (setq plist (cddr plist))
7794 (insert " " (prin1-to-string (pop plist)))))
7795 (insert "\n\n#+END:\n")
7796 (beginning-of-line -2)))
7798 (defun org-prepare-dblock ()
7799 "Prepare dynamic block for refresh.
7800 This empties the block, puts the cursor at the insert position and returns
7801 the property list including an extra property :name with the block name."
7802 (unless (looking-at org-dblock-start-re)
7803 (error "Not at a dynamic block"))
7804 (let* ((begdel (1+ (match-end 0)))
7805 (name (org-no-properties (match-string 1)))
7806 (params (append (list :name name)
7807 (read (concat "(" (match-string 3) ")")))))
7808 (unless (re-search-forward org-dblock-end-re nil t)
7809 (error "Dynamic block not terminated"))
7810 (setq params
7811 (append params
7812 (list :content (buffer-substring
7813 begdel (match-beginning 0)))))
7814 (delete-region begdel (match-beginning 0))
7815 (goto-char begdel)
7816 (open-line 1)
7817 params))
7819 (defun org-map-dblocks (&optional command)
7820 "Apply COMMAND to all dynamic blocks in the current buffer.
7821 If COMMAND is not given, use `org-update-dblock'."
7822 (let ((cmd (or command 'org-update-dblock))
7823 pos)
7824 (save-excursion
7825 (goto-char (point-min))
7826 (while (re-search-forward org-dblock-start-re nil t)
7827 (goto-char (setq pos (match-beginning 0)))
7828 (condition-case nil
7829 (funcall cmd)
7830 (error (message "Error during update of dynamic block")))
7831 (goto-char pos)
7832 (unless (re-search-forward org-dblock-end-re nil t)
7833 (error "Dynamic block not terminated"))))))
7835 (defun org-dblock-update (&optional arg)
7836 "User command for updating dynamic blocks.
7837 Update the dynamic block at point. With prefix ARG, update all dynamic
7838 blocks in the buffer."
7839 (interactive "P")
7840 (if arg
7841 (org-update-all-dblocks)
7842 (or (looking-at org-dblock-start-re)
7843 (org-beginning-of-dblock))
7844 (org-update-dblock)))
7846 (defun org-update-dblock ()
7847 "Update the dynamic block at point
7848 This means to empty the block, parse for parameters and then call
7849 the correct writing function."
7850 (save-window-excursion
7851 (let* ((pos (point))
7852 (line (org-current-line))
7853 (params (org-prepare-dblock))
7854 (name (plist-get params :name))
7855 (cmd (intern (concat "org-dblock-write:" name))))
7856 (message "Updating dynamic block `%s' at line %d..." name line)
7857 (funcall cmd params)
7858 (message "Updating dynamic block `%s' at line %d...done" name line)
7859 (goto-char pos))))
7861 (defun org-beginning-of-dblock ()
7862 "Find the beginning of the dynamic block at point.
7863 Error if there is no such block at point."
7864 (let ((pos (point))
7865 beg)
7866 (end-of-line 1)
7867 (if (and (re-search-backward org-dblock-start-re nil t)
7868 (setq beg (match-beginning 0))
7869 (re-search-forward org-dblock-end-re nil t)
7870 (> (match-end 0) pos))
7871 (goto-char beg)
7872 (goto-char pos)
7873 (error "Not in a dynamic block"))))
7875 (defun org-update-all-dblocks ()
7876 "Update all dynamic blocks in the buffer.
7877 This function can be used in a hook."
7878 (when (org-mode-p)
7879 (org-map-dblocks 'org-update-dblock)))
7882 ;;;; Completion
7884 (defconst org-additional-option-like-keywords
7885 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7886 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7887 "BEGIN_EXAMPLE" "END_EXAMPLE"
7888 "BEGIN_QUOTE" "END_QUOTE"
7889 "BEGIN_VERSE" "END_VERSE"
7890 "BEGIN_SRC" "END_SRC"
7891 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7893 (defcustom org-structure-template-alist
7895 ("s" "#+begin_src ?\n\n#+end_src"
7896 "<src lang=\"?\">\n\n</src>")
7897 ("e" "#+begin_example\n?\n#+end_example"
7898 "<example>\n?\n</example>")
7899 ("q" "#+begin_quote\n?\n#+end_quote"
7900 "<quote>\n?\n</quote>")
7901 ("v" "#+begin_verse\n?\n#+end_verse"
7902 "<verse>\n?\n/verse>")
7903 ("l" "#+begin_latex\n?\n#+end_latex"
7904 "<literal style=\"latex\">\n?\n</literal>")
7905 ("L" "#+latex: "
7906 "<literal style=\"latex\">?</literal>")
7907 ("h" "#+begin_html\n?\n#+end_html"
7908 "<literal style=\"html\">\n?\n</literal>")
7909 ("H" "#+html: "
7910 "<literal style=\"html\">?</literal>")
7911 ("a" "#+begin_ascii\n?\n#+end_ascii")
7912 ("A" "#+ascii: ")
7913 ("i" "#+include %file ?"
7914 "<include file=%file markup=\"?\">")
7916 "Structure completion elements.
7917 This is a list of abbreviation keys and values. The value gets inserted
7918 it you type @samp{.} followed by the key and then the completion key,
7919 usually `M-TAB'. %file will be replaced by a file name after prompting
7920 for the file using completion.
7921 There are two templates for each key, the first uses the original Org syntax,
7922 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7923 the default when the /org-mtags.el/ module has been loaded. See also the
7924 variable `org-mtags-prefer-muse-templates'.
7925 This is an experimental feature, it is undecided if it is going to stay in."
7926 :group 'org-completion
7927 :type '(repeat
7928 (string :tag "Key")
7929 (string :tag "Template")
7930 (string :tag "Muse Template")))
7932 (defun org-try-structure-completion ()
7933 "Try to complete a structure template before point.
7934 This looks for strings like \"<e\" on an otherwise empty line and
7935 expands them."
7936 (let ((l (buffer-substring (point-at-bol) (point)))
7938 (when (and (looking-at "[ \t]*$")
7939 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7940 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7941 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7942 (match-beginning 1)) a)
7943 t)))
7945 (defun org-complete-expand-structure-template (start cell)
7946 "Expand a structure template."
7947 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7948 (rpl (nth (if musep 2 1) cell)))
7949 (delete-region start (point))
7950 (when (string-match "\\`#\\+" rpl)
7951 (cond
7952 ((bolp))
7953 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7954 (delete-region (point-at-bol) (point)))
7955 (t (newline))))
7956 (setq start (point))
7957 (if (string-match "%file" rpl)
7958 (setq rpl (replace-match
7959 (concat
7960 "\""
7961 (save-match-data
7962 (abbreviate-file-name (read-file-name "Include file: ")))
7963 "\"")
7964 t t rpl)))
7965 (insert rpl)
7966 (if (re-search-backward "\\?" start t) (delete-char 1))))
7969 (defun org-complete (&optional arg)
7970 "Perform completion on word at point.
7971 At the beginning of a headline, this completes TODO keywords as given in
7972 `org-todo-keywords'.
7973 If the current word is preceded by a backslash, completes the TeX symbols
7974 that are supported for HTML support.
7975 If the current word is preceded by \"#+\", completes special words for
7976 setting file options.
7977 In the line after \"#+STARTUP:, complete valid keywords.\"
7978 At all other locations, this simply calls the value of
7979 `org-completion-fallback-command'."
7980 (interactive "P")
7981 (org-without-partial-completion
7982 (catch 'exit
7983 (let* ((a nil)
7984 (end (point))
7985 (beg1 (save-excursion
7986 (skip-chars-backward (org-re "[:alnum:]_@"))
7987 (point)))
7988 (beg (save-excursion
7989 (skip-chars-backward "a-zA-Z0-9_:$")
7990 (point)))
7991 (confirm (lambda (x) (stringp (car x))))
7992 (searchhead (equal (char-before beg) ?*))
7993 (struct
7994 (when (and (member (char-before beg1) '(?. ?<))
7995 (setq a (assoc (buffer-substring beg1 (point))
7996 org-structure-template-alist)))
7997 (org-complete-expand-structure-template (1- beg1) a)
7998 (throw 'exit t)))
7999 (tag (and (equal (char-before beg1) ?:)
8000 (equal (char-after (point-at-bol)) ?*)))
8001 (prop (and (equal (char-before beg1) ?:)
8002 (not (equal (char-after (point-at-bol)) ?*))))
8003 (texp (equal (char-before beg) ?\\))
8004 (link (equal (char-before beg) ?\[))
8005 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8006 beg)
8007 "#+"))
8008 (startup (string-match "^#\\+STARTUP:.*"
8009 (buffer-substring (point-at-bol) (point))))
8010 (completion-ignore-case opt)
8011 (type nil)
8012 (tbl nil)
8013 (table (cond
8014 (opt
8015 (setq type :opt)
8016 (require 'org-exp)
8017 (append
8018 (mapcar
8019 (lambda (x)
8020 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8021 (cons (match-string 2 x) (match-string 1 x)))
8022 (org-split-string (org-get-current-options) "\n"))
8023 (mapcar 'list org-additional-option-like-keywords)))
8024 (startup
8025 (setq type :startup)
8026 org-startup-options)
8027 (link (append org-link-abbrev-alist-local
8028 org-link-abbrev-alist))
8029 (texp
8030 (setq type :tex)
8031 org-html-entities)
8032 ((string-match "\\`\\*+[ \t]+\\'"
8033 (buffer-substring (point-at-bol) beg))
8034 (setq type :todo)
8035 (mapcar 'list org-todo-keywords-1))
8036 (searchhead
8037 (setq type :searchhead)
8038 (save-excursion
8039 (goto-char (point-min))
8040 (while (re-search-forward org-todo-line-regexp nil t)
8041 (push (list
8042 (org-make-org-heading-search-string
8043 (match-string 3) t))
8044 tbl)))
8045 tbl)
8046 (tag (setq type :tag beg beg1)
8047 (or org-tag-alist (org-get-buffer-tags)))
8048 (prop (setq type :prop beg beg1)
8049 (mapcar 'list (org-buffer-property-keys nil t t)))
8050 (t (progn
8051 (call-interactively org-completion-fallback-command)
8052 (throw 'exit nil)))))
8053 (pattern (buffer-substring-no-properties beg end))
8054 (completion (try-completion pattern table confirm)))
8055 (cond ((eq completion t)
8056 (if (not (assoc (upcase pattern) table))
8057 (message "Already complete")
8058 (if (and (equal type :opt)
8059 (not (member (car (assoc (upcase pattern) table))
8060 org-additional-option-like-keywords)))
8061 (insert (substring (cdr (assoc (upcase pattern) table))
8062 (length pattern)))
8063 (if (memq type '(:tag :prop)) (insert ":")))))
8064 ((null completion)
8065 (message "Can't find completion for \"%s\"" pattern)
8066 (ding))
8067 ((not (string= pattern completion))
8068 (delete-region beg end)
8069 (if (string-match " +$" completion)
8070 (setq completion (replace-match "" t t completion)))
8071 (insert completion)
8072 (if (get-buffer-window "*Completions*")
8073 (delete-window (get-buffer-window "*Completions*")))
8074 (if (assoc completion table)
8075 (if (eq type :todo) (insert " ")
8076 (if (memq type '(:tag :prop)) (insert ":"))))
8077 (if (and (equal type :opt) (assoc completion table))
8078 (message "%s" (substitute-command-keys
8079 "Press \\[org-complete] again to insert example settings"))))
8081 (message "Making completion list...")
8082 (let ((list (sort (all-completions pattern table confirm)
8083 'string<)))
8084 (with-output-to-temp-buffer "*Completions*"
8085 (condition-case nil
8086 ;; Protection needed for XEmacs and emacs 21
8087 (display-completion-list list pattern)
8088 (error (display-completion-list list)))))
8089 (message "Making completion list...%s" "done")))))))
8091 ;;;; TODO, DEADLINE, Comments
8093 (defun org-toggle-comment ()
8094 "Change the COMMENT state of an entry."
8095 (interactive)
8096 (save-excursion
8097 (org-back-to-heading)
8098 (let (case-fold-search)
8099 (if (looking-at (concat outline-regexp
8100 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8101 (replace-match "" t t nil 1)
8102 (if (looking-at outline-regexp)
8103 (progn
8104 (goto-char (match-end 0))
8105 (insert org-comment-string " ")))))))
8107 (defvar org-last-todo-state-is-todo nil
8108 "This is non-nil when the last TODO state change led to a TODO state.
8109 If the last change removed the TODO tag or switched to DONE, then
8110 this is nil.")
8112 (defvar org-setting-tags nil) ; dynamically skipped
8114 (defun org-parse-local-options (string var)
8115 "Parse STRING for startup setting relevant for variable VAR."
8116 (let ((rtn (symbol-value var))
8117 e opts)
8118 (save-match-data
8119 (if (or (not string) (not (string-match "\\S-" string)))
8121 (setq opts (delq nil (mapcar (lambda (x)
8122 (setq e (assoc x org-startup-options))
8123 (if (eq (nth 1 e) var) e nil))
8124 (org-split-string string "[ \t]+"))))
8125 (if (not opts)
8127 (setq rtn nil)
8128 (while (setq e (pop opts))
8129 (if (not (nth 3 e))
8130 (setq rtn (nth 2 e))
8131 (if (not (listp rtn)) (setq rtn nil))
8132 (push (nth 2 e) rtn)))
8133 rtn)))))
8135 (defvar org-blocker-hook nil
8136 "Hook for functions that are allowed to block a state change.
8138 Each function gets as its single argument a property list, see
8139 `org-trigger-hook' for more information about this list.
8141 If any of the functions in this hook returns nil, the state change
8142 is blocked.")
8144 (defvar org-trigger-hook nil
8145 "Hook for functions that are triggered by a state change.
8147 Each function gets as its single argument a property list with at least
8148 the following elements:
8150 (:type type-of-change :position pos-at-entry-start
8151 :from old-state :to new-state)
8153 Depending on the type, more properties may be present.
8155 This mechanism is currently implemented for:
8157 TODO state changes
8158 ------------------
8159 :type todo-state-change
8160 :from previous state (keyword as a string), or nil
8161 :to new state (keyword as a string), or nil")
8163 (defvar org-agenda-headline-snapshot-before-repeat)
8164 (defun org-todo (&optional arg)
8165 "Change the TODO state of an item.
8166 The state of an item is given by a keyword at the start of the heading,
8167 like
8168 *** TODO Write paper
8169 *** DONE Call mom
8171 The different keywords are specified in the variable `org-todo-keywords'.
8172 By default the available states are \"TODO\" and \"DONE\".
8173 So for this example: when the item starts with TODO, it is changed to DONE.
8174 When it starts with DONE, the DONE is removed. And when neither TODO nor
8175 DONE are present, add TODO at the beginning of the heading.
8177 With C-u prefix arg, use completion to determine the new state.
8178 With numeric prefix arg, switch to that state.
8180 For calling through lisp, arg is also interpreted in the following way:
8181 'none -> empty state
8182 \"\"(empty string) -> switch to empty state
8183 'done -> switch to DONE
8184 'nextset -> switch to the next set of keywords
8185 'previousset -> switch to the previous set of keywords
8186 \"WAITING\" -> switch to the specified keyword, but only if it
8187 really is a member of `org-todo-keywords'."
8188 (interactive "P")
8189 (save-excursion
8190 (catch 'exit
8191 (org-back-to-heading)
8192 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8193 (or (looking-at (concat " +" org-todo-regexp " *"))
8194 (looking-at " *"))
8195 (let* ((match-data (match-data))
8196 (startpos (point-at-bol))
8197 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8198 (org-log-done org-log-done)
8199 (org-log-repeat org-log-repeat)
8200 (org-todo-log-states org-todo-log-states)
8201 (this (match-string 1))
8202 (hl-pos (match-beginning 0))
8203 (head (org-get-todo-sequence-head this))
8204 (ass (assoc head org-todo-kwd-alist))
8205 (interpret (nth 1 ass))
8206 (done-word (nth 3 ass))
8207 (final-done-word (nth 4 ass))
8208 (last-state (or this ""))
8209 (completion-ignore-case t)
8210 (member (member this org-todo-keywords-1))
8211 (tail (cdr member))
8212 (state (cond
8213 ((and org-todo-key-trigger
8214 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8215 (and (not arg) org-use-fast-todo-selection
8216 (not (eq org-use-fast-todo-selection 'prefix)))))
8217 ;; Use fast selection
8218 (org-fast-todo-selection))
8219 ((and (equal arg '(4))
8220 (or (not org-use-fast-todo-selection)
8221 (not org-todo-key-trigger)))
8222 ;; Read a state with completion
8223 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8224 org-todo-keywords-1)
8225 nil t))
8226 ((eq arg 'right)
8227 (if this
8228 (if tail (car tail) nil)
8229 (car org-todo-keywords-1)))
8230 ((eq arg 'left)
8231 (if (equal member org-todo-keywords-1)
8233 (if this
8234 (nth (- (length org-todo-keywords-1) (length tail) 2)
8235 org-todo-keywords-1)
8236 (org-last org-todo-keywords-1))))
8237 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8238 (setq arg nil))) ; hack to fall back to cycling
8239 (arg
8240 ;; user or caller requests a specific state
8241 (cond
8242 ((equal arg "") nil)
8243 ((eq arg 'none) nil)
8244 ((eq arg 'done) (or done-word (car org-done-keywords)))
8245 ((eq arg 'nextset)
8246 (or (car (cdr (member head org-todo-heads)))
8247 (car org-todo-heads)))
8248 ((eq arg 'previousset)
8249 (let ((org-todo-heads (reverse org-todo-heads)))
8250 (or (car (cdr (member head org-todo-heads)))
8251 (car org-todo-heads))))
8252 ((car (member arg org-todo-keywords-1)))
8253 ((nth (1- (prefix-numeric-value arg))
8254 org-todo-keywords-1))))
8255 ((null member) (or head (car org-todo-keywords-1)))
8256 ((equal this final-done-word) nil) ;; -> make empty
8257 ((null tail) nil) ;; -> first entry
8258 ((eq interpret 'sequence)
8259 (car tail))
8260 ((memq interpret '(type priority))
8261 (if (eq this-command last-command)
8262 (car tail)
8263 (if (> (length tail) 0)
8264 (or done-word (car org-done-keywords))
8265 nil)))
8266 (t nil)))
8267 (next (if state (concat " " state " ") " "))
8268 (change-plist (list :type 'todo-state-change :from this :to state
8269 :position startpos))
8270 dolog now-done-p)
8271 (when org-blocker-hook
8272 (unless (save-excursion
8273 (save-match-data
8274 (run-hook-with-args-until-failure
8275 'org-blocker-hook change-plist)))
8276 (if (interactive-p)
8277 (error "TODO state change from %s to %s blocked" this state)
8278 ;; fail silently
8279 (message "TODO state change from %s to %s blocked" this state)
8280 (throw 'exit nil))))
8281 (store-match-data match-data)
8282 (replace-match next t t)
8283 (unless (pos-visible-in-window-p hl-pos)
8284 (message "TODO state changed to %s" (org-trim next)))
8285 (unless head
8286 (setq head (org-get-todo-sequence-head state)
8287 ass (assoc head org-todo-kwd-alist)
8288 interpret (nth 1 ass)
8289 done-word (nth 3 ass)
8290 final-done-word (nth 4 ass)))
8291 (when (memq arg '(nextset previousset))
8292 (message "Keyword-Set %d/%d: %s"
8293 (- (length org-todo-sets) -1
8294 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8295 (length org-todo-sets)
8296 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8297 (setq org-last-todo-state-is-todo
8298 (not (member state org-done-keywords)))
8299 (setq now-done-p (and (member state org-done-keywords)
8300 (not (member this org-done-keywords))))
8301 (and logging (org-local-logging logging))
8302 (when (and (or org-todo-log-states org-log-done)
8303 (not (memq arg '(nextset previousset))))
8304 ;; we need to look at recording a time and note
8305 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8306 (nth 2 (assoc this org-todo-log-states))))
8307 (when (and state
8308 (member state org-not-done-keywords)
8309 (not (member this org-not-done-keywords)))
8310 ;; This is now a todo state and was not one before
8311 ;; If there was a CLOSED time stamp, get rid of it.
8312 (org-add-planning-info nil nil 'closed))
8313 (when (and now-done-p org-log-done)
8314 ;; It is now done, and it was not done before
8315 (org-add-planning-info 'closed (org-current-time))
8316 (if (and (not dolog) (eq 'note org-log-done))
8317 (org-add-log-setup 'done state 'findpos 'note)))
8318 (when (and state dolog)
8319 ;; This is a non-nil state, and we need to log it
8320 (org-add-log-setup 'state state 'findpos dolog)))
8321 ;; Fixup tag positioning
8322 (org-todo-trigger-tag-changes state)
8323 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8324 (when org-provide-todo-statistics
8325 (org-update-parent-todo-statistics))
8326 (run-hooks 'org-after-todo-state-change-hook)
8327 (if (and arg (not (member state org-done-keywords)))
8328 (setq head (org-get-todo-sequence-head state)))
8329 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8330 ;; Do we need to trigger a repeat?
8331 (when now-done-p
8332 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8333 ;; This is for the agenda, take a snapshot of the headline.
8334 (save-match-data
8335 (setq org-agenda-headline-snapshot-before-repeat
8336 (org-get-heading))))
8337 (org-auto-repeat-maybe state))
8338 ;; Fixup cursor location if close to the keyword
8339 (if (and (outline-on-heading-p)
8340 (not (bolp))
8341 (save-excursion (beginning-of-line 1)
8342 (looking-at org-todo-line-regexp))
8343 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8344 (progn
8345 (goto-char (or (match-end 2) (match-end 1)))
8346 (just-one-space)))
8347 (when org-trigger-hook
8348 (save-excursion
8349 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8351 (defun org-update-parent-todo-statistics ()
8352 "Update any statistics cookie in the parent of the current headline."
8353 (interactive)
8354 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8355 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8356 (catch 'exit
8357 (save-excursion
8358 (setq level (org-up-heading-safe))
8359 (unless (and level
8360 (re-search-forward box-re (point-at-eol) t))
8361 (throw 'exit nil))
8362 (setq is-percent (match-end 2))
8363 (save-match-data
8364 (unless (outline-next-heading) (throw 'exit nil))
8365 (while (looking-at org-todo-line-regexp)
8366 (setq kwd (match-string 2))
8367 (and kwd (setq cnt-all (1+ cnt-all)))
8368 (and (member kwd org-done-keywords)
8369 (setq cnt-done (1+ cnt-done)))
8370 (condition-case nil
8371 (org-forward-same-level 1)
8372 (error (end-of-line 1)))))
8373 (replace-match
8374 (if is-percent
8375 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8376 (format "[%d/%d]" cnt-done cnt-all)))
8377 (run-hook-with-args 'org-after-todo-statistics-hook
8378 cnt-done (- cnt-all cnt-done))))))
8380 (defvar org-after-todo-statistics-hook nil
8381 "Hook that is called after a TODO statistics cookie has been updated.
8382 Each function is called with two arguments: the number of not-done entries
8383 and the number of done entries.
8385 For example, the following function, when added to this hook, will switch
8386 an entry to DONE when all children are done, and back to TODO when new
8387 entries are set to a TODO status. Note that this hook is only called
8388 when there is a statistics cookie in the headline!
8390 (defun org-summary-todo (n-done n-not-done)
8391 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8392 (let (org-log-done org-log-states) ; turn off logging
8393 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8396 (defun org-todo-trigger-tag-changes (state)
8397 "Apply the changes defined in `org-todo-state-tags-triggers'."
8398 (let ((l org-todo-state-tags-triggers)
8399 changes)
8400 (when (or (not state) (equal state ""))
8401 (setq changes (append changes (cdr (assoc "" l)))))
8402 (when (and (stringp state) (> (length state) 0))
8403 (setq changes (append changes (cdr (assoc state l)))))
8404 (when (member state org-not-done-keywords)
8405 (setq changes (append changes (cdr (assoc 'todo l)))))
8406 (when (member state org-done-keywords)
8407 (setq changes (append changes (cdr (assoc 'done l)))))
8408 (dolist (c changes)
8409 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8411 (defun org-local-logging (value)
8412 "Get logging settings from a property VALUE."
8413 (let* (words w a)
8414 ;; directly set the variables, they are already local.
8415 (setq org-log-done nil
8416 org-log-repeat nil
8417 org-todo-log-states nil)
8418 (setq words (org-split-string value))
8419 (while (setq w (pop words))
8420 (cond
8421 ((setq a (assoc w org-startup-options))
8422 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8423 (set (nth 1 a) (nth 2 a))))
8424 ((setq a (org-extract-log-state-settings w))
8425 (and (member (car a) org-todo-keywords-1)
8426 (push a org-todo-log-states)))))))
8428 (defun org-get-todo-sequence-head (kwd)
8429 "Return the head of the TODO sequence to which KWD belongs.
8430 If KWD is not set, check if there is a text property remembering the
8431 right sequence."
8432 (let (p)
8433 (cond
8434 ((not kwd)
8435 (or (get-text-property (point-at-bol) 'org-todo-head)
8436 (progn
8437 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8438 nil (point-at-eol)))
8439 (get-text-property p 'org-todo-head))))
8440 ((not (member kwd org-todo-keywords-1))
8441 (car org-todo-keywords-1))
8442 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8444 (defun org-fast-todo-selection ()
8445 "Fast TODO keyword selection with single keys.
8446 Returns the new TODO keyword, or nil if no state change should occur."
8447 (let* ((fulltable org-todo-key-alist)
8448 (done-keywords org-done-keywords) ;; needed for the faces.
8449 (maxlen (apply 'max (mapcar
8450 (lambda (x)
8451 (if (stringp (car x)) (string-width (car x)) 0))
8452 fulltable)))
8453 (expert nil)
8454 (fwidth (+ maxlen 3 1 3))
8455 (ncol (/ (- (window-width) 4) fwidth))
8456 tg cnt e c tbl
8457 groups ingroup)
8458 (save-window-excursion
8459 (if expert
8460 (set-buffer (get-buffer-create " *Org todo*"))
8461 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8462 (erase-buffer)
8463 (org-set-local 'org-done-keywords done-keywords)
8464 (setq tbl fulltable cnt 0)
8465 (while (setq e (pop tbl))
8466 (cond
8467 ((equal e '(:startgroup))
8468 (push '() groups) (setq ingroup t)
8469 (when (not (= cnt 0))
8470 (setq cnt 0)
8471 (insert "\n"))
8472 (insert "{ "))
8473 ((equal e '(:endgroup))
8474 (setq ingroup nil cnt 0)
8475 (insert "}\n"))
8477 (setq tg (car e) c (cdr e))
8478 (if ingroup (push tg (car groups)))
8479 (setq tg (org-add-props tg nil 'face
8480 (org-get-todo-face tg)))
8481 (if (and (= cnt 0) (not ingroup)) (insert " "))
8482 (insert "[" c "] " tg (make-string
8483 (- fwidth 4 (length tg)) ?\ ))
8484 (when (= (setq cnt (1+ cnt)) ncol)
8485 (insert "\n")
8486 (if ingroup (insert " "))
8487 (setq cnt 0)))))
8488 (insert "\n")
8489 (goto-char (point-min))
8490 (if (not expert) (org-fit-window-to-buffer))
8491 (message "[a-z..]:Set [SPC]:clear")
8492 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8493 (cond
8494 ((or (= c ?\C-g)
8495 (and (= c ?q) (not (rassoc c fulltable))))
8496 (setq quit-flag t))
8497 ((= c ?\ ) nil)
8498 ((setq e (rassoc c fulltable) tg (car e))
8500 (t (setq quit-flag t))))))
8502 (defun org-entry-is-todo-p ()
8503 (member (org-get-todo-state) org-not-done-keywords))
8505 (defun org-entry-is-done-p ()
8506 (member (org-get-todo-state) org-done-keywords))
8508 (defun org-get-todo-state ()
8509 (save-excursion
8510 (org-back-to-heading t)
8511 (and (looking-at org-todo-line-regexp)
8512 (match-end 2)
8513 (match-string 2))))
8515 (defun org-at-date-range-p (&optional inactive-ok)
8516 "Is the cursor inside a date range?"
8517 (interactive)
8518 (save-excursion
8519 (catch 'exit
8520 (let ((pos (point)))
8521 (skip-chars-backward "^[<\r\n")
8522 (skip-chars-backward "<[")
8523 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8524 (>= (match-end 0) pos)
8525 (throw 'exit t))
8526 (skip-chars-backward "^<[\r\n")
8527 (skip-chars-backward "<[")
8528 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8529 (>= (match-end 0) pos)
8530 (throw 'exit t)))
8531 nil)))
8533 (defun org-get-repeat ()
8534 "Check if there is a deadline/schedule with repeater in this entry."
8535 (save-match-data
8536 (save-excursion
8537 (org-back-to-heading t)
8538 (if (re-search-forward
8539 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8540 (match-string 1)))))
8542 (defvar org-last-changed-timestamp)
8543 (defvar org-last-inserted-timestamp)
8544 (defvar org-log-post-message)
8545 (defvar org-log-note-purpose)
8546 (defvar org-log-note-how)
8547 (defvar org-log-note-extra)
8548 (defun org-auto-repeat-maybe (done-word)
8549 "Check if the current headline contains a repeated deadline/schedule.
8550 If yes, set TODO state back to what it was and change the base date
8551 of repeating deadline/scheduled time stamps to new date.
8552 This function is run automatically after each state change to a DONE state."
8553 ;; last-state is dynamically scoped into this function
8554 (let* ((repeat (org-get-repeat))
8555 (aa (assoc last-state org-todo-kwd-alist))
8556 (interpret (nth 1 aa))
8557 (head (nth 2 aa))
8558 (whata '(("d" . day) ("m" . month) ("y" . year)))
8559 (msg "Entry repeats: ")
8560 (org-log-done nil)
8561 (org-todo-log-states nil)
8562 (nshiftmax 10) (nshift 0)
8563 re type n what ts mb0 time)
8564 (when repeat
8565 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8566 (org-todo (if (eq interpret 'type) last-state head))
8567 (when org-log-repeat
8568 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8569 (memq 'org-add-log-note post-command-hook))
8570 ;; OK, we are already setup for some record
8571 (if (eq org-log-repeat 'note)
8572 ;; make sure we take a note, not only a time stamp
8573 (setq org-log-note-how 'note))
8574 ;; Set up for taking a record
8575 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8576 'findpos org-log-repeat)))
8577 (org-back-to-heading t)
8578 (org-add-planning-info nil nil 'closed)
8579 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8580 org-deadline-time-regexp "\\)\\|\\("
8581 org-ts-regexp "\\)"))
8582 (while (re-search-forward
8583 re (save-excursion (outline-next-heading) (point)) t)
8584 (setq type (if (match-end 1) org-scheduled-string
8585 (if (match-end 3) org-deadline-string "Plain:"))
8586 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8587 mb0 (match-beginning 0))
8588 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8589 (setq n (string-to-number (match-string 2 ts))
8590 what (match-string 3 ts))
8591 (if (equal what "w") (setq n (* n 7) what "d"))
8592 ;; Preparation, see if we need to modify the start date for the change
8593 (when (match-end 1)
8594 (setq time (save-match-data (org-time-string-to-time ts)))
8595 (cond
8596 ((equal (match-string 1 ts) ".")
8597 ;; Shift starting date to today
8598 (org-timestamp-change
8599 (- (time-to-days (current-time)) (time-to-days time))
8600 'day))
8601 ((equal (match-string 1 ts) "+")
8602 (while (or (= nshift 0)
8603 (<= (time-to-days time) (time-to-days (current-time))))
8604 (when (= (incf nshift) nshiftmax)
8605 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8606 (error "Abort")))
8607 (org-timestamp-change n (cdr (assoc what whata)))
8608 (org-at-timestamp-p t)
8609 (setq ts (match-string 1))
8610 (setq time (save-match-data (org-time-string-to-time ts))))
8611 (org-timestamp-change (- n) (cdr (assoc what whata)))
8612 ;; rematch, so that we have everything in place for the real shift
8613 (org-at-timestamp-p t)
8614 (setq ts (match-string 1))
8615 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8616 (org-timestamp-change n (cdr (assoc what whata)))
8617 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8618 (setq org-log-post-message msg)
8619 (message "%s" msg))))
8621 (defun org-show-todo-tree (arg)
8622 "Make a compact tree which shows all headlines marked with TODO.
8623 The tree will show the lines where the regexp matches, and all higher
8624 headlines above the match.
8625 With a \\[universal-argument] prefix, also show the DONE entries.
8626 With a numeric prefix N, construct a sparse tree for the Nth element
8627 of `org-todo-keywords-1'."
8628 (interactive "P")
8629 (let ((case-fold-search nil)
8630 (kwd-re
8631 (cond ((null arg) org-not-done-regexp)
8632 ((equal arg '(4))
8633 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8634 (mapcar 'list org-todo-keywords-1))))
8635 (concat "\\("
8636 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8637 "\\)\\>")))
8638 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8639 (regexp-quote (nth (1- (prefix-numeric-value arg))
8640 org-todo-keywords-1)))
8641 (t (error "Invalid prefix argument: %s" arg)))))
8642 (message "%d TODO entries found"
8643 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8645 (defun org-deadline (&optional remove time)
8646 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8647 With argument REMOVE, remove any deadline from the item.
8648 When TIME is set, it should be an internal time specification, and the
8649 scheduling will use the corresponding date."
8650 (interactive "P")
8651 (if remove
8652 (progn
8653 (org-remove-timestamp-with-keyword org-deadline-string)
8654 (message "Item no longer has a deadline."))
8655 (if (org-get-repeat)
8656 (error "Cannot change deadline on task with repeater, please do that by hand")
8657 (org-add-planning-info 'deadline time 'closed)
8658 (message "Deadline on %s" org-last-inserted-timestamp))))
8660 (defun org-schedule (&optional remove time)
8661 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8662 With argument REMOVE, remove any scheduling date from the item.
8663 When TIME is set, it should be an internal time specification, and the
8664 scheduling will use the corresponding date."
8665 (interactive "P")
8666 (if remove
8667 (progn
8668 (org-remove-timestamp-with-keyword org-scheduled-string)
8669 (message "Item is no longer scheduled."))
8670 (if (org-get-repeat)
8671 (error "Cannot reschedule task with repeater, please do that by hand")
8672 (org-add-planning-info 'scheduled time 'closed)
8673 (message "Scheduled to %s" org-last-inserted-timestamp))))
8675 (defun org-remove-timestamp-with-keyword (keyword)
8676 "Remove all time stamps with KEYWORD in the current entry."
8677 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8678 beg)
8679 (save-excursion
8680 (org-back-to-heading t)
8681 (setq beg (point))
8682 (org-end-of-subtree t t)
8683 (while (re-search-backward re beg t)
8684 (replace-match "")
8685 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8686 (equal (char-before) ?\ ))
8687 (backward-delete-char 1)
8688 (if (string-match "^[ \t]*$" (buffer-substring
8689 (point-at-bol) (point-at-eol)))
8690 (delete-region (point-at-bol)
8691 (min (point-max) (1+ (point-at-eol))))))))))
8693 (defun org-add-planning-info (what &optional time &rest remove)
8694 "Insert new timestamp with keyword in the line directly after the headline.
8695 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8696 If non is given, the user is prompted for a date.
8697 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8698 be removed."
8699 (interactive)
8700 (let (org-time-was-given org-end-time-was-given ts
8701 end default-time default-input)
8703 (when (and (not time) (memq what '(scheduled deadline)))
8704 ;; Try to get a default date/time from existing timestamp
8705 (save-excursion
8706 (org-back-to-heading t)
8707 (setq end (save-excursion (outline-next-heading) (point)))
8708 (when (re-search-forward (if (eq what 'scheduled)
8709 org-scheduled-time-regexp
8710 org-deadline-time-regexp)
8711 end t)
8712 (setq ts (match-string 1)
8713 default-time
8714 (apply 'encode-time (org-parse-time-string ts))
8715 default-input (and ts (org-get-compact-tod ts))))))
8716 (when what
8717 ;; If necessary, get the time from the user
8718 (setq time (or time (org-read-date nil 'to-time nil nil
8719 default-time default-input))))
8721 (when (and org-insert-labeled-timestamps-at-point
8722 (member what '(scheduled deadline)))
8723 (insert
8724 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8725 (org-insert-time-stamp time org-time-was-given
8726 nil nil nil (list org-end-time-was-given))
8727 (setq what nil))
8728 (save-excursion
8729 (save-restriction
8730 (let (col list elt ts buffer-invisibility-spec)
8731 (org-back-to-heading t)
8732 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8733 (goto-char (match-end 1))
8734 (setq col (current-column))
8735 (goto-char (match-end 0))
8736 (if (eobp) (insert "\n") (forward-char 1))
8737 (if (and (not (looking-at outline-regexp))
8738 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8739 "[^\r\n]*"))
8740 (not (equal (match-string 1) org-clock-string)))
8741 (narrow-to-region (match-beginning 0) (match-end 0))
8742 (insert-before-markers "\n")
8743 (backward-char 1)
8744 (narrow-to-region (point) (point))
8745 (and org-adapt-indentation (org-indent-to-column col)))
8746 ;; Check if we have to remove something.
8747 (setq list (cons what remove))
8748 (while list
8749 (setq elt (pop list))
8750 (goto-char (point-min))
8751 (when (or (and (eq elt 'scheduled)
8752 (re-search-forward org-scheduled-time-regexp nil t))
8753 (and (eq elt 'deadline)
8754 (re-search-forward org-deadline-time-regexp nil t))
8755 (and (eq elt 'closed)
8756 (re-search-forward org-closed-time-regexp nil t)))
8757 (replace-match "")
8758 (if (looking-at "--+<[^>]+>") (replace-match ""))
8759 (if (looking-at " +") (replace-match ""))))
8760 (goto-char (point-max))
8761 (when what
8762 (insert
8763 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8764 (cond ((eq what 'scheduled) org-scheduled-string)
8765 ((eq what 'deadline) org-deadline-string)
8766 ((eq what 'closed) org-closed-string))
8767 " ")
8768 (setq ts (org-insert-time-stamp
8769 time
8770 (or org-time-was-given
8771 (and (eq what 'closed) org-log-done-with-time))
8772 (eq what 'closed)
8773 nil nil (list org-end-time-was-given)))
8774 (end-of-line 1))
8775 (goto-char (point-min))
8776 (widen)
8777 (if (and (looking-at "[ \t]+\n")
8778 (equal (char-before) ?\n))
8779 (delete-region (1- (point)) (point-at-eol)))
8780 ts)))))
8782 (defvar org-log-note-marker (make-marker))
8783 (defvar org-log-note-purpose nil)
8784 (defvar org-log-note-state nil)
8785 (defvar org-log-note-how nil)
8786 (defvar org-log-note-extra nil)
8787 (defvar org-log-note-window-configuration nil)
8788 (defvar org-log-note-return-to (make-marker))
8789 (defvar org-log-post-message nil
8790 "Message to be displayed after a log note has been stored.
8791 The auto-repeater uses this.")
8793 (defun org-add-note ()
8794 "Add a note to the current entry.
8795 This is done in the same way as adding a state change note."
8796 (interactive)
8797 (org-add-log-setup 'note nil 'findpos nil))
8799 (defvar org-property-end-re)
8800 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8801 "Set up the post command hook to take a note.
8802 If this is about to TODO state change, the new state is expected in STATE.
8803 When FINDPOS is non-nil, find the correct position for the note in
8804 the current entry. If not, assume that it can be inserted at point.
8805 HOW is an indicator what kind of note should be created.
8806 EXTRA is additional text that will be inserted into the notes buffer."
8807 (save-restriction
8808 (save-excursion
8809 (when findpos
8810 (org-back-to-heading t)
8811 (narrow-to-region (point) (save-excursion
8812 (outline-next-heading) (point)))
8813 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8814 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8815 "[^\r\n]*\\)?"))
8816 (goto-char (match-end 0))
8817 (when (and org-log-state-notes-insert-after-drawers
8818 (save-excursion
8819 (forward-line) (looking-at org-drawer-regexp)))
8820 (progn (forward-line)
8821 (while (looking-at org-drawer-regexp)
8822 (goto-char (match-end 0))
8823 (re-search-forward org-property-end-re (point-max) t)
8824 (forward-line))
8825 (forward-line -1)))
8826 (unless org-log-states-order-reversed
8827 (and (= (char-after) ?\n) (forward-char 1))
8828 (org-skip-over-state-notes)
8829 (skip-chars-backward " \t\n\r")))
8830 (move-marker org-log-note-marker (point))
8831 (setq org-log-note-purpose purpose
8832 org-log-note-state state
8833 org-log-note-how how
8834 org-log-note-extra extra)
8835 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8837 (defun org-skip-over-state-notes ()
8838 "Skip past the list of State notes in an entry."
8839 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8840 (while (looking-at "[ \t]*- State")
8841 (condition-case nil
8842 (org-next-item)
8843 (error (org-end-of-item)))))
8845 (defun org-add-log-note (&optional purpose)
8846 "Pop up a window for taking a note, and add this note later at point."
8847 (remove-hook 'post-command-hook 'org-add-log-note)
8848 (setq org-log-note-window-configuration (current-window-configuration))
8849 (delete-other-windows)
8850 (move-marker org-log-note-return-to (point))
8851 (switch-to-buffer (marker-buffer org-log-note-marker))
8852 (goto-char org-log-note-marker)
8853 (org-switch-to-buffer-other-window "*Org Note*")
8854 (erase-buffer)
8855 (if (memq org-log-note-how '(time state))
8856 (let (current-prefix-arg) (org-store-log-note))
8857 (let ((org-inhibit-startup t)) (org-mode))
8858 (insert (format "# Insert note for %s.
8859 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8860 (cond
8861 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8862 ((eq org-log-note-purpose 'done) "closed todo item")
8863 ((eq org-log-note-purpose 'state)
8864 (format "state change to \"%s\"" org-log-note-state))
8865 ((eq org-log-note-purpose 'note)
8866 "this entry")
8867 (t (error "This should not happen")))))
8868 (if org-log-note-extra (insert org-log-note-extra))
8869 (org-set-local 'org-finish-function 'org-store-log-note)))
8871 (defvar org-note-abort nil) ; dynamically scoped
8872 (defun org-store-log-note ()
8873 "Finish taking a log note, and insert it to where it belongs."
8874 (let ((txt (buffer-string))
8875 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8876 lines ind)
8877 (kill-buffer (current-buffer))
8878 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8879 (setq txt (replace-match "" t t txt)))
8880 (if (string-match "\\s-+\\'" txt)
8881 (setq txt (replace-match "" t t txt)))
8882 (setq lines (org-split-string txt "\n"))
8883 (when (and note (string-match "\\S-" note))
8884 (setq note
8885 (org-replace-escapes
8886 note
8887 (list (cons "%u" (user-login-name))
8888 (cons "%U" user-full-name)
8889 (cons "%t" (format-time-string
8890 (org-time-stamp-format 'long 'inactive)
8891 (current-time)))
8892 (cons "%s" (if org-log-note-state
8893 (concat "\"" org-log-note-state "\"")
8894 "")))))
8895 (if lines (setq note (concat note " \\\\")))
8896 (push note lines))
8897 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8898 (when lines
8899 (save-excursion
8900 (set-buffer (marker-buffer org-log-note-marker))
8901 (save-excursion
8902 (goto-char org-log-note-marker)
8903 (move-marker org-log-note-marker nil)
8904 (end-of-line 1)
8905 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8906 (indent-relative nil)
8907 (insert "- " (pop lines))
8908 (org-indent-line-function)
8909 (beginning-of-line 1)
8910 (looking-at "[ \t]*")
8911 (setq ind (concat (match-string 0) " "))
8912 (end-of-line 1)
8913 (while lines (insert "\n" ind (pop lines)))))))
8914 (set-window-configuration org-log-note-window-configuration)
8915 (with-current-buffer (marker-buffer org-log-note-return-to)
8916 (goto-char org-log-note-return-to))
8917 (move-marker org-log-note-return-to nil)
8918 (and org-log-post-message (message "%s" org-log-post-message)))
8920 (defun org-sparse-tree (&optional arg)
8921 "Create a sparse tree, prompt for the details.
8922 This command can create sparse trees. You first need to select the type
8923 of match used to create the tree:
8925 t Show entries with a specific TODO keyword.
8926 T Show entries selected by a tags match.
8927 p Enter a property name and its value (both with completion on existing
8928 names/values) and show entries with that property.
8929 r Show entries matching a regular expression
8930 d Show deadlines due within `org-deadline-warning-days'."
8931 (interactive "P")
8932 (let (ans kwd value)
8933 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8934 (setq ans (read-char-exclusive))
8935 (cond
8936 ((equal ans ?d)
8937 (call-interactively 'org-check-deadlines))
8938 ((equal ans ?b)
8939 (call-interactively 'org-check-before-date))
8940 ((equal ans ?t)
8941 (org-show-todo-tree '(4)))
8942 ((equal ans ?T)
8943 (call-interactively 'org-tags-sparse-tree))
8944 ((member ans '(?p ?P))
8945 (setq kwd (org-ido-completing-read "Property: "
8946 (mapcar 'list (org-buffer-property-keys))))
8947 (setq value (org-ido-completing-read "Value: "
8948 (mapcar 'list (org-property-values kwd))))
8949 (unless (string-match "\\`{.*}\\'" value)
8950 (setq value (concat "\"" value "\"")))
8951 (org-tags-sparse-tree arg (concat kwd "=" value)))
8952 ((member ans '(?r ?R ?/))
8953 (call-interactively 'org-occur))
8954 (t (error "No such sparse tree command \"%c\"" ans)))))
8956 (defvar org-occur-highlights nil
8957 "List of overlays used for occur matches.")
8958 (make-variable-buffer-local 'org-occur-highlights)
8959 (defvar org-occur-parameters nil
8960 "Parameters of the active org-occur calls.
8961 This is a list, each call to org-occur pushes as cons cell,
8962 containing the regular expression and the callback, onto the list.
8963 The list can contain several entries if `org-occur' has been called
8964 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8965 will only contain one set of parameters. When the highlights are
8966 removed (for example with `C-c C-c', or with the next edit (depending
8967 on `org-remove-highlights-with-change'), this variable is emptied
8968 as well.")
8969 (make-variable-buffer-local 'org-occur-parameters)
8971 (defun org-occur (regexp &optional keep-previous callback)
8972 "Make a compact tree which shows all matches of REGEXP.
8973 The tree will show the lines where the regexp matches, and all higher
8974 headlines above the match. It will also show the heading after the match,
8975 to make sure editing the matching entry is easy.
8976 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8977 call to `org-occur' will be kept, to allow stacking of calls to this
8978 command.
8979 If CALLBACK is non-nil, it is a function which is called to confirm
8980 that the match should indeed be shown."
8981 (interactive "sRegexp: \nP")
8982 (unless keep-previous
8983 (org-remove-occur-highlights nil nil t))
8984 (push (cons regexp callback) org-occur-parameters)
8985 (let ((cnt 0))
8986 (save-excursion
8987 (goto-char (point-min))
8988 (if (or (not keep-previous) ; do not want to keep
8989 (not org-occur-highlights)) ; no previous matches
8990 ;; hide everything
8991 (org-overview))
8992 (while (re-search-forward regexp nil t)
8993 (when (or (not callback)
8994 (save-match-data (funcall callback)))
8995 (setq cnt (1+ cnt))
8996 (when org-highlight-sparse-tree-matches
8997 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8998 (org-show-context 'occur-tree))))
8999 (when org-remove-highlights-with-change
9000 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9001 nil 'local))
9002 (unless org-sparse-tree-open-archived-trees
9003 (org-hide-archived-subtrees (point-min) (point-max)))
9004 (run-hooks 'org-occur-hook)
9005 (if (interactive-p)
9006 (message "%d match(es) for regexp %s" cnt regexp))
9007 cnt))
9009 (defun org-show-context (&optional key)
9010 "Make sure point and context and visible.
9011 How much context is shown depends upon the variables
9012 `org-show-hierarchy-above', `org-show-following-heading'. and
9013 `org-show-siblings'."
9014 (let ((heading-p (org-on-heading-p t))
9015 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9016 (following-p (org-get-alist-option org-show-following-heading key))
9017 (entry-p (org-get-alist-option org-show-entry-below key))
9018 (siblings-p (org-get-alist-option org-show-siblings key)))
9019 (catch 'exit
9020 ;; Show heading or entry text
9021 (if (and heading-p (not entry-p))
9022 (org-flag-heading nil) ; only show the heading
9023 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9024 (org-show-hidden-entry))) ; show entire entry
9025 (when following-p
9026 ;; Show next sibling, or heading below text
9027 (save-excursion
9028 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9029 (org-flag-heading nil))))
9030 (when siblings-p (org-show-siblings))
9031 (when hierarchy-p
9032 ;; show all higher headings, possibly with siblings
9033 (save-excursion
9034 (while (and (condition-case nil
9035 (progn (org-up-heading-all 1) t)
9036 (error nil))
9037 (not (bobp)))
9038 (org-flag-heading nil)
9039 (when siblings-p (org-show-siblings))))))))
9041 (defun org-reveal (&optional siblings)
9042 "Show current entry, hierarchy above it, and the following headline.
9043 This can be used to show a consistent set of context around locations
9044 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9045 not t for the search context.
9047 With optional argument SIBLINGS, on each level of the hierarchy all
9048 siblings are shown. This repairs the tree structure to what it would
9049 look like when opened with hierarchical calls to `org-cycle'."
9050 (interactive "P")
9051 (let ((org-show-hierarchy-above t)
9052 (org-show-following-heading t)
9053 (org-show-siblings (if siblings t org-show-siblings)))
9054 (org-show-context nil)))
9056 (defun org-highlight-new-match (beg end)
9057 "Highlight from BEG to END and mark the highlight is an occur headline."
9058 (let ((ov (org-make-overlay beg end)))
9059 (org-overlay-put ov 'face 'secondary-selection)
9060 (push ov org-occur-highlights)))
9062 (defun org-remove-occur-highlights (&optional beg end noremove)
9063 "Remove the occur highlights from the buffer.
9064 BEG and END are ignored. If NOREMOVE is nil, remove this function
9065 from the `before-change-functions' in the current buffer."
9066 (interactive)
9067 (unless org-inhibit-highlight-removal
9068 (mapc 'org-delete-overlay org-occur-highlights)
9069 (setq org-occur-highlights nil)
9070 (setq org-occur-parameters nil)
9071 (unless noremove
9072 (remove-hook 'before-change-functions
9073 'org-remove-occur-highlights 'local))))
9075 ;;;; Priorities
9077 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9078 "Regular expression matching the priority indicator.")
9080 (defvar org-remove-priority-next-time nil)
9082 (defun org-priority-up ()
9083 "Increase the priority of the current item."
9084 (interactive)
9085 (org-priority 'up))
9087 (defun org-priority-down ()
9088 "Decrease the priority of the current item."
9089 (interactive)
9090 (org-priority 'down))
9092 (defun org-priority (&optional action)
9093 "Change the priority of an item by ARG.
9094 ACTION can be `set', `up', `down', or a character."
9095 (interactive)
9096 (setq action (or action 'set))
9097 (let (current new news have remove)
9098 (save-excursion
9099 (org-back-to-heading)
9100 (if (looking-at org-priority-regexp)
9101 (setq current (string-to-char (match-string 2))
9102 have t)
9103 (setq current org-default-priority))
9104 (cond
9105 ((or (eq action 'set)
9106 (if (featurep 'xemacs) (characterp action) (integerp action)))
9107 (if (not (eq action 'set))
9108 (setq new action)
9109 (message "Priority %c-%c, SPC to remove: "
9110 org-highest-priority org-lowest-priority)
9111 (setq new (read-char-exclusive)))
9112 (if (and (= (upcase org-highest-priority) org-highest-priority)
9113 (= (upcase org-lowest-priority) org-lowest-priority))
9114 (setq new (upcase new)))
9115 (cond ((equal new ?\ ) (setq remove t))
9116 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9117 (error "Priority must be between `%c' and `%c'"
9118 org-highest-priority org-lowest-priority))))
9119 ((eq action 'up)
9120 (if (and (not have) (eq last-command this-command))
9121 (setq new org-lowest-priority)
9122 (setq new (if (and org-priority-start-cycle-with-default (not have))
9123 org-default-priority (1- current)))))
9124 ((eq action 'down)
9125 (if (and (not have) (eq last-command this-command))
9126 (setq new org-highest-priority)
9127 (setq new (if (and org-priority-start-cycle-with-default (not have))
9128 org-default-priority (1+ current)))))
9129 (t (error "Invalid action")))
9130 (if (or (< (upcase new) org-highest-priority)
9131 (> (upcase new) org-lowest-priority))
9132 (setq remove t))
9133 (setq news (format "%c" new))
9134 (if have
9135 (if remove
9136 (replace-match "" t t nil 1)
9137 (replace-match news t t nil 2))
9138 (if remove
9139 (error "No priority cookie found in line")
9140 (looking-at org-todo-line-regexp)
9141 (if (match-end 2)
9142 (progn
9143 (goto-char (match-end 2))
9144 (insert " [#" news "]"))
9145 (goto-char (match-beginning 3))
9146 (insert "[#" news "] ")))))
9147 (org-preserve-lc (org-set-tags nil 'align))
9148 (if remove
9149 (message "Priority removed")
9150 (message "Priority of current item set to %s" news))))
9153 (defun org-get-priority (s)
9154 "Find priority cookie and return priority."
9155 (save-match-data
9156 (if (not (string-match org-priority-regexp s))
9157 (* 1000 (- org-lowest-priority org-default-priority))
9158 (* 1000 (- org-lowest-priority
9159 (string-to-char (match-string 2 s)))))))
9161 ;;;; Tags
9163 (defvar org-agenda-archives-mode)
9164 (defun org-scan-tags (action matcher &optional todo-only)
9165 "Scan headline tags with inheritance and produce output ACTION.
9167 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9168 or `agenda' to produce an entry list for an agenda view. It can also be
9169 a Lisp form or a function that should be called at each matched headline, in
9170 this case the return value is a list of all return values from these calls.
9172 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9173 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9174 only lines with a TODO keyword are included in the output."
9175 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9176 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9177 (org-re
9178 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9179 (props (list 'face 'default
9180 'done-face 'org-done
9181 'undone-face 'default
9182 'mouse-face 'highlight
9183 'org-not-done-regexp org-not-done-regexp
9184 'org-todo-regexp org-todo-regexp
9185 'keymap org-agenda-keymap
9186 'help-echo
9187 (format "mouse-2 or RET jump to org file %s"
9188 (abbreviate-file-name
9189 (or (buffer-file-name (buffer-base-buffer))
9190 (buffer-name (buffer-base-buffer)))))))
9191 (case-fold-search nil)
9192 lspos tags tags-list
9193 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9194 (llast 0) rtn rtn1 level category i txt
9195 todo marker entry priority)
9196 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9197 (setq action (list 'lambda nil action)))
9198 (save-excursion
9199 (goto-char (point-min))
9200 (when (eq action 'sparse-tree)
9201 (org-overview)
9202 (org-remove-occur-highlights))
9203 (while (re-search-forward re nil t)
9204 (catch :skip
9205 (setq todo (if (match-end 1) (match-string 2))
9206 tags (if (match-end 4) (match-string 4)))
9207 (goto-char (setq lspos (1+ (match-beginning 0))))
9208 (setq level (org-reduced-level (funcall outline-level))
9209 category (org-get-category))
9210 (setq i llast llast level)
9211 ;; remove tag lists from same and sublevels
9212 (while (>= i level)
9213 (when (setq entry (assoc i tags-alist))
9214 (setq tags-alist (delete entry tags-alist)))
9215 (setq i (1- i)))
9216 ;; add the next tags
9217 (when tags
9218 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9219 tags-alist
9220 (cons (cons level tags) tags-alist)))
9221 ;; compile tags for current headline
9222 (setq tags-list
9223 (if org-use-tag-inheritance
9224 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9225 tags))
9226 (when org-use-tag-inheritance
9227 (setcdr (car tags-alist)
9228 (mapcar (lambda (x)
9229 (setq x (copy-sequence x))
9230 (org-add-prop-inherited x))
9231 (cdar tags-alist))))
9232 (when (and tags org-use-tag-inheritance
9233 (not (eq t org-use-tag-inheritance)))
9234 ;; selective inheritance, remove uninherited ones
9235 (setcdr (car tags-alist)
9236 (org-remove-uniherited-tags (cdar tags-alist))))
9237 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9238 (let ((case-fold-search t)) (eval matcher))
9240 (not (member org-archive-tag tags-list))
9241 ;; we have an archive tag, should we use this anyway?
9242 (or (not org-agenda-skip-archived-trees)
9243 (and (eq action 'agenda) org-agenda-archives-mode))))
9244 (unless (eq action 'sparse-tree) (org-agenda-skip))
9246 ;; select this headline
9248 (cond
9249 ((eq action 'sparse-tree)
9250 (and org-highlight-sparse-tree-matches
9251 (org-get-heading) (match-end 0)
9252 (org-highlight-new-match
9253 (match-beginning 0) (match-beginning 1)))
9254 (org-show-context 'tags-tree))
9255 ((eq action 'agenda)
9256 (setq txt (org-format-agenda-item
9258 (concat
9259 (if org-tags-match-list-sublevels
9260 (make-string (1- level) ?.) "")
9261 (org-get-heading))
9262 category (org-get-tags-at))
9263 priority (org-get-priority txt))
9264 (goto-char lspos)
9265 (setq marker (org-agenda-new-marker))
9266 (org-add-props txt props
9267 'org-marker marker 'org-hd-marker marker 'org-category category
9268 'priority priority 'type "tagsmatch")
9269 (push txt rtn))
9270 ((functionp action)
9271 (save-excursion
9272 (setq rtn1 (funcall action))
9273 (push rtn1 rtn))
9274 (goto-char (point-at-eol)))
9275 (t (error "Invalid action")))
9277 ;; if we are to skip sublevels, jump to end of subtree
9278 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9279 (when (and (eq action 'sparse-tree)
9280 (not org-sparse-tree-open-archived-trees))
9281 (org-hide-archived-subtrees (point-min) (point-max)))
9282 (nreverse rtn)))
9284 (defun org-remove-uniherited-tags (tags)
9285 "Remove all tags that are not inherited from the list TAGS."
9286 (cond
9287 ((eq org-use-tag-inheritance t)
9288 (if org-tags-exclude-from-inheritance
9289 (org-delete-all org-tags-exclude-from-inheritance tags)
9290 tags))
9291 ((not org-use-tag-inheritance) nil)
9292 ((stringp org-use-tag-inheritance)
9293 (delq nil (mapcar
9294 (lambda (x)
9295 (if (and (string-match org-use-tag-inheritance x)
9296 (not (member x org-tags-exclude-from-inheritance)))
9297 x nil))
9298 tags)))
9299 ((listp org-use-tag-inheritance)
9300 (delq nil (mapcar
9301 (lambda (x)
9302 (if (member x org-use-tag-inheritance) x nil))
9303 tags)))))
9305 (defvar todo-only) ;; dynamically scoped
9307 (defun org-tags-sparse-tree (&optional todo-only match)
9308 "Create a sparse tree according to tags string MATCH.
9309 MATCH can contain positive and negative selection of tags, like
9310 \"+WORK+URGENT-WITHBOSS\".
9311 If optional argument TODO-ONLY is non-nil, only select lines that are
9312 also TODO lines."
9313 (interactive "P")
9314 (org-prepare-agenda-buffers (list (current-buffer)))
9315 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9317 (defvar org-cached-props nil)
9318 (defun org-cached-entry-get (pom property)
9319 (if (or (eq t org-use-property-inheritance)
9320 (and (stringp org-use-property-inheritance)
9321 (string-match org-use-property-inheritance property))
9322 (and (listp org-use-property-inheritance)
9323 (member property org-use-property-inheritance)))
9324 ;; Caching is not possible, check it directly
9325 (org-entry-get pom property 'inherit)
9326 ;; Get all properties, so that we can do complicated checks easily
9327 (cdr (assoc property (or org-cached-props
9328 (setq org-cached-props
9329 (org-entry-properties pom)))))))
9331 (defun org-global-tags-completion-table (&optional files)
9332 "Return the list of all tags in all agenda buffer/files."
9333 (save-excursion
9334 (org-uniquify
9335 (delq nil
9336 (apply 'append
9337 (mapcar
9338 (lambda (file)
9339 (set-buffer (find-file-noselect file))
9340 (append (org-get-buffer-tags)
9341 (mapcar (lambda (x) (if (stringp (car-safe x))
9342 (list (car-safe x)) nil))
9343 org-tag-alist)))
9344 (if (and files (car files))
9345 files
9346 (org-agenda-files))))))))
9348 (defun org-make-tags-matcher (match)
9349 "Create the TAGS//TODO matcher form for the selection string MATCH."
9350 ;; todo-only is scoped dynamically into this function, and the function
9351 ;; may change it if the matcher asks for it.
9352 (unless match
9353 ;; Get a new match request, with completion
9354 (let ((org-last-tags-completion-table
9355 (org-global-tags-completion-table)))
9356 (setq match (org-ido-completing-read
9357 "Match: " 'org-tags-completion-function nil nil nil
9358 'org-tags-history))))
9360 ;; Parse the string and create a lisp form
9361 (let ((match0 match)
9362 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9363 minus tag mm
9364 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9365 orterms term orlist re-p str-p level-p level-op time-p
9366 prop-p pn pv po cat-p gv rest)
9367 (if (string-match "/+" match)
9368 ;; match contains also a todo-matching request
9369 (progn
9370 (setq tagsmatch (substring match 0 (match-beginning 0))
9371 todomatch (substring match (match-end 0)))
9372 (if (string-match "^!" todomatch)
9373 (setq todo-only t todomatch (substring todomatch 1)))
9374 (if (string-match "^\\s-*$" todomatch)
9375 (setq todomatch nil)))
9376 ;; only matching tags
9377 (setq tagsmatch match todomatch nil))
9379 ;; Make the tags matcher
9380 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9381 (setq tagsmatcher t)
9382 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9383 (while (setq term (pop orterms))
9384 (while (and (equal (substring term -1) "\\") orterms)
9385 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9386 (while (string-match re term)
9387 (setq rest (substring term (match-end 0))
9388 minus (and (match-end 1)
9389 (equal (match-string 1 term) "-"))
9390 tag (match-string 2 term)
9391 re-p (equal (string-to-char tag) ?{)
9392 level-p (match-end 4)
9393 prop-p (match-end 5)
9394 mm (cond
9395 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9396 (level-p
9397 (setq level-op (org-op-to-function (match-string 3 term)))
9398 `(,level-op level ,(string-to-number
9399 (match-string 4 term))))
9400 (prop-p
9401 (setq pn (match-string 5 term)
9402 po (match-string 6 term)
9403 pv (match-string 7 term)
9404 cat-p (equal pn "CATEGORY")
9405 re-p (equal (string-to-char pv) ?{)
9406 str-p (equal (string-to-char pv) ?\")
9407 time-p (save-match-data
9408 (string-match "^\"[[<].*[]>]\"$" pv))
9409 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9410 (if time-p (setq pv (org-matcher-time pv)))
9411 (setq po (org-op-to-function po (if time-p 'time str-p)))
9412 (cond
9413 ((equal pn "CATEGORY")
9414 (setq gv '(get-text-property (point) 'org-category)))
9415 ((equal pn "TODO")
9416 (setq gv 'todo))
9418 (setq gv `(org-cached-entry-get nil ,pn))))
9419 (if re-p
9420 (if (eq po 'org<>)
9421 `(not (string-match ,pv (or ,gv "")))
9422 `(string-match ,pv (or ,gv "")))
9423 (if str-p
9424 `(,po (or ,gv "") ,pv)
9425 `(,po (string-to-number (or ,gv ""))
9426 ,(string-to-number pv) ))))
9427 (t `(member ,(downcase tag) tags-list)))
9428 mm (if minus (list 'not mm) mm)
9429 term rest)
9430 (push mm tagsmatcher))
9431 (push (if (> (length tagsmatcher) 1)
9432 (cons 'and tagsmatcher)
9433 (car tagsmatcher))
9434 orlist)
9435 (setq tagsmatcher nil))
9436 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9437 (setq tagsmatcher
9438 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9439 ;; Make the todo matcher
9440 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9441 (setq todomatcher t)
9442 (setq orterms (org-split-string todomatch "|") orlist nil)
9443 (while (setq term (pop orterms))
9444 (while (string-match re term)
9445 (setq minus (and (match-end 1)
9446 (equal (match-string 1 term) "-"))
9447 kwd (match-string 2 term)
9448 re-p (equal (string-to-char kwd) ?{)
9449 term (substring term (match-end 0))
9450 mm (if re-p
9451 `(string-match ,(substring kwd 1 -1) todo)
9452 (list 'equal 'todo kwd))
9453 mm (if minus (list 'not mm) mm))
9454 (push mm todomatcher))
9455 (push (if (> (length todomatcher) 1)
9456 (cons 'and todomatcher)
9457 (car todomatcher))
9458 orlist)
9459 (setq todomatcher nil))
9460 (setq todomatcher (if (> (length orlist) 1)
9461 (cons 'or orlist) (car orlist))))
9463 ;; Return the string and lisp forms of the matcher
9464 (setq matcher (if todomatcher
9465 (list 'and tagsmatcher todomatcher)
9466 tagsmatcher))
9467 (cons match0 matcher)))
9469 (defun org-op-to-function (op &optional stringp)
9470 "Turn an operator into the appropriate function."
9471 (setq op
9472 (cond
9473 ((equal op "<" ) '(< string< org-time<))
9474 ((equal op ">" ) '(> org-string> org-time>))
9475 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9476 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9477 ((member op '("=" "==")) '(= string= org-time=))
9478 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9479 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9481 (defun org<> (a b) (not (= a b)))
9482 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9483 (defun org-string>= (a b) (not (string< a b)))
9484 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9485 (defun org-string<> (a b) (not (string= a b)))
9486 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9487 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9488 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9489 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9490 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9491 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9492 (defun org-2ft (s)
9493 "Convert S to a floating point time.
9494 If S is already a number, just return it. If it is a string, parse
9495 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9496 (cond
9497 ((numberp s) s)
9498 ((stringp s)
9499 (condition-case nil
9500 (float-time (apply 'encode-time (org-parse-time-string s)))
9501 (error 0.)))
9502 (t 0.)))
9504 (defun org-time-today ()
9505 "Time in seconds today at 0:00.
9506 Returns the float number of seconds since the beginning of the
9507 epoch to the beginning of today (00:00)."
9508 (float-time (apply 'encode-time
9509 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9511 (defun org-matcher-time (s)
9512 "Interpret a time comparison value."
9513 (save-match-data
9514 (cond
9515 ((string= s "<now>") (float-time))
9516 ((string= s "<today>") (org-time-today))
9517 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9518 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9519 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9520 (+ (org-time-today)
9521 (* (string-to-number (match-string 1 s))
9522 (cdr (assoc (match-string 2 s)
9523 '(("d" . 86400.0) ("w" . 604800.0)
9524 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9525 (t (org-2ft s)))))
9527 (defun org-match-any-p (re list)
9528 "Does re match any element of list?"
9529 (setq list (mapcar (lambda (x) (string-match re x)) list))
9530 (delq nil list))
9532 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9533 (defvar org-tags-overlay (org-make-overlay 1 1))
9534 (org-detach-overlay org-tags-overlay)
9536 (defun org-get-local-tags-at (&optional pos)
9537 "Get a list of tags defined in the current headline."
9538 (org-get-tags-at pos 'local))
9540 (defun org-get-local-tags ()
9541 "Get a list of tags defined in the current headline."
9542 (org-get-tags-at nil 'local))
9544 (defun org-get-tags-at (&optional pos local)
9545 "Get a list of all headline tags applicable at POS.
9546 POS defaults to point. If tags are inherited, the list contains
9547 the targets in the same sequence as the headlines appear, i.e.
9548 the tags of the current headline come last.
9549 When LOCAL is non-nil, only return tags from the current headline,
9550 ignore inherited ones."
9551 (interactive)
9552 (let (tags ltags lastpos parent)
9553 (save-excursion
9554 (save-restriction
9555 (widen)
9556 (goto-char (or pos (point)))
9557 (save-match-data
9558 (catch 'done
9559 (condition-case nil
9560 (progn
9561 (org-back-to-heading t)
9562 (while (not (equal lastpos (point)))
9563 (setq lastpos (point))
9564 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9565 (setq ltags (org-split-string
9566 (org-match-string-no-properties 1) ":"))
9567 (when parent
9568 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9569 (setq tags (append
9570 (if parent
9571 (org-remove-uniherited-tags ltags)
9572 ltags)
9573 tags)))
9574 (or org-use-tag-inheritance (throw 'done t))
9575 (if local (throw 'done t))
9576 (org-up-heading-all 1)
9577 (setq parent t)))
9578 (error nil)))))
9579 (append (org-remove-uniherited-tags org-file-tags) tags))))
9581 (defun org-add-prop-inherited (s)
9582 (add-text-properties 0 (length s) '(inherited t) s)
9585 (defun org-toggle-tag (tag &optional onoff)
9586 "Toggle the tag TAG for the current line.
9587 If ONOFF is `on' or `off', don't toggle but set to this state."
9588 (let (res current)
9589 (save-excursion
9590 (org-back-to-heading t)
9591 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9592 (point-at-eol) t)
9593 (progn
9594 (setq current (match-string 1))
9595 (replace-match ""))
9596 (setq current ""))
9597 (setq current (nreverse (org-split-string current ":")))
9598 (cond
9599 ((eq onoff 'on)
9600 (setq res t)
9601 (or (member tag current) (push tag current)))
9602 ((eq onoff 'off)
9603 (or (not (member tag current)) (setq current (delete tag current))))
9604 (t (if (member tag current)
9605 (setq current (delete tag current))
9606 (setq res t)
9607 (push tag current))))
9608 (end-of-line 1)
9609 (if current
9610 (progn
9611 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9612 (org-set-tags nil t))
9613 (delete-horizontal-space))
9614 (run-hooks 'org-after-tags-change-hook))
9615 res))
9617 (defun org-align-tags-here (to-col)
9618 ;; Assumes that this is a headline
9619 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9620 (beginning-of-line 1)
9621 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9622 (< pos (match-beginning 2)))
9623 (progn
9624 (setq tags-l (- (match-end 2) (match-beginning 2)))
9625 (goto-char (match-beginning 1))
9626 (insert " ")
9627 (delete-region (point) (1+ (match-beginning 2)))
9628 (setq ncol (max (1+ (current-column))
9629 (1+ col)
9630 (if (> to-col 0)
9631 to-col
9632 (- (abs to-col) tags-l))))
9633 (setq p (point))
9634 (insert (make-string (- ncol (current-column)) ?\ ))
9635 (setq ncol (current-column))
9636 (when indent-tabs-mode (tabify p (point-at-eol)))
9637 (org-move-to-column (min ncol col) t))
9638 (goto-char pos))))
9640 (defun org-set-tags-command (&optional arg just-align)
9641 "Call the set-tags command for the current entry."
9642 (interactive "P")
9643 (if (org-on-heading-p)
9644 (org-set-tags arg just-align)
9645 (save-excursion
9646 (org-back-to-heading t)
9647 (org-set-tags arg just-align))))
9649 (defun org-set-tags (&optional arg just-align)
9650 "Set the tags for the current headline.
9651 With prefix ARG, realign all tags in headings in the current buffer."
9652 (interactive "P")
9653 (let* ((re (concat "^" outline-regexp))
9654 (current (org-get-tags-string))
9655 (col (current-column))
9656 (org-setting-tags t)
9657 table current-tags inherited-tags ; computed below when needed
9658 tags p0 c0 c1 rpl)
9659 (if arg
9660 (save-excursion
9661 (goto-char (point-min))
9662 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9663 (while (re-search-forward re nil t)
9664 (org-set-tags nil t)
9665 (end-of-line 1)))
9666 (message "All tags realigned to column %d" org-tags-column))
9667 (if just-align
9668 (setq tags current)
9669 ;; Get a new set of tags from the user
9670 (save-excursion
9671 (setq table (or org-tag-alist (org-get-buffer-tags))
9672 org-last-tags-completion-table table
9673 current-tags (org-split-string current ":")
9674 inherited-tags (nreverse
9675 (nthcdr (length current-tags)
9676 (nreverse (org-get-tags-at))))
9677 tags
9678 (if (or (eq t org-use-fast-tag-selection)
9679 (and org-use-fast-tag-selection
9680 (delq nil (mapcar 'cdr table))))
9681 (org-fast-tag-selection
9682 current-tags inherited-tags table
9683 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9684 (let ((org-add-colon-after-tag-completion t))
9685 (org-trim
9686 (org-without-partial-completion
9687 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9688 nil nil current 'org-tags-history)))))))
9689 (while (string-match "[-+&]+" tags)
9690 ;; No boolean logic, just a list
9691 (setq tags (replace-match ":" t t tags))))
9693 (if (string-match "\\`[\t ]*\\'" tags)
9694 (setq tags "")
9695 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9696 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9698 ;; Insert new tags at the correct column
9699 (beginning-of-line 1)
9700 (cond
9701 ((and (equal current "") (equal tags "")))
9702 ((re-search-forward
9703 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9704 (point-at-eol) t)
9705 (if (equal tags "")
9706 (setq rpl "")
9707 (goto-char (match-beginning 0))
9708 (setq c0 (current-column) p0 (point)
9709 c1 (max (1+ c0) (if (> org-tags-column 0)
9710 org-tags-column
9711 (- (- org-tags-column) (length tags))))
9712 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9713 (replace-match rpl t t)
9714 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9715 tags)
9716 (t (error "Tags alignment failed")))
9717 (org-move-to-column col)
9718 (unless just-align
9719 (run-hooks 'org-after-tags-change-hook)))))
9721 (defun org-change-tag-in-region (beg end tag off)
9722 "Add or remove TAG for each entry in the region.
9723 This works in the agenda, and also in an org-mode buffer."
9724 (interactive
9725 (list (region-beginning) (region-end)
9726 (let ((org-last-tags-completion-table
9727 (if (org-mode-p)
9728 (org-get-buffer-tags)
9729 (org-global-tags-completion-table))))
9730 (org-ido-completing-read
9731 "Tag: " 'org-tags-completion-function nil nil nil
9732 'org-tags-history))
9733 (progn
9734 (message "[s]et or [r]emove? ")
9735 (equal (read-char-exclusive) ?r))))
9736 (if (fboundp 'deactivate-mark) (deactivate-mark))
9737 (let ((agendap (equal major-mode 'org-agenda-mode))
9738 l1 l2 m buf pos newhead (cnt 0))
9739 (goto-char end)
9740 (setq l2 (1- (org-current-line)))
9741 (goto-char beg)
9742 (setq l1 (org-current-line))
9743 (loop for l from l1 to l2 do
9744 (goto-line l)
9745 (setq m (get-text-property (point) 'org-hd-marker))
9746 (when (or (and (org-mode-p) (org-on-heading-p))
9747 (and agendap m))
9748 (setq buf (if agendap (marker-buffer m) (current-buffer))
9749 pos (if agendap m (point)))
9750 (with-current-buffer buf
9751 (save-excursion
9752 (save-restriction
9753 (goto-char pos)
9754 (setq cnt (1+ cnt))
9755 (org-toggle-tag tag (if off 'off 'on))
9756 (setq newhead (org-get-heading)))))
9757 (and agendap (org-agenda-change-all-lines newhead m))))
9758 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9760 (defun org-tags-completion-function (string predicate &optional flag)
9761 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9762 (confirm (lambda (x) (stringp (car x)))))
9763 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9764 (setq s1 (match-string 1 string)
9765 s2 (match-string 2 string))
9766 (setq s1 "" s2 string))
9767 (cond
9768 ((eq flag nil)
9769 ;; try completion
9770 (setq rtn (try-completion s2 ctable confirm))
9771 (if (stringp rtn)
9772 (setq rtn
9773 (concat s1 s2 (substring rtn (length s2))
9774 (if (and org-add-colon-after-tag-completion
9775 (assoc rtn ctable))
9776 ":" ""))))
9777 rtn)
9778 ((eq flag t)
9779 ;; all-completions
9780 (all-completions s2 ctable confirm)
9782 ((eq flag 'lambda)
9783 ;; exact match?
9784 (assoc s2 ctable)))
9787 (defun org-fast-tag-insert (kwd tags face &optional end)
9788 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9789 (insert (format "%-12s" (concat kwd ":"))
9790 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9791 (or end "")))
9793 (defun org-fast-tag-show-exit (flag)
9794 (save-excursion
9795 (goto-line 3)
9796 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9797 (replace-match ""))
9798 (when flag
9799 (end-of-line 1)
9800 (org-move-to-column (- (window-width) 19) t)
9801 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9803 (defun org-set-current-tags-overlay (current prefix)
9804 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9805 (if (featurep 'xemacs)
9806 (org-overlay-display org-tags-overlay (concat prefix s)
9807 'secondary-selection)
9808 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9809 (org-overlay-display org-tags-overlay (concat prefix s)))))
9811 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9812 "Fast tag selection with single keys.
9813 CURRENT is the current list of tags in the headline, INHERITED is the
9814 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9815 possibly with grouping information. TODO-TABLE is a similar table with
9816 TODO keywords, should these have keys assigned to them.
9817 If the keys are nil, a-z are automatically assigned.
9818 Returns the new tags string, or nil to not change the current settings."
9819 (let* ((fulltable (append table todo-table))
9820 (maxlen (apply 'max (mapcar
9821 (lambda (x)
9822 (if (stringp (car x)) (string-width (car x)) 0))
9823 fulltable)))
9824 (buf (current-buffer))
9825 (expert (eq org-fast-tag-selection-single-key 'expert))
9826 (buffer-tags nil)
9827 (fwidth (+ maxlen 3 1 3))
9828 (ncol (/ (- (window-width) 4) fwidth))
9829 (i-face 'org-done)
9830 (c-face 'org-todo)
9831 tg cnt e c char c1 c2 ntable tbl rtn
9832 ov-start ov-end ov-prefix
9833 (exit-after-next org-fast-tag-selection-single-key)
9834 (done-keywords org-done-keywords)
9835 groups ingroup)
9836 (save-excursion
9837 (beginning-of-line 1)
9838 (if (looking-at
9839 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9840 (setq ov-start (match-beginning 1)
9841 ov-end (match-end 1)
9842 ov-prefix "")
9843 (setq ov-start (1- (point-at-eol))
9844 ov-end (1+ ov-start))
9845 (skip-chars-forward "^\n\r")
9846 (setq ov-prefix
9847 (concat
9848 (buffer-substring (1- (point)) (point))
9849 (if (> (current-column) org-tags-column)
9851 (make-string (- org-tags-column (current-column)) ?\ ))))))
9852 (org-move-overlay org-tags-overlay ov-start ov-end)
9853 (save-window-excursion
9854 (if expert
9855 (set-buffer (get-buffer-create " *Org tags*"))
9856 (delete-other-windows)
9857 (split-window-vertically)
9858 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9859 (erase-buffer)
9860 (org-set-local 'org-done-keywords done-keywords)
9861 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9862 (org-fast-tag-insert "Current" current c-face "\n\n")
9863 (org-fast-tag-show-exit exit-after-next)
9864 (org-set-current-tags-overlay current ov-prefix)
9865 (setq tbl fulltable char ?a cnt 0)
9866 (while (setq e (pop tbl))
9867 (cond
9868 ((equal e '(:startgroup))
9869 (push '() groups) (setq ingroup t)
9870 (when (not (= cnt 0))
9871 (setq cnt 0)
9872 (insert "\n"))
9873 (insert "{ "))
9874 ((equal e '(:endgroup))
9875 (setq ingroup nil cnt 0)
9876 (insert "}\n"))
9878 (setq tg (car e) c2 nil)
9879 (if (cdr e)
9880 (setq c (cdr e))
9881 ;; automatically assign a character.
9882 (setq c1 (string-to-char
9883 (downcase (substring
9884 tg (if (= (string-to-char tg) ?@) 1 0)))))
9885 (if (or (rassoc c1 ntable) (rassoc c1 table))
9886 (while (or (rassoc char ntable) (rassoc char table))
9887 (setq char (1+ char)))
9888 (setq c2 c1))
9889 (setq c (or c2 char)))
9890 (if ingroup (push tg (car groups)))
9891 (setq tg (org-add-props tg nil 'face
9892 (cond
9893 ((not (assoc tg table))
9894 (org-get-todo-face tg))
9895 ((member tg current) c-face)
9896 ((member tg inherited) i-face)
9897 (t nil))))
9898 (if (and (= cnt 0) (not ingroup)) (insert " "))
9899 (insert "[" c "] " tg (make-string
9900 (- fwidth 4 (length tg)) ?\ ))
9901 (push (cons tg c) ntable)
9902 (when (= (setq cnt (1+ cnt)) ncol)
9903 (insert "\n")
9904 (if ingroup (insert " "))
9905 (setq cnt 0)))))
9906 (setq ntable (nreverse ntable))
9907 (insert "\n")
9908 (goto-char (point-min))
9909 (if (not expert) (org-fit-window-to-buffer))
9910 (setq rtn
9911 (catch 'exit
9912 (while t
9913 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9914 (if groups " [!] no groups" " [!]groups")
9915 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9916 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9917 (cond
9918 ((= c ?\r) (throw 'exit t))
9919 ((= c ?!)
9920 (setq groups (not groups))
9921 (goto-char (point-min))
9922 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9923 ((= c ?\C-c)
9924 (if (not expert)
9925 (org-fast-tag-show-exit
9926 (setq exit-after-next (not exit-after-next)))
9927 (setq expert nil)
9928 (delete-other-windows)
9929 (split-window-vertically)
9930 (org-switch-to-buffer-other-window " *Org tags*")
9931 (org-fit-window-to-buffer)))
9932 ((or (= c ?\C-g)
9933 (and (= c ?q) (not (rassoc c ntable))))
9934 (org-detach-overlay org-tags-overlay)
9935 (setq quit-flag t))
9936 ((= c ?\ )
9937 (setq current nil)
9938 (if exit-after-next (setq exit-after-next 'now)))
9939 ((= c ?\t)
9940 (condition-case nil
9941 (setq tg (org-ido-completing-read
9942 "Tag: "
9943 (or buffer-tags
9944 (with-current-buffer buf
9945 (org-get-buffer-tags)))))
9946 (quit (setq tg "")))
9947 (when (string-match "\\S-" tg)
9948 (add-to-list 'buffer-tags (list tg))
9949 (if (member tg current)
9950 (setq current (delete tg current))
9951 (push tg current)))
9952 (if exit-after-next (setq exit-after-next 'now)))
9953 ((setq e (rassoc c todo-table) tg (car e))
9954 (with-current-buffer buf
9955 (save-excursion (org-todo tg)))
9956 (if exit-after-next (setq exit-after-next 'now)))
9957 ((setq e (rassoc c ntable) tg (car e))
9958 (if (member tg current)
9959 (setq current (delete tg current))
9960 (loop for g in groups do
9961 (if (member tg g)
9962 (mapc (lambda (x)
9963 (setq current (delete x current)))
9964 g)))
9965 (push tg current))
9966 (if exit-after-next (setq exit-after-next 'now))))
9968 ;; Create a sorted list
9969 (setq current
9970 (sort current
9971 (lambda (a b)
9972 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9973 (if (eq exit-after-next 'now) (throw 'exit t))
9974 (goto-char (point-min))
9975 (beginning-of-line 2)
9976 (delete-region (point) (point-at-eol))
9977 (org-fast-tag-insert "Current" current c-face)
9978 (org-set-current-tags-overlay current ov-prefix)
9979 (while (re-search-forward
9980 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9981 (setq tg (match-string 1))
9982 (add-text-properties
9983 (match-beginning 1) (match-end 1)
9984 (list 'face
9985 (cond
9986 ((member tg current) c-face)
9987 ((member tg inherited) i-face)
9988 (t (get-text-property (match-beginning 1) 'face))))))
9989 (goto-char (point-min)))))
9990 (org-detach-overlay org-tags-overlay)
9991 (if rtn
9992 (mapconcat 'identity current ":")
9993 nil))))
9995 (defun org-get-tags-string ()
9996 "Get the TAGS string in the current headline."
9997 (unless (org-on-heading-p t)
9998 (error "Not on a heading"))
9999 (save-excursion
10000 (beginning-of-line 1)
10001 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10002 (org-match-string-no-properties 1)
10003 "")))
10005 (defun org-get-tags ()
10006 "Get the list of tags specified in the current headline."
10007 (org-split-string (org-get-tags-string) ":"))
10009 (defun org-get-buffer-tags ()
10010 "Get a table of all tags used in the buffer, for completion."
10011 (let (tags)
10012 (save-excursion
10013 (goto-char (point-min))
10014 (while (re-search-forward
10015 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10016 (when (equal (char-after (point-at-bol 0)) ?*)
10017 (mapc (lambda (x) (add-to-list 'tags x))
10018 (org-split-string (org-match-string-no-properties 1) ":")))))
10019 (mapcar 'list tags)))
10021 ;;;; The mapping API
10023 ;;;###autoload
10024 (defun org-map-entries (func &optional match scope &rest skip)
10025 "Call FUNC at each headline selected by MATCH in SCOPE.
10027 FUNC is a function or a lisp form. The function will be called without
10028 arguments, with the cursor positioned at the beginning of the headline.
10029 The return values of all calls to the function will be collected and
10030 returned as a list.
10032 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10033 Only headlines that are matched by this query will be considered during
10034 the iteration. When MATCH is nil or t, all headlines will be
10035 visited by the iteration.
10037 SCOPE determines the scope of this command. It can be any of:
10039 nil The current buffer, respecting the restriction if any
10040 tree The subtree started with the entry at point
10041 file The current buffer, without restriction
10042 file-with-archives
10043 The current buffer, and any archives associated with it
10044 agenda All agenda files
10045 agenda-with-archives
10046 All agenda files with any archive files associated with them
10047 \(file1 file2 ...)
10048 If this is a list, all files in the list will be scanned
10050 The remaining args are treated as settings for the skipping facilities of
10051 the scanner. The following items can be given here:
10053 archive skip trees with the archive tag.
10054 comment skip trees with the COMMENT keyword
10055 function or Emacs Lisp form:
10056 will be used as value for `org-agenda-skip-function', so whenever
10057 the the function returns t, FUNC will not be called for that
10058 entry and search will continue from the point where the
10059 function leaves it."
10060 (let* ((org-agenda-archives-mode nil) ; just to make sure
10061 (org-agenda-skip-archived-trees (memq 'archive skip))
10062 (org-agenda-skip-comment-trees (memq 'comment skip))
10063 (org-agenda-skip-function
10064 (car (org-delete-all '(comment archive) skip)))
10065 (org-tags-match-list-sublevels t)
10066 matcher pos file res
10067 org-todo-keywords-for-agenda
10068 org-done-keywords-for-agenda
10069 org-todo-keyword-alist-for-agenda
10070 org-tag-alist-for-agenda)
10072 (cond
10073 ((eq match t) (setq matcher t))
10074 ((eq match nil) (setq matcher t))
10075 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10077 (when (eq scope 'tree)
10078 (org-back-to-heading t)
10079 (org-narrow-to-subtree)
10080 (setq scope nil))
10082 (if (not scope)
10083 (progn
10084 (org-prepare-agenda-buffers
10085 (list (buffer-file-name (current-buffer))))
10086 (org-scan-tags func matcher))
10087 ;; Get the right scope
10088 (setq pos (point))
10089 (cond
10090 ((and scope (listp scope) (symbolp (car scope)))
10091 (setq scope (eval scope)))
10092 ((eq scope 'agenda)
10093 (setq scope (org-agenda-files t)))
10094 ((eq scope 'agenda-with-archives)
10095 (setq scope (org-agenda-files t))
10096 (setq scope (org-add-archive-files scope)))
10097 ((eq scope 'file)
10098 (setq scope (list (buffer-file-name))))
10099 ((eq scope 'file-with-archives)
10100 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10101 (org-prepare-agenda-buffers scope)
10102 (while (setq file (pop scope))
10103 (with-current-buffer (org-find-base-buffer-visiting file)
10104 (save-excursion
10105 (save-restriction
10106 (widen)
10107 (goto-char (point-min))
10108 (setq res (append res (org-scan-tags func matcher)))))))
10109 res)))
10111 ;;;; Properties
10113 ;;; Setting and retrieving properties
10115 (defconst org-special-properties
10116 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10117 "TIMESTAMP" "TIMESTAMP_IA")
10118 "The special properties valid in Org-mode.
10120 These are properties that are not defined in the property drawer,
10121 but in some other way.")
10123 (defconst org-default-properties
10124 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10125 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10126 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10127 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10128 "Some properties that are used by Org-mode for various purposes.
10129 Being in this list makes sure that they are offered for completion.")
10131 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10132 "Regular expression matching the first line of a property drawer.")
10134 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10135 "Regular expression matching the first line of a property drawer.")
10137 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10138 "Regular expression matching the first line of a property drawer.")
10140 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10141 "Regular expression matching the first line of a property drawer.")
10143 (defconst org-property-drawer-re
10144 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10145 org-property-end-re "\\)\n?")
10146 "Matches an entire property drawer.")
10148 (defconst org-clock-drawer-re
10149 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10150 org-property-end-re "\\)\n?")
10151 "Matches an entire clock drawer.")
10153 (defun org-property-action ()
10154 "Do an action on properties."
10155 (interactive)
10156 (let (c)
10157 (org-at-property-p)
10158 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10159 (setq c (read-char-exclusive))
10160 (cond
10161 ((equal c ?s)
10162 (call-interactively 'org-set-property))
10163 ((equal c ?d)
10164 (call-interactively 'org-delete-property))
10165 ((equal c ?D)
10166 (call-interactively 'org-delete-property-globally))
10167 ((equal c ?c)
10168 (call-interactively 'org-compute-property-at-point))
10169 (t (error "No such property action %c" c)))))
10171 (defun org-at-property-p ()
10172 "Is the cursor in a property line?"
10173 ;; FIXME: Does not check if we are actually in the drawer.
10174 ;; FIXME: also returns true on any drawers.....
10175 ;; This is used by C-c C-c for property action.
10176 (save-excursion
10177 (beginning-of-line 1)
10178 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10180 (defun org-get-property-block (&optional beg end force)
10181 "Return the (beg . end) range of the body of the property drawer.
10182 BEG and END can be beginning and end of subtree, if not given
10183 they will be found.
10184 If the drawer does not exist and FORCE is non-nil, create the drawer."
10185 (catch 'exit
10186 (save-excursion
10187 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10188 (end (or end (progn (outline-next-heading) (point)))))
10189 (goto-char beg)
10190 (if (re-search-forward org-property-start-re end t)
10191 (setq beg (1+ (match-end 0)))
10192 (if force
10193 (save-excursion
10194 (org-insert-property-drawer)
10195 (setq end (progn (outline-next-heading) (point))))
10196 (throw 'exit nil))
10197 (goto-char beg)
10198 (if (re-search-forward org-property-start-re end t)
10199 (setq beg (1+ (match-end 0)))))
10200 (if (re-search-forward org-property-end-re end t)
10201 (setq end (match-beginning 0))
10202 (or force (throw 'exit nil))
10203 (goto-char beg)
10204 (setq end beg)
10205 (org-indent-line-function)
10206 (insert ":END:\n"))
10207 (cons beg end)))))
10209 (defun org-entry-properties (&optional pom which)
10210 "Get all properties of the entry at point-or-marker POM.
10211 This includes the TODO keyword, the tags, time strings for deadline,
10212 scheduled, and clocking, and any additional properties defined in the
10213 entry. The return value is an alist, keys may occur multiple times
10214 if the property key was used several times.
10215 POM may also be nil, in which case the current entry is used.
10216 If WHICH is nil or `all', get all properties. If WHICH is
10217 `special' or `standard', only get that subclass."
10218 (setq which (or which 'all))
10219 (org-with-point-at pom
10220 (let ((clockstr (substring org-clock-string 0 -1))
10221 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10222 beg end range props sum-props key value string clocksum)
10223 (save-excursion
10224 (when (condition-case nil (org-back-to-heading t) (error nil))
10225 (setq beg (point))
10226 (setq sum-props (get-text-property (point) 'org-summaries))
10227 (setq clocksum (get-text-property (point) :org-clock-minutes))
10228 (outline-next-heading)
10229 (setq end (point))
10230 (when (memq which '(all special))
10231 ;; Get the special properties, like TODO and tags
10232 (goto-char beg)
10233 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10234 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10235 (when (looking-at org-priority-regexp)
10236 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10237 (when (and (setq value (org-get-tags-string))
10238 (string-match "\\S-" value))
10239 (push (cons "TAGS" value) props))
10240 (when (setq value (org-get-tags-at))
10241 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10242 props))
10243 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10244 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10245 string (if (equal key clockstr)
10246 (org-no-properties
10247 (org-trim
10248 (buffer-substring
10249 (match-beginning 3) (goto-char (point-at-eol)))))
10250 (substring (org-match-string-no-properties 3) 1 -1)))
10251 (unless key
10252 (if (= (char-after (match-beginning 3)) ?\[)
10253 (setq key "TIMESTAMP_IA")
10254 (setq key "TIMESTAMP")))
10255 (when (or (equal key clockstr) (not (assoc key props)))
10256 (push (cons key string) props)))
10260 (when (memq which '(all standard))
10261 ;; Get the standard properties, like :PORP: ...
10262 (setq range (org-get-property-block beg end))
10263 (when range
10264 (goto-char (car range))
10265 (while (re-search-forward
10266 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10267 (cdr range) t)
10268 (setq key (org-match-string-no-properties 1)
10269 value (org-trim (or (org-match-string-no-properties 2) "")))
10270 (unless (member key excluded)
10271 (push (cons key (or value "")) props)))))
10272 (if clocksum
10273 (push (cons "CLOCKSUM"
10274 (org-columns-number-to-string (/ (float clocksum) 60.)
10275 'add_times))
10276 props))
10277 (unless (assoc "CATEGORY" props)
10278 (setq value (or (org-get-category)
10279 (progn (org-refresh-category-properties)
10280 (org-get-category))))
10281 (push (cons "CATEGORY" value) props))
10282 (append sum-props (nreverse props)))))))
10284 (defun org-entry-get (pom property &optional inherit)
10285 "Get value of PROPERTY for entry at point-or-marker POM.
10286 If INHERIT is non-nil and the entry does not have the property,
10287 then also check higher levels of the hierarchy.
10288 If INHERIT is the symbol `selective', use inheritance only if the setting
10289 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10290 If the property is present but empty, the return value is the empty string.
10291 If the property is not present at all, nil is returned."
10292 (org-with-point-at pom
10293 (if (and inherit (if (eq inherit 'selective)
10294 (org-property-inherit-p property)
10296 (org-entry-get-with-inheritance property)
10297 (if (member property org-special-properties)
10298 ;; We need a special property. Use brute force, get all properties.
10299 (cdr (assoc property (org-entry-properties nil 'special)))
10300 (let ((range (org-get-property-block)))
10301 (if (and range
10302 (goto-char (car range))
10303 (re-search-forward
10304 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10305 (cdr range) t))
10306 ;; Found the property, return it.
10307 (if (match-end 1)
10308 (org-match-string-no-properties 1)
10309 "")))))))
10311 (defun org-property-or-variable-value (var &optional inherit)
10312 "Check if there is a property fixing the value of VAR.
10313 If yes, return this value. If not, return the current value of the variable."
10314 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10315 (if (and prop (stringp prop) (string-match "\\S-" prop))
10316 (read prop)
10317 (symbol-value var))))
10319 (defun org-entry-delete (pom property)
10320 "Delete the property PROPERTY from entry at point-or-marker POM."
10321 (org-with-point-at pom
10322 (if (member property org-special-properties)
10323 nil ; cannot delete these properties.
10324 (let ((range (org-get-property-block)))
10325 (if (and range
10326 (goto-char (car range))
10327 (re-search-forward
10328 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10329 (cdr range) t))
10330 (progn
10331 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10333 nil)))))
10335 ;; Multi-values properties are properties that contain multiple values
10336 ;; These values are assumed to be single words, separated by whitespace.
10337 (defun org-entry-add-to-multivalued-property (pom property value)
10338 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10339 (let* ((old (org-entry-get pom property))
10340 (values (and old (org-split-string old "[ \t]"))))
10341 (setq value (org-entry-protect-space value))
10342 (unless (member value values)
10343 (setq values (cons value values))
10344 (org-entry-put pom property
10345 (mapconcat 'identity values " ")))))
10347 (defun org-entry-remove-from-multivalued-property (pom property value)
10348 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10349 (let* ((old (org-entry-get pom property))
10350 (values (and old (org-split-string old "[ \t]"))))
10351 (setq value (org-entry-protect-space value))
10352 (when (member value values)
10353 (setq values (delete value values))
10354 (org-entry-put pom property
10355 (mapconcat 'identity values " ")))))
10357 (defun org-entry-member-in-multivalued-property (pom property value)
10358 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10359 (let* ((old (org-entry-get pom property))
10360 (values (and old (org-split-string old "[ \t]"))))
10361 (setq value (org-entry-protect-space value))
10362 (member value values)))
10364 (defun org-entry-get-multivalued-property (pom property)
10365 "Return a list of values in a multivalued property."
10366 (let* ((value (org-entry-get pom property))
10367 (values (and value (org-split-string value "[ \t]"))))
10368 (mapcar 'org-entry-restore-space values)))
10370 (defun org-entry-put-multivalued-property (pom property &rest values)
10371 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10372 VALUES should be a list of strings. Spaces will be protected."
10373 (org-entry-put pom property
10374 (mapconcat 'org-entry-protect-space values " "))
10375 (let* ((value (org-entry-get pom property))
10376 (values (and value (org-split-string value "[ \t]"))))
10377 (mapcar 'org-entry-restore-space values)))
10379 (defun org-entry-protect-space (s)
10380 "Protect spaces and newline in string S."
10381 (while (string-match " " s)
10382 (setq s (replace-match "%20" t t s)))
10383 (while (string-match "\n" s)
10384 (setq s (replace-match "%0A" t t s)))
10387 (defun org-entry-restore-space (s)
10388 "Restore spaces and newline in string S."
10389 (while (string-match "%20" s)
10390 (setq s (replace-match " " t t s)))
10391 (while (string-match "%0A" s)
10392 (setq s (replace-match "\n" t t s)))
10395 (defvar org-entry-property-inherited-from (make-marker)
10396 "Marker pointing to the entry from where a property was inherited.
10397 Each call to `org-entry-get-with-inheritance' will set this marker to the
10398 location of the entry where the inheritance search matched. If there was
10399 no match, the marker will point nowhere.
10400 Note that also `org-entry-get' calls this function, if the INHERIT flag
10401 is set.")
10403 (defun org-entry-get-with-inheritance (property)
10404 "Get entry property, and search higher levels if not present."
10405 (move-marker org-entry-property-inherited-from nil)
10406 (let (tmp)
10407 (save-excursion
10408 (save-restriction
10409 (widen)
10410 (catch 'ex
10411 (while t
10412 (when (setq tmp (org-entry-get nil property))
10413 (org-back-to-heading t)
10414 (move-marker org-entry-property-inherited-from (point))
10415 (throw 'ex tmp))
10416 (or (org-up-heading-safe) (throw 'ex nil)))))
10417 (or tmp
10418 (cdr (assoc property org-file-properties))
10419 (cdr (assoc property org-global-properties))
10420 (cdr (assoc property org-global-properties-fixed))))))
10422 (defun org-entry-put (pom property value)
10423 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10424 (org-with-point-at pom
10425 (org-back-to-heading t)
10426 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10427 range)
10428 (cond
10429 ((equal property "TODO")
10430 (when (and (stringp value) (string-match "\\S-" value)
10431 (not (member value org-todo-keywords-1)))
10432 (error "\"%s\" is not a valid TODO state" value))
10433 (if (or (not value)
10434 (not (string-match "\\S-" value)))
10435 (setq value 'none))
10436 (org-todo value)
10437 (org-set-tags nil 'align))
10438 ((equal property "PRIORITY")
10439 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10440 (string-to-char value) ?\ ))
10441 (org-set-tags nil 'align))
10442 ((equal property "SCHEDULED")
10443 (if (re-search-forward org-scheduled-time-regexp end t)
10444 (cond
10445 ((eq value 'earlier) (org-timestamp-change -1 'day))
10446 ((eq value 'later) (org-timestamp-change 1 'day))
10447 (t (call-interactively 'org-schedule)))
10448 (call-interactively 'org-schedule)))
10449 ((equal property "DEADLINE")
10450 (if (re-search-forward org-deadline-time-regexp end t)
10451 (cond
10452 ((eq value 'earlier) (org-timestamp-change -1 'day))
10453 ((eq value 'later) (org-timestamp-change 1 'day))
10454 (t (call-interactively 'org-deadline)))
10455 (call-interactively 'org-deadline)))
10456 ((member property org-special-properties)
10457 (error "The %s property can not yet be set with `org-entry-put'"
10458 property))
10459 (t ; a non-special property
10460 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10461 (setq range (org-get-property-block beg end 'force))
10462 (goto-char (car range))
10463 (if (re-search-forward
10464 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10465 (progn
10466 (delete-region (match-beginning 1) (match-end 1))
10467 (goto-char (match-beginning 1)))
10468 (goto-char (cdr range))
10469 (insert "\n")
10470 (backward-char 1)
10471 (org-indent-line-function)
10472 (insert ":" property ":"))
10473 (and value (insert " " value))
10474 (org-indent-line-function)))))))
10476 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10477 "Get all property keys in the current buffer.
10478 With INCLUDE-SPECIALS, also list the special properties that reflect things
10479 like tags and TODO state.
10480 With INCLUDE-DEFAULTS, also include properties that has special meaning
10481 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10482 With INCLUDE-COLUMNS, also include property names given in COLUMN
10483 formats in the current buffer."
10484 (let (rtn range cfmt cols s p)
10485 (save-excursion
10486 (save-restriction
10487 (widen)
10488 (goto-char (point-min))
10489 (while (re-search-forward org-property-start-re nil t)
10490 (setq range (org-get-property-block))
10491 (goto-char (car range))
10492 (while (re-search-forward
10493 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10494 (cdr range) t)
10495 (add-to-list 'rtn (org-match-string-no-properties 1)))
10496 (outline-next-heading))))
10498 (when include-specials
10499 (setq rtn (append org-special-properties rtn)))
10501 (when include-defaults
10502 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10504 (when include-columns
10505 (save-excursion
10506 (save-restriction
10507 (widen)
10508 (goto-char (point-min))
10509 (while (re-search-forward
10510 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10511 nil t)
10512 (setq cfmt (match-string 2) s 0)
10513 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10514 cfmt s)
10515 (setq s (match-end 0)
10516 p (match-string 1 cfmt))
10517 (unless (or (equal p "ITEM")
10518 (member p org-special-properties))
10519 (add-to-list 'rtn (match-string 1 cfmt))))))))
10521 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10523 (defun org-property-values (key)
10524 "Return a list of all values of property KEY."
10525 (save-excursion
10526 (save-restriction
10527 (widen)
10528 (goto-char (point-min))
10529 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10530 values)
10531 (while (re-search-forward re nil t)
10532 (add-to-list 'values (org-trim (match-string 1))))
10533 (delete "" values)))))
10535 (defun org-insert-property-drawer ()
10536 "Insert a property drawer into the current entry."
10537 (interactive)
10538 (org-back-to-heading t)
10539 (looking-at outline-regexp)
10540 (let ((indent (- (match-end 0)(match-beginning 0)))
10541 (beg (point))
10542 (re (concat "^[ \t]*" org-keyword-time-regexp))
10543 end hiddenp)
10544 (outline-next-heading)
10545 (setq end (point))
10546 (goto-char beg)
10547 (while (re-search-forward re end t))
10548 (setq hiddenp (org-invisible-p))
10549 (end-of-line 1)
10550 (and (equal (char-after) ?\n) (forward-char 1))
10551 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10552 (beginning-of-line 2))
10553 (org-skip-over-state-notes)
10554 (skip-chars-backward " \t\n\r")
10555 (if (eq (char-before) ?*) (forward-char 1))
10556 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10557 (beginning-of-line 0)
10558 (org-indent-to-column indent)
10559 (beginning-of-line 2)
10560 (org-indent-to-column indent)
10561 (beginning-of-line 0)
10562 (if hiddenp
10563 (save-excursion
10564 (org-back-to-heading t)
10565 (hide-entry))
10566 (org-flag-drawer t))))
10568 (defun org-set-property (property value)
10569 "In the current entry, set PROPERTY to VALUE.
10570 When called interactively, this will prompt for a property name, offering
10571 completion on existing and default properties. And then it will prompt
10572 for a value, offering completion either on allowed values (via an inherited
10573 xxx_ALL property) or on existing values in other instances of this property
10574 in the current file."
10575 (interactive
10576 (let* ((completion-ignore-case t)
10577 (keys (org-buffer-property-keys nil t t))
10578 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10579 (prop (if (member prop0 keys)
10580 prop0
10581 (or (cdr (assoc (downcase prop0)
10582 (mapcar (lambda (x) (cons (downcase x) x))
10583 keys)))
10584 prop0)))
10585 (cur (org-entry-get nil prop))
10586 (allowed (org-property-get-allowed-values nil prop 'table))
10587 (existing (mapcar 'list (org-property-values prop)))
10588 (val (if allowed
10589 (org-completing-read "Value: " allowed nil 'req-match)
10590 (org-completing-read
10591 (concat "Value" (if (and cur (string-match "\\S-" cur))
10592 (concat "[" cur "]") "")
10593 ": ")
10594 existing nil nil "" nil cur))))
10595 (list prop (if (equal val "") cur val))))
10596 (unless (equal (org-entry-get nil property) value)
10597 (org-entry-put nil property value)))
10599 (defun org-delete-property (property)
10600 "In the current entry, delete PROPERTY."
10601 (interactive
10602 (let* ((completion-ignore-case t)
10603 (prop (org-ido-completing-read
10604 "Property: " (org-entry-properties nil 'standard))))
10605 (list prop)))
10606 (message "Property %s %s" property
10607 (if (org-entry-delete nil property)
10608 "deleted"
10609 "was not present in the entry")))
10611 (defun org-delete-property-globally (property)
10612 "Remove PROPERTY globally, from all entries."
10613 (interactive
10614 (let* ((completion-ignore-case t)
10615 (prop (org-ido-completing-read
10616 "Globally remove property: "
10617 (mapcar 'list (org-buffer-property-keys)))))
10618 (list prop)))
10619 (save-excursion
10620 (save-restriction
10621 (widen)
10622 (goto-char (point-min))
10623 (let ((cnt 0))
10624 (while (re-search-forward
10625 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10626 nil t)
10627 (setq cnt (1+ cnt))
10628 (replace-match ""))
10629 (message "Property \"%s\" removed from %d entries" property cnt)))))
10631 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10633 (defun org-compute-property-at-point ()
10634 "Compute the property at point.
10635 This looks for an enclosing column format, extracts the operator and
10636 then applies it to the property in the column format's scope."
10637 (interactive)
10638 (unless (org-at-property-p)
10639 (error "Not at a property"))
10640 (let ((prop (org-match-string-no-properties 2)))
10641 (org-columns-get-format-and-top-level)
10642 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10643 (error "No operator defined for property %s" prop))
10644 (org-columns-compute prop)))
10646 (defun org-property-get-allowed-values (pom property &optional table)
10647 "Get allowed values for the property PROPERTY.
10648 When TABLE is non-nil, return an alist that can directly be used for
10649 completion."
10650 (let (vals)
10651 (cond
10652 ((equal property "TODO")
10653 (setq vals (org-with-point-at pom
10654 (append org-todo-keywords-1 '("")))))
10655 ((equal property "PRIORITY")
10656 (let ((n org-lowest-priority))
10657 (while (>= n org-highest-priority)
10658 (push (char-to-string n) vals)
10659 (setq n (1- n)))))
10660 ((member property org-special-properties))
10662 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10664 (when (and vals (string-match "\\S-" vals))
10665 (setq vals (car (read-from-string (concat "(" vals ")"))))
10666 (setq vals (mapcar (lambda (x)
10667 (cond ((stringp x) x)
10668 ((numberp x) (number-to-string x))
10669 ((symbolp x) (symbol-name x))
10670 (t "???")))
10671 vals)))))
10672 (if table (mapcar 'list vals) vals)))
10674 (defun org-property-previous-allowed-value (&optional previous)
10675 "Switch to the next allowed value for this property."
10676 (interactive)
10677 (org-property-next-allowed-value t))
10679 (defun org-property-next-allowed-value (&optional previous)
10680 "Switch to the next allowed value for this property."
10681 (interactive)
10682 (unless (org-at-property-p)
10683 (error "Not at a property"))
10684 (let* ((key (match-string 2))
10685 (value (match-string 3))
10686 (allowed (or (org-property-get-allowed-values (point) key)
10687 (and (member value '("[ ]" "[-]" "[X]"))
10688 '("[ ]" "[X]"))))
10689 nval)
10690 (unless allowed
10691 (error "Allowed values for this property have not been defined"))
10692 (if previous (setq allowed (reverse allowed)))
10693 (if (member value allowed)
10694 (setq nval (car (cdr (member value allowed)))))
10695 (setq nval (or nval (car allowed)))
10696 (if (equal nval value)
10697 (error "Only one allowed value for this property"))
10698 (org-at-property-p)
10699 (replace-match (concat " :" key ": " nval) t t)
10700 (org-indent-line-function)
10701 (beginning-of-line 1)
10702 (skip-chars-forward " \t")))
10704 (defun org-find-entry-with-id (ident)
10705 "Locate the entry that contains the ID property with exact value IDENT.
10706 IDENT can be a string, a symbol or a number, this function will search for
10707 the string representation of it.
10708 Return the position where this entry starts, or nil if there is no such entry."
10709 (interactive "sID: ")
10710 (let ((id (cond
10711 ((stringp ident) ident)
10712 ((symbol-name ident) (symbol-name ident))
10713 ((numberp ident) (number-to-string ident))
10714 (t (error "IDENT %s must be a string, symbol or number" ident))))
10715 (case-fold-search nil))
10716 (save-excursion
10717 (save-restriction
10718 (widen)
10719 (goto-char (point-min))
10720 (when (re-search-forward
10721 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10722 nil t)
10723 (org-back-to-heading)
10724 (point))))))
10726 ;;;; Timestamps
10728 (defvar org-last-changed-timestamp nil)
10729 (defvar org-last-inserted-timestamp nil
10730 "The last time stamp inserted with `org-insert-time-stamp'.")
10731 (defvar org-time-was-given) ; dynamically scoped parameter
10732 (defvar org-end-time-was-given) ; dynamically scoped parameter
10733 (defvar org-ts-what) ; dynamically scoped parameter
10735 (defun org-time-stamp (arg &optional inactive)
10736 "Prompt for a date/time and insert a time stamp.
10737 If the user specifies a time like HH:MM, or if this command is called
10738 with a prefix argument, the time stamp will contain date and time.
10739 Otherwise, only the date will be included. All parts of a date not
10740 specified by the user will be filled in from the current date/time.
10741 So if you press just return without typing anything, the time stamp
10742 will represent the current date/time. If there is already a timestamp
10743 at the cursor, it will be modified."
10744 (interactive "P")
10745 (let* ((ts nil)
10746 (default-time
10747 ;; Default time is either today, or, when entering a range,
10748 ;; the range start.
10749 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10750 (save-excursion
10751 (re-search-backward
10752 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10753 (- (point) 20) t)))
10754 (apply 'encode-time (org-parse-time-string (match-string 1)))
10755 (current-time)))
10756 (default-input (and ts (org-get-compact-tod ts)))
10757 org-time-was-given org-end-time-was-given time)
10758 (cond
10759 ((and (org-at-timestamp-p t)
10760 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10761 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10762 (insert "--")
10763 (setq time (let ((this-command this-command))
10764 (org-read-date arg 'totime nil nil
10765 default-time default-input)))
10766 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10767 ((org-at-timestamp-p t)
10768 (setq time (let ((this-command this-command))
10769 (org-read-date arg 'totime nil nil default-time default-input)))
10770 (when (org-at-timestamp-p t) ; just to get the match data
10771 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10772 (replace-match "")
10773 (setq org-last-changed-timestamp
10774 (org-insert-time-stamp
10775 time (or org-time-was-given arg)
10776 inactive nil nil (list org-end-time-was-given))))
10777 (message "Timestamp updated"))
10779 (setq time (let ((this-command this-command))
10780 (org-read-date arg 'totime nil nil default-time default-input)))
10781 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10782 nil nil (list org-end-time-was-given))))))
10784 ;; FIXME: can we use this for something else, like computing time differences?
10785 (defun org-get-compact-tod (s)
10786 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10787 (let* ((t1 (match-string 1 s))
10788 (h1 (string-to-number (match-string 2 s)))
10789 (m1 (string-to-number (match-string 3 s)))
10790 (t2 (and (match-end 4) (match-string 5 s)))
10791 (h2 (and t2 (string-to-number (match-string 6 s))))
10792 (m2 (and t2 (string-to-number (match-string 7 s))))
10793 dh dm)
10794 (if (not t2)
10796 (setq dh (- h2 h1) dm (- m2 m1))
10797 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10798 (concat t1 "+" (number-to-string dh)
10799 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10801 (defun org-time-stamp-inactive (&optional arg)
10802 "Insert an inactive time stamp.
10803 An inactive time stamp is enclosed in square brackets instead of angle
10804 brackets. It is inactive in the sense that it does not trigger agenda entries,
10805 does not link to the calendar and cannot be changed with the S-cursor keys.
10806 So these are more for recording a certain time/date."
10807 (interactive "P")
10808 (org-time-stamp arg 'inactive))
10810 (defvar org-date-ovl (org-make-overlay 1 1))
10811 (org-overlay-put org-date-ovl 'face 'org-warning)
10812 (org-detach-overlay org-date-ovl)
10814 (defvar org-ans1) ; dynamically scoped parameter
10815 (defvar org-ans2) ; dynamically scoped parameter
10817 (defvar org-plain-time-of-day-regexp) ; defined below
10819 (defvar org-overriding-default-time nil) ; dynamically scoped
10820 (defvar org-read-date-overlay nil)
10821 (defvar org-dcst nil) ; dynamically scoped
10823 (defun org-read-date (&optional with-time to-time from-string prompt
10824 default-time default-input)
10825 "Read a date, possibly a time, and make things smooth for the user.
10826 The prompt will suggest to enter an ISO date, but you can also enter anything
10827 which will at least partially be understood by `parse-time-string'.
10828 Unrecognized parts of the date will default to the current day, month, year,
10829 hour and minute. If this command is called to replace a timestamp at point,
10830 of to enter the second timestamp of a range, the default time is taken from the
10831 existing stamp. For example,
10832 3-2-5 --> 2003-02-05
10833 feb 15 --> currentyear-02-15
10834 sep 12 9 --> 2009-09-12
10835 12:45 --> today 12:45
10836 22 sept 0:34 --> currentyear-09-22 0:34
10837 12 --> currentyear-currentmonth-12
10838 Fri --> nearest Friday (today or later)
10839 etc.
10841 Furthermore you can specify a relative date by giving, as the *first* thing
10842 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10843 change in days weeks, months, years.
10844 With a single plus or minus, the date is relative to today. With a double
10845 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10846 +4d --> four days from today
10847 +4 --> same as above
10848 +2w --> two weeks from today
10849 ++5 --> five days from default date
10851 The function understands only English month and weekday abbreviations,
10852 but this can be configured with the variables `parse-time-months' and
10853 `parse-time-weekdays'.
10855 While prompting, a calendar is popped up - you can also select the
10856 date with the mouse (button 1). The calendar shows a period of three
10857 months. To scroll it to other months, use the keys `>' and `<'.
10858 If you don't like the calendar, turn it off with
10859 \(setq org-read-date-popup-calendar nil)
10861 With optional argument TO-TIME, the date will immediately be converted
10862 to an internal time.
10863 With an optional argument WITH-TIME, the prompt will suggest to also
10864 insert a time. Note that when WITH-TIME is not set, you can still
10865 enter a time, and this function will inform the calling routine about
10866 this change. The calling routine may then choose to change the format
10867 used to insert the time stamp into the buffer to include the time.
10868 With optional argument FROM-STRING, read from this string instead from
10869 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10870 the time/date that is used for everything that is not specified by the
10871 user."
10872 (require 'parse-time)
10873 (let* ((org-time-stamp-rounding-minutes
10874 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10875 (org-dcst org-display-custom-times)
10876 (ct (org-current-time))
10877 (def (or org-overriding-default-time default-time ct))
10878 (defdecode (decode-time def))
10879 (dummy (progn
10880 (when (< (nth 2 defdecode) org-extend-today-until)
10881 (setcar (nthcdr 2 defdecode) -1)
10882 (setcar (nthcdr 1 defdecode) 59)
10883 (setq def (apply 'encode-time defdecode)
10884 defdecode (decode-time def)))))
10885 (calendar-move-hook nil)
10886 (calendar-view-diary-initially-flag nil)
10887 (view-diary-entries-initially nil)
10888 (calendar-view-holidays-initially-flag nil)
10889 (view-calendar-holidays-initially nil)
10890 (timestr (format-time-string
10891 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10892 (prompt (concat (if prompt (concat prompt " ") "")
10893 (format "Date+time [%s]: " timestr)))
10894 ans (org-ans0 "") org-ans1 org-ans2 final)
10896 (cond
10897 (from-string (setq ans from-string))
10898 (org-read-date-popup-calendar
10899 (save-excursion
10900 (save-window-excursion
10901 (calendar)
10902 (calendar-forward-day (- (time-to-days def)
10903 (calendar-absolute-from-gregorian
10904 (calendar-current-date))))
10905 (org-eval-in-calendar nil t)
10906 (let* ((old-map (current-local-map))
10907 (map (copy-keymap calendar-mode-map))
10908 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10909 (org-defkey map (kbd "RET") 'org-calendar-select)
10910 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10911 'org-calendar-select-mouse)
10912 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10913 'org-calendar-select-mouse)
10914 (org-defkey minibuffer-local-map [(meta shift left)]
10915 (lambda () (interactive)
10916 (org-eval-in-calendar '(calendar-backward-month 1))))
10917 (org-defkey minibuffer-local-map [(meta shift right)]
10918 (lambda () (interactive)
10919 (org-eval-in-calendar '(calendar-forward-month 1))))
10920 (org-defkey minibuffer-local-map [(meta shift up)]
10921 (lambda () (interactive)
10922 (org-eval-in-calendar '(calendar-backward-year 1))))
10923 (org-defkey minibuffer-local-map [(meta shift down)]
10924 (lambda () (interactive)
10925 (org-eval-in-calendar '(calendar-forward-year 1))))
10926 (org-defkey minibuffer-local-map [(shift up)]
10927 (lambda () (interactive)
10928 (org-eval-in-calendar '(calendar-backward-week 1))))
10929 (org-defkey minibuffer-local-map [(shift down)]
10930 (lambda () (interactive)
10931 (org-eval-in-calendar '(calendar-forward-week 1))))
10932 (org-defkey minibuffer-local-map [(shift left)]
10933 (lambda () (interactive)
10934 (org-eval-in-calendar '(calendar-backward-day 1))))
10935 (org-defkey minibuffer-local-map [(shift right)]
10936 (lambda () (interactive)
10937 (org-eval-in-calendar '(calendar-forward-day 1))))
10938 (org-defkey minibuffer-local-map ">"
10939 (lambda () (interactive)
10940 (org-eval-in-calendar '(scroll-calendar-left 1))))
10941 (org-defkey minibuffer-local-map "<"
10942 (lambda () (interactive)
10943 (org-eval-in-calendar '(scroll-calendar-right 1))))
10944 (unwind-protect
10945 (progn
10946 (use-local-map map)
10947 (add-hook 'post-command-hook 'org-read-date-display)
10948 (setq org-ans0 (read-string prompt default-input nil nil))
10949 ;; org-ans0: from prompt
10950 ;; org-ans1: from mouse click
10951 ;; org-ans2: from calendar motion
10952 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10953 (remove-hook 'post-command-hook 'org-read-date-display)
10954 (use-local-map old-map)
10955 (when org-read-date-overlay
10956 (org-delete-overlay org-read-date-overlay)
10957 (setq org-read-date-overlay nil)))))))
10959 (t ; Naked prompt only
10960 (unwind-protect
10961 (setq ans (read-string prompt default-input nil timestr))
10962 (when org-read-date-overlay
10963 (org-delete-overlay org-read-date-overlay)
10964 (setq org-read-date-overlay nil)))))
10966 (setq final (org-read-date-analyze ans def defdecode))
10968 (if to-time
10969 (apply 'encode-time final)
10970 (if (and (boundp 'org-time-was-given) org-time-was-given)
10971 (format "%04d-%02d-%02d %02d:%02d"
10972 (nth 5 final) (nth 4 final) (nth 3 final)
10973 (nth 2 final) (nth 1 final))
10974 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10975 (defvar def)
10976 (defvar defdecode)
10977 (defvar with-time)
10978 (defun org-read-date-display ()
10979 "Display the current date prompt interpretation in the minibuffer."
10980 (when org-read-date-display-live
10981 (when org-read-date-overlay
10982 (org-delete-overlay org-read-date-overlay))
10983 (let ((p (point)))
10984 (end-of-line 1)
10985 (while (not (equal (buffer-substring
10986 (max (point-min) (- (point) 4)) (point))
10987 " "))
10988 (insert " "))
10989 (goto-char p))
10990 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10991 " " (or org-ans1 org-ans2)))
10992 (org-end-time-was-given nil)
10993 (f (org-read-date-analyze ans def defdecode))
10994 (fmts (if org-dcst
10995 org-time-stamp-custom-formats
10996 org-time-stamp-formats))
10997 (fmt (if (or with-time
10998 (and (boundp 'org-time-was-given) org-time-was-given))
10999 (cdr fmts)
11000 (car fmts)))
11001 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11002 (when (and org-end-time-was-given
11003 (string-match org-plain-time-of-day-regexp txt))
11004 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11005 org-end-time-was-given
11006 (substring txt (match-end 0)))))
11007 (setq org-read-date-overlay
11008 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11009 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11011 (defun org-read-date-analyze (ans def defdecode)
11012 "Analyse the combined answer of the date prompt."
11013 ;; FIXME: cleanup and comment
11014 (let (delta deltan deltaw deltadef year month day
11015 hour minute second wday pm h2 m2 tl wday1
11016 iso-year iso-weekday iso-week iso-year iso-date)
11018 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11019 (setq ans "+0"))
11021 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11022 (setq ans (replace-match "" t t ans)
11023 deltan (car delta)
11024 deltaw (nth 1 delta)
11025 deltadef (nth 2 delta)))
11027 ;; Check if there is an iso week date in there
11028 ;; If yes, sore the info and postpone interpreting it until the rest
11029 ;; of the parsing is done
11030 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11031 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11032 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11033 iso-week (string-to-number (match-string 2 ans)))
11034 (setq ans (replace-match "" t t ans)))
11036 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11037 (when (string-match
11038 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11039 (setq year (if (match-end 2)
11040 (string-to-number (match-string 2 ans))
11041 (string-to-number (format-time-string "%Y")))
11042 month (string-to-number (match-string 3 ans))
11043 day (string-to-number (match-string 4 ans)))
11044 (if (< year 100) (setq year (+ 2000 year)))
11045 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11046 t nil ans)))
11047 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11048 ;; If there is a time with am/pm, and *no* time without it, we convert
11049 ;; so that matching will be successful.
11050 (loop for i from 1 to 2 do ; twice, for end time as well
11051 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11052 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11053 (setq hour (string-to-number (match-string 1 ans))
11054 minute (if (match-end 3)
11055 (string-to-number (match-string 3 ans))
11057 pm (equal ?p
11058 (string-to-char (downcase (match-string 4 ans)))))
11059 (if (and (= hour 12) (not pm))
11060 (setq hour 0)
11061 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11062 (setq ans (replace-match (format "%02d:%02d" hour minute)
11063 t t ans))))
11065 ;; Check if a time range is given as a duration
11066 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11067 (setq hour (string-to-number (match-string 1 ans))
11068 h2 (+ hour (string-to-number (match-string 3 ans)))
11069 minute (string-to-number (match-string 2 ans))
11070 m2 (+ minute (if (match-end 5) (string-to-number
11071 (match-string 5 ans))0)))
11072 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11073 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11074 t t ans)))
11076 ;; Check if there is a time range
11077 (when (boundp 'org-end-time-was-given)
11078 (setq org-time-was-given nil)
11079 (when (and (string-match org-plain-time-of-day-regexp ans)
11080 (match-end 8))
11081 (setq org-end-time-was-given (match-string 8 ans))
11082 (setq ans (concat (substring ans 0 (match-beginning 7))
11083 (substring ans (match-end 7))))))
11085 (setq tl (parse-time-string ans)
11086 day (or (nth 3 tl) (nth 3 defdecode))
11087 month (or (nth 4 tl)
11088 (if (and org-read-date-prefer-future
11089 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11090 (1+ (nth 4 defdecode))
11091 (nth 4 defdecode)))
11092 year (or (nth 5 tl)
11093 (if (and org-read-date-prefer-future
11094 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11095 (1+ (nth 5 defdecode))
11096 (nth 5 defdecode)))
11097 hour (or (nth 2 tl) (nth 2 defdecode))
11098 minute (or (nth 1 tl) (nth 1 defdecode))
11099 second (or (nth 0 tl) 0)
11100 wday (nth 6 tl))
11102 ;; Special date definitions below
11103 (cond
11104 (iso-week
11105 ;; There was an iso week
11106 (setq year (or iso-year year)
11107 day (or iso-weekday wday 1)
11108 wday nil ; to make sure that the trigger below does not match
11109 iso-date (calendar-gregorian-from-absolute
11110 (calendar-absolute-from-iso
11111 (list iso-week day year))))
11112 ; FIXME: Should we also push ISO weeks into the future?
11113 ; (when (and org-read-date-prefer-future
11114 ; (not iso-year)
11115 ; (< (calendar-absolute-from-gregorian iso-date)
11116 ; (time-to-days (current-time))))
11117 ; (setq year (1+ year)
11118 ; iso-date (calendar-gregorian-from-absolute
11119 ; (calendar-absolute-from-iso
11120 ; (list iso-week day year)))))
11121 (setq month (car iso-date)
11122 year (nth 2 iso-date)
11123 day (nth 1 iso-date)))
11124 (deltan
11125 (unless deltadef
11126 (let ((now (decode-time (current-time))))
11127 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11128 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11129 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11130 ((equal deltaw "m") (setq month (+ month deltan)))
11131 ((equal deltaw "y") (setq year (+ year deltan)))))
11132 ((and wday (not (nth 3 tl)))
11133 ;; Weekday was given, but no day, so pick that day in the week
11134 ;; on or after the derived date.
11135 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11136 (unless (equal wday wday1)
11137 (setq day (+ day (% (- wday wday1 -7) 7))))))
11138 (if (and (boundp 'org-time-was-given)
11139 (nth 2 tl))
11140 (setq org-time-was-given t))
11141 (if (< year 100) (setq year (+ 2000 year)))
11142 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11143 (list second minute hour day month year)))
11145 (defvar parse-time-weekdays)
11147 (defun org-read-date-get-relative (s today default)
11148 "Check string S for special relative date string.
11149 TODAY and DEFAULT are internal times, for today and for a default.
11150 Return shift list (N what def-flag)
11151 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11152 N is the number of WHATs to shift.
11153 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11154 the DEFAULT date rather than TODAY."
11155 (when (and
11156 (string-match
11157 (concat
11158 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11159 "\\([0-9]+\\)?"
11160 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11161 "\\([ \t]\\|$\\)") s)
11162 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11163 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11164 (string-to-char (substring (match-string 1 s) -1))
11165 ?+))
11166 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11167 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11168 (what (if (match-end 3) (match-string 3 s) "d"))
11169 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11170 (date (if rel default today))
11171 (wday (nth 6 (decode-time date)))
11172 delta)
11173 (if wday1
11174 (progn
11175 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11176 (if (= dir ?-) (setq delta (- delta 7)))
11177 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11178 (list delta "d" rel))
11179 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11181 (defun org-eval-in-calendar (form &optional keepdate)
11182 "Eval FORM in the calendar window and return to current window.
11183 Also, store the cursor date in variable org-ans2."
11184 (let ((sw (selected-window)))
11185 (select-window (get-buffer-window "*Calendar*"))
11186 (eval form)
11187 (when (and (not keepdate) (calendar-cursor-to-date))
11188 (let* ((date (calendar-cursor-to-date))
11189 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11190 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11191 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11192 (select-window sw)))
11194 (defun org-calendar-select ()
11195 "Return to `org-read-date' with the date currently selected.
11196 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11197 (interactive)
11198 (when (calendar-cursor-to-date)
11199 (let* ((date (calendar-cursor-to-date))
11200 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11201 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11202 (if (active-minibuffer-window) (exit-minibuffer))))
11204 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11205 "Insert a date stamp for the date given by the internal TIME.
11206 WITH-HM means, use the stamp format that includes the time of the day.
11207 INACTIVE means use square brackets instead of angular ones, so that the
11208 stamp will not contribute to the agenda.
11209 PRE and POST are optional strings to be inserted before and after the
11210 stamp.
11211 The command returns the inserted time stamp."
11212 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11213 stamp)
11214 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11215 (insert-before-markers (or pre ""))
11216 (insert-before-markers (setq stamp (format-time-string fmt time)))
11217 (when (listp extra)
11218 (setq extra (car extra))
11219 (if (and (stringp extra)
11220 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11221 (setq extra (format "-%02d:%02d"
11222 (string-to-number (match-string 1 extra))
11223 (string-to-number (match-string 2 extra))))
11224 (setq extra nil)))
11225 (when extra
11226 (backward-char 1)
11227 (insert-before-markers extra)
11228 (forward-char 1))
11229 (insert-before-markers (or post ""))
11230 (setq org-last-inserted-timestamp stamp)))
11232 (defun org-toggle-time-stamp-overlays ()
11233 "Toggle the use of custom time stamp formats."
11234 (interactive)
11235 (setq org-display-custom-times (not org-display-custom-times))
11236 (unless org-display-custom-times
11237 (let ((p (point-min)) (bmp (buffer-modified-p)))
11238 (while (setq p (next-single-property-change p 'display))
11239 (if (and (get-text-property p 'display)
11240 (eq (get-text-property p 'face) 'org-date))
11241 (remove-text-properties
11242 p (setq p (next-single-property-change p 'display))
11243 '(display t))))
11244 (set-buffer-modified-p bmp)))
11245 (if (featurep 'xemacs)
11246 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11247 (org-restart-font-lock)
11248 (setq org-table-may-need-update t)
11249 (if org-display-custom-times
11250 (message "Time stamps are overlayed with custom format")
11251 (message "Time stamp overlays removed")))
11253 (defun org-display-custom-time (beg end)
11254 "Overlay modified time stamp format over timestamp between BEG and END."
11255 (let* ((ts (buffer-substring beg end))
11256 t1 w1 with-hm tf time str w2 (off 0))
11257 (save-match-data
11258 (setq t1 (org-parse-time-string ts t))
11259 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11260 (setq off (- (match-end 0) (match-beginning 0)))))
11261 (setq end (- end off))
11262 (setq w1 (- end beg)
11263 with-hm (and (nth 1 t1) (nth 2 t1))
11264 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11265 time (org-fix-decoded-time t1)
11266 str (org-add-props
11267 (format-time-string
11268 (substring tf 1 -1) (apply 'encode-time time))
11269 nil 'mouse-face 'highlight)
11270 w2 (length str))
11271 (if (not (= w2 w1))
11272 (add-text-properties (1+ beg) (+ 2 beg)
11273 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11274 (if (featurep 'xemacs)
11275 (progn
11276 (put-text-property beg end 'invisible t)
11277 (put-text-property beg end 'end-glyph (make-glyph str)))
11278 (put-text-property beg end 'display str))))
11280 (defun org-translate-time (string)
11281 "Translate all timestamps in STRING to custom format.
11282 But do this only if the variable `org-display-custom-times' is set."
11283 (when org-display-custom-times
11284 (save-match-data
11285 (let* ((start 0)
11286 (re org-ts-regexp-both)
11287 t1 with-hm inactive tf time str beg end)
11288 (while (setq start (string-match re string start))
11289 (setq beg (match-beginning 0)
11290 end (match-end 0)
11291 t1 (save-match-data
11292 (org-parse-time-string (substring string beg end) t))
11293 with-hm (and (nth 1 t1) (nth 2 t1))
11294 inactive (equal (substring string beg (1+ beg)) "[")
11295 tf (funcall (if with-hm 'cdr 'car)
11296 org-time-stamp-custom-formats)
11297 time (org-fix-decoded-time t1)
11298 str (format-time-string
11299 (concat
11300 (if inactive "[" "<") (substring tf 1 -1)
11301 (if inactive "]" ">"))
11302 (apply 'encode-time time))
11303 string (replace-match str t t string)
11304 start (+ start (length str)))))))
11305 string)
11307 (defun org-fix-decoded-time (time)
11308 "Set 0 instead of nil for the first 6 elements of time.
11309 Don't touch the rest."
11310 (let ((n 0))
11311 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11313 (defun org-days-to-time (timestamp-string)
11314 "Difference between TIMESTAMP-STRING and now in days."
11315 (- (time-to-days (org-time-string-to-time timestamp-string))
11316 (time-to-days (current-time))))
11318 (defun org-deadline-close (timestamp-string &optional ndays)
11319 "Is the time in TIMESTAMP-STRING close to the current date?"
11320 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11321 (and (< (org-days-to-time timestamp-string) ndays)
11322 (not (org-entry-is-done-p))))
11324 (defun org-get-wdays (ts)
11325 "Get the deadline lead time appropriate for timestring TS."
11326 (cond
11327 ((<= org-deadline-warning-days 0)
11328 ;; 0 or negative, enforce this value no matter what
11329 (- org-deadline-warning-days))
11330 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11331 ;; lead time is specified.
11332 (floor (* (string-to-number (match-string 1 ts))
11333 (cdr (assoc (match-string 2 ts)
11334 '(("d" . 1) ("w" . 7)
11335 ("m" . 30.4) ("y" . 365.25)))))))
11336 ;; go for the default.
11337 (t org-deadline-warning-days)))
11339 (defun org-calendar-select-mouse (ev)
11340 "Return to `org-read-date' with the date currently selected.
11341 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11342 (interactive "e")
11343 (mouse-set-point ev)
11344 (when (calendar-cursor-to-date)
11345 (let* ((date (calendar-cursor-to-date))
11346 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11347 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11348 (if (active-minibuffer-window) (exit-minibuffer))))
11350 (defun org-check-deadlines (ndays)
11351 "Check if there are any deadlines due or past due.
11352 A deadline is considered due if it happens within `org-deadline-warning-days'
11353 days from today's date. If the deadline appears in an entry marked DONE,
11354 it is not shown. The prefix arg NDAYS can be used to test that many
11355 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11356 (interactive "P")
11357 (let* ((org-warn-days
11358 (cond
11359 ((equal ndays '(4)) 100000)
11360 (ndays (prefix-numeric-value ndays))
11361 (t (abs org-deadline-warning-days))))
11362 (case-fold-search nil)
11363 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11364 (callback
11365 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11367 (message "%d deadlines past-due or due within %d days"
11368 (org-occur regexp nil callback)
11369 org-warn-days)))
11371 (defun org-check-before-date (date)
11372 "Check if there are deadlines or scheduled entries before DATE."
11373 (interactive (list (org-read-date)))
11374 (let ((case-fold-search nil)
11375 (regexp (concat "\\<\\(" org-deadline-string
11376 "\\|" org-scheduled-string
11377 "\\) *<\\([^>]+\\)>"))
11378 (callback
11379 (lambda () (time-less-p
11380 (org-time-string-to-time (match-string 2))
11381 (org-time-string-to-time date)))))
11382 (message "%d entries before %s"
11383 (org-occur regexp nil callback) date)))
11385 (defun org-evaluate-time-range (&optional to-buffer)
11386 "Evaluate a time range by computing the difference between start and end.
11387 Normally the result is just printed in the echo area, but with prefix arg
11388 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11389 If the time range is actually in a table, the result is inserted into the
11390 next column.
11391 For time difference computation, a year is assumed to be exactly 365
11392 days in order to avoid rounding problems."
11393 (interactive "P")
11395 (org-clock-update-time-maybe)
11396 (save-excursion
11397 (unless (org-at-date-range-p t)
11398 (goto-char (point-at-bol))
11399 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11400 (if (not (org-at-date-range-p t))
11401 (error "Not at a time-stamp range, and none found in current line")))
11402 (let* ((ts1 (match-string 1))
11403 (ts2 (match-string 2))
11404 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11405 (match-end (match-end 0))
11406 (time1 (org-time-string-to-time ts1))
11407 (time2 (org-time-string-to-time ts2))
11408 (t1 (time-to-seconds time1))
11409 (t2 (time-to-seconds time2))
11410 (diff (abs (- t2 t1)))
11411 (negative (< (- t2 t1) 0))
11412 ;; (ys (floor (* 365 24 60 60)))
11413 (ds (* 24 60 60))
11414 (hs (* 60 60))
11415 (fy "%dy %dd %02d:%02d")
11416 (fy1 "%dy %dd")
11417 (fd "%dd %02d:%02d")
11418 (fd1 "%dd")
11419 (fh "%02d:%02d")
11420 y d h m align)
11421 (if havetime
11422 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11424 d (floor (/ diff ds)) diff (mod diff ds)
11425 h (floor (/ diff hs)) diff (mod diff hs)
11426 m (floor (/ diff 60)))
11427 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11429 d (floor (+ (/ diff ds) 0.5))
11430 h 0 m 0))
11431 (if (not to-buffer)
11432 (message "%s" (org-make-tdiff-string y d h m))
11433 (if (org-at-table-p)
11434 (progn
11435 (goto-char match-end)
11436 (setq align t)
11437 (and (looking-at " *|") (goto-char (match-end 0))))
11438 (goto-char match-end))
11439 (if (looking-at
11440 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11441 (replace-match ""))
11442 (if negative (insert " -"))
11443 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11444 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11445 (insert " " (format fh h m))))
11446 (if align (org-table-align))
11447 (message "Time difference inserted")))))
11449 (defun org-make-tdiff-string (y d h m)
11450 (let ((fmt "")
11451 (l nil))
11452 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11453 l (push y l)))
11454 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11455 l (push d l)))
11456 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11457 l (push h l)))
11458 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11459 l (push m l)))
11460 (apply 'format fmt (nreverse l))))
11462 (defun org-time-string-to-time (s)
11463 (apply 'encode-time (org-parse-time-string s)))
11465 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11466 "Convert a time stamp to an absolute day number.
11467 If there is a specifyer for a cyclic time stamp, get the closest date to
11468 DAYNR.
11469 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11470 (cond
11471 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11472 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11473 daynr
11474 (+ daynr 1000)))
11475 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11476 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11477 (time-to-days (current-time))) (match-string 0 s)
11478 prefer show-all))
11479 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11481 (defun org-days-to-iso-week (days)
11482 "Return the iso week number."
11483 (require 'cal-iso)
11484 (car (calendar-iso-from-absolute days)))
11486 (defun org-small-year-to-year (year)
11487 "Convert 2-digit years into 4-digit years.
11488 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11489 The year 2000 cannot be abbreviated. Any year larger than 99
11490 is returned unchanged."
11491 (if (< year 38)
11492 (setq year (+ 2000 year))
11493 (if (< year 100)
11494 (setq year (+ 1900 year))))
11495 year)
11497 (defun org-time-from-absolute (d)
11498 "Return the time corresponding to date D.
11499 D may be an absolute day number, or a calendar-type list (month day year)."
11500 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11501 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11503 (defun org-calendar-holiday ()
11504 "List of holidays, for Diary display in Org-mode."
11505 (require 'holidays)
11506 (let ((hl (funcall
11507 (if (fboundp 'calendar-check-holidays)
11508 'calendar-check-holidays 'check-calendar-holidays) date)))
11509 (if hl (mapconcat 'identity hl "; "))))
11511 (defun org-diary-sexp-entry (sexp entry date)
11512 "Process a SEXP diary ENTRY for DATE."
11513 (require 'diary-lib)
11514 (let ((result (if calendar-debug-sexp
11515 (let ((stack-trace-on-error t))
11516 (eval (car (read-from-string sexp))))
11517 (condition-case nil
11518 (eval (car (read-from-string sexp)))
11519 (error
11520 (beep)
11521 (message "Bad sexp at line %d in %s: %s"
11522 (org-current-line)
11523 (buffer-file-name) sexp)
11524 (sleep-for 2))))))
11525 (cond ((stringp result) result)
11526 ((and (consp result)
11527 (stringp (cdr result))) (cdr result))
11528 (result entry)
11529 (t nil))))
11531 (defun org-diary-to-ical-string (frombuf)
11532 "Get iCalendar entries from diary entries in buffer FROMBUF.
11533 This uses the icalendar.el library."
11534 (let* ((tmpdir (if (featurep 'xemacs)
11535 (temp-directory)
11536 temporary-file-directory))
11537 (tmpfile (make-temp-name
11538 (expand-file-name "orgics" tmpdir)))
11539 buf rtn b e)
11540 (save-excursion
11541 (set-buffer frombuf)
11542 (icalendar-export-region (point-min) (point-max) tmpfile)
11543 (setq buf (find-buffer-visiting tmpfile))
11544 (set-buffer buf)
11545 (goto-char (point-min))
11546 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11547 (setq b (match-beginning 0)))
11548 (goto-char (point-max))
11549 (if (re-search-backward "^END:VEVENT" nil t)
11550 (setq e (match-end 0)))
11551 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11552 (kill-buffer buf)
11553 (delete-file tmpfile)
11554 rtn))
11556 (defun org-closest-date (start current change prefer show-all)
11557 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11558 When PREFER is `past' return a date that is either CURRENT or past.
11559 When PREFER is `future', return a date that is either CURRENT or future.
11560 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11561 ;; Make the proper lists from the dates
11562 (catch 'exit
11563 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11564 dn dw sday cday n1 n2
11565 d m y y1 y2 date1 date2 nmonths nm ny m2)
11567 (setq start (org-date-to-gregorian start)
11568 current (org-date-to-gregorian
11569 (if show-all
11570 current
11571 (time-to-days (current-time))))
11572 sday (calendar-absolute-from-gregorian start)
11573 cday (calendar-absolute-from-gregorian current))
11575 (if (<= cday sday) (throw 'exit sday))
11577 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11578 (setq dn (string-to-number (match-string 1 change))
11579 dw (cdr (assoc (match-string 2 change) a1)))
11580 (error "Invalid change specifyer: %s" change))
11581 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11582 (cond
11583 ((eq dw 'day)
11584 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11585 n2 (+ n1 dn)))
11586 ((eq dw 'year)
11587 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11588 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11589 (setq date1 (list m d y1)
11590 n1 (calendar-absolute-from-gregorian date1)
11591 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11592 n2 (calendar-absolute-from-gregorian date2)))
11593 ((eq dw 'month)
11594 ;; approx number of month between the two dates
11595 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11596 ;; How often does dn fit in there?
11597 (setq d (nth 1 start) m (car start) y (nth 2 start)
11598 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11599 m (+ m nm)
11600 ny (floor (/ m 12))
11601 y (+ y ny)
11602 m (- m (* ny 12)))
11603 (while (> m 12) (setq m (- m 12) y (1+ y)))
11604 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11605 (setq m2 (+ m dn) y2 y)
11606 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11607 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11608 (while (<= n2 cday)
11609 (setq n1 n2 m m2 y y2)
11610 (setq m2 (+ m dn) y2 y)
11611 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11612 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11613 (if show-all
11614 (cond
11615 ((eq prefer 'past) n1)
11616 ((eq prefer 'future) (if (= cday n1) n1 n2))
11617 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11618 (cond
11619 ((eq prefer 'past) n1)
11620 ((eq prefer 'future) (if (= cday n1) n1 n2))
11621 (t (if (= cday n1) n1 n2)))))))
11623 (defun org-date-to-gregorian (date)
11624 "Turn any specification of DATE into a gregorian date for the calendar."
11625 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11626 ((and (listp date) (= (length date) 3)) date)
11627 ((stringp date)
11628 (setq date (org-parse-time-string date))
11629 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11630 ((listp date)
11631 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11633 (defun org-parse-time-string (s &optional nodefault)
11634 "Parse the standard Org-mode time string.
11635 This should be a lot faster than the normal `parse-time-string'.
11636 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11637 hour and minute fields will be nil if not given."
11638 (if (string-match org-ts-regexp0 s)
11639 (list 0
11640 (if (or (match-beginning 8) (not nodefault))
11641 (string-to-number (or (match-string 8 s) "0")))
11642 (if (or (match-beginning 7) (not nodefault))
11643 (string-to-number (or (match-string 7 s) "0")))
11644 (string-to-number (match-string 4 s))
11645 (string-to-number (match-string 3 s))
11646 (string-to-number (match-string 2 s))
11647 nil nil nil)
11648 (make-list 9 0)))
11650 (defun org-timestamp-up (&optional arg)
11651 "Increase the date item at the cursor by one.
11652 If the cursor is on the year, change the year. If it is on the month or
11653 the day, change that.
11654 With prefix ARG, change by that many units."
11655 (interactive "p")
11656 (org-timestamp-change (prefix-numeric-value arg)))
11658 (defun org-timestamp-down (&optional arg)
11659 "Decrease the date item at the cursor by one.
11660 If the cursor is on the year, change the year. If it is on the month or
11661 the day, change that.
11662 With prefix ARG, change by that many units."
11663 (interactive "p")
11664 (org-timestamp-change (- (prefix-numeric-value arg))))
11666 (defun org-timestamp-up-day (&optional arg)
11667 "Increase the date in the time stamp by one day.
11668 With prefix ARG, change that many days."
11669 (interactive "p")
11670 (if (and (not (org-at-timestamp-p t))
11671 (org-on-heading-p))
11672 (org-todo 'up)
11673 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11675 (defun org-timestamp-down-day (&optional arg)
11676 "Decrease the date in the time stamp by one day.
11677 With prefix ARG, change that many days."
11678 (interactive "p")
11679 (if (and (not (org-at-timestamp-p t))
11680 (org-on-heading-p))
11681 (org-todo 'down)
11682 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11684 (defun org-at-timestamp-p (&optional inactive-ok)
11685 "Determine if the cursor is in or at a timestamp."
11686 (interactive)
11687 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11688 (pos (point))
11689 (ans (or (looking-at tsr)
11690 (save-excursion
11691 (skip-chars-backward "^[<\n\r\t")
11692 (if (> (point) (point-min)) (backward-char 1))
11693 (and (looking-at tsr)
11694 (> (- (match-end 0) pos) -1))))))
11695 (and ans
11696 (boundp 'org-ts-what)
11697 (setq org-ts-what
11698 (cond
11699 ((= pos (match-beginning 0)) 'bracket)
11700 ((= pos (1- (match-end 0))) 'bracket)
11701 ((org-pos-in-match-range pos 2) 'year)
11702 ((org-pos-in-match-range pos 3) 'month)
11703 ((org-pos-in-match-range pos 7) 'hour)
11704 ((org-pos-in-match-range pos 8) 'minute)
11705 ((or (org-pos-in-match-range pos 4)
11706 (org-pos-in-match-range pos 5)) 'day)
11707 ((and (> pos (or (match-end 8) (match-end 5)))
11708 (< pos (match-end 0)))
11709 (- pos (or (match-end 8) (match-end 5))))
11710 (t 'day))))
11711 ans))
11713 (defun org-toggle-timestamp-type ()
11714 "Toggle the type (<active> or [inactive]) of a time stamp."
11715 (interactive)
11716 (when (org-at-timestamp-p t)
11717 (let ((beg (match-beginning 0)) (end (match-end 0))
11718 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11719 (save-excursion
11720 (goto-char beg)
11721 (while (re-search-forward "[][<>]" end t)
11722 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11723 t t)))
11724 (message "Timestamp is now %sactive"
11725 (if (equal (char-after beg) ?<) "" "in")))))
11727 (defun org-timestamp-change (n &optional what)
11728 "Change the date in the time stamp at point.
11729 The date will be changed by N times WHAT. WHAT can be `day', `month',
11730 `year', `minute', `second'. If WHAT is not given, the cursor position
11731 in the timestamp determines what will be changed."
11732 (let ((pos (point))
11733 with-hm inactive
11734 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11735 org-ts-what
11736 extra rem
11737 ts time time0)
11738 (if (not (org-at-timestamp-p t))
11739 (error "Not at a timestamp"))
11740 (if (and (not what) (eq org-ts-what 'bracket))
11741 (org-toggle-timestamp-type)
11742 (if (and (not what) (not (eq org-ts-what 'day))
11743 org-display-custom-times
11744 (get-text-property (point) 'display)
11745 (not (get-text-property (1- (point)) 'display)))
11746 (setq org-ts-what 'day))
11747 (setq org-ts-what (or what org-ts-what)
11748 inactive (= (char-after (match-beginning 0)) ?\[)
11749 ts (match-string 0))
11750 (replace-match "")
11751 (if (string-match
11752 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11754 (setq extra (match-string 1 ts)))
11755 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11756 (setq with-hm t))
11757 (setq time0 (org-parse-time-string ts))
11758 (when (and (eq org-ts-what 'minute)
11759 (eq current-prefix-arg nil))
11760 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11761 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11762 (setcar (cdr time0) (+ (nth 1 time0)
11763 (if (> n 0) (- rem) (- dm rem))))))
11764 (setq time
11765 (encode-time (or (car time0) 0)
11766 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11767 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11768 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11769 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11770 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11771 (nthcdr 6 time0)))
11772 (when (integerp org-ts-what)
11773 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11774 (if (eq what 'calendar)
11775 (let ((cal-date (org-get-date-from-calendar)))
11776 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11777 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11778 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11779 (setcar time0 (or (car time0) 0))
11780 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11781 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11782 (setq time (apply 'encode-time time0))))
11783 (setq org-last-changed-timestamp
11784 (org-insert-time-stamp time with-hm inactive nil nil extra))
11785 (org-clock-update-time-maybe)
11786 (goto-char pos)
11787 ;; Try to recenter the calendar window, if any
11788 (if (and org-calendar-follow-timestamp-change
11789 (get-buffer-window "*Calendar*" t)
11790 (memq org-ts-what '(day month year)))
11791 (org-recenter-calendar (time-to-days time))))))
11793 (defun org-modify-ts-extra (s pos n dm)
11794 "Change the different parts of the lead-time and repeat fields in timestamp."
11795 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11796 ng h m new rem)
11797 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11798 (cond
11799 ((or (org-pos-in-match-range pos 2)
11800 (org-pos-in-match-range pos 3))
11801 (setq m (string-to-number (match-string 3 s))
11802 h (string-to-number (match-string 2 s)))
11803 (if (org-pos-in-match-range pos 2)
11804 (setq h (+ h n))
11805 (setq n (* dm (org-no-warnings (signum n))))
11806 (when (not (= 0 (setq rem (% m dm))))
11807 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11808 (setq m (+ m n)))
11809 (if (< m 0) (setq m (+ m 60) h (1- h)))
11810 (if (> m 59) (setq m (- m 60) h (1+ h)))
11811 (setq h (min 24 (max 0 h)))
11812 (setq ng 1 new (format "-%02d:%02d" h m)))
11813 ((org-pos-in-match-range pos 6)
11814 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11815 ((org-pos-in-match-range pos 5)
11816 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11818 ((org-pos-in-match-range pos 9)
11819 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11820 ((org-pos-in-match-range pos 8)
11821 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11823 (when ng
11824 (setq s (concat
11825 (substring s 0 (match-beginning ng))
11827 (substring s (match-end ng))))))
11830 (defun org-recenter-calendar (date)
11831 "If the calendar is visible, recenter it to DATE."
11832 (let* ((win (selected-window))
11833 (cwin (get-buffer-window "*Calendar*" t))
11834 (calendar-move-hook nil))
11835 (when cwin
11836 (select-window cwin)
11837 (calendar-goto-date (if (listp date) date
11838 (calendar-gregorian-from-absolute date)))
11839 (select-window win))))
11841 (defun org-goto-calendar (&optional arg)
11842 "Go to the Emacs calendar at the current date.
11843 If there is a time stamp in the current line, go to that date.
11844 A prefix ARG can be used to force the current date."
11845 (interactive "P")
11846 (let ((tsr org-ts-regexp) diff
11847 (calendar-move-hook nil)
11848 (calendar-view-holidays-initially-flag nil)
11849 (view-calendar-holidays-initially nil)
11850 (calendar-view-diary-initially-flag nil)
11851 (view-diary-entries-initially nil))
11852 (if (or (org-at-timestamp-p)
11853 (save-excursion
11854 (beginning-of-line 1)
11855 (looking-at (concat ".*" tsr))))
11856 (let ((d1 (time-to-days (current-time)))
11857 (d2 (time-to-days
11858 (org-time-string-to-time (match-string 1)))))
11859 (setq diff (- d2 d1))))
11860 (calendar)
11861 (calendar-goto-today)
11862 (if (and diff (not arg)) (calendar-forward-day diff))))
11864 (defun org-get-date-from-calendar ()
11865 "Return a list (month day year) of date at point in calendar."
11866 (with-current-buffer "*Calendar*"
11867 (save-match-data
11868 (calendar-cursor-to-date))))
11870 (defun org-date-from-calendar ()
11871 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11872 If there is already a time stamp at the cursor position, update it."
11873 (interactive)
11874 (if (org-at-timestamp-p t)
11875 (org-timestamp-change 0 'calendar)
11876 (let ((cal-date (org-get-date-from-calendar)))
11877 (org-insert-time-stamp
11878 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11880 (defun org-minutes-to-hh:mm-string (m)
11881 "Compute H:MM from a number of minutes."
11882 (let ((h (/ m 60)))
11883 (setq m (- m (* 60 h)))
11884 (format org-time-clocksum-format h m)))
11886 (defun org-hh:mm-string-to-minutes (s)
11887 "Convert a string H:MM to a number of minutes."
11888 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11889 (+ (* (string-to-number (match-string 1 s)) 60)
11890 (string-to-number (match-string 2 s)))
11893 ;;;; Agenda files
11895 ;;;###autoload
11896 (defun org-iswitchb (&optional arg)
11897 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11898 With a prefix argument, restrict available to files.
11899 With two prefix arguments, restrict available buffers to agenda files.
11901 Due to some yet unresolved reason, the global function
11902 `iswitchb-mode' needs to be active for this function to work."
11903 (interactive "P")
11904 (require 'iswitchb)
11905 (let ((enabled iswitchb-mode) blist)
11906 (or enabled (iswitchb-mode 1))
11907 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11908 ((equal arg '(16)) (org-buffer-list 'agenda))
11909 (t (org-buffer-list))))
11910 (unwind-protect
11911 (let ((iswitchb-make-buflist-hook
11912 (lambda ()
11913 (setq iswitchb-temp-buflist
11914 (mapcar 'buffer-name blist)))))
11915 (switch-to-buffer
11916 (iswitchb-read-buffer
11917 "Switch-to: " nil t))
11918 (or enabled (iswitchb-mode -1))))))
11920 ;;;###autoload
11921 (defun org-ido-switchb (&optional arg)
11922 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
11923 With a prefix argument, restrict available to files.
11924 With two prefix arguments, restrict available buffers to agenda files."
11925 (interactive "P")
11926 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11927 ((equal arg '(16)) (org-buffer-list 'agenda))
11928 (t (org-buffer-list)))))
11929 (switch-to-buffer
11930 (org-ido-completing-read "Org buffer: "
11931 (mapcar 'buffer-name blist)
11932 nil t))))
11934 (defun org-buffer-list (&optional predicate exclude-tmp)
11935 "Return a list of Org buffers.
11936 PREDICATE can be `export', `files' or `agenda'.
11938 export restrict the list to Export buffers.
11939 files restrict the list to buffers visiting Org files.
11940 agenda restrict the list to buffers visiting agenda files.
11942 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11943 (let* ((bfn nil)
11944 (agenda-files (and (eq predicate 'agenda)
11945 (mapcar 'file-truename (org-agenda-files t))))
11946 (filter
11947 (cond
11948 ((eq predicate 'files)
11949 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11950 ((eq predicate 'export)
11951 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11952 ((eq predicate 'agenda)
11953 (lambda (b)
11954 (with-current-buffer b
11955 (and (eq major-mode 'org-mode)
11956 (setq bfn (buffer-file-name b))
11957 (member (file-truename bfn) agenda-files)))))
11958 (t (lambda (b) (with-current-buffer b
11959 (or (eq major-mode 'org-mode)
11960 (string-match "\*Org .*Export"
11961 (buffer-name b)))))))))
11962 (delq nil
11963 (mapcar
11964 (lambda(b)
11965 (if (and (funcall filter b)
11966 (or (not exclude-tmp)
11967 (not (string-match "tmp" (buffer-name b)))))
11969 nil))
11970 (buffer-list)))))
11972 (defun org-agenda-files (&optional unrestricted archives)
11973 "Get the list of agenda files.
11974 Optional UNRESTRICTED means return the full list even if a restriction
11975 is currently in place.
11976 When ARCHIVES is t, include all archive files hat are really being
11977 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11978 `org-agenda-archives-mode' is t."
11979 (let ((files
11980 (cond
11981 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11982 ((stringp org-agenda-files) (org-read-agenda-file-list))
11983 ((listp org-agenda-files) org-agenda-files)
11984 (t (error "Invalid value of `org-agenda-files'")))))
11985 (setq files (apply 'append
11986 (mapcar (lambda (f)
11987 (if (file-directory-p f)
11988 (directory-files
11989 f t org-agenda-file-regexp)
11990 (list f)))
11991 files)))
11992 (when org-agenda-skip-unavailable-files
11993 (setq files (delq nil
11994 (mapcar (function
11995 (lambda (file)
11996 (and (file-readable-p file) file)))
11997 files))))
11998 (when (or (eq archives t)
11999 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12000 (setq files (org-add-archive-files files)))
12001 files))
12003 (defun org-edit-agenda-file-list ()
12004 "Edit the list of agenda files.
12005 Depending on setup, this either uses customize to edit the variable
12006 `org-agenda-files', or it visits the file that is holding the list. In the
12007 latter case, the buffer is set up in a way that saving it automatically kills
12008 the buffer and restores the previous window configuration."
12009 (interactive)
12010 (if (stringp org-agenda-files)
12011 (let ((cw (current-window-configuration)))
12012 (find-file org-agenda-files)
12013 (org-set-local 'org-window-configuration cw)
12014 (org-add-hook 'after-save-hook
12015 (lambda ()
12016 (set-window-configuration
12017 (prog1 org-window-configuration
12018 (kill-buffer (current-buffer))))
12019 (org-install-agenda-files-menu)
12020 (message "New agenda file list installed"))
12021 nil 'local)
12022 (message "%s" (substitute-command-keys
12023 "Edit list and finish with \\[save-buffer]")))
12024 (customize-variable 'org-agenda-files)))
12026 (defun org-store-new-agenda-file-list (list)
12027 "Set new value for the agenda file list and save it correctly."
12028 (if (stringp org-agenda-files)
12029 (let ((f org-agenda-files) b)
12030 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12031 (with-temp-file f
12032 (insert (mapconcat 'identity list "\n") "\n")))
12033 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12034 (setq org-agenda-files list)
12035 (customize-save-variable 'org-agenda-files org-agenda-files))))
12037 (defun org-read-agenda-file-list ()
12038 "Read the list of agenda files from a file."
12039 (when (file-directory-p org-agenda-files)
12040 (error "`org-agenda-files' cannot be a single directory"))
12041 (when (stringp org-agenda-files)
12042 (with-temp-buffer
12043 (insert-file-contents org-agenda-files)
12044 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12047 ;;;###autoload
12048 (defun org-cycle-agenda-files ()
12049 "Cycle through the files in `org-agenda-files'.
12050 If the current buffer visits an agenda file, find the next one in the list.
12051 If the current buffer does not, find the first agenda file."
12052 (interactive)
12053 (let* ((fs (org-agenda-files t))
12054 (files (append fs (list (car fs))))
12055 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12056 file)
12057 (unless files (error "No agenda files"))
12058 (catch 'exit
12059 (while (setq file (pop files))
12060 (if (equal (file-truename file) tcf)
12061 (when (car files)
12062 (find-file (car files))
12063 (throw 'exit t))))
12064 (find-file (car fs)))
12065 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12067 (defun org-agenda-file-to-front (&optional to-end)
12068 "Move/add the current file to the top of the agenda file list.
12069 If the file is not present in the list, it is added to the front. If it is
12070 present, it is moved there. With optional argument TO-END, add/move to the
12071 end of the list."
12072 (interactive "P")
12073 (let ((org-agenda-skip-unavailable-files nil)
12074 (file-alist (mapcar (lambda (x)
12075 (cons (file-truename x) x))
12076 (org-agenda-files t)))
12077 (ctf (file-truename buffer-file-name))
12078 x had)
12079 (setq x (assoc ctf file-alist) had x)
12081 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12082 (if to-end
12083 (setq file-alist (append (delq x file-alist) (list x)))
12084 (setq file-alist (cons x (delq x file-alist))))
12085 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12086 (org-install-agenda-files-menu)
12087 (message "File %s to %s of agenda file list"
12088 (if had "moved" "added") (if to-end "end" "front"))))
12090 (defun org-remove-file (&optional file)
12091 "Remove current file from the list of files in variable `org-agenda-files'.
12092 These are the files which are being checked for agenda entries.
12093 Optional argument FILE means, use this file instead of the current."
12094 (interactive)
12095 (let* ((org-agenda-skip-unavailable-files nil)
12096 (file (or file buffer-file-name))
12097 (true-file (file-truename file))
12098 (afile (abbreviate-file-name file))
12099 (files (delq nil (mapcar
12100 (lambda (x)
12101 (if (equal true-file
12102 (file-truename x))
12103 nil x))
12104 (org-agenda-files t)))))
12105 (if (not (= (length files) (length (org-agenda-files t))))
12106 (progn
12107 (org-store-new-agenda-file-list files)
12108 (org-install-agenda-files-menu)
12109 (message "Removed file: %s" afile))
12110 (message "File was not in list: %s (not removed)" afile))))
12112 (defun org-file-menu-entry (file)
12113 (vector file (list 'find-file file) t))
12115 (defun org-check-agenda-file (file)
12116 "Make sure FILE exists. If not, ask user what to do."
12117 (when (not (file-exists-p file))
12118 (message "non-existent file %s. [R]emove from list or [A]bort?"
12119 (abbreviate-file-name file))
12120 (let ((r (downcase (read-char-exclusive))))
12121 (cond
12122 ((equal r ?r)
12123 (org-remove-file file)
12124 (throw 'nextfile t))
12125 (t (error "Abort"))))))
12127 (defun org-get-agenda-file-buffer (file)
12128 "Get a buffer visiting FILE. If the buffer needs to be created, add
12129 it to the list of buffers which might be released later."
12130 (let ((buf (org-find-base-buffer-visiting file)))
12131 (if buf
12132 buf ; just return it
12133 ;; Make a new buffer and remember it
12134 (setq buf (find-file-noselect file))
12135 (if buf (push buf org-agenda-new-buffers))
12136 buf)))
12138 (defun org-release-buffers (blist)
12139 "Release all buffers in list, asking the user for confirmation when needed.
12140 When a buffer is unmodified, it is just killed. When modified, it is saved
12141 \(if the user agrees) and then killed."
12142 (let (buf file)
12143 (while (setq buf (pop blist))
12144 (setq file (buffer-file-name buf))
12145 (when (and (buffer-modified-p buf)
12146 file
12147 (y-or-n-p (format "Save file %s? " file)))
12148 (with-current-buffer buf (save-buffer)))
12149 (kill-buffer buf))))
12151 (defun org-prepare-agenda-buffers (files)
12152 "Create buffers for all agenda files, protect archived trees and comments."
12153 (interactive)
12154 (let ((pa '(:org-archived t))
12155 (pc '(:org-comment t))
12156 (pall '(:org-archived t :org-comment t))
12157 (inhibit-read-only t)
12158 (rea (concat ":" org-archive-tag ":"))
12159 bmp file re)
12160 (save-excursion
12161 (save-restriction
12162 (while (setq file (pop files))
12163 (if (bufferp file)
12164 (set-buffer file)
12165 (org-check-agenda-file file)
12166 (set-buffer (org-get-agenda-file-buffer file)))
12167 (widen)
12168 (setq bmp (buffer-modified-p))
12169 (org-refresh-category-properties)
12170 (setq org-todo-keywords-for-agenda
12171 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12172 (setq org-done-keywords-for-agenda
12173 (append org-done-keywords-for-agenda org-done-keywords))
12174 (setq org-todo-keyword-alist-for-agenda
12175 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12176 (setq org-tag-alist-for-agenda
12177 (append org-tag-alist-for-agenda org-tag-alist))
12179 (save-excursion
12180 (remove-text-properties (point-min) (point-max) pall)
12181 (when org-agenda-skip-archived-trees
12182 (goto-char (point-min))
12183 (while (re-search-forward rea nil t)
12184 (if (org-on-heading-p t)
12185 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12186 (goto-char (point-min))
12187 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12188 (while (re-search-forward re nil t)
12189 (add-text-properties
12190 (match-beginning 0) (org-end-of-subtree t) pc)))
12191 (set-buffer-modified-p bmp))))
12192 (setq org-todo-keyword-alist-for-agenda
12193 (org-uniquify org-todo-keyword-alist-for-agenda)
12194 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12196 ;;;; Embedded LaTeX
12198 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12199 "Keymap for the minor `org-cdlatex-mode'.")
12201 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12202 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12203 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12204 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12205 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12207 (defvar org-cdlatex-texmathp-advice-is-done nil
12208 "Flag remembering if we have applied the advice to texmathp already.")
12210 (define-minor-mode org-cdlatex-mode
12211 "Toggle the minor `org-cdlatex-mode'.
12212 This mode supports entering LaTeX environment and math in LaTeX fragments
12213 in Org-mode.
12214 \\{org-cdlatex-mode-map}"
12215 nil " OCDL" nil
12216 (when org-cdlatex-mode (require 'cdlatex))
12217 (unless org-cdlatex-texmathp-advice-is-done
12218 (setq org-cdlatex-texmathp-advice-is-done t)
12219 (defadvice texmathp (around org-math-always-on activate)
12220 "Always return t in org-mode buffers.
12221 This is because we want to insert math symbols without dollars even outside
12222 the LaTeX math segments. If Orgmode thinks that point is actually inside
12223 an embedded LaTeX fragment, let texmathp do its job.
12224 \\[org-cdlatex-mode-map]"
12225 (interactive)
12226 (let (p)
12227 (cond
12228 ((not (org-mode-p)) ad-do-it)
12229 ((eq this-command 'cdlatex-math-symbol)
12230 (setq ad-return-value t
12231 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12233 (let ((p (org-inside-LaTeX-fragment-p)))
12234 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12235 (setq ad-return-value t
12236 texmathp-why '("Org-mode embedded math" . 0))
12237 (if p ad-do-it)))))))))
12239 (defun turn-on-org-cdlatex ()
12240 "Unconditionally turn on `org-cdlatex-mode'."
12241 (org-cdlatex-mode 1))
12243 (defun org-inside-LaTeX-fragment-p ()
12244 "Test if point is inside a LaTeX fragment.
12245 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12246 sequence appearing also before point.
12247 Even though the matchers for math are configurable, this function assumes
12248 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12249 delimiters are skipped when they have been removed by customization.
12250 The return value is nil, or a cons cell with the delimiter and
12251 and the position of this delimiter.
12253 This function does a reasonably good job, but can locally be fooled by
12254 for example currency specifications. For example it will assume being in
12255 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12256 fragments that are properly closed, but during editing, we have to live
12257 with the uncertainty caused by missing closing delimiters. This function
12258 looks only before point, not after."
12259 (catch 'exit
12260 (let ((pos (point))
12261 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12262 (lim (progn
12263 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12264 (point)))
12265 dd-on str (start 0) m re)
12266 (goto-char pos)
12267 (when dodollar
12268 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12269 re (nth 1 (assoc "$" org-latex-regexps)))
12270 (while (string-match re str start)
12271 (cond
12272 ((= (match-end 0) (length str))
12273 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12274 ((= (match-end 0) (- (length str) 5))
12275 (throw 'exit nil))
12276 (t (setq start (match-end 0))))))
12277 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12278 (goto-char pos)
12279 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12280 (and (match-beginning 2) (throw 'exit nil))
12281 ;; count $$
12282 (while (re-search-backward "\\$\\$" lim t)
12283 (setq dd-on (not dd-on)))
12284 (goto-char pos)
12285 (if dd-on (cons "$$" m))))))
12288 (defun org-try-cdlatex-tab ()
12289 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12290 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12291 - inside a LaTeX fragment, or
12292 - after the first word in a line, where an abbreviation expansion could
12293 insert a LaTeX environment."
12294 (when org-cdlatex-mode
12295 (cond
12296 ((save-excursion
12297 (skip-chars-backward "a-zA-Z0-9*")
12298 (skip-chars-backward " \t")
12299 (bolp))
12300 (cdlatex-tab) t)
12301 ((org-inside-LaTeX-fragment-p)
12302 (cdlatex-tab) t)
12303 (t nil))))
12305 (defun org-cdlatex-underscore-caret (&optional arg)
12306 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12307 Revert to the normal definition outside of these fragments."
12308 (interactive "P")
12309 (if (org-inside-LaTeX-fragment-p)
12310 (call-interactively 'cdlatex-sub-superscript)
12311 (let (org-cdlatex-mode)
12312 (call-interactively (key-binding (vector last-input-event))))))
12314 (defun org-cdlatex-math-modify (&optional arg)
12315 "Execute `cdlatex-math-modify' in LaTeX fragments.
12316 Revert to the normal definition outside of these fragments."
12317 (interactive "P")
12318 (if (org-inside-LaTeX-fragment-p)
12319 (call-interactively 'cdlatex-math-modify)
12320 (let (org-cdlatex-mode)
12321 (call-interactively (key-binding (vector last-input-event))))))
12323 (defvar org-latex-fragment-image-overlays nil
12324 "List of overlays carrying the images of latex fragments.")
12325 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12327 (defun org-remove-latex-fragment-image-overlays ()
12328 "Remove all overlays with LaTeX fragment images in current buffer."
12329 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12330 (setq org-latex-fragment-image-overlays nil))
12332 (defun org-preview-latex-fragment (&optional subtree)
12333 "Preview the LaTeX fragment at point, or all locally or globally.
12334 If the cursor is in a LaTeX fragment, create the image and overlay
12335 it over the source code. If there is no fragment at point, display
12336 all fragments in the current text, from one headline to the next. With
12337 prefix SUBTREE, display all fragments in the current subtree. With a
12338 double prefix `C-u C-u', or when the cursor is before the first headline,
12339 display all fragments in the buffer.
12340 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12341 (interactive "P")
12342 (org-remove-latex-fragment-image-overlays)
12343 (save-excursion
12344 (save-restriction
12345 (let (beg end at msg)
12346 (cond
12347 ((or (equal subtree '(16))
12348 (not (save-excursion
12349 (re-search-backward (concat "^" outline-regexp) nil t))))
12350 (setq beg (point-min) end (point-max)
12351 msg "Creating images for buffer...%s"))
12352 ((equal subtree '(4))
12353 (org-back-to-heading)
12354 (setq beg (point) end (org-end-of-subtree t)
12355 msg "Creating images for subtree...%s"))
12357 (if (setq at (org-inside-LaTeX-fragment-p))
12358 (goto-char (max (point-min) (- (cdr at) 2)))
12359 (org-back-to-heading))
12360 (setq beg (point) end (progn (outline-next-heading) (point))
12361 msg (if at "Creating image...%s"
12362 "Creating images for entry...%s"))))
12363 (message msg "")
12364 (narrow-to-region beg end)
12365 (goto-char beg)
12366 (org-format-latex
12367 (concat "ltxpng/" (file-name-sans-extension
12368 (file-name-nondirectory
12369 buffer-file-name)))
12370 default-directory 'overlays msg at 'forbuffer)
12371 (message msg "done. Use `C-c C-c' to remove images.")))))
12373 (defvar org-latex-regexps
12374 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12375 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12376 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12377 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12378 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12379 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12380 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12381 "Regular expressions for matching embedded LaTeX.")
12383 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12384 "Replace LaTeX fragments with links to an image, and produce images."
12385 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12386 (let* ((prefixnodir (file-name-nondirectory prefix))
12387 (absprefix (expand-file-name prefix dir))
12388 (todir (file-name-directory absprefix))
12389 (opt org-format-latex-options)
12390 (matchers (plist-get opt :matchers))
12391 (re-list org-latex-regexps)
12392 (cnt 0) txt link beg end re e checkdir
12393 m n block linkfile movefile ov)
12394 ;; Check if there are old images files with this prefix, and remove them
12395 (when (file-directory-p todir)
12396 (mapc 'delete-file
12397 (directory-files
12398 todir 'full
12399 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12400 ;; Check the different regular expressions
12401 (while (setq e (pop re-list))
12402 (setq m (car e) re (nth 1 e) n (nth 2 e)
12403 block (if (nth 3 e) "\n\n" ""))
12404 (when (member m matchers)
12405 (goto-char (point-min))
12406 (while (re-search-forward re nil t)
12407 (when (or (not at) (equal (cdr at) (match-beginning n)))
12408 (setq txt (match-string n)
12409 beg (match-beginning n) end (match-end n)
12410 cnt (1+ cnt)
12411 linkfile (format "%s_%04d.png" prefix cnt)
12412 movefile (format "%s_%04d.png" absprefix cnt)
12413 link (concat block "[[file:" linkfile "]]" block))
12414 (if msg (message msg cnt))
12415 (goto-char beg)
12416 (unless checkdir ; make sure the directory exists
12417 (setq checkdir t)
12418 (or (file-directory-p todir) (make-directory todir)))
12419 (org-create-formula-image
12420 txt movefile opt forbuffer)
12421 (if overlays
12422 (progn
12423 (setq ov (org-make-overlay beg end))
12424 (if (featurep 'xemacs)
12425 (progn
12426 (org-overlay-put ov 'invisible t)
12427 (org-overlay-put
12428 ov 'end-glyph
12429 (make-glyph (vector 'png :file movefile))))
12430 (org-overlay-put
12431 ov 'display
12432 (list 'image :type 'png :file movefile :ascent 'center)))
12433 (push ov org-latex-fragment-image-overlays)
12434 (goto-char end))
12435 (delete-region beg end)
12436 (insert link))))))))
12438 ;; This function borrows from Ganesh Swami's latex2png.el
12439 (defun org-create-formula-image (string tofile options buffer)
12440 (let* ((tmpdir (if (featurep 'xemacs)
12441 (temp-directory)
12442 temporary-file-directory))
12443 (texfilebase (make-temp-name
12444 (expand-file-name "orgtex" tmpdir)))
12445 (texfile (concat texfilebase ".tex"))
12446 (dvifile (concat texfilebase ".dvi"))
12447 (pngfile (concat texfilebase ".png"))
12448 (fnh (if (featurep 'xemacs)
12449 (font-height (get-face-font 'default))
12450 (face-attribute 'default :height nil)))
12451 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12452 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12453 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12454 "Black"))
12455 (bg (or (plist-get options (if buffer :background :html-background))
12456 "Transparent")))
12457 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12458 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12459 (with-temp-file texfile
12460 (insert org-format-latex-header
12461 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12462 (let ((dir default-directory))
12463 (condition-case nil
12464 (progn
12465 (cd tmpdir)
12466 (call-process "latex" nil nil nil texfile))
12467 (error nil))
12468 (cd dir))
12469 (if (not (file-exists-p dvifile))
12470 (progn (message "Failed to create dvi file from %s" texfile) nil)
12471 (condition-case nil
12472 (call-process "dvipng" nil nil nil
12473 "-E" "-fg" fg "-bg" bg
12474 "-D" dpi
12475 ;;"-x" scale "-y" scale
12476 "-T" "tight"
12477 "-o" pngfile
12478 dvifile)
12479 (error nil))
12480 (if (not (file-exists-p pngfile))
12481 (progn (message "Failed to create png file from %s" texfile) nil)
12482 ;; Use the requested file name and clean up
12483 (copy-file pngfile tofile 'replace)
12484 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12485 (delete-file (concat texfilebase e)))
12486 pngfile))))
12488 (defun org-dvipng-color (attr)
12489 "Return an rgb color specification for dvipng."
12490 (apply 'format "rgb %s %s %s"
12491 (mapcar 'org-normalize-color
12492 (color-values (face-attribute 'default attr nil)))))
12494 (defun org-normalize-color (value)
12495 "Return string to be used as color value for an RGB component."
12496 (format "%g" (/ value 65535.0)))
12498 ;;;; Key bindings
12500 ;; Make `C-c C-x' a prefix key
12501 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12503 ;; TAB key with modifiers
12504 (org-defkey org-mode-map "\C-i" 'org-cycle)
12505 (org-defkey org-mode-map [(tab)] 'org-cycle)
12506 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12507 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12508 (org-defkey org-mode-map "\M-\t" 'org-complete)
12509 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12510 ;; The following line is necessary under Suse GNU/Linux
12511 (unless (featurep 'xemacs)
12512 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12513 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12514 (define-key org-mode-map [backtab] 'org-shifttab)
12516 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12517 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12518 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12520 ;; Cursor keys with modifiers
12521 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12522 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12523 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12524 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12526 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12527 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12528 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12529 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12531 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12532 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12533 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12534 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12536 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12537 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12539 ;;; Extra keys for tty access.
12540 ;; We only set them when really needed because otherwise the
12541 ;; menus don't show the simple keys
12543 (when (or org-use-extra-keys
12544 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12545 (not window-system))
12546 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12547 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12548 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12549 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12550 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12551 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12552 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12553 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12554 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12555 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12556 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12557 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12558 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12559 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12560 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12561 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12562 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12563 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12564 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12565 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12566 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12567 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12569 ;; All the other keys
12571 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12572 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12573 (if (boundp 'narrow-map)
12574 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12575 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12576 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12577 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12578 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12579 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12580 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12581 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12582 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12583 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12584 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12585 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12586 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12587 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12588 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12589 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12590 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12591 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12592 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12593 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12594 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12595 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12596 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12597 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12598 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12599 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12600 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12601 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12602 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12603 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12604 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12605 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12606 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12607 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12608 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12609 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12610 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12611 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12612 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12613 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12614 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12615 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12616 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12617 (org-defkey org-mode-map "\C-c^" 'org-sort)
12618 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12619 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12620 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12621 (org-defkey org-mode-map "\C-m" 'org-return)
12622 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12623 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12624 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12625 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12626 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12627 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12628 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12629 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12630 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12631 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12632 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12633 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12634 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12635 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12636 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12637 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12638 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12640 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12641 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12642 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12643 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12645 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12646 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12647 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12648 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12649 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12650 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12651 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12652 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12653 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12654 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12655 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12656 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12658 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12659 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12660 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12662 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12664 (when (featurep 'xemacs)
12665 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12667 (defvar org-table-auto-blank-field) ; defined in org-table.el
12668 (defun org-self-insert-command (N)
12669 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12670 If the cursor is in a table looking at whitespace, the whitespace is
12671 overwritten, and the table is not marked as requiring realignment."
12672 (interactive "p")
12673 (if (and (org-table-p)
12674 (progn
12675 ;; check if we blank the field, and if that triggers align
12676 (and (featurep 'org-table) org-table-auto-blank-field
12677 (member last-command
12678 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12679 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12680 ;; got extra space, this field does not determine column width
12681 (let (org-table-may-need-update) (org-table-blank-field))
12682 ;; no extra space, this field may determine column width
12683 (org-table-blank-field)))
12685 (eq N 1)
12686 (looking-at "[^|\n]* |"))
12687 (let (org-table-may-need-update)
12688 (goto-char (1- (match-end 0)))
12689 (delete-backward-char 1)
12690 (goto-char (match-beginning 0))
12691 (self-insert-command N))
12692 (setq org-table-may-need-update t)
12693 (self-insert-command N)
12694 (org-fix-tags-on-the-fly)))
12696 (defun org-fix-tags-on-the-fly ()
12697 (when (and (equal (char-after (point-at-bol)) ?*)
12698 (org-on-heading-p))
12699 (org-align-tags-here org-tags-column)))
12701 (defun org-delete-backward-char (N)
12702 "Like `delete-backward-char', insert whitespace at field end in tables.
12703 When deleting backwards, in tables this function will insert whitespace in
12704 front of the next \"|\" separator, to keep the table aligned. The table will
12705 still be marked for re-alignment if the field did fill the entire column,
12706 because, in this case the deletion might narrow the column."
12707 (interactive "p")
12708 (if (and (org-table-p)
12709 (eq N 1)
12710 (string-match "|" (buffer-substring (point-at-bol) (point)))
12711 (looking-at ".*?|"))
12712 (let ((pos (point))
12713 (noalign (looking-at "[^|\n\r]* |"))
12714 (c org-table-may-need-update))
12715 (backward-delete-char N)
12716 (skip-chars-forward "^|")
12717 (insert " ")
12718 (goto-char (1- pos))
12719 ;; noalign: if there were two spaces at the end, this field
12720 ;; does not determine the width of the column.
12721 (if noalign (setq org-table-may-need-update c)))
12722 (backward-delete-char N)
12723 (org-fix-tags-on-the-fly)))
12725 (defun org-delete-char (N)
12726 "Like `delete-char', but insert whitespace at field end in tables.
12727 When deleting characters, in tables this function will insert whitespace in
12728 front of the next \"|\" separator, to keep the table aligned. The table will
12729 still be marked for re-alignment if the field did fill the entire column,
12730 because, in this case the deletion might narrow the column."
12731 (interactive "p")
12732 (if (and (org-table-p)
12733 (not (bolp))
12734 (not (= (char-after) ?|))
12735 (eq N 1))
12736 (if (looking-at ".*?|")
12737 (let ((pos (point))
12738 (noalign (looking-at "[^|\n\r]* |"))
12739 (c org-table-may-need-update))
12740 (replace-match (concat
12741 (substring (match-string 0) 1 -1)
12742 " |"))
12743 (goto-char pos)
12744 ;; noalign: if there were two spaces at the end, this field
12745 ;; does not determine the width of the column.
12746 (if noalign (setq org-table-may-need-update c)))
12747 (delete-char N))
12748 (delete-char N)
12749 (org-fix-tags-on-the-fly)))
12751 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12752 (put 'org-self-insert-command 'delete-selection t)
12753 (put 'orgtbl-self-insert-command 'delete-selection t)
12754 (put 'org-delete-char 'delete-selection 'supersede)
12755 (put 'org-delete-backward-char 'delete-selection 'supersede)
12757 ;; Make `flyspell-mode' delay after some commands
12758 (put 'org-self-insert-command 'flyspell-delayed t)
12759 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12760 (put 'org-delete-char 'flyspell-delayed t)
12761 (put 'org-delete-backward-char 'flyspell-delayed t)
12763 ;; Make pabbrev-mode expand after org-mode commands
12764 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12765 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12767 ;; How to do this: Measure non-white length of current string
12768 ;; If equal to column width, we should realign.
12770 (defun org-remap (map &rest commands)
12771 "In MAP, remap the functions given in COMMANDS.
12772 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12773 (let (new old)
12774 (while commands
12775 (setq old (pop commands) new (pop commands))
12776 (if (fboundp 'command-remapping)
12777 (org-defkey map (vector 'remap old) new)
12778 (substitute-key-definition old new map global-map)))))
12780 (when (eq org-enable-table-editor 'optimized)
12781 ;; If the user wants maximum table support, we need to hijack
12782 ;; some standard editing functions
12783 (org-remap org-mode-map
12784 'self-insert-command 'org-self-insert-command
12785 'delete-char 'org-delete-char
12786 'delete-backward-char 'org-delete-backward-char)
12787 (org-defkey org-mode-map "|" 'org-force-self-insert))
12789 (defun org-shiftcursor-error ()
12790 "Throw an error because Shift-Cursor command was applied in wrong context."
12791 (error "This command is active in special context like tables, headlines or timestamps"))
12793 (defun org-shifttab (&optional arg)
12794 "Global visibility cycling or move to previous table field.
12795 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12796 on context.
12797 See the individual commands for more information."
12798 (interactive "P")
12799 (cond
12800 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12801 ((integerp arg)
12802 (message "Content view to level: %d" arg)
12803 (org-content (prefix-numeric-value arg))
12804 (setq org-cycle-global-status 'overview))
12805 (t (call-interactively 'org-global-cycle))))
12807 (defun org-shiftmetaleft ()
12808 "Promote subtree or delete table column.
12809 Calls `org-promote-subtree', `org-outdent-item',
12810 or `org-table-delete-column', depending on context.
12811 See the individual commands for more information."
12812 (interactive)
12813 (cond
12814 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12815 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12816 ((org-at-item-p) (call-interactively 'org-outdent-item))
12817 (t (org-shiftcursor-error))))
12819 (defun org-shiftmetaright ()
12820 "Demote subtree or insert table column.
12821 Calls `org-demote-subtree', `org-indent-item',
12822 or `org-table-insert-column', depending on context.
12823 See the individual commands for more information."
12824 (interactive)
12825 (cond
12826 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12827 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12828 ((org-at-item-p) (call-interactively 'org-indent-item))
12829 (t (org-shiftcursor-error))))
12831 (defun org-shiftmetaup (&optional arg)
12832 "Move subtree up or kill table row.
12833 Calls `org-move-subtree-up' or `org-table-kill-row' or
12834 `org-move-item-up' depending on context. See the individual commands
12835 for more information."
12836 (interactive "P")
12837 (cond
12838 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12839 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12840 ((org-at-item-p) (call-interactively 'org-move-item-up))
12841 (t (org-shiftcursor-error))))
12842 (defun org-shiftmetadown (&optional arg)
12843 "Move subtree down or insert table row.
12844 Calls `org-move-subtree-down' or `org-table-insert-row' or
12845 `org-move-item-down', depending on context. See the individual
12846 commands for more information."
12847 (interactive "P")
12848 (cond
12849 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12850 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12851 ((org-at-item-p) (call-interactively 'org-move-item-down))
12852 (t (org-shiftcursor-error))))
12854 (defun org-metaleft (&optional arg)
12855 "Promote heading or move table column to left.
12856 Calls `org-do-promote' or `org-table-move-column', depending on context.
12857 With no specific context, calls the Emacs default `backward-word'.
12858 See the individual commands for more information."
12859 (interactive "P")
12860 (cond
12861 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12862 ((or (org-on-heading-p) (org-region-active-p))
12863 (call-interactively 'org-do-promote))
12864 ((org-at-item-p) (call-interactively 'org-outdent-item))
12865 (t (call-interactively 'backward-word))))
12867 (defun org-metaright (&optional arg)
12868 "Demote subtree or move table column to right.
12869 Calls `org-do-demote' or `org-table-move-column', depending on context.
12870 With no specific context, calls the Emacs default `forward-word'.
12871 See the individual commands for more information."
12872 (interactive "P")
12873 (cond
12874 ((org-at-table-p) (call-interactively 'org-table-move-column))
12875 ((or (org-on-heading-p) (org-region-active-p))
12876 (call-interactively 'org-do-demote))
12877 ((org-at-item-p) (call-interactively 'org-indent-item))
12878 (t (call-interactively 'forward-word))))
12880 (defun org-metaup (&optional arg)
12881 "Move subtree up or move table row up.
12882 Calls `org-move-subtree-up' or `org-table-move-row' or
12883 `org-move-item-up', depending on context. See the individual commands
12884 for more information."
12885 (interactive "P")
12886 (cond
12887 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12888 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12889 ((org-at-item-p) (call-interactively 'org-move-item-up))
12890 (t (transpose-lines 1) (beginning-of-line -1))))
12892 (defun org-metadown (&optional arg)
12893 "Move subtree down or move table row down.
12894 Calls `org-move-subtree-down' or `org-table-move-row' or
12895 `org-move-item-down', depending on context. See the individual
12896 commands for more information."
12897 (interactive "P")
12898 (cond
12899 ((org-at-table-p) (call-interactively 'org-table-move-row))
12900 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12901 ((org-at-item-p) (call-interactively 'org-move-item-down))
12902 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12904 (defun org-shiftup (&optional arg)
12905 "Increase item in timestamp or increase priority of current headline.
12906 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12907 depending on context. See the individual commands for more information."
12908 (interactive "P")
12909 (cond
12910 ((org-at-timestamp-p t)
12911 (call-interactively (if org-edit-timestamp-down-means-later
12912 'org-timestamp-down 'org-timestamp-up)))
12913 ((org-on-heading-p) (call-interactively 'org-priority-up))
12914 ((org-at-item-p) (call-interactively 'org-previous-item))
12915 ((org-clocktable-try-shift 'up arg))
12916 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12918 (defun org-shiftdown (&optional arg)
12919 "Decrease item in timestamp or decrease priority of current headline.
12920 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12921 depending on context. See the individual commands for more information."
12922 (interactive "P")
12923 (cond
12924 ((org-at-timestamp-p t)
12925 (call-interactively (if org-edit-timestamp-down-means-later
12926 'org-timestamp-up 'org-timestamp-down)))
12927 ((org-on-heading-p) (call-interactively 'org-priority-down))
12928 ((org-clocktable-try-shift 'down arg))
12929 (t (call-interactively 'org-next-item))))
12931 (defun org-shiftright (&optional arg)
12932 "Cycle the thing at point or in the current line, depending on context.
12933 Depending on context, this does one of the following:
12935 - switch a timestamp at point one day into the future
12936 - on a headline, switch to the next TODO keyword.
12937 - on an item, switch entire list to the next bullet type
12938 - on a property line, switch to the next allowed value
12939 - on a clocktable definition line, move time block into the future"
12940 (interactive "P")
12941 (cond
12942 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12943 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12944 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12945 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12946 ((org-clocktable-try-shift 'right arg))
12947 (t (org-shiftcursor-error))))
12949 (defun org-shiftleft (&optional arg)
12950 "Cycle the thing at point or in the current line, depending on context.
12951 Depending on context, this does one of the following:
12953 - switch a timestamp at point one day into the past
12954 - on a headline, switch to the previous TODO keyword.
12955 - on an item, switch entire list to the previous bullet type
12956 - on a property line, switch to the previous allowed value
12957 - on a clocktable definition line, move time block into the past"
12958 (interactive "P")
12959 (cond
12960 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12961 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12962 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12963 ((org-at-property-p)
12964 (call-interactively 'org-property-previous-allowed-value))
12965 ((org-clocktable-try-shift 'left arg))
12966 (t (org-shiftcursor-error))))
12968 (defun org-shiftcontrolright ()
12969 "Switch to next TODO set."
12970 (interactive)
12971 (cond
12972 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12973 (t (org-shiftcursor-error))))
12975 (defun org-shiftcontrolleft ()
12976 "Switch to previous TODO set."
12977 (interactive)
12978 (cond
12979 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12980 (t (org-shiftcursor-error))))
12982 (defun org-ctrl-c-ret ()
12983 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12984 (interactive)
12985 (cond
12986 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12987 (t (call-interactively 'org-insert-heading))))
12989 (defun org-copy-special ()
12990 "Copy region in table or copy current subtree.
12991 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12992 See the individual commands for more information."
12993 (interactive)
12994 (call-interactively
12995 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12997 (defun org-cut-special ()
12998 "Cut region in table or cut current subtree.
12999 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13000 See the individual commands for more information."
13001 (interactive)
13002 (call-interactively
13003 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13005 (defun org-paste-special (arg)
13006 "Paste rectangular region into table, or past subtree relative to level.
13007 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13008 See the individual commands for more information."
13009 (interactive "P")
13010 (if (org-at-table-p)
13011 (org-table-paste-rectangle)
13012 (org-paste-subtree arg)))
13014 (defun org-edit-special ()
13015 "Call a special editor for the stuff at point.
13016 When at a table, call the formula editor with `org-table-edit-formulas'.
13017 When at the first line of an src example, call `org-edit-src-code'.
13018 When in an #+include line, visit the include file. Otherwise call
13019 `ffap' to visit the file at point."
13020 (interactive)
13021 (cond
13022 ((org-at-table-p)
13023 (call-interactively 'org-table-edit-formulas))
13024 ((save-excursion
13025 (beginning-of-line 1)
13026 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13027 (find-file (org-trim (match-string 1))))
13028 ((org-edit-src-code))
13029 ((org-edit-fixed-width-region))
13030 (t (call-interactively 'ffap))))
13032 (defun org-ctrl-c-ctrl-c (&optional arg)
13033 "Set tags in headline, or update according to changed information at point.
13035 This command does many different things, depending on context:
13037 - If the cursor is in a headline, prompt for tags and insert them
13038 into the current line, aligned to `org-tags-column'. When called
13039 with prefix arg, realign all tags in the current buffer.
13041 - If the cursor is in one of the special #+KEYWORD lines, this
13042 triggers scanning the buffer for these lines and updating the
13043 information.
13045 - If the cursor is inside a table, realign the table. This command
13046 works even if the automatic table editor has been turned off.
13048 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13049 the entire table.
13051 - If the cursor is at a footnote reference or definition, jump to
13052 the corresponding definition or references, respectively.
13054 - If the cursor is a the beginning of a dynamic block, update it.
13056 - If the cursor is inside a table created by the table.el package,
13057 activate that table.
13059 - If the current buffer is a remember buffer, close note and file
13060 it. A prefix argument of 1 files to the default location
13061 without further interaction. A prefix argument of 2 files to
13062 the currently clocking task.
13064 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13065 links in this buffer.
13067 - If the cursor is on a numbered item in a plain list, renumber the
13068 ordered list.
13070 - If the cursor is on a checkbox, toggle it."
13071 (interactive "P")
13072 (let ((org-enable-table-editor t))
13073 (cond
13074 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13075 org-occur-highlights
13076 org-latex-fragment-image-overlays)
13077 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13078 (org-remove-occur-highlights)
13079 (org-remove-latex-fragment-image-overlays)
13080 (message "Temporary highlights/overlays removed from current buffer"))
13081 ((and (local-variable-p 'org-finish-function (current-buffer))
13082 (fboundp org-finish-function))
13083 (funcall org-finish-function))
13084 ((org-at-property-p)
13085 (call-interactively 'org-property-action))
13086 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13087 ((org-on-heading-p) (call-interactively 'org-set-tags))
13088 ((org-at-table.el-p)
13089 (require 'table)
13090 (beginning-of-line 1)
13091 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13092 (call-interactively 'table-recognize-table))
13093 ((org-at-table-p)
13094 (org-table-maybe-eval-formula)
13095 (if arg
13096 (call-interactively 'org-table-recalculate)
13097 (org-table-maybe-recalculate-line))
13098 (call-interactively 'org-table-align))
13099 ((or (org-footnote-at-reference-p)
13100 (org-footnote-at-definition-p))
13101 (call-interactively 'org-footnote-action))
13102 ((org-at-item-checkbox-p)
13103 (call-interactively 'org-toggle-checkbox))
13104 ((org-at-item-p)
13105 (call-interactively 'org-maybe-renumber-ordered-list))
13106 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13107 ;; Dynamic block
13108 (beginning-of-line 1)
13109 (save-excursion (org-update-dblock)))
13110 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13111 (cond
13112 ((equal (match-string 1) "TBLFM")
13113 ;; Recalculate the table before this line
13114 (save-excursion
13115 (beginning-of-line 1)
13116 (skip-chars-backward " \r\n\t")
13117 (if (org-at-table-p)
13118 (org-call-with-arg 'org-table-recalculate t))))
13120 ; (org-set-regexps-and-options)
13121 ; (org-restart-font-lock)
13122 (let ((org-inhibit-startup t)) (org-mode-restart))
13123 (message "Local setup has been refreshed"))))
13124 (t (error "C-c C-c can do nothing useful at this location.")))))
13126 (defun org-mode-restart ()
13127 "Restart Org-mode, to scan again for special lines.
13128 Also updates the keyword regular expressions."
13129 (interactive)
13130 (org-mode)
13131 (message "Org-mode restarted"))
13133 (defun org-kill-note-or-show-branches ()
13134 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13135 (interactive)
13136 (if (not org-finish-function)
13137 (call-interactively 'show-branches)
13138 (let ((org-note-abort t))
13139 (funcall org-finish-function))))
13141 (defun org-return (&optional indent)
13142 "Goto next table row or insert a newline.
13143 Calls `org-table-next-row' or `newline', depending on context.
13144 See the individual commands for more information."
13145 (interactive)
13146 (cond
13147 ((bobp) (if indent (newline-and-indent) (newline)))
13148 ((and (org-at-heading-p)
13149 (looking-at
13150 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13151 (org-show-entry)
13152 (end-of-line 1)
13153 (newline))
13154 ((org-at-table-p)
13155 (org-table-justify-field-maybe)
13156 (call-interactively 'org-table-next-row))
13157 (t (if indent (newline-and-indent) (newline)))))
13159 (defun org-return-indent ()
13160 "Goto next table row or insert a newline and indent.
13161 Calls `org-table-next-row' or `newline-and-indent', depending on
13162 context. See the individual commands for more information."
13163 (interactive)
13164 (org-return t))
13166 (defun org-ctrl-c-star ()
13167 "Compute table, or change heading status of lines.
13168 Calls `org-table-recalculate' or `org-toggle-region-headings',
13169 depending on context. This will also turn a plain list item or a normal
13170 line into a subheading."
13171 (interactive)
13172 (cond
13173 ((org-at-table-p)
13174 (call-interactively 'org-table-recalculate))
13175 ((org-region-active-p)
13176 ;; Convert all lines in region to list items
13177 (call-interactively 'org-toggle-region-headings))
13178 ((org-on-heading-p)
13179 (org-toggle-region-headings (point-at-bol)
13180 (min (1+ (point-at-eol)) (point-max))))
13181 ((org-at-item-p)
13182 ;; Convert to heading
13183 (let ((level (save-match-data
13184 (save-excursion
13185 (condition-case nil
13186 (progn
13187 (org-back-to-heading t)
13188 (funcall outline-level))
13189 (error 0))))))
13190 (replace-match
13191 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13192 (t (org-toggle-region-headings (point-at-bol)
13193 (min (1+ (point-at-eol)) (point-max))))))
13195 (defun org-ctrl-c-minus ()
13196 "Insert separator line in table or modify bullet status of line.
13197 Also turns a plain line or a region of lines into list items.
13198 Calls `org-table-insert-hline', `org-toggle-region-items', or
13199 `org-cycle-list-bullet', depending on context."
13200 (interactive)
13201 (cond
13202 ((org-at-table-p)
13203 (call-interactively 'org-table-insert-hline))
13204 ((org-on-heading-p)
13205 ;; Convert to item
13206 (save-excursion
13207 (beginning-of-line 1)
13208 (if (looking-at "\\*+ ")
13209 (replace-match
13210 (concat (make-string
13211 (- (match-end 0) (point) (if org-odd-levels-only 2 1)) ?\ )
13212 "- ")))))
13213 ((org-region-active-p)
13214 ;; Convert all lines in region to list items
13215 (call-interactively 'org-toggle-region-items))
13216 ((org-in-item-p)
13217 (call-interactively 'org-cycle-list-bullet))
13218 (t (org-toggle-region-items (point-at-bol)
13219 (min (1+ (point-at-eol)) (point-max))))))
13221 (defun org-toggle-region-items (beg end)
13222 "Convert all lines in region to list items.
13223 If the first line is already an item, convert all list items in the region
13224 to normal lines."
13225 (interactive "r")
13226 (let (l2 l)
13227 (save-excursion
13228 (goto-char end)
13229 (setq l2 (org-current-line))
13230 (goto-char beg)
13231 (beginning-of-line 1)
13232 (setq l (1- (org-current-line)))
13233 (if (org-at-item-p)
13234 ;; We already have items, de-itemize
13235 (while (< (setq l (1+ l)) l2)
13236 (when (org-at-item-p)
13237 (goto-char (match-beginning 2))
13238 (delete-region (match-beginning 2) (match-end 2))
13239 (and (looking-at "[ \t]+") (replace-match "")))
13240 (beginning-of-line 2))
13241 (while (< (setq l (1+ l)) l2)
13242 (unless (org-at-item-p)
13243 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13244 (replace-match "\\1- \\2")))
13245 (beginning-of-line 2))))))
13247 (defun org-toggle-region-headings (beg end)
13248 "Convert all lines in region to list items.
13249 If the first line is already an item, convert all list items in the region
13250 to normal lines."
13251 (interactive "r")
13252 (let (l2 l)
13253 (save-excursion
13254 (goto-char end)
13255 (setq l2 (org-current-line))
13256 (goto-char beg)
13257 (beginning-of-line 1)
13258 (setq l (1- (org-current-line)))
13259 (if (org-on-heading-p)
13260 ;; We already have headlines, de-star them
13261 (while (< (setq l (1+ l)) l2)
13262 (when (org-on-heading-p t)
13263 (and (looking-at outline-regexp) (replace-match "")))
13264 (beginning-of-line 2))
13265 (let* ((stars (save-excursion
13266 (re-search-backward org-complex-heading-regexp nil t)
13267 (or (match-string 1) "*")))
13268 (add-stars (if org-odd-levels-only "**" "*"))
13269 (rpl (concat stars add-stars " \\2")))
13270 (while (< (setq l (1+ l)) l2)
13271 (unless (org-on-heading-p)
13272 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13273 (replace-match rpl)))
13274 (beginning-of-line 2)))))))
13276 (defun org-meta-return (&optional arg)
13277 "Insert a new heading or wrap a region in a table.
13278 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13279 See the individual commands for more information."
13280 (interactive "P")
13281 (cond
13282 ((org-at-table-p)
13283 (call-interactively 'org-table-wrap-region))
13284 (t (call-interactively 'org-insert-heading))))
13286 ;;; Menu entries
13288 ;; Define the Org-mode menus
13289 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13290 '("Tbl"
13291 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13292 ["Next Field" org-cycle (org-at-table-p)]
13293 ["Previous Field" org-shifttab (org-at-table-p)]
13294 ["Next Row" org-return (org-at-table-p)]
13295 "--"
13296 ["Blank Field" org-table-blank-field (org-at-table-p)]
13297 ["Edit Field" org-table-edit-field (org-at-table-p)]
13298 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13299 "--"
13300 ("Column"
13301 ["Move Column Left" org-metaleft (org-at-table-p)]
13302 ["Move Column Right" org-metaright (org-at-table-p)]
13303 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13304 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13305 ("Row"
13306 ["Move Row Up" org-metaup (org-at-table-p)]
13307 ["Move Row Down" org-metadown (org-at-table-p)]
13308 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13309 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13310 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13311 "--"
13312 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13313 ("Rectangle"
13314 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13315 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13316 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13317 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13318 "--"
13319 ("Calculate"
13320 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13321 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13322 ["Edit Formulas" org-edit-special (org-at-table-p)]
13323 "--"
13324 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13325 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13326 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13327 "--"
13328 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13329 "--"
13330 ["Sum Column/Rectangle" org-table-sum
13331 (or (org-at-table-p) (org-region-active-p))]
13332 ["Which Column?" org-table-current-column (org-at-table-p)])
13333 ["Debug Formulas"
13334 org-table-toggle-formula-debugger
13335 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13336 ["Show Col/Row Numbers"
13337 org-table-toggle-coordinate-overlays
13338 :style toggle
13339 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13340 "--"
13341 ["Create" org-table-create (and (not (org-at-table-p))
13342 org-enable-table-editor)]
13343 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13344 ["Import from File" org-table-import (not (org-at-table-p))]
13345 ["Export to File" org-table-export (org-at-table-p)]
13346 "--"
13347 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13349 (easy-menu-define org-org-menu org-mode-map "Org menu"
13350 '("Org"
13351 ("Show/Hide"
13352 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13353 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13354 ["Sparse Tree..." org-sparse-tree t]
13355 ["Reveal Context" org-reveal t]
13356 ["Show All" show-all t]
13357 "--"
13358 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13359 "--"
13360 ["New Heading" org-insert-heading t]
13361 ("Navigate Headings"
13362 ["Up" outline-up-heading t]
13363 ["Next" outline-next-visible-heading t]
13364 ["Previous" outline-previous-visible-heading t]
13365 ["Next Same Level" outline-forward-same-level t]
13366 ["Previous Same Level" outline-backward-same-level t]
13367 "--"
13368 ["Jump" org-goto t])
13369 ("Edit Structure"
13370 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13371 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13372 "--"
13373 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13374 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13375 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13376 "--"
13377 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13378 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13379 ["Demote Heading" org-metaright (not (org-at-table-p))]
13380 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13381 "--"
13382 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13383 "--"
13384 ["Convert to odd levels" org-convert-to-odd-levels t]
13385 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13386 ("Editing"
13387 ["Emphasis..." org-emphasize t]
13388 ["Edit Source Example" org-edit-special t]
13389 "--"
13390 ["Footnote new/jump" org-footnote-action t]
13391 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13392 ("Archive"
13393 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13394 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13395 ; :active t :keys "C-u C-c C-x C-a"]
13396 ["Sparse trees open ARCHIVE trees"
13397 (setq org-sparse-tree-open-archived-trees
13398 (not org-sparse-tree-open-archived-trees))
13399 :style toggle :selected org-sparse-tree-open-archived-trees]
13400 ["Cycling opens ARCHIVE trees"
13401 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13402 :style toggle :selected org-cycle-open-archived-trees]
13403 "--"
13404 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13405 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13406 ; ["Check and Move Children" (org-archive-subtree '(4))
13407 ; :active t :keys "C-u C-c C-x C-s"]
13409 "--"
13410 ("TODO Lists"
13411 ["TODO/DONE/-" org-todo t]
13412 ("Select keyword"
13413 ["Next keyword" org-shiftright (org-on-heading-p)]
13414 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13415 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13416 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13417 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13418 ["Show TODO Tree" org-show-todo-tree t]
13419 ["Global TODO list" org-todo-list t]
13420 "--"
13421 ["Set Priority" org-priority t]
13422 ["Priority Up" org-shiftup t]
13423 ["Priority Down" org-shiftdown t])
13424 ("TAGS and Properties"
13425 ["Set Tags" org-set-tags-command t]
13426 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13427 "--"
13428 ["Set property" org-set-property t]
13429 ["Column view of properties" org-columns t]
13430 ["Insert Column View DBlock" org-insert-columns-dblock t])
13431 ("Dates and Scheduling"
13432 ["Timestamp" org-time-stamp t]
13433 ["Timestamp (inactive)" org-time-stamp-inactive t]
13434 ("Change Date"
13435 ["1 Day Later" org-shiftright t]
13436 ["1 Day Earlier" org-shiftleft t]
13437 ["1 ... Later" org-shiftup t]
13438 ["1 ... Earlier" org-shiftdown t])
13439 ["Compute Time Range" org-evaluate-time-range t]
13440 ["Schedule Item" org-schedule t]
13441 ["Deadline" org-deadline t]
13442 "--"
13443 ["Custom time format" org-toggle-time-stamp-overlays
13444 :style radio :selected org-display-custom-times]
13445 "--"
13446 ["Goto Calendar" org-goto-calendar t]
13447 ["Date from Calendar" org-date-from-calendar t]
13448 "--"
13449 ["Start/restart timer" org-timer-start t]
13450 ["Insert timer string" org-timer t]
13451 ["Insert timer item" org-timer-item t])
13452 ("Logging work"
13453 ["Clock in" org-clock-in t]
13454 ["Clock out" org-clock-out t]
13455 ["Clock cancel" org-clock-cancel t]
13456 ["Goto running clock" org-clock-goto t]
13457 ["Display times" org-clock-display t]
13458 ["Create clock table" org-clock-report t]
13459 "--"
13460 ["Record DONE time"
13461 (progn (setq org-log-done (not org-log-done))
13462 (message "Switching to %s will %s record a timestamp"
13463 (car org-done-keywords)
13464 (if org-log-done "automatically" "not")))
13465 :style toggle :selected org-log-done])
13466 "--"
13467 ["Agenda Command..." org-agenda t]
13468 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13469 ("File List for Agenda")
13470 ("Special views current file"
13471 ["TODO Tree" org-show-todo-tree t]
13472 ["Check Deadlines" org-check-deadlines t]
13473 ["Timeline" org-timeline t]
13474 ["Tags Tree" org-tags-sparse-tree t])
13475 "--"
13476 ("Hyperlinks"
13477 ["Store Link (Global)" org-store-link t]
13478 ["Insert Link" org-insert-link t]
13479 ["Follow Link" org-open-at-point t]
13480 "--"
13481 ["Next link" org-next-link t]
13482 ["Previous link" org-previous-link t]
13483 "--"
13484 ["Descriptive Links"
13485 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13486 :style radio
13487 :selected (member '(org-link) buffer-invisibility-spec)]
13488 ["Literal Links"
13489 (progn
13490 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13491 :style radio
13492 :selected (not (member '(org-link) buffer-invisibility-spec))])
13493 "--"
13494 ["Export/Publish..." org-export t]
13495 ("LaTeX"
13496 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13497 :selected org-cdlatex-mode]
13498 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13499 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13500 ["Modify math symbol" org-cdlatex-math-modify
13501 (org-inside-LaTeX-fragment-p)]
13502 ["Export LaTeX fragments as images"
13503 (if (featurep 'org-exp)
13504 (setq org-export-with-LaTeX-fragments
13505 (not org-export-with-LaTeX-fragments))
13506 (require 'org-exp))
13507 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13508 org-export-with-LaTeX-fragments)])
13509 "--"
13510 ("Documentation"
13511 ["Show Version" org-version t]
13512 ["Info Documentation" org-info t])
13513 ("Customize"
13514 ["Browse Org Group" org-customize t]
13515 "--"
13516 ["Expand This Menu" org-create-customize-menu
13517 (fboundp 'customize-menu-create)])
13518 "--"
13519 ["Refresh setup" org-mode-restart t]
13522 (defun org-info (&optional node)
13523 "Read documentation for Org-mode in the info system.
13524 With optional NODE, go directly to that node."
13525 (interactive)
13526 (info (format "(org)%s" (or node ""))))
13528 (defun org-install-agenda-files-menu ()
13529 (let ((bl (buffer-list)))
13530 (save-excursion
13531 (while bl
13532 (set-buffer (pop bl))
13533 (if (org-mode-p) (setq bl nil)))
13534 (when (org-mode-p)
13535 (easy-menu-change
13536 '("Org") "File List for Agenda"
13537 (append
13538 (list
13539 ["Edit File List" (org-edit-agenda-file-list) t]
13540 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13541 ["Remove Current File from List" org-remove-file t]
13542 ["Cycle through agenda files" org-cycle-agenda-files t]
13543 ["Occur in all agenda files" org-occur-in-agenda-files t]
13544 "--")
13545 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13547 ;;;; Documentation
13549 ;;;###autoload
13550 (defun org-require-autoloaded-modules ()
13551 (interactive)
13552 (mapc 'require
13553 '(org-agenda org-archive org-clock org-colview
13554 org-exp org-id org-export-latex org-publish
13555 org-remember org-table)))
13557 ;;;###autoload
13558 (defun org-customize ()
13559 "Call the customize function with org as argument."
13560 (interactive)
13561 (org-load-modules-maybe)
13562 (org-require-autoloaded-modules)
13563 (customize-browse 'org))
13565 (defun org-create-customize-menu ()
13566 "Create a full customization menu for Org-mode, insert it into the menu."
13567 (interactive)
13568 (org-load-modules-maybe)
13569 (org-require-autoloaded-modules)
13570 (if (fboundp 'customize-menu-create)
13571 (progn
13572 (easy-menu-change
13573 '("Org") "Customize"
13574 `(["Browse Org group" org-customize t]
13575 "--"
13576 ,(customize-menu-create 'org)
13577 ["Set" Custom-set t]
13578 ["Save" Custom-save t]
13579 ["Reset to Current" Custom-reset-current t]
13580 ["Reset to Saved" Custom-reset-saved t]
13581 ["Reset to Standard Settings" Custom-reset-standard t]))
13582 (message "\"Org\"-menu now contains full customization menu"))
13583 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13585 ;;;; Miscellaneous stuff
13587 ;;; Generally useful functions
13589 (defun org-find-text-property-in-string (prop s)
13590 "Return the first non-nil value of property PROP in string S."
13591 (or (get-text-property 0 prop s)
13592 (get-text-property (or (next-single-property-change 0 prop s) 0)
13593 prop s)))
13595 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13596 "Display the given MESSAGE as a warning."
13597 (if (fboundp 'display-warning)
13598 (display-warning 'org message
13599 (if (featurep 'xemacs)
13600 'warning
13601 :warning))
13602 (let ((buf (get-buffer-create "*Org warnings*")))
13603 (with-current-buffer buf
13604 (goto-char (point-max))
13605 (insert "Warning (Org): " message)
13606 (unless (bolp)
13607 (newline)))
13608 (display-buffer buf)
13609 (sit-for 0))))
13611 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13612 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13613 (if (and marker (marker-buffer marker)
13614 (buffer-live-p (marker-buffer marker)))
13615 (progn
13616 (switch-to-buffer (marker-buffer marker))
13617 (if (or (> marker (point-max)) (< marker (point-min)))
13618 (widen))
13619 (goto-char marker))
13620 (if bookmark
13621 (bookmark-jump bookmark)
13622 (error "Cannot find location"))))
13624 (defun org-quote-csv-field (s)
13625 "Quote field for inclusion in CSV material."
13626 (if (string-match "[\",]" s)
13627 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13630 (defun org-plist-delete (plist property)
13631 "Delete PROPERTY from PLIST.
13632 This is in contrast to merely setting it to 0."
13633 (let (p)
13634 (while plist
13635 (if (not (eq property (car plist)))
13636 (setq p (plist-put p (car plist) (nth 1 plist))))
13637 (setq plist (cddr plist)))
13640 (defun org-force-self-insert (N)
13641 "Needed to enforce self-insert under remapping."
13642 (interactive "p")
13643 (self-insert-command N))
13645 (defun org-string-width (s)
13646 "Compute width of string, ignoring invisible characters.
13647 This ignores character with invisibility property `org-link', and also
13648 characters with property `org-cwidth', because these will become invisible
13649 upon the next fontification round."
13650 (let (b l)
13651 (when (or (eq t buffer-invisibility-spec)
13652 (assq 'org-link buffer-invisibility-spec))
13653 (while (setq b (text-property-any 0 (length s)
13654 'invisible 'org-link s))
13655 (setq s (concat (substring s 0 b)
13656 (substring s (or (next-single-property-change
13657 b 'invisible s) (length s)))))))
13658 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13659 (setq s (concat (substring s 0 b)
13660 (substring s (or (next-single-property-change
13661 b 'org-cwidth s) (length s))))))
13662 (setq l (string-width s) b -1)
13663 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13664 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13667 (defun org-get-indentation (&optional line)
13668 "Get the indentation of the current line, interpreting tabs.
13669 When LINE is given, assume it represents a line and compute its indentation."
13670 (if line
13671 (if (string-match "^ *" (org-remove-tabs line))
13672 (match-end 0))
13673 (save-excursion
13674 (beginning-of-line 1)
13675 (skip-chars-forward " \t")
13676 (current-column))))
13678 (defun org-remove-tabs (s &optional width)
13679 "Replace tabulators in S with spaces.
13680 Assumes that s is a single line, starting in column 0."
13681 (setq width (or width tab-width))
13682 (while (string-match "\t" s)
13683 (setq s (replace-match
13684 (make-string
13685 (- (* width (/ (+ (match-beginning 0) width) width))
13686 (match-beginning 0)) ?\ )
13687 t t s)))
13690 (defun org-fix-indentation (line ind)
13691 "Fix indentation in LINE.
13692 IND is a cons cell with target and minimum indentation.
13693 If the current indentation in LINE is smaller than the minimum,
13694 leave it alone. If it is larger than ind, set it to the target."
13695 (let* ((l (org-remove-tabs line))
13696 (i (org-get-indentation l))
13697 (i1 (car ind)) (i2 (cdr ind)))
13698 (if (>= i i2) (setq l (substring line i2)))
13699 (if (> i1 0)
13700 (concat (make-string i1 ?\ ) l)
13701 l)))
13703 (defun org-base-buffer (buffer)
13704 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13705 (if (not buffer)
13706 buffer
13707 (or (buffer-base-buffer buffer)
13708 buffer)))
13710 (defun org-trim (s)
13711 "Remove whitespace at beginning and end of string."
13712 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13713 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13716 (defun org-wrap (string &optional width lines)
13717 "Wrap string to either a number of lines, or a width in characters.
13718 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13719 that costs. If there is a word longer than WIDTH, the text is actually
13720 wrapped to the length of that word.
13721 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13722 many lines, whatever width that takes.
13723 The return value is a list of lines, without newlines at the end."
13724 (let* ((words (org-split-string string "[ \t\n]+"))
13725 (maxword (apply 'max (mapcar 'org-string-width words)))
13726 w ll)
13727 (cond (width
13728 (org-do-wrap words (max maxword width)))
13729 (lines
13730 (setq w maxword)
13731 (setq ll (org-do-wrap words maxword))
13732 (if (<= (length ll) lines)
13734 (setq ll words)
13735 (while (> (length ll) lines)
13736 (setq w (1+ w))
13737 (setq ll (org-do-wrap words w)))
13738 ll))
13739 (t (error "Cannot wrap this")))))
13741 (defun org-do-wrap (words width)
13742 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13743 (let (lines line)
13744 (while words
13745 (setq line (pop words))
13746 (while (and words (< (+ (length line) (length (car words))) width))
13747 (setq line (concat line " " (pop words))))
13748 (setq lines (push line lines)))
13749 (nreverse lines)))
13751 (defun org-split-string (string &optional separators)
13752 "Splits STRING into substrings at SEPARATORS.
13753 No empty strings are returned if there are matches at the beginning
13754 and end of string."
13755 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13756 (start 0)
13757 notfirst
13758 (list nil))
13759 (while (and (string-match rexp string
13760 (if (and notfirst
13761 (= start (match-beginning 0))
13762 (< start (length string)))
13763 (1+ start) start))
13764 (< (match-beginning 0) (length string)))
13765 (setq notfirst t)
13766 (or (eq (match-beginning 0) 0)
13767 (and (eq (match-beginning 0) (match-end 0))
13768 (eq (match-beginning 0) start))
13769 (setq list
13770 (cons (substring string start (match-beginning 0))
13771 list)))
13772 (setq start (match-end 0)))
13773 (or (eq start (length string))
13774 (setq list
13775 (cons (substring string start)
13776 list)))
13777 (nreverse list)))
13779 (defun org-context ()
13780 "Return a list of contexts of the current cursor position.
13781 If several contexts apply, all are returned.
13782 Each context entry is a list with a symbol naming the context, and
13783 two positions indicating start and end of the context. Possible
13784 contexts are:
13786 :headline anywhere in a headline
13787 :headline-stars on the leading stars in a headline
13788 :todo-keyword on a TODO keyword (including DONE) in a headline
13789 :tags on the TAGS in a headline
13790 :priority on the priority cookie in a headline
13791 :item on the first line of a plain list item
13792 :item-bullet on the bullet/number of a plain list item
13793 :checkbox on the checkbox in a plain list item
13794 :table in an org-mode table
13795 :table-special on a special filed in a table
13796 :table-table in a table.el table
13797 :link on a hyperlink
13798 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13799 :target on a <<target>>
13800 :radio-target on a <<<radio-target>>>
13801 :latex-fragment on a LaTeX fragment
13802 :latex-preview on a LaTeX fragment with overlayed preview image
13804 This function expects the position to be visible because it uses font-lock
13805 faces as a help to recognize the following contexts: :table-special, :link,
13806 and :keyword."
13807 (let* ((f (get-text-property (point) 'face))
13808 (faces (if (listp f) f (list f)))
13809 (p (point)) clist o)
13810 ;; First the large context
13811 (cond
13812 ((org-on-heading-p t)
13813 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13814 (when (progn
13815 (beginning-of-line 1)
13816 (looking-at org-todo-line-tags-regexp))
13817 (push (org-point-in-group p 1 :headline-stars) clist)
13818 (push (org-point-in-group p 2 :todo-keyword) clist)
13819 (push (org-point-in-group p 4 :tags) clist))
13820 (goto-char p)
13821 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13822 (if (looking-at "\\[#[A-Z0-9]\\]")
13823 (push (org-point-in-group p 0 :priority) clist)))
13825 ((org-at-item-p)
13826 (push (org-point-in-group p 2 :item-bullet) clist)
13827 (push (list :item (point-at-bol)
13828 (save-excursion (org-end-of-item) (point)))
13829 clist)
13830 (and (org-at-item-checkbox-p)
13831 (push (org-point-in-group p 0 :checkbox) clist)))
13833 ((org-at-table-p)
13834 (push (list :table (org-table-begin) (org-table-end)) clist)
13835 (if (memq 'org-formula faces)
13836 (push (list :table-special
13837 (previous-single-property-change p 'face)
13838 (next-single-property-change p 'face)) clist)))
13839 ((org-at-table-p 'any)
13840 (push (list :table-table) clist)))
13841 (goto-char p)
13843 ;; Now the small context
13844 (cond
13845 ((org-at-timestamp-p)
13846 (push (org-point-in-group p 0 :timestamp) clist))
13847 ((memq 'org-link faces)
13848 (push (list :link
13849 (previous-single-property-change p 'face)
13850 (next-single-property-change p 'face)) clist))
13851 ((memq 'org-special-keyword faces)
13852 (push (list :keyword
13853 (previous-single-property-change p 'face)
13854 (next-single-property-change p 'face)) clist))
13855 ((org-on-target-p)
13856 (push (org-point-in-group p 0 :target) clist)
13857 (goto-char (1- (match-beginning 0)))
13858 (if (looking-at org-radio-target-regexp)
13859 (push (org-point-in-group p 0 :radio-target) clist))
13860 (goto-char p))
13861 ((setq o (car (delq nil
13862 (mapcar
13863 (lambda (x)
13864 (if (memq x org-latex-fragment-image-overlays) x))
13865 (org-overlays-at (point))))))
13866 (push (list :latex-fragment
13867 (org-overlay-start o) (org-overlay-end o)) clist)
13868 (push (list :latex-preview
13869 (org-overlay-start o) (org-overlay-end o)) clist))
13870 ((org-inside-LaTeX-fragment-p)
13871 ;; FIXME: positions wrong.
13872 (push (list :latex-fragment (point) (point)) clist)))
13874 (setq clist (nreverse (delq nil clist)))
13875 clist))
13877 ;; FIXME: Compare with at-regexp-p Do we need both?
13878 (defun org-in-regexp (re &optional nlines visually)
13879 "Check if point is inside a match of regexp.
13880 Normally only the current line is checked, but you can include NLINES extra
13881 lines both before and after point into the search.
13882 If VISUALLY is set, require that the cursor is not after the match but
13883 really on, so that the block visually is on the match."
13884 (catch 'exit
13885 (let ((pos (point))
13886 (eol (point-at-eol (+ 1 (or nlines 0))))
13887 (inc (if visually 1 0)))
13888 (save-excursion
13889 (beginning-of-line (- 1 (or nlines 0)))
13890 (while (re-search-forward re eol t)
13891 (if (and (<= (match-beginning 0) pos)
13892 (>= (+ inc (match-end 0)) pos))
13893 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13895 (defun org-at-regexp-p (regexp)
13896 "Is point inside a match of REGEXP in the current line?"
13897 (catch 'exit
13898 (save-excursion
13899 (let ((pos (point)) (end (point-at-eol)))
13900 (beginning-of-line 1)
13901 (while (re-search-forward regexp end t)
13902 (if (and (<= (match-beginning 0) pos)
13903 (>= (match-end 0) pos))
13904 (throw 'exit t)))
13905 nil))))
13907 (defun org-occur-in-agenda-files (regexp &optional nlines)
13908 "Call `multi-occur' with buffers for all agenda files."
13909 (interactive "sOrg-files matching: \np")
13910 (let* ((files (org-agenda-files))
13911 (tnames (mapcar 'file-truename files))
13912 (extra org-agenda-text-search-extra-files)
13914 (when (eq (car extra) 'agenda-archives)
13915 (setq extra (cdr extra))
13916 (setq files (org-add-archive-files files)))
13917 (while (setq f (pop extra))
13918 (unless (member (file-truename f) tnames)
13919 (add-to-list 'files f 'append)
13920 (add-to-list 'tnames (file-truename f) 'append)))
13921 (multi-occur
13922 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13923 regexp)))
13925 (if (boundp 'occur-mode-find-occurrence-hook)
13926 ;; Emacs 23
13927 (add-hook 'occur-mode-find-occurrence-hook
13928 (lambda ()
13929 (when (org-mode-p)
13930 (org-reveal))))
13931 ;; Emacs 22
13932 (defadvice occur-mode-goto-occurrence
13933 (after org-occur-reveal activate)
13934 (and (org-mode-p) (org-reveal)))
13935 (defadvice occur-mode-goto-occurrence-other-window
13936 (after org-occur-reveal activate)
13937 (and (org-mode-p) (org-reveal)))
13938 (defadvice occur-mode-display-occurrence
13939 (after org-occur-reveal activate)
13940 (when (org-mode-p)
13941 (let ((pos (occur-mode-find-occurrence)))
13942 (with-current-buffer (marker-buffer pos)
13943 (save-excursion
13944 (goto-char pos)
13945 (org-reveal)))))))
13947 (defun org-uniquify (list)
13948 "Remove duplicate elements from LIST."
13949 (let (res)
13950 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13951 res))
13953 (defun org-delete-all (elts list)
13954 "Remove all elements in ELTS from LIST."
13955 (while elts
13956 (setq list (delete (pop elts) list)))
13957 list)
13959 (defun org-back-over-empty-lines ()
13960 "Move backwards over whitespace, to the beginning of the first empty line.
13961 Returns the number of empty lines passed."
13962 (let ((pos (point)))
13963 (skip-chars-backward " \t\n\r")
13964 (beginning-of-line 2)
13965 (goto-char (min (point) pos))
13966 (count-lines (point) pos)))
13968 (defun org-skip-whitespace ()
13969 (skip-chars-forward " \t\n\r"))
13971 (defun org-point-in-group (point group &optional context)
13972 "Check if POINT is in match-group GROUP.
13973 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13974 match. If the match group does ot exist or point is not inside it,
13975 return nil."
13976 (and (match-beginning group)
13977 (>= point (match-beginning group))
13978 (<= point (match-end group))
13979 (if context
13980 (list context (match-beginning group) (match-end group))
13981 t)))
13983 (defun org-switch-to-buffer-other-window (&rest args)
13984 "Switch to buffer in a second window on the current frame.
13985 In particular, do not allow pop-up frames."
13986 (let (pop-up-frames special-display-buffer-names special-display-regexps
13987 special-display-function)
13988 (apply 'switch-to-buffer-other-window args)))
13990 (defun org-combine-plists (&rest plists)
13991 "Create a single property list from all plists in PLISTS.
13992 The process starts by copying the first list, and then setting properties
13993 from the other lists. Settings in the last list are the most significant
13994 ones and overrule settings in the other lists."
13995 (let ((rtn (copy-sequence (pop plists)))
13996 p v ls)
13997 (while plists
13998 (setq ls (pop plists))
13999 (while ls
14000 (setq p (pop ls) v (pop ls))
14001 (setq rtn (plist-put rtn p v))))
14002 rtn))
14004 (defun org-move-line-down (arg)
14005 "Move the current line down. With prefix argument, move it past ARG lines."
14006 (interactive "p")
14007 (let ((col (current-column))
14008 beg end pos)
14009 (beginning-of-line 1) (setq beg (point))
14010 (beginning-of-line 2) (setq end (point))
14011 (beginning-of-line (+ 1 arg))
14012 (setq pos (move-marker (make-marker) (point)))
14013 (insert (delete-and-extract-region beg end))
14014 (goto-char pos)
14015 (org-move-to-column col)))
14017 (defun org-move-line-up (arg)
14018 "Move the current line up. With prefix argument, move it past ARG lines."
14019 (interactive "p")
14020 (let ((col (current-column))
14021 beg end pos)
14022 (beginning-of-line 1) (setq beg (point))
14023 (beginning-of-line 2) (setq end (point))
14024 (beginning-of-line (- arg))
14025 (setq pos (move-marker (make-marker) (point)))
14026 (insert (delete-and-extract-region beg end))
14027 (goto-char pos)
14028 (org-move-to-column col)))
14030 (defun org-replace-escapes (string table)
14031 "Replace %-escapes in STRING with values in TABLE.
14032 TABLE is an association list with keys like \"%a\" and string values.
14033 The sequences in STRING may contain normal field width and padding information,
14034 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14035 so values can contain further %-escapes if they are define later in TABLE."
14036 (let ((case-fold-search nil)
14037 e re rpl)
14038 (while (setq e (pop table))
14039 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14040 (while (string-match re string)
14041 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14042 (cdr e)))
14043 (setq string (replace-match rpl t t string))))
14044 string))
14047 (defun org-sublist (list start end)
14048 "Return a section of LIST, from START to END.
14049 Counting starts at 1."
14050 (let (rtn (c start))
14051 (setq list (nthcdr (1- start) list))
14052 (while (and list (<= c end))
14053 (push (pop list) rtn)
14054 (setq c (1+ c)))
14055 (nreverse rtn)))
14057 (defun org-find-base-buffer-visiting (file)
14058 "Like `find-buffer-visiting' but alway return the base buffer and
14059 not an indirect buffer."
14060 (let ((buf (find-buffer-visiting file)))
14061 (if buf
14062 (or (buffer-base-buffer buf) buf)
14063 nil)))
14065 (defun org-image-file-name-regexp ()
14066 "Return regexp matching the file names of images."
14067 (if (fboundp 'image-file-name-regexp)
14068 (image-file-name-regexp)
14069 (let ((image-file-name-extensions
14070 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14071 "xbm" "xpm" "pbm" "pgm" "ppm")))
14072 (concat "\\."
14073 (regexp-opt (nconc (mapcar 'upcase
14074 image-file-name-extensions)
14075 image-file-name-extensions)
14077 "\\'"))))
14079 (defun org-file-image-p (file)
14080 "Return non-nil if FILE is an image."
14081 (save-match-data
14082 (string-match (org-image-file-name-regexp) file)))
14084 (defun org-get-cursor-date ()
14085 "Return the date at cursor in as a time.
14086 This works in the calendar and in the agenda, anywhere else it just
14087 returns the current time."
14088 (let (date day defd)
14089 (cond
14090 ((eq major-mode 'calendar-mode)
14091 (setq date (calendar-cursor-to-date)
14092 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14093 ((eq major-mode 'org-agenda-mode)
14094 (setq day (get-text-property (point) 'day))
14095 (if day
14096 (setq date (calendar-gregorian-from-absolute day)
14097 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14098 (nth 2 date))))))
14099 (or defd (current-time))))
14101 (defvar org-agenda-action-marker (make-marker)
14102 "Marker pointing to the entry for the next agenda action.")
14104 (defun org-mark-entry-for-agenda-action ()
14105 "Mark the current entry as target of an agenda action.
14106 Agenda actions are actions executed from the agenda with the key `k',
14107 which make use of the date at the cursor."
14108 (interactive)
14109 (move-marker org-agenda-action-marker
14110 (save-excursion (org-back-to-heading t) (point))
14111 (current-buffer))
14112 (message
14113 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14115 ;;; Paragraph filling stuff.
14116 ;; We want this to be just right, so use the full arsenal.
14118 (defun org-indent-line-function ()
14119 "Indent line like previous, but further if previous was headline or item."
14120 (interactive)
14121 (let* ((pos (point))
14122 (itemp (org-at-item-p))
14123 column bpos bcol tpos tcol bullet btype bullet-type)
14124 ;; Find the previous relevant line
14125 (beginning-of-line 1)
14126 (cond
14127 ((looking-at "#") (setq column 0))
14128 ((looking-at "\\*+ ") (setq column 0))
14130 (beginning-of-line 0)
14131 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14132 (beginning-of-line 0))
14133 (cond
14134 ((looking-at "\\*+[ \t]+")
14135 (if (not org-adapt-indentation)
14136 (setq column 0)
14137 (goto-char (match-end 0))
14138 (setq column (current-column))))
14139 ((org-in-item-p)
14140 (org-beginning-of-item)
14141 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14142 (setq bpos (match-beginning 1) tpos (match-end 0)
14143 bcol (progn (goto-char bpos) (current-column))
14144 tcol (progn (goto-char tpos) (current-column))
14145 bullet (match-string 1)
14146 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14147 (if (> tcol (+ bcol org-description-max-indent))
14148 (setq tcol (+ bcol 5)))
14149 (if (not itemp)
14150 (setq column tcol)
14151 (goto-char pos)
14152 (beginning-of-line 1)
14153 (if (looking-at "\\S-")
14154 (progn
14155 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14156 (setq bullet (match-string 1)
14157 btype (if (string-match "[0-9]" bullet) "n" bullet))
14158 (setq column (if (equal btype bullet-type) bcol tcol)))
14159 (setq column (org-get-indentation)))))
14160 (t (setq column (org-get-indentation))))))
14161 (goto-char pos)
14162 (if (<= (current-column) (current-indentation))
14163 (org-indent-line-to column)
14164 (save-excursion (org-indent-line-to column)))
14165 (setq column (current-column))
14166 (beginning-of-line 1)
14167 (if (looking-at
14168 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14169 (replace-match (concat "\\1" (format org-property-format
14170 (match-string 2) (match-string 3)))
14171 t nil))
14172 (org-move-to-column column)))
14174 (defun org-set-autofill-regexps ()
14175 (interactive)
14176 ;; In the paragraph separator we include headlines, because filling
14177 ;; text in a line directly attached to a headline would otherwise
14178 ;; fill the headline as well.
14179 (org-set-local 'comment-start-skip "^#+[ \t]*")
14180 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14181 ;; The paragraph starter includes hand-formatted lists.
14182 (org-set-local 'paragraph-start
14183 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14184 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14185 ;; But only if the user has not turned off tables or fixed-width regions
14186 (org-set-local
14187 'auto-fill-inhibit-regexp
14188 (concat "\\*+ \\|#\\+"
14189 "\\|[ \t]*" org-keyword-time-regexp
14190 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14191 (concat
14192 "\\|[ \t]*["
14193 (if org-enable-table-editor "|" "")
14194 (if org-enable-fixed-width-editor ":" "")
14195 "]"))))
14196 ;; We use our own fill-paragraph function, to make sure that tables
14197 ;; and fixed-width regions are not wrapped. That function will pass
14198 ;; through to `fill-paragraph' when appropriate.
14199 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14200 ; Adaptive filling: To get full control, first make sure that
14201 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14202 (org-set-local 'adaptive-fill-regexp "\000")
14203 (org-set-local 'adaptive-fill-function
14204 'org-adaptive-fill-function)
14205 (org-set-local
14206 'align-mode-rules-list
14207 '((org-in-buffer-settings
14208 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14209 (modes . '(org-mode))))))
14211 (defun org-fill-paragraph (&optional justify)
14212 "Re-align a table, pass through to fill-paragraph if no table."
14213 (let ((table-p (org-at-table-p))
14214 (table.el-p (org-at-table.el-p)))
14215 (cond ((and (equal (char-after (point-at-bol)) ?*)
14216 (save-excursion (goto-char (point-at-bol))
14217 (looking-at outline-regexp)))
14218 t) ; skip headlines
14219 (table.el-p t) ; skip table.el tables
14220 (table-p (org-table-align) t) ; align org-mode tables
14221 (t nil)))) ; call paragraph-fill
14223 ;; For reference, this is the default value of adaptive-fill-regexp
14224 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14226 (defun org-adaptive-fill-function ()
14227 "Return a fill prefix for org-mode files.
14228 In particular, this makes sure hanging paragraphs for hand-formatted lists
14229 work correctly."
14230 (cond ((looking-at "#[ \t]+")
14231 (match-string 0))
14232 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14233 (save-excursion
14234 (if (> (match-end 1) (+ (match-beginning 1)
14235 org-description-max-indent))
14236 (goto-char (+ (match-beginning 1) 5))
14237 (goto-char (match-end 0)))
14238 (make-string (current-column) ?\ )))
14239 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14240 (save-excursion
14241 (goto-char (match-end 0))
14242 (make-string (current-column) ?\ )))
14243 (t nil)))
14245 ;;; Other stuff.
14247 (defun org-toggle-fixed-width-section (arg)
14248 "Toggle the fixed-width export.
14249 If there is no active region, the QUOTE keyword at the current headline is
14250 inserted or removed. When present, it causes the text between this headline
14251 and the next to be exported as fixed-width text, and unmodified.
14252 If there is an active region, this command adds or removes a colon as the
14253 first character of this line. If the first character of a line is a colon,
14254 this line is also exported in fixed-width font."
14255 (interactive "P")
14256 (let* ((cc 0)
14257 (regionp (org-region-active-p))
14258 (beg (if regionp (region-beginning) (point)))
14259 (end (if regionp (region-end)))
14260 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14261 (case-fold-search nil)
14262 (re "[ \t]*\\(:\\)")
14263 off)
14264 (if regionp
14265 (save-excursion
14266 (goto-char beg)
14267 (setq cc (current-column))
14268 (beginning-of-line 1)
14269 (setq off (looking-at re))
14270 (while (> nlines 0)
14271 (setq nlines (1- nlines))
14272 (beginning-of-line 1)
14273 (cond
14274 (arg
14275 (org-move-to-column cc t)
14276 (insert ":\n")
14277 (forward-line -1))
14278 ((and off (looking-at re))
14279 (replace-match "" t t nil 1))
14280 ((not off) (org-move-to-column cc t) (insert ":")))
14281 (forward-line 1)))
14282 (save-excursion
14283 (org-back-to-heading)
14284 (if (looking-at (concat outline-regexp
14285 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14286 (replace-match "" t t nil 1)
14287 (if (looking-at outline-regexp)
14288 (progn
14289 (goto-char (match-end 0))
14290 (insert org-quote-string " "))))))))
14292 ;;;; Functions extending outline functionality
14294 (defun org-beginning-of-line (&optional arg)
14295 "Go to the beginning of the current line. If that is invisible, continue
14296 to a visible line beginning. This makes the function of C-a more intuitive.
14297 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14298 first attempt, and only move to after the tags when the cursor is already
14299 beyond the end of the headline."
14300 (interactive "P")
14301 (let ((pos (point)) refpos)
14302 (beginning-of-line 1)
14303 (if (bobp)
14305 (backward-char 1)
14306 (if (org-invisible-p)
14307 (while (and (not (bobp)) (org-invisible-p))
14308 (backward-char 1)
14309 (beginning-of-line 1))
14310 (forward-char 1)))
14311 (when org-special-ctrl-a/e
14312 (cond
14313 ((and (looking-at org-complex-heading-regexp)
14314 (= (char-after (match-end 1)) ?\ ))
14315 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14316 (point-at-eol)))
14317 (goto-char
14318 (if (eq org-special-ctrl-a/e t)
14319 (cond ((> pos refpos) refpos)
14320 ((= pos (point)) refpos)
14321 (t (point)))
14322 (cond ((> pos (point)) (point))
14323 ((not (eq last-command this-command)) (point))
14324 (t refpos)))))
14325 ((org-at-item-p)
14326 (goto-char
14327 (if (eq org-special-ctrl-a/e t)
14328 (cond ((> pos (match-end 4)) (match-end 4))
14329 ((= pos (point)) (match-end 4))
14330 (t (point)))
14331 (cond ((> pos (point)) (point))
14332 ((not (eq last-command this-command)) (point))
14333 (t (match-end 4))))))))
14334 (org-no-warnings
14335 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14337 (defun org-end-of-line (&optional arg)
14338 "Go to the end of the line.
14339 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14340 first attempt, and only move to after the tags when the cursor is already
14341 beyond the end of the headline."
14342 (interactive "P")
14343 (if (or (not org-special-ctrl-a/e)
14344 (not (org-on-heading-p)))
14345 (end-of-line arg)
14346 (let ((pos (point)))
14347 (beginning-of-line 1)
14348 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14349 (if (eq org-special-ctrl-a/e t)
14350 (if (or (< pos (match-beginning 1))
14351 (= pos (match-end 0)))
14352 (goto-char (match-beginning 1))
14353 (goto-char (match-end 0)))
14354 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14355 (goto-char (match-end 0))
14356 (goto-char (match-beginning 1))))
14357 (end-of-line arg))))
14358 (org-no-warnings
14359 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14362 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14363 (define-key org-mode-map "\C-e" 'org-end-of-line)
14365 (defun org-kill-line (&optional arg)
14366 "Kill line, to tags or end of line."
14367 (interactive "P")
14368 (cond
14369 ((or (not org-special-ctrl-k)
14370 (bolp)
14371 (not (org-on-heading-p)))
14372 (call-interactively 'kill-line))
14373 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14374 (kill-region (point) (match-beginning 1))
14375 (org-set-tags nil t))
14376 (t (kill-region (point) (point-at-eol)))))
14378 (define-key org-mode-map "\C-k" 'org-kill-line)
14380 (defun org-yank (&optional arg)
14381 "Yank. If the kill is a subtree, treat it specially.
14382 This command will look at the current kill and check if is a single
14383 subtree, or a series of subtrees[1]. If it passes the test, and if the
14384 cursor is at the beginning of a line or after the stars of a currently
14385 empty headline, then the yank is handled specially. How exactly depends
14386 on the value of the following variables, both set by default.
14388 org-yank-folded-subtrees
14389 When set, the subtree(s) will be folded after insertion, but only
14390 if doing so would now swallow text after the yanked text.
14392 org-yank-adjusted-subtrees
14393 When set, the subtree will be promoted or demoted in order to
14394 fit into the local outline tree structure, which means that the level
14395 will be adjusted so that it becomes the smaller one of the two
14396 *visible* surrounding headings.
14398 Any prefix to this command will cause `yank' to be called directly with
14399 no special treatment. In particular, a simple `C-u' prefix will just
14400 plainly yank the text as it is.
14402 \[1] Basically, the test checks if the first non-white line is a heading
14403 and if there are no other headings with fewer stars."
14404 (interactive "P")
14405 (setq this-command 'yank)
14406 (if arg
14407 (call-interactively 'yank)
14408 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14409 (and (org-kill-is-subtree-p)
14410 (or (bolp)
14411 (and (looking-at "[ \t]*$")
14412 (string-match
14413 "\\`\\*+\\'"
14414 (buffer-substring (point-at-bol) (point)))))))
14415 swallowp)
14416 (cond
14417 ((and subtreep org-yank-folded-subtrees)
14418 (let ((beg (point))
14419 end)
14420 (if (and subtreep org-yank-adjusted-subtrees)
14421 (org-paste-subtree nil nil 'for-yank)
14422 (call-interactively 'yank))
14423 (setq end (point))
14424 (goto-char beg)
14425 (when (and (bolp) subtreep
14426 (not (setq swallowp
14427 (org-yank-folding-would-swallow-text beg end))))
14428 (or (looking-at outline-regexp)
14429 (re-search-forward (concat "^" outline-regexp) end t))
14430 (while (and (< (point) end) (looking-at outline-regexp))
14431 (hide-subtree)
14432 (org-cycle-show-empty-lines 'folded)
14433 (condition-case nil
14434 (outline-forward-same-level 1)
14435 (error (goto-char end)))))
14436 (when swallowp
14437 (message
14438 "Yanked text not folded because that would swallow text"))
14439 (goto-char end)
14440 (skip-chars-forward " \t\n\r")
14441 (beginning-of-line 1)
14442 (push-mark beg 'nomsg)))
14443 ((and subtreep org-yank-adjusted-subtrees)
14444 (let ((beg (point-at-bol)))
14445 (org-paste-subtree nil nil 'for-yank)
14446 (push-mark beg 'nomsg)))
14448 (call-interactively 'yank))))))
14450 (defun org-yank-folding-would-swallow-text (beg end)
14451 "Would hide-subtree at BEG swallow any text after END?"
14452 (let (level)
14453 (save-excursion
14454 (goto-char beg)
14455 (when (or (looking-at outline-regexp)
14456 (re-search-forward (concat "^" outline-regexp) end t))
14457 (setq level (org-outline-level)))
14458 (goto-char end)
14459 (skip-chars-forward " \t\r\n\v\f")
14460 (if (or (eobp)
14461 (and (bolp) (looking-at org-outline-regexp)
14462 (<= (org-outline-level) level)))
14463 nil ; Nothing would be swallowed
14464 t)))) ; something would swallow
14466 (define-key org-mode-map "\C-y" 'org-yank)
14468 (defun org-invisible-p ()
14469 "Check if point is at a character currently not visible."
14470 ;; Early versions of noutline don't have `outline-invisible-p'.
14471 (if (fboundp 'outline-invisible-p)
14472 (outline-invisible-p)
14473 (get-char-property (point) 'invisible)))
14475 (defun org-invisible-p2 ()
14476 "Check if point is at a character currently not visible."
14477 (save-excursion
14478 (if (and (eolp) (not (bobp))) (backward-char 1))
14479 ;; Early versions of noutline don't have `outline-invisible-p'.
14480 (if (fboundp 'outline-invisible-p)
14481 (outline-invisible-p)
14482 (get-char-property (point) 'invisible))))
14484 (defun org-back-to-heading (&optional invisible-ok)
14485 "Call `outline-back-to-heading', but provide a better error message."
14486 (condition-case nil
14487 (outline-back-to-heading invisible-ok)
14488 (error (error "Before first headline at position %d in buffer %s"
14489 (point) (current-buffer)))))
14491 (defun org-before-first-heading-p ()
14492 "Before first heading?"
14493 (save-excursion
14494 (null (re-search-backward "^\\*+ " nil t))))
14496 (defalias 'org-on-heading-p 'outline-on-heading-p)
14497 (defalias 'org-at-heading-p 'outline-on-heading-p)
14498 (defun org-at-heading-or-item-p ()
14499 (or (org-on-heading-p) (org-at-item-p)))
14501 (defun org-on-target-p ()
14502 (or (org-in-regexp org-radio-target-regexp)
14503 (org-in-regexp org-target-regexp)))
14505 (defun org-up-heading-all (arg)
14506 "Move to the heading line of which the present line is a subheading.
14507 This function considers both visible and invisible heading lines.
14508 With argument, move up ARG levels."
14509 (if (fboundp 'outline-up-heading-all)
14510 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14511 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14513 (defun org-up-heading-safe ()
14514 "Move to the heading line of which the present line is a subheading.
14515 This version will not throw an error. It will return the level of the
14516 headline found, or nil if no higher level is found."
14517 (let (start-level re)
14518 (org-back-to-heading t)
14519 (setq start-level (funcall outline-level))
14520 (if (equal start-level 1)
14522 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14523 (if (re-search-backward re nil t)
14524 (funcall outline-level)))))
14526 (defun org-first-sibling-p ()
14527 "Is this heading the first child of its parents?"
14528 (interactive)
14529 (let ((re (concat "^" outline-regexp))
14530 level l)
14531 (unless (org-at-heading-p t)
14532 (error "Not at a heading"))
14533 (setq level (funcall outline-level))
14534 (save-excursion
14535 (if (not (re-search-backward re nil t))
14537 (setq l (funcall outline-level))
14538 (< l level)))))
14540 (defun org-goto-sibling (&optional previous)
14541 "Goto the next sibling, even if it is invisible.
14542 When PREVIOUS is set, go to the previous sibling instead. Returns t
14543 when a sibling was found. When none is found, return nil and don't
14544 move point."
14545 (let ((fun (if previous 're-search-backward 're-search-forward))
14546 (pos (point))
14547 (re (concat "^" outline-regexp))
14548 level l)
14549 (when (condition-case nil (org-back-to-heading t) (error nil))
14550 (setq level (funcall outline-level))
14551 (catch 'exit
14552 (or previous (forward-char 1))
14553 (while (funcall fun re nil t)
14554 (setq l (funcall outline-level))
14555 (when (< l level) (goto-char pos) (throw 'exit nil))
14556 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14557 (goto-char pos)
14558 nil))))
14560 (defun org-show-siblings ()
14561 "Show all siblings of the current headline."
14562 (save-excursion
14563 (while (org-goto-sibling) (org-flag-heading nil)))
14564 (save-excursion
14565 (while (org-goto-sibling 'previous)
14566 (org-flag-heading nil))))
14568 (defun org-show-hidden-entry ()
14569 "Show an entry where even the heading is hidden."
14570 (save-excursion
14571 (org-show-entry)))
14573 (defun org-flag-heading (flag &optional entry)
14574 "Flag the current heading. FLAG non-nil means make invisible.
14575 When ENTRY is non-nil, show the entire entry."
14576 (save-excursion
14577 (org-back-to-heading t)
14578 ;; Check if we should show the entire entry
14579 (if entry
14580 (progn
14581 (org-show-entry)
14582 (save-excursion
14583 (and (outline-next-heading)
14584 (org-flag-heading nil))))
14585 (outline-flag-region (max (point-min) (1- (point)))
14586 (save-excursion (outline-end-of-heading) (point))
14587 flag))))
14589 (defun org-forward-same-level (arg)
14590 "Move forward to the ARG'th subheading at same level as this one.
14591 Stop at the first and last subheadings of a superior heading.
14592 This is like outline-forward-same-level, but invisible headings are ok."
14593 (interactive "p")
14594 (org-back-to-heading t)
14595 (while (> arg 0)
14596 (let ((point-to-move-to (save-excursion
14597 (org-get-next-sibling))))
14598 (if point-to-move-to
14599 (progn
14600 (goto-char point-to-move-to)
14601 (setq arg (1- arg)))
14602 (progn
14603 (setq arg 0)
14604 (error "No following same-level heading"))))))
14606 (defun org-get-next-sibling ()
14607 "Move to next heading of the same level, and return point.
14608 If there is no such heading, return nil.
14609 This is like outline-next-sibling, but invisible headings are ok."
14610 (let ((level (funcall outline-level)))
14611 (outline-next-heading)
14612 (while (and (not (eobp)) (> (funcall outline-level) level))
14613 (outline-next-heading))
14614 (if (or (eobp) (< (funcall outline-level) level))
14616 (point))))
14618 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14619 ;; This is an exact copy of the original function, but it uses
14620 ;; `org-back-to-heading', to make it work also in invisible
14621 ;; trees. And is uses an invisible-OK argument.
14622 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14623 (org-back-to-heading invisible-OK)
14624 (let ((first t)
14625 (level (funcall outline-level)))
14626 (while (and (not (eobp))
14627 (or first (> (funcall outline-level) level)))
14628 (setq first nil)
14629 (outline-next-heading))
14630 (unless to-heading
14631 (if (memq (preceding-char) '(?\n ?\^M))
14632 (progn
14633 ;; Go to end of line before heading
14634 (forward-char -1)
14635 (if (memq (preceding-char) '(?\n ?\^M))
14636 ;; leave blank line before heading
14637 (forward-char -1))))))
14638 (point))
14640 (defun org-show-subtree ()
14641 "Show everything after this heading at deeper levels."
14642 (outline-flag-region
14643 (point)
14644 (save-excursion
14645 (outline-end-of-subtree) (outline-next-heading) (point))
14646 nil))
14648 (defun org-show-entry ()
14649 "Show the body directly following this heading.
14650 Show the heading too, if it is currently invisible."
14651 (interactive)
14652 (save-excursion
14653 (condition-case nil
14654 (progn
14655 (org-back-to-heading t)
14656 (outline-flag-region
14657 (max (point-min) (1- (point)))
14658 (save-excursion
14659 (re-search-forward
14660 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14661 (or (match-beginning 1) (point-max)))
14662 nil))
14663 (error nil))))
14665 (defun org-make-options-regexp (kwds)
14666 "Make a regular expression for keyword lines."
14667 (concat
14669 "#?[ \t]*\\+\\("
14670 (mapconcat 'regexp-quote kwds "\\|")
14671 "\\):[ \t]*"
14672 "\\(.+\\)"))
14674 ;; Make isearch reveal the necessary context
14675 (defun org-isearch-end ()
14676 "Reveal context after isearch exits."
14677 (when isearch-success ; only if search was successful
14678 (if (featurep 'xemacs)
14679 ;; Under XEmacs, the hook is run in the correct place,
14680 ;; we directly show the context.
14681 (org-show-context 'isearch)
14682 ;; In Emacs the hook runs *before* restoring the overlays.
14683 ;; So we have to use a one-time post-command-hook to do this.
14684 ;; (Emacs 22 has a special variable, see function `org-mode')
14685 (unless (and (boundp 'isearch-mode-end-hook-quit)
14686 isearch-mode-end-hook-quit)
14687 ;; Only when the isearch was not quitted.
14688 (org-add-hook 'post-command-hook 'org-isearch-post-command
14689 'append 'local)))))
14691 (defun org-isearch-post-command ()
14692 "Remove self from hook, and show context."
14693 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14694 (org-show-context 'isearch))
14697 ;;;; Integration with and fixes for other packages
14699 ;;; Imenu support
14701 (defvar org-imenu-markers nil
14702 "All markers currently used by Imenu.")
14703 (make-variable-buffer-local 'org-imenu-markers)
14705 (defun org-imenu-new-marker (&optional pos)
14706 "Return a new marker for use by Imenu, and remember the marker."
14707 (let ((m (make-marker)))
14708 (move-marker m (or pos (point)))
14709 (push m org-imenu-markers)
14712 (defun org-imenu-get-tree ()
14713 "Produce the index for Imenu."
14714 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14715 (setq org-imenu-markers nil)
14716 (let* ((n org-imenu-depth)
14717 (re (concat "^" outline-regexp))
14718 (subs (make-vector (1+ n) nil))
14719 (last-level 0)
14720 m tree level head)
14721 (save-excursion
14722 (save-restriction
14723 (widen)
14724 (goto-char (point-max))
14725 (while (re-search-backward re nil t)
14726 (setq level (org-reduced-level (funcall outline-level)))
14727 (when (<= level n)
14728 (looking-at org-complex-heading-regexp)
14729 (setq head (org-link-display-format
14730 (org-match-string-no-properties 4))
14731 m (org-imenu-new-marker))
14732 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14733 (if (>= level last-level)
14734 (push (cons head m) (aref subs level))
14735 (push (cons head (aref subs (1+ level))) (aref subs level))
14736 (loop for i from (1+ level) to n do (aset subs i nil)))
14737 (setq last-level level)))))
14738 (aref subs 1)))
14740 (eval-after-load "imenu"
14741 '(progn
14742 (add-hook 'imenu-after-jump-hook
14743 (lambda ()
14744 (if (eq major-mode 'org-mode)
14745 (org-show-context 'org-goto))))))
14747 (defun org-link-display-format (link)
14748 "Replace a link with either the description, or the link target
14749 if no description is present"
14750 (save-match-data
14751 (if (string-match org-bracket-link-analytic-regexp link)
14752 (replace-match (or (match-string 5 link)
14753 (concat (match-string 1 link)
14754 (match-string 3 link)))
14755 nil nil link)
14756 link)))
14758 ;; Speedbar support
14760 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14761 "Overlay marking the agenda restriction line in speedbar.")
14762 (org-overlay-put org-speedbar-restriction-lock-overlay
14763 'face 'org-agenda-restriction-lock)
14764 (org-overlay-put org-speedbar-restriction-lock-overlay
14765 'help-echo "Agendas are currently limited to this item.")
14766 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14768 (defun org-speedbar-set-agenda-restriction ()
14769 "Restrict future agenda commands to the location at point in speedbar.
14770 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14771 (interactive)
14772 (require 'org-agenda)
14773 (let (p m tp np dir txt w)
14774 (cond
14775 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14776 'org-imenu t))
14777 (setq m (get-text-property p 'org-imenu-marker))
14778 (save-excursion
14779 (save-restriction
14780 (set-buffer (marker-buffer m))
14781 (goto-char m)
14782 (org-agenda-set-restriction-lock 'subtree))))
14783 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14784 'speedbar-function 'speedbar-find-file))
14785 (setq tp (previous-single-property-change
14786 (1+ p) 'speedbar-function)
14787 np (next-single-property-change
14788 tp 'speedbar-function)
14789 dir (speedbar-line-directory)
14790 txt (buffer-substring-no-properties (or tp (point-min))
14791 (or np (point-max))))
14792 (save-excursion
14793 (save-restriction
14794 (set-buffer (find-file-noselect
14795 (let ((default-directory dir))
14796 (expand-file-name txt))))
14797 (unless (org-mode-p)
14798 (error "Cannot restrict to non-Org-mode file"))
14799 (org-agenda-set-restriction-lock 'file))))
14800 (t (error "Don't know how to restrict Org-mode's agenda")))
14801 (org-move-overlay org-speedbar-restriction-lock-overlay
14802 (point-at-bol) (point-at-eol))
14803 (setq current-prefix-arg nil)
14804 (org-agenda-maybe-redo)))
14806 (eval-after-load "speedbar"
14807 '(progn
14808 (speedbar-add-supported-extension ".org")
14809 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14810 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14811 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14812 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14813 (add-hook 'speedbar-visiting-tag-hook
14814 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14817 ;;; Fixes and Hacks for problems with other packages
14819 ;; Make flyspell not check words in links, to not mess up our keymap
14820 (defun org-mode-flyspell-verify ()
14821 "Don't let flyspell put overlays at active buttons."
14822 (not (get-text-property (point) 'keymap)))
14824 ;; Make `bookmark-jump' show the jump location if it was hidden.
14825 (eval-after-load "bookmark"
14826 '(if (boundp 'bookmark-after-jump-hook)
14827 ;; We can use the hook
14828 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14829 ;; Hook not available, use advice
14830 (defadvice bookmark-jump (after org-make-visible activate)
14831 "Make the position visible."
14832 (org-bookmark-jump-unhide))))
14834 ;; Make sure saveplace show the location if it was hidden
14835 (eval-after-load "saveplace"
14836 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14837 "Make the position visible."
14838 (org-bookmark-jump-unhide)))
14840 (defun org-bookmark-jump-unhide ()
14841 "Unhide the current position, to show the bookmark location."
14842 (and (org-mode-p)
14843 (or (org-invisible-p)
14844 (save-excursion (goto-char (max (point-min) (1- (point))))
14845 (org-invisible-p)))
14846 (org-show-context 'bookmark-jump)))
14848 ;; Make session.el ignore our circular variable
14849 (eval-after-load "session"
14850 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14852 ;;;; Experimental code
14854 (defun org-closed-in-range ()
14855 "Sparse tree of items closed in a certain time range.
14856 Still experimental, may disappear in the future."
14857 (interactive)
14858 ;; Get the time interval from the user.
14859 (let* ((time1 (time-to-seconds
14860 (org-read-date nil 'to-time nil "Starting date: ")))
14861 (time2 (time-to-seconds
14862 (org-read-date nil 'to-time nil "End date:")))
14863 ;; callback function
14864 (callback (lambda ()
14865 (let ((time
14866 (time-to-seconds
14867 (apply 'encode-time
14868 (org-parse-time-string
14869 (match-string 1))))))
14870 ;; check if time in interval
14871 (and (>= time time1) (<= time time2))))))
14872 ;; make tree, check each match with the callback
14873 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14876 ;;;; Finish up
14878 (provide 'org)
14880 (run-hooks 'org-load-hook)
14882 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14884 ;;; org.el ends here