Fix bug that could push note into a child.
[org-mode.git] / lisp / org.el
blobe6981c5edaae97ac3e41cc0fcf9706852bb982d2
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.08-pre01
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)
91 ;;;; Customization variables
93 ;;; Version
95 (defconst org-version "6.08-pre01"
96 "The version number of the file org.el.")
98 (defun org-version (&optional here)
99 "Show the org-mode version in the echo area.
100 With prefix arg HERE, insert it at point."
101 (interactive "P")
102 (let ((version (format "Org-mode version %s" org-version)))
103 (message version)
104 (if here
105 (insert version))))
107 ;;; Compatibility constants
109 ;;; The custom variables
111 (defgroup org nil
112 "Outline-based notes management and organizer."
113 :tag "Org"
114 :group 'outlines
115 :group 'hypermedia
116 :group 'calendar)
118 (defcustom org-load-hook nil
119 "Hook that is run after org.el has been loaded."
120 :group 'org
121 :type 'hook)
123 (defvar org-modules) ; defined below
124 (defvar org-modules-loaded nil
125 "Have the modules been loaded already?")
127 (defun org-load-modules-maybe (&optional force)
128 "Load all extensions listed in `org-default-extensions'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
142 (when (org-bound-and-true-p org-modules)
143 (let ((a (member 'org-infojs org-modules)))
144 (and a (setcar a 'org-jsinfo))))
146 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
147 "Modules that should always be loaded together with org.el.
148 If a description starts with <C>, the file is not part of Emacs
149 and loading it will require that you have downloaded and properly installed
150 the org-mode distribution.
152 You can also use this system to load external packages (i.e. neither Org
153 core modules, not modules from the CONTRIB directory). Just add symbols
154 to the end of the list. If the package is called org-xyz.el, then you need
155 to add the symbol `xyz', and the package must have a call to
157 (provide 'org-xyz)"
158 :group 'org
159 :set 'org-set-modules
160 :type
161 '(set :greedy t
162 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
163 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
164 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
165 (const :tag " id: Global id's for identifying entries" org-id)
166 (const :tag " info: Links to Info nodes" org-info)
167 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
168 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
169 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
170 (const :tag " mew Links to Mew folders/messages" org-mew)
171 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
172 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
173 (const :tag " vm: Links to VM folders/messages" org-vm)
174 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
175 (const :tag " mouse: Additional mouse support" org-mouse)
177 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
178 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
179 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
180 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
181 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
182 (const :tag "C eval: Include command output as text" org-eval)
183 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
184 (const :tag "C id: Global id's for identifying entries" org-id)
185 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
186 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
187 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
188 (const :tag "C mtags: Support for muse-like tags" org-mtags)
189 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
190 (const :tag "C registry: A registry for Org links" org-registry)
191 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
192 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
193 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
194 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
195 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
198 (defgroup org-startup nil
199 "Options concerning startup of Org-mode."
200 :tag "Org Startup"
201 :group 'org)
203 (defcustom org-startup-folded t
204 "Non-nil means, entering Org-mode will switch to OVERVIEW.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
208 #+STARTUP: fold
209 #+STARTUP: nofold
210 #+STARTUP: content"
211 :group 'org-startup
212 :type '(choice
213 (const :tag "nofold: show all" nil)
214 (const :tag "fold: overview" t)
215 (const :tag "content: all headlines" content)))
217 (defcustom org-startup-truncated t
218 "Non-nil means, entering Org-mode will set `truncate-lines'.
219 This is useful since some lines containing links can be very long and
220 uninteresting. Also tables look terrible when wrapped."
221 :group 'org-startup
222 :type 'boolean)
224 (defcustom org-startup-align-all-tables nil
225 "Non-nil means, align all tables when visiting a file.
226 This is useful when the column width in tables is forced with <N> cookies
227 in table fields. Such tables will look correct only after the first re-align.
228 This can also be configured on a per-file basis by adding one of
229 the following lines anywhere in the buffer:
230 #+STARTUP: align
231 #+STARTUP: noalign"
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-insert-mode-line-in-empty-file nil
236 "Non-nil means insert the first line setting Org-mode in empty files.
237 When the function `org-mode' is called interactively in an empty file, this
238 normally means that the file name does not automatically trigger Org-mode.
239 To ensure that the file will always be in Org-mode in the future, a
240 line enforcing Org-mode will be inserted into the buffer, if this option
241 has been set."
242 :group 'org-startup
243 :type 'boolean)
245 (defcustom org-replace-disputed-keys nil
246 "Non-nil means use alternative key bindings for some keys.
247 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
248 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
249 If you want to use Org-mode together with one of these other modes,
250 or more generally if you would like to move some Org-mode commands to
251 other keys, set this variable and configure the keys with the variable
252 `org-disputed-keys'.
254 This option is only relevant at load-time of Org-mode, and must be set
255 *before* org.el is loaded. Changing it requires a restart of Emacs to
256 become effective."
257 :group 'org-startup
258 :type 'boolean)
260 (defcustom org-use-extra-keys nil
261 "Non-nil means use extra key sequence definitions for certain
262 commands. This happens automatically if you run XEmacs or if
263 window-system is nil. This variable lets you do the same
264 manually. You must set it before loading org.
266 Example: on Carbon Emacs 22 running graphically, with an external
267 keyboard on a Powerbook, the default way of setting M-left might
268 not work for either Alt or ESC. Setting this variable will make
269 it work for ESC."
270 :group 'org-startup
271 :type 'boolean)
273 (if (fboundp 'defvaralias)
274 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
276 (defcustom org-disputed-keys
277 '(([(shift up)] . [(meta p)])
278 ([(shift down)] . [(meta n)])
279 ([(shift left)] . [(meta -)])
280 ([(shift right)] . [(meta +)])
281 ([(control shift right)] . [(meta shift +)])
282 ([(control shift left)] . [(meta shift -)]))
283 "Keys for which Org-mode and other modes compete.
284 This is an alist, cars are the default keys, second element specifies
285 the alternative to use when `org-replace-disputed-keys' is t.
287 Keys can be specified in any syntax supported by `define-key'.
288 The value of this option takes effect only at Org-mode's startup,
289 therefore you'll have to restart Emacs to apply it after changing."
290 :group 'org-startup
291 :type 'alist)
293 (defun org-key (key)
294 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
295 Or return the original if not disputed."
296 (if org-replace-disputed-keys
297 (let* ((nkey (key-description key))
298 (x (org-find-if (lambda (x)
299 (equal (key-description (car x)) nkey))
300 org-disputed-keys)))
301 (if x (cdr x) key))
302 key))
304 (defun org-find-if (predicate seq)
305 (catch 'exit
306 (while seq
307 (if (funcall predicate (car seq))
308 (throw 'exit (car seq))
309 (pop seq)))))
311 (defun org-defkey (keymap key def)
312 "Define a key, possibly translated, as returned by `org-key'."
313 (define-key keymap (org-key key) def))
315 (defcustom org-ellipsis nil
316 "The ellipsis to use in the Org-mode outline.
317 When nil, just use the standard three dots. When a string, use that instead,
318 When a face, use the standart 3 dots, but with the specified face.
319 The change affects only Org-mode (which will then use its own display table).
320 Changing this requires executing `M-x org-mode' in a buffer to become
321 effective."
322 :group 'org-startup
323 :type '(choice (const :tag "Default" nil)
324 (face :tag "Face" :value org-warning)
325 (string :tag "String" :value "...#")))
327 (defvar org-display-table nil
328 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
330 (defgroup org-keywords nil
331 "Keywords in Org-mode."
332 :tag "Org Keywords"
333 :group 'org)
335 (defcustom org-deadline-string "DEADLINE:"
336 "String to mark deadline entries.
337 A deadline is this string, followed by a time stamp. Should be a word,
338 terminated by a colon. You can insert a schedule keyword and
339 a timestamp with \\[org-deadline].
340 Changes become only effective after restarting Emacs."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-scheduled-string "SCHEDULED:"
345 "String to mark scheduled TODO entries.
346 A schedule is this string, followed by a time stamp. Should be a word,
347 terminated by a colon. You can insert a schedule keyword and
348 a timestamp with \\[org-schedule].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-closed-string "CLOSED:"
354 "String used as the prefix for timestamps logging closing a TODO entry."
355 :group 'org-keywords
356 :type 'string)
358 (defcustom org-clock-string "CLOCK:"
359 "String used as prefix for timestamps clocking work hours on an item."
360 :group 'org-keywords
361 :type 'string)
363 (defcustom org-comment-string "COMMENT"
364 "Entries starting with this keyword will never be exported.
365 An entry can be toggled between COMMENT and normal with
366 \\[org-toggle-comment].
367 Changes become only effective after restarting Emacs."
368 :group 'org-keywords
369 :type 'string)
371 (defcustom org-quote-string "QUOTE"
372 "Entries starting with this keyword will be exported in fixed-width font.
373 Quoting applies only to the text in the entry following the headline, and does
374 not extend beyond the next headline, even if that is lower level.
375 An entry can be toggled between QUOTE and normal with
376 \\[org-toggle-fixed-width-section]."
377 :group 'org-keywords
378 :type 'string)
380 (defconst org-repeat-re
381 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
382 "Regular expression for specifying repeated events.
383 After a match, group 1 contains the repeat expression.")
385 (defgroup org-structure nil
386 "Options concerning the general structure of Org-mode files."
387 :tag "Org Structure"
388 :group 'org)
390 (defgroup org-reveal-location nil
391 "Options about how to make context of a location visible."
392 :tag "Org Reveal Location"
393 :group 'org-structure)
395 (defconst org-context-choice
396 '(choice
397 (const :tag "Always" t)
398 (const :tag "Never" nil)
399 (repeat :greedy t :tag "Individual contexts"
400 (cons
401 (choice :tag "Context"
402 (const agenda)
403 (const org-goto)
404 (const occur-tree)
405 (const tags-tree)
406 (const link-search)
407 (const mark-goto)
408 (const bookmark-jump)
409 (const isearch)
410 (const default))
411 (boolean))))
412 "Contexts for the reveal options.")
414 (defcustom org-show-hierarchy-above '((default . t))
415 "Non-nil means, show full hierarchy when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the hierarchy of headings
418 above the exposed location is shown.
419 Turning this off for example for sparse trees makes them very compact.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. Valid contexts are
422 agenda when exposing an entry from the agenda
423 org-goto when using the command `org-goto' on key C-c C-j
424 occur-tree when using the command `org-occur' on key C-c /
425 tags-tree when constructing a sparse tree based on tags matches
426 link-search when exposing search matches associated with a link
427 mark-goto when exposing the jump goal of a mark
428 bookmark-jump when exposing a bookmark location
429 isearch when exiting from an incremental search
430 default default for all contexts not set explicitly"
431 :group 'org-reveal-location
432 :type org-context-choice)
434 (defcustom org-show-following-heading '((default . nil))
435 "Non-nil means, show following heading when revealing a location.
436 Org-mode often shows locations in an org-mode file which might have
437 been invisible before. When this is set, the heading following the
438 match is shown.
439 Turning this off for example for sparse trees makes them very compact,
440 but makes it harder to edit the location of the match. In such a case,
441 use the command \\[org-reveal] to show more context.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. See `org-show-hierarchy-above' for valid contexts."
444 :group 'org-reveal-location
445 :type org-context-choice)
447 (defcustom org-show-siblings '((default . nil) (isearch t))
448 "Non-nil means, show all sibling heading when revealing a location.
449 Org-mode often shows locations in an org-mode file which might have
450 been invisible before. When this is set, the sibling of the current entry
451 heading are all made visible. If `org-show-hierarchy-above' is t,
452 the same happens on each level of the hierarchy above the current entry.
454 By default this is on for the isearch context, off for all other contexts.
455 Turning this off for example for sparse trees makes them very compact,
456 but makes it harder to edit the location of the match. In such a case,
457 use the command \\[org-reveal] to show more context.
458 Instead of t, this can also be an alist specifying this option for different
459 contexts. See `org-show-hierarchy-above' for valid contexts."
460 :group 'org-reveal-location
461 :type org-context-choice)
463 (defcustom org-show-entry-below '((default . nil))
464 "Non-nil means, show the entry below a headline when revealing a location.
465 Org-mode often shows locations in an org-mode file which might have
466 been invisible before. When this is set, the text below the headline that is
467 exposed is also shown.
469 By default this is off for all contexts.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. See `org-show-hierarchy-above' for valid contexts."
472 :group 'org-reveal-location
473 :type org-context-choice)
475 (defcustom org-indirect-buffer-display 'other-window
476 "How should indirect tree buffers be displayed?
477 This applies to indirect buffers created with the commands
478 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
479 Valid values are:
480 current-window Display in the current window
481 other-window Just display in another window.
482 dedicated-frame Create one new frame, and re-use it each time.
483 new-frame Make a new frame each time. Note that in this case
484 previously-made indirect buffers are kept, and you need to
485 kill these buffers yourself."
486 :group 'org-structure
487 :group 'org-agenda-windows
488 :type '(choice
489 (const :tag "In current window" current-window)
490 (const :tag "In current frame, other window" other-window)
491 (const :tag "Each time a new frame" new-frame)
492 (const :tag "One dedicated frame" dedicated-frame)))
494 (defgroup org-cycle nil
495 "Options concerning visibility cycling in Org-mode."
496 :tag "Org Cycle"
497 :group 'org-structure)
499 (defcustom org-drawers '("PROPERTIES" "CLOCK")
500 "Names of drawers. Drawers are not opened by cycling on the headline above.
501 Drawers only open with a TAB on the drawer line itself. A drawer looks like
502 this:
503 :DRAWERNAME:
504 .....
505 :END:
506 The drawer \"PROPERTIES\" is special for capturing properties through
507 the property API.
509 Drawers can be defined on the per-file basis with a line like:
511 #+DRAWERS: HIDDEN STATE PROPERTIES"
512 :group 'org-structure
513 :type '(repeat (string :tag "Drawer Name")))
515 (defcustom org-cycle-global-at-bob nil
516 "Cycle globally if cursor is at beginning of buffer and not at a headline.
517 This makes it possible to do global cycling without having to use S-TAB or
518 C-u TAB. For this special case to work, the first line of the buffer
519 must not be a headline - it may be empty ot some other text. When used in
520 this way, `org-cycle-hook' is disables temporarily, to make sure the
521 cursor stays at the beginning of the buffer.
522 When this option is nil, don't do anything special at the beginning
523 of the buffer."
524 :group 'org-cycle
525 :type 'boolean)
527 (defcustom org-cycle-emulate-tab t
528 "Where should `org-cycle' emulate TAB.
529 nil Never
530 white Only in completely white lines
531 whitestart Only at the beginning of lines, before the first non-white char
532 t Everywhere except in headlines
533 exc-hl-bol Everywhere except at the start of a headline
534 If TAB is used in a place where it does not emulate TAB, the current subtree
535 visibility is cycled."
536 :group 'org-cycle
537 :type '(choice (const :tag "Never" nil)
538 (const :tag "Only in completely white lines" white)
539 (const :tag "Before first char in a line" whitestart)
540 (const :tag "Everywhere except in headlines" t)
541 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
544 (defcustom org-cycle-separator-lines 2
545 "Number of empty lines needed to keep an empty line between collapsed trees.
546 If you leave an empty line between the end of a subtree and the following
547 headline, this empty line is hidden when the subtree is folded.
548 Org-mode will leave (exactly) one empty line visible if the number of
549 empty lines is equal or larger to the number given in this variable.
550 So the default 2 means, at least 2 empty lines after the end of a subtree
551 are needed to produce free space between a collapsed subtree and the
552 following headline.
554 Special case: when 0, never leave empty lines in collapsed view."
555 :group 'org-cycle
556 :type 'integer)
557 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
559 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
560 org-cycle-hide-drawers
561 org-cycle-show-empty-lines
562 org-optimize-window-after-visibility-change)
563 "Hook that is run after `org-cycle' has changed the buffer visibility.
564 The function(s) in this hook must accept a single argument which indicates
565 the new state that was set by the most recent `org-cycle' command. The
566 argument is a symbol. After a global state change, it can have the values
567 `overview', `content', or `all'. After a local state change, it can have
568 the values `folded', `children', or `subtree'."
569 :group 'org-cycle
570 :type 'hook)
572 (defgroup org-edit-structure nil
573 "Options concerning structure editing in Org-mode."
574 :tag "Org Edit Structure"
575 :group 'org-structure)
577 (defcustom org-odd-levels-only nil
578 "Non-nil means, skip even levels and only use odd levels for the outline.
579 This has the effect that two stars are being added/taken away in
580 promotion/demotion commands. It also influences how levels are
581 handled by the exporters.
582 Changing it requires restart of `font-lock-mode' to become effective
583 for fontification also in regions already fontified.
584 You may also set this on a per-file basis by adding one of the following
585 lines to the buffer:
587 #+STARTUP: odd
588 #+STARTUP: oddeven"
589 :group 'org-edit-structure
590 :group 'org-font-lock
591 :type 'boolean)
593 (defcustom org-adapt-indentation t
594 "Non-nil means, adapt indentation when promoting and demoting.
595 When this is set and the *entire* text in an entry is indented, the
596 indentation is increased by one space in a demotion command, and
597 decreased by one in a promotion command. If any line in the entry
598 body starts at column 0, indentation is not changed at all."
599 :group 'org-edit-structure
600 :type 'boolean)
602 (defcustom org-special-ctrl-a/e nil
603 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
604 When t, `C-a' will bring back the cursor to the beginning of the
605 headline text, i.e. after the stars and after a possible TODO keyword.
606 In an item, this will be the position after the bullet.
607 When the cursor is already at that position, another `C-a' will bring
608 it to the beginning of the line.
609 `C-e' will jump to the end of the headline, ignoring the presence of tags
610 in the headline. A second `C-e' will then jump to the true end of the
611 line, after any tags.
612 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
613 and only a directly following, identical keypress will bring the cursor
614 to the special positions."
615 :group 'org-edit-structure
616 :type '(choice
617 (const :tag "off" nil)
618 (const :tag "after bullet first" t)
619 (const :tag "border first" reversed)))
621 (if (fboundp 'defvaralias)
622 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
624 (defcustom org-special-ctrl-k nil
625 "Non-nil means `C-k' will behave specially in headlines.
626 When nil, `C-k' will call the default `kill-line' command.
627 When t, the following will happen while the cursor is in the headline:
629 - When the cursor is at the beginning of a headline, kill the entire
630 line and possible the folded subtree below the line.
631 - When in the middle of the headline text, kill the headline up to the tags.
632 - When after the headline text, kill the tags."
633 :group 'org-edit-structure
634 :type 'boolean)
636 (defcustom org-yank-folded-subtrees t
637 "Non-nil means, when yanking subtrees, fold them.
638 If the kill is a single subtree, or a sequence of subtrees, i.e. if
639 it starts with a heading and all other headings in it are either children
640 or siblings, then fold all the subtrees."
641 :group 'org-edit-structure
642 :type 'boolean)
644 (defcustom org-M-RET-may-split-line '((default . t))
645 "Non-nil means, M-RET will split the line at the cursor position.
646 When nil, it will go to the end of the line before making a
647 new line.
648 You may also set this option in a different way for different
649 contexts. Valid contexts are:
651 headline when creating a new headline
652 item when creating a new item
653 table in a table field
654 default the value to be used for all contexts not explicitly
655 customized"
656 :group 'org-structure
657 :group 'org-table
658 :type '(choice
659 (const :tag "Always" t)
660 (const :tag "Never" nil)
661 (repeat :greedy t :tag "Individual contexts"
662 (cons
663 (choice :tag "Context"
664 (const headline)
665 (const item)
666 (const table)
667 (const default))
668 (boolean)))))
671 (defcustom org-insert-heading-respect-content nil
672 "Non-nil means, insert new headings after the current subtree.
673 When nil, the new heading is created directly after the current line.
674 The commands \\[org-insert-heading-respect-content] and
675 \\[org-insert-todo-heading-respect-content] turn this variable on
676 for the duration of the command."
677 :group 'org-structure
678 :type 'boolean)
680 (defcustom org-blank-before-new-entry '((heading . nil)
681 (plain-list-item . nil))
682 "Should `org-insert-heading' leave a blank line before new heading/item?
683 The value is an alist, with `heading' and `plain-list-item' as car,
684 and a boolean flag as cdr."
685 :group 'org-edit-structure
686 :type '(list
687 (cons (const heading) (boolean))
688 (cons (const plain-list-item) (boolean))))
690 (defcustom org-insert-heading-hook nil
691 "Hook being run after inserting a new heading."
692 :group 'org-edit-structure
693 :type 'hook)
695 (defcustom org-enable-fixed-width-editor t
696 "Non-nil means, lines starting with \":\" are treated as fixed-width.
697 This currently only means, they are never auto-wrapped.
698 When nil, such lines will be treated like ordinary lines.
699 See also the QUOTE keyword."
700 :group 'org-edit-structure
701 :type 'boolean)
703 (defcustom org-edit-src-region-extra nil
704 "Additional regexps to identify regions for editing with `org-edit-src-code'.
705 For examples see the function `org-edit-src-find-region-and-lang'.
706 The regular expression identifying the begin marker should end with a newline,
707 and the regexp marking the end line should start with a newline, to make sure
708 there are kept outside the narrowed region."
709 :group 'org-edit-structure
710 :type '(repeat
711 (list
712 (regexp :tag "begin regexp")
713 (regexp :tag "end regexp")
714 (choice :tag "language"
715 (string :tag "specify")
716 (integer :tag "from match group")
717 (const :tag "from `lang' element")
718 (const :tag "from `style' element")))))
720 (defcustom org-edit-fixed-width-region-mode 'artist-mode
721 "The mode that should be used to edit fixed-width regions.
722 These are the regions where each line starts with a colon."
723 :group 'org-edit-structure
724 :type '(choice
725 (const artist-mode)
726 (const picture-mode)
727 (const fundamental-mode)
728 (function :tag "Other (specify)")))
730 (defcustom org-goto-auto-isearch t
731 "Non-nil means, typing characters in org-goto starts incremental search."
732 :group 'org-edit-structure
733 :type 'boolean)
735 (defgroup org-sparse-trees nil
736 "Options concerning sparse trees in Org-mode."
737 :tag "Org Sparse Trees"
738 :group 'org-structure)
740 (defcustom org-highlight-sparse-tree-matches t
741 "Non-nil means, highlight all matches that define a sparse tree.
742 The highlights will automatically disappear the next time the buffer is
743 changed by an edit command."
744 :group 'org-sparse-trees
745 :type 'boolean)
747 (defcustom org-remove-highlights-with-change t
748 "Non-nil means, any change to the buffer will remove temporary highlights.
749 Such highlights are created by `org-occur' and `org-clock-display'.
750 When nil, `C-c C-c needs to be used to get rid of the highlights.
751 The highlights created by `org-preview-latex-fragment' always need
752 `C-c C-c' to be removed."
753 :group 'org-sparse-trees
754 :group 'org-time
755 :type 'boolean)
758 (defcustom org-occur-hook '(org-first-headline-recenter)
759 "Hook that is run after `org-occur' has constructed a sparse tree.
760 This can be used to recenter the window to show as much of the structure
761 as possible."
762 :group 'org-sparse-trees
763 :type 'hook)
765 (defgroup org-imenu-and-speedbar nil
766 "Options concerning imenu and speedbar in Org-mode."
767 :tag "Org Imenu and Speedbar"
768 :group 'org-structure)
770 (defcustom org-imenu-depth 2
771 "The maximum level for Imenu access to Org-mode headlines.
772 This also applied for speedbar access."
773 :group 'org-imenu-and-speedbar
774 :type 'number)
776 (defgroup org-table nil
777 "Options concerning tables in Org-mode."
778 :tag "Org Table"
779 :group 'org)
781 (defcustom org-enable-table-editor 'optimized
782 "Non-nil means, lines starting with \"|\" are handled by the table editor.
783 When nil, such lines will be treated like ordinary lines.
785 When equal to the symbol `optimized', the table editor will be optimized to
786 do the following:
787 - Automatic overwrite mode in front of whitespace in table fields.
788 This makes the structure of the table stay in tact as long as the edited
789 field does not exceed the column width.
790 - Minimize the number of realigns. Normally, the table is aligned each time
791 TAB or RET are pressed to move to another field. With optimization this
792 happens only if changes to a field might have changed the column width.
793 Optimization requires replacing the functions `self-insert-command',
794 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
795 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
796 very good at guessing when a re-align will be necessary, but you can always
797 force one with \\[org-ctrl-c-ctrl-c].
799 If you would like to use the optimized version in Org-mode, but the
800 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
802 This variable can be used to turn on and off the table editor during a session,
803 but in order to toggle optimization, a restart is required.
805 See also the variable `org-table-auto-blank-field'."
806 :group 'org-table
807 :type '(choice
808 (const :tag "off" nil)
809 (const :tag "on" t)
810 (const :tag "on, optimized" optimized)))
812 (defcustom org-table-tab-recognizes-table.el t
813 "Non-nil means, TAB will automatically notice a table.el table.
814 When it sees such a table, it moves point into it and - if necessary -
815 calls `table-recognize-table'."
816 :group 'org-table-editing
817 :type 'boolean)
819 (defgroup org-link nil
820 "Options concerning links in Org-mode."
821 :tag "Org Link"
822 :group 'org)
824 (defvar org-link-abbrev-alist-local nil
825 "Buffer-local version of `org-link-abbrev-alist', which see.
826 The value of this is taken from the #+LINK lines.")
827 (make-variable-buffer-local 'org-link-abbrev-alist-local)
829 (defcustom org-link-abbrev-alist nil
830 "Alist of link abbreviations.
831 The car of each element is a string, to be replaced at the start of a link.
832 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
833 links in Org-mode buffers can have an optional tag after a double colon, e.g.
835 [[linkkey:tag][description]]
837 If REPLACE is a string, the tag will simply be appended to create the link.
838 If the string contains \"%s\", the tag will be inserted there.
840 REPLACE may also be a function that will be called with the tag as the
841 only argument to create the link, which should be returned as a string.
843 See the manual for examples."
844 :group 'org-link
845 :type 'alist)
847 (defcustom org-descriptive-links t
848 "Non-nil means, hide link part and only show description of bracket links.
849 Bracket links are like [[link][descritpion]]. This variable sets the initial
850 state in new org-mode buffers. The setting can then be toggled on a
851 per-buffer basis from the Org->Hyperlinks menu."
852 :group 'org-link
853 :type 'boolean)
855 (defcustom org-link-file-path-type 'adaptive
856 "How the path name in file links should be stored.
857 Valid values are:
859 relative Relative to the current directory, i.e. the directory of the file
860 into which the link is being inserted.
861 absolute Absolute path, if possible with ~ for home directory.
862 noabbrev Absolute path, no abbreviation of home directory.
863 adaptive Use relative path for files in the current directory and sub-
864 directories of it. For other files, use an absolute path."
865 :group 'org-link
866 :type '(choice
867 (const relative)
868 (const absolute)
869 (const noabbrev)
870 (const adaptive)))
872 (defcustom org-activate-links '(bracket angle plain radio tag date)
873 "Types of links that should be activated in Org-mode files.
874 This is a list of symbols, each leading to the activation of a certain link
875 type. In principle, it does not hurt to turn on most link types - there may
876 be a small gain when turning off unused link types. The types are:
878 bracket The recommended [[link][description]] or [[link]] links with hiding.
879 angular Links in angular brackes that may contain whitespace like
880 <bbdb:Carsten Dominik>.
881 plain Plain links in normal text, no whitespace, like http://google.com.
882 radio Text that is matched by a radio target, see manual for details.
883 tag Tag settings in a headline (link to tag search).
884 date Time stamps (link to calendar).
886 Changing this variable requires a restart of Emacs to become effective."
887 :group 'org-link
888 :type '(set (const :tag "Double bracket links (new style)" bracket)
889 (const :tag "Angular bracket links (old style)" angular)
890 (const :tag "Plain text links" plain)
891 (const :tag "Radio target matches" radio)
892 (const :tag "Tags" tag)
893 (const :tag "Timestamps" date)))
895 (defcustom org-make-link-description-function nil
896 "Function to use to generate link descriptions from links. If
897 nil the link location will be used. This function must take two
898 parameters; the first is the link and the second the description
899 org-insert-link has generated, and should return the description
900 to use."
901 :group 'org-link
902 :type 'function)
904 (defgroup org-link-store nil
905 "Options concerning storing links in Org-mode."
906 :tag "Org Store Link"
907 :group 'org-link)
909 (defcustom org-email-link-description-format "Email %c: %.30s"
910 "Format of the description part of a link to an email or usenet message.
911 The following %-excapes will be replaced by corresponding information:
913 %F full \"From\" field
914 %f name, taken from \"From\" field, address if no name
915 %T full \"To\" field
916 %t first name in \"To\" field, address if no name
917 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
918 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
919 %s subject
920 %m message-id.
922 You may use normal field width specification between the % and the letter.
923 This is for example useful to limit the length of the subject.
925 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
926 :group 'org-link-store
927 :type 'string)
929 (defcustom org-from-is-user-regexp
930 (let (r1 r2)
931 (when (and user-mail-address (not (string= user-mail-address "")))
932 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
933 (when (and user-full-name (not (string= user-full-name "")))
934 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
935 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
936 "Regexp mached against the \"From:\" header of an email or usenet message.
937 It should match if the message is from the user him/herself."
938 :group 'org-link-store
939 :type 'regexp)
941 (defcustom org-context-in-file-links t
942 "Non-nil means, file links from `org-store-link' contain context.
943 A search string will be added to the file name with :: as separator and
944 used to find the context when the link is activated by the command
945 `org-open-at-point'.
946 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
947 negates this setting for the duration of the command."
948 :group 'org-link-store
949 :type 'boolean)
951 (defcustom org-keep-stored-link-after-insertion nil
952 "Non-nil means, keep link in list for entire session.
954 The command `org-store-link' adds a link pointing to the current
955 location to an internal list. These links accumulate during a session.
956 The command `org-insert-link' can be used to insert links into any
957 Org-mode file (offering completion for all stored links). When this
958 option is nil, every link which has been inserted once using \\[org-insert-link]
959 will be removed from the list, to make completing the unused links
960 more efficient."
961 :group 'org-link-store
962 :type 'boolean)
964 (defgroup org-link-follow nil
965 "Options concerning following links in Org-mode."
966 :tag "Org Follow Link"
967 :group 'org-link)
969 (defcustom org-follow-link-hook nil
970 "Hook that is run after a link has been followed."
971 :group 'org-link-follow
972 :type 'hook)
974 (defcustom org-tab-follows-link nil
975 "Non-nil means, on links TAB will follow the link.
976 Needs to be set before org.el is loaded."
977 :group 'org-link-follow
978 :type 'boolean)
980 (defcustom org-return-follows-link nil
981 "Non-nil means, on links RET will follow the link.
982 Needs to be set before org.el is loaded."
983 :group 'org-link-follow
984 :type 'boolean)
986 (defcustom org-mouse-1-follows-link
987 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
988 "Non-nil means, mouse-1 on a link will follow the link.
989 A longer mouse click will still set point. Does not work on XEmacs.
990 Needs to be set before org.el is loaded."
991 :group 'org-link-follow
992 :type 'boolean)
994 (defcustom org-mark-ring-length 4
995 "Number of different positions to be recorded in the ring
996 Changing this requires a restart of Emacs to work correctly."
997 :group 'org-link-follow
998 :type 'interger)
1000 (defcustom org-link-frame-setup
1001 '((vm . vm-visit-folder-other-frame)
1002 (gnus . gnus-other-frame)
1003 (file . find-file-other-window))
1004 "Setup the frame configuration for following links.
1005 When following a link with Emacs, it may often be useful to display
1006 this link in another window or frame. This variable can be used to
1007 set this up for the different types of links.
1008 For VM, use any of
1009 `vm-visit-folder'
1010 `vm-visit-folder-other-frame'
1011 For Gnus, use any of
1012 `gnus'
1013 `gnus-other-frame'
1014 For FILE, use any of
1015 `find-file'
1016 `find-file-other-window'
1017 `find-file-other-frame'
1018 For the calendar, use the variable `calendar-setup'.
1019 For BBDB, it is currently only possible to display the matches in
1020 another window."
1021 :group 'org-link-follow
1022 :type '(list
1023 (cons (const vm)
1024 (choice
1025 (const vm-visit-folder)
1026 (const vm-visit-folder-other-window)
1027 (const vm-visit-folder-other-frame)))
1028 (cons (const gnus)
1029 (choice
1030 (const gnus)
1031 (const gnus-other-frame)))
1032 (cons (const file)
1033 (choice
1034 (const find-file)
1035 (const find-file-other-window)
1036 (const find-file-other-frame)))))
1038 (defcustom org-display-internal-link-with-indirect-buffer nil
1039 "Non-nil means, use indirect buffer to display infile links.
1040 Activating internal links (from one location in a file to another location
1041 in the same file) normally just jumps to the location. When the link is
1042 activated with a C-u prefix (or with mouse-3), the link is displayed in
1043 another window. When this option is set, the other window actually displays
1044 an indirect buffer clone of the current buffer, to avoid any visibility
1045 changes to the current buffer."
1046 :group 'org-link-follow
1047 :type 'boolean)
1049 (defcustom org-open-non-existing-files nil
1050 "Non-nil means, `org-open-file' will open non-existing files.
1051 When nil, an error will be generated."
1052 :group 'org-link-follow
1053 :type 'boolean)
1055 (defcustom org-open-directory-means-index-dot-org nil
1056 "Non-nil means, a link to a directory really means to index.org.
1057 When nil, following a directory link will run dired or open a finder/explorer
1058 window on that directory."
1059 :group 'org-link-follow
1060 :type 'boolean)
1062 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1063 "Function and arguments to call for following mailto links.
1064 This is a list with the first element being a lisp function, and the
1065 remaining elements being arguments to the function. In string arguments,
1066 %a will be replaced by the address, and %s will be replaced by the subject
1067 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1068 :group 'org-link-follow
1069 :type '(choice
1070 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1071 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1072 (const :tag "message-mail" (message-mail "%a" "%s"))
1073 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1075 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1076 "Non-nil means, ask for confirmation before executing shell links.
1077 Shell links can be dangerous: just think about a link
1079 [[shell:rm -rf ~/*][Google Search]]
1081 This link would show up in your Org-mode document as \"Google Search\",
1082 but really it would remove your entire home directory.
1083 Therefore we advise against setting this variable to nil.
1084 Just change it to `y-or-n-p' of you want to confirm with a
1085 single keystroke rather than having to type \"yes\"."
1086 :group 'org-link-follow
1087 :type '(choice
1088 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1089 (const :tag "with y-or-n (faster)" y-or-n-p)
1090 (const :tag "no confirmation (dangerous)" nil)))
1092 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1093 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1094 Elisp links can be dangerous: just think about a link
1096 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1098 This link would show up in your Org-mode document as \"Google Search\",
1099 but really it would remove your entire home directory.
1100 Therefore we advise against setting this variable to nil.
1101 Just change it to `y-or-n-p' of you want to confirm with a
1102 single keystroke rather than having to type \"yes\"."
1103 :group 'org-link-follow
1104 :type '(choice
1105 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1106 (const :tag "with y-or-n (faster)" y-or-n-p)
1107 (const :tag "no confirmation (dangerous)" nil)))
1109 (defconst org-file-apps-defaults-gnu
1110 '((remote . emacs)
1111 (t . mailcap))
1112 "Default file applications on a UNIX or GNU/Linux system.
1113 See `org-file-apps'.")
1115 (defconst org-file-apps-defaults-macosx
1116 '((remote . emacs)
1117 (t . "open %s")
1118 ("ps.gz" . "gv %s")
1119 ("eps.gz" . "gv %s")
1120 ("dvi" . "xdvi %s")
1121 ("fig" . "xfig %s"))
1122 "Default file applications on a MacOS X system.
1123 The system \"open\" is known as a default, but we use X11 applications
1124 for some files for which the OS does not have a good default.
1125 See `org-file-apps'.")
1127 (defconst org-file-apps-defaults-windowsnt
1128 (list
1129 '(remote . emacs)
1130 (cons t
1131 (list (if (featurep 'xemacs)
1132 'mswindows-shell-execute
1133 'w32-shell-execute)
1134 "open" 'file)))
1135 "Default file applications on a Windows NT system.
1136 The system \"open\" is used for most files.
1137 See `org-file-apps'.")
1139 (defcustom org-file-apps
1141 ("txt" . emacs)
1142 ("tex" . emacs)
1143 ("ltx" . emacs)
1144 ("org" . emacs)
1145 ("el" . emacs)
1146 ("bib" . emacs)
1148 "External applications for opening `file:path' items in a document.
1149 Org-mode uses system defaults for different file types, but
1150 you can use this variable to set the application for a given file
1151 extension. The entries in this list are cons cells where the car identifies
1152 files and the cdr the corresponding command. Possible values for the
1153 file identifier are
1154 \"ext\" A string identifying an extension
1155 `directory' Matches a directory
1156 `remote' Matches a remote file, accessible through tramp or efs.
1157 Remote files most likely should be visited through Emacs
1158 because external applications cannot handle such paths.
1159 t Default for all remaining files
1161 Possible values for the command are:
1162 `emacs' The file will be visited by the current Emacs process.
1163 `default' Use the default application for this file type.
1164 string A command to be executed by a shell; %s will be replaced
1165 by the path to the file.
1166 sexp A Lisp form which will be evaluated. The file path will
1167 be available in the Lisp variable `file'.
1168 For more examples, see the system specific constants
1169 `org-file-apps-defaults-macosx'
1170 `org-file-apps-defaults-windowsnt'
1171 `org-file-apps-defaults-gnu'."
1172 :group 'org-link-follow
1173 :type '(repeat
1174 (cons (choice :value ""
1175 (string :tag "Extension")
1176 (const :tag "Default for unrecognized files" t)
1177 (const :tag "Remote file" remote)
1178 (const :tag "Links to a directory" directory))
1179 (choice :value ""
1180 (const :tag "Visit with Emacs" emacs)
1181 (const :tag "Use system default" default)
1182 (string :tag "Command")
1183 (sexp :tag "Lisp form")))))
1185 (defgroup org-refile nil
1186 "Options concerning refiling entries in Org-mode."
1187 :tag "Org Remember"
1188 :group 'org)
1190 (defcustom org-directory "~/org"
1191 "Directory with org files.
1192 This directory will be used as default to prompt for org files.
1193 Used by the hooks for remember.el."
1194 :group 'org-refile
1195 :group 'org-remember
1196 :type 'directory)
1198 (defcustom org-default-notes-file "~/.notes"
1199 "Default target for storing notes.
1200 Used by the hooks for remember.el. This can be a string, or nil to mean
1201 the value of `remember-data-file'.
1202 You can set this on a per-template basis with the variable
1203 `org-remember-templates'."
1204 :group 'org-refile
1205 :group 'org-remember
1206 :type '(choice
1207 (const :tag "Default from remember-data-file" nil)
1208 file))
1210 (defcustom org-goto-interface 'outline
1211 "The default interface to be used for `org-goto'.
1212 Allowed vaues are:
1213 outline The interface shows an outline of the relevant file
1214 and the correct heading is found by moving through
1215 the outline or by searching with incremental search.
1216 outline-path-completion Headlines in the current buffer are offered via
1217 completion."
1218 :group 'org-refile
1219 :type '(choice
1220 (const :tag "Outline" outline)
1221 (const :tag "Outline-path-completion" outline-path-completion)))
1223 (defcustom org-reverse-note-order nil
1224 "Non-nil means, store new notes at the beginning of a file or entry.
1225 When nil, new notes will be filed to the end of a file or entry.
1226 This can also be a list with cons cells of regular expressions that
1227 are matched against file names, and values."
1228 :group 'org-remember
1229 :type '(choice
1230 (const :tag "Reverse always" t)
1231 (const :tag "Reverse never" nil)
1232 (repeat :tag "By file name regexp"
1233 (cons regexp boolean))))
1235 (defcustom org-refile-targets nil
1236 "Targets for refiling entries with \\[org-refile].
1237 This is list of cons cells. Each cell contains:
1238 - a specification of the files to be considered, either a list of files,
1239 or a symbol whose function or variable value will be used to retrieve
1240 a file name or a list of file names. Nil means, refile to a different
1241 heading in the current buffer.
1242 - A specification of how to find candidate refile targets. This may be
1243 any of
1244 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1245 This tag has to be present in all target headlines, inheritance will
1246 not be considered.
1247 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1248 todo keyword.
1249 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1250 headlines that are refiling targets.
1251 - a cons cell (:level . N). Any headline of level N is considered a target.
1252 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1254 When this variable is nil, all top-level headlines in the current buffer
1255 are used, equivalent to the vlaue `((nil . (:level . 1))'."
1256 :group 'org-remember
1257 :type '(repeat
1258 (cons
1259 (choice :value org-agenda-files
1260 (const :tag "All agenda files" org-agenda-files)
1261 (const :tag "Current buffer" nil)
1262 (function) (variable) (file))
1263 (choice :tag "Identify target headline by"
1264 (cons :tag "Specific tag" (const :tag) (string))
1265 (cons :tag "TODO keyword" (const :todo) (string))
1266 (cons :tag "Regular expression" (const :regexp) (regexp))
1267 (cons :tag "Level number" (const :level) (integer))
1268 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1270 (defcustom org-refile-use-outline-path nil
1271 "Non-nil means, provide refile targets as paths.
1272 So a level 3 headline will be available as level1/level2/level3.
1273 When the value is `file', also include the file name (without directory)
1274 into the path. When `full-file-path', include the full file path."
1275 :group 'org-remember
1276 :type '(choice
1277 (const :tag "Not" nil)
1278 (const :tag "Yes" t)
1279 (const :tag "Start with file name" file)
1280 (const :tag "Start with full file path" full-file-path)))
1282 (defgroup org-todo nil
1283 "Options concerning TODO items in Org-mode."
1284 :tag "Org TODO"
1285 :group 'org)
1287 (defgroup org-progress nil
1288 "Options concerning Progress logging in Org-mode."
1289 :tag "Org Progress"
1290 :group 'org-time)
1292 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1293 "List of TODO entry keyword sequences and their interpretation.
1294 \\<org-mode-map>This is a list of sequences.
1296 Each sequence starts with a symbol, either `sequence' or `type',
1297 indicating if the keywords should be interpreted as a sequence of
1298 action steps, or as different types of TODO items. The first
1299 keywords are states requiring action - these states will select a headline
1300 for inclusion into the global TODO list Org-mode produces. If one of
1301 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1302 signify that no further action is necessary. If \"|\" is not found,
1303 the last keyword is treated as the only DONE state of the sequence.
1305 The command \\[org-todo] cycles an entry through these states, and one
1306 additional state where no keyword is present. For details about this
1307 cycling, see the manual.
1309 TODO keywords and interpretation can also be set on a per-file basis with
1310 the special #+SEQ_TODO and #+TYP_TODO lines.
1312 Each keyword can optionally specify a character for fast state selection
1313 \(in combination with the variable `org-use-fast-todo-selection')
1314 and specifiers for state change logging, using the same syntax
1315 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1316 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1317 indicates to record a time stamp each time this state is selected.
1319 Each keyword may also specify if a timestamp or a note should be
1320 recorded when entering or leaving the state, by adding additional
1321 characters in the parenthesis after the keyword. This looks like this:
1322 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1323 record only the time of the state change. With X and Y being either
1324 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1325 Y when leaving the state if and only if the *target* state does not
1326 define X. You may omit any of the fast-selection key or X or /Y,
1327 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1329 For backward compatibility, this variable may also be just a list
1330 of keywords - in this case the interptetation (sequence or type) will be
1331 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1332 :group 'org-todo
1333 :group 'org-keywords
1334 :type '(choice
1335 (repeat :tag "Old syntax, just keywords"
1336 (string :tag "Keyword"))
1337 (repeat :tag "New syntax"
1338 (cons
1339 (choice
1340 :tag "Interpretation"
1341 (const :tag "Sequence (cycling hits every state)" sequence)
1342 (const :tag "Type (cycling directly to DONE)" type))
1343 (repeat
1344 (string :tag "Keyword"))))))
1346 (defvar org-todo-keywords-1 nil
1347 "All TODO and DONE keywords active in a buffer.")
1348 (make-variable-buffer-local 'org-todo-keywords-1)
1349 (defvar org-todo-keywords-for-agenda nil)
1350 (defvar org-done-keywords-for-agenda nil)
1351 (defvar org-todo-keyword-alist-for-agenda nil)
1352 (defvar org-tag-alist-for-agenda nil)
1353 (defvar org-agenda-contributing-files nil)
1354 (defvar org-not-done-keywords nil)
1355 (make-variable-buffer-local 'org-not-done-keywords)
1356 (defvar org-done-keywords nil)
1357 (make-variable-buffer-local 'org-done-keywords)
1358 (defvar org-todo-heads nil)
1359 (make-variable-buffer-local 'org-todo-heads)
1360 (defvar org-todo-sets nil)
1361 (make-variable-buffer-local 'org-todo-sets)
1362 (defvar org-todo-log-states nil)
1363 (make-variable-buffer-local 'org-todo-log-states)
1364 (defvar org-todo-kwd-alist nil)
1365 (make-variable-buffer-local 'org-todo-kwd-alist)
1366 (defvar org-todo-key-alist nil)
1367 (make-variable-buffer-local 'org-todo-key-alist)
1368 (defvar org-todo-key-trigger nil)
1369 (make-variable-buffer-local 'org-todo-key-trigger)
1371 (defcustom org-todo-interpretation 'sequence
1372 "Controls how TODO keywords are interpreted.
1373 This variable is in principle obsolete and is only used for
1374 backward compatibility, if the interpretation of todo keywords is
1375 not given already in `org-todo-keywords'. See that variable for
1376 more information."
1377 :group 'org-todo
1378 :group 'org-keywords
1379 :type '(choice (const sequence)
1380 (const type)))
1382 (defcustom org-use-fast-todo-selection 'prefix
1383 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1384 This variable describes if and under what circumstances the cycling
1385 mechanism for TODO keywords will be replaced by a single-key, direct
1386 selection scheme.
1388 When nil, fast selection is never used.
1390 When the symbol `prefix', it will be used when `org-todo' is called with
1391 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1392 in an agenda buffer.
1394 When t, fast selection is used by default. In this case, the prefix
1395 argument forces cycling instead.
1397 In all cases, the special interface is only used if access keys have actually
1398 been assigned by the user, i.e. if keywords in the configuration are followed
1399 by a letter in parenthesis, like TODO(t)."
1400 :group 'org-todo
1401 :type '(choice
1402 (const :tag "Never" nil)
1403 (const :tag "By default" t)
1404 (const :tag "Only with C-u C-c C-t" prefix)))
1406 (defcustom org-provide-todo-statistics t
1407 "Non-nil means, update todo statistics after insert and toggle.
1408 When this is set, todo statistics is updated in the parent of the current
1409 entry each time a todo state is changed."
1410 :group 'org-todo
1411 :type 'boolean)
1413 (defcustom org-after-todo-state-change-hook nil
1414 "Hook which is run after the state of a TODO item was changed.
1415 The new state (a string with a TODO keyword, or nil) is available in the
1416 Lisp variable `state'."
1417 :group 'org-todo
1418 :type 'hook)
1420 (defcustom org-log-done nil
1421 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1422 When equal to the list (done), also prompt for a closing note.
1423 This can also be configured on a per-file basis by adding one of
1424 the following lines anywhere in the buffer:
1426 #+STARTUP: logdone
1427 #+STARTUP: lognotedone
1428 #+STARTUP: nologdone"
1429 :group 'org-todo
1430 :group 'org-progress
1431 :type '(choice
1432 (const :tag "No logging" nil)
1433 (const :tag "Record CLOSED timestamp" time)
1434 (const :tag "Record CLOSED timestamp with closing note." note)))
1436 ;; Normalize old uses of org-log-done.
1437 (cond
1438 ((eq org-log-done t) (setq org-log-done 'time))
1439 ((and (listp org-log-done) (memq 'done org-log-done))
1440 (setq org-log-done 'note)))
1442 (defcustom org-log-note-clock-out nil
1443 "Non-nil means, record a note when clocking out of an item.
1444 This can also be configured on a per-file basis by adding one of
1445 the following lines anywhere in the buffer:
1447 #+STARTUP: lognoteclock-out
1448 #+STARTUP: nolognoteclock-out"
1449 :group 'org-todo
1450 :group 'org-progress
1451 :type 'boolean)
1453 (defcustom org-log-done-with-time t
1454 "Non-nil means, the CLOSED time stamp will contain date and time.
1455 When nil, only the date will be recorded."
1456 :group 'org-progress
1457 :type 'boolean)
1459 (defcustom org-log-note-headings
1460 '((done . "CLOSING NOTE %t")
1461 (state . "State %-12s %t")
1462 (note . "Note taken on %t")
1463 (clock-out . ""))
1464 "Headings for notes added to entries.
1465 The value is an alist, with the car being a symbol indicating the note
1466 context, and the cdr is the heading to be used. The heading may also be the
1467 empty string.
1468 %t in the heading will be replaced by a time stamp.
1469 %s will be replaced by the new TODO state, in double quotes.
1470 %u will be replaced by the user name.
1471 %U will be replaced by the full user name."
1472 :group 'org-todo
1473 :group 'org-progress
1474 :type '(list :greedy t
1475 (cons (const :tag "Heading when closing an item" done) string)
1476 (cons (const :tag
1477 "Heading when changing todo state (todo sequence only)"
1478 state) string)
1479 (cons (const :tag "Heading when just taking a note" note) string)
1480 (cons (const :tag "Heading when clocking out" clock-out) string)))
1482 (unless (assq 'note org-log-note-headings)
1483 (push '(note . "%t") org-log-note-headings))
1485 (defcustom org-log-states-order-reversed t
1486 "Non-nil means, the latest state change note will be directly after heading.
1487 When nil, the notes will be orderer according to time."
1488 :group 'org-todo
1489 :group 'org-progress
1490 :type 'boolean)
1492 (defcustom org-log-repeat 'time
1493 "Non-nil means, record moving through the DONE state when triggering repeat.
1494 An auto-repeating tasks is immediately switched back to TODO when marked
1495 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1496 the TODO keyword definition, or recording a closing note by setting
1497 `org-log-done', there will be no record of the task moving through DONE.
1498 This variable forces taking a note anyway. Possible values are:
1500 nil Don't force a record
1501 time Record a time stamp
1502 note Record a note
1504 This option can also be set with on a per-file-basis with
1506 #+STARTUP: logrepeat
1507 #+STARTUP: lognoterepeat
1508 #+STARTUP: nologrepeat
1510 You can have local logging settings for a subtree by setting the LOGGING
1511 property to one or more of these keywords."
1512 :group 'org-todo
1513 :group 'org-progress
1514 :type '(choice
1515 (const :tag "Don't force a record" nil)
1516 (const :tag "Force recording the DONE state" time)
1517 (const :tag "Force recording a note with the DONE state" note)))
1520 (defgroup org-priorities nil
1521 "Priorities in Org-mode."
1522 :tag "Org Priorities"
1523 :group 'org-todo)
1525 (defcustom org-highest-priority ?A
1526 "The highest priority of TODO items. A character like ?A, ?B etc.
1527 Must have a smaller ASCII number than `org-lowest-priority'."
1528 :group 'org-priorities
1529 :type 'character)
1531 (defcustom org-lowest-priority ?C
1532 "The lowest priority of TODO items. A character like ?A, ?B etc.
1533 Must have a larger ASCII number than `org-highest-priority'."
1534 :group 'org-priorities
1535 :type 'character)
1537 (defcustom org-default-priority ?B
1538 "The default priority of TODO items.
1539 This is the priority an item get if no explicit priority is given."
1540 :group 'org-priorities
1541 :type 'character)
1543 (defcustom org-priority-start-cycle-with-default t
1544 "Non-nil means, start with default priority when starting to cycle.
1545 When this is nil, the first step in the cycle will be (depending on the
1546 command used) one higher or lower that the default priority."
1547 :group 'org-priorities
1548 :type 'boolean)
1550 (defgroup org-time nil
1551 "Options concerning time stamps and deadlines in Org-mode."
1552 :tag "Org Time"
1553 :group 'org)
1555 (defcustom org-insert-labeled-timestamps-at-point nil
1556 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1557 When nil, these labeled time stamps are forces into the second line of an
1558 entry, just after the headline. When scheduling from the global TODO list,
1559 the time stamp will always be forced into the second line."
1560 :group 'org-time
1561 :type 'boolean)
1563 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1564 "Formats for `format-time-string' which are used for time stamps.
1565 It is not recommended to change this constant.")
1567 (defcustom org-time-stamp-rounding-minutes '(0 5)
1568 "Number of minutes to round time stamps to.
1569 These are two values, the first applies when first creating a time stamp.
1570 The second applies when changing it with the commands `S-up' and `S-down'.
1571 When changing the time stamp, this means that it will change in steps
1572 of N minutes, as given by the second value.
1574 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1575 numbers should be factors of 60, so for example 5, 10, 15.
1577 When this is larger than 1, you can still force an exact time-stamp by using
1578 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1579 and by using a prefix arg to `S-up/down' to specify the exact number
1580 of minutes to shift."
1581 :group 'org-time
1582 :get '(lambda (var) ; Make sure all entries have 5 elements
1583 (if (integerp (default-value var))
1584 (list (default-value var) 5)
1585 (default-value var)))
1586 :type '(list
1587 (integer :tag "when inserting times")
1588 (integer :tag "when modifying times")))
1590 ;; Normalize old customizations of this variable.
1591 (when (integerp org-time-stamp-rounding-minutes)
1592 (setq org-time-stamp-rounding-minutes
1593 (list org-time-stamp-rounding-minutes
1594 org-time-stamp-rounding-minutes)))
1596 (defcustom org-display-custom-times nil
1597 "Non-nil means, overlay custom formats over all time stamps.
1598 The formats are defined through the variable `org-time-stamp-custom-formats'.
1599 To turn this on on a per-file basis, insert anywhere in the file:
1600 #+STARTUP: customtime"
1601 :group 'org-time
1602 :set 'set-default
1603 :type 'sexp)
1604 (make-variable-buffer-local 'org-display-custom-times)
1606 (defcustom org-time-stamp-custom-formats
1607 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1608 "Custom formats for time stamps. See `format-time-string' for the syntax.
1609 These are overlayed over the default ISO format if the variable
1610 `org-display-custom-times' is set. Time like %H:%M should be at the
1611 end of the second format."
1612 :group 'org-time
1613 :type 'sexp)
1615 (defun org-time-stamp-format (&optional long inactive)
1616 "Get the right format for a time string."
1617 (let ((f (if long (cdr org-time-stamp-formats)
1618 (car org-time-stamp-formats))))
1619 (if inactive
1620 (concat "[" (substring f 1 -1) "]")
1621 f)))
1623 (defcustom org-time-clocksum-format "%d:%02d"
1624 "The format string used when creating CLOCKSUM lines, or when
1625 org-mode generates a time duration."
1626 :group 'org-time
1627 :type 'string)
1629 (defcustom org-deadline-warning-days 14
1630 "No. of days before expiration during which a deadline becomes active.
1631 This variable governs the display in sparse trees and in the agenda.
1632 When 0 or negative, it means use this number (the absolute value of it)
1633 even if a deadline has a different individual lead time specified."
1634 :group 'org-time
1635 :group 'org-agenda-daily/weekly
1636 :type 'number)
1638 (defcustom org-read-date-prefer-future t
1639 "Non-nil means, assume future for incomplete date input from user.
1640 This affects the following situations:
1641 1. The user gives a day, but no month.
1642 For example, if today is the 15th, and you enter \"3\", Org-mode will
1643 read this as the third of *next* month. However, if you enter \"17\",
1644 it will be considered as *this* month.
1645 2. The user gives a month but not a year.
1646 For example, if it is april and you enter \"feb 2\", this will be read
1647 as feb 2, *next* year. \"May 5\", however, will be this year.
1649 Currently this does not work for ISO week specifications.
1651 When this option is nil, the current month and year will always be used
1652 as defaults."
1653 :group 'org-time
1654 :type 'boolean)
1656 (defcustom org-read-date-display-live t
1657 "Non-nil means, display current interpretation of date prompt live.
1658 This display will be in an overlay, in the minibuffer."
1659 :group 'org-time
1660 :type 'boolean)
1662 (defcustom org-read-date-popup-calendar t
1663 "Non-nil means, pop up a calendar when prompting for a date.
1664 In the calendar, the date can be selected with mouse-1. However, the
1665 minibuffer will also be active, and you can simply enter the date as well.
1666 When nil, only the minibuffer will be available."
1667 :group 'org-time
1668 :type 'boolean)
1669 (if (fboundp 'defvaralias)
1670 (defvaralias 'org-popup-calendar-for-date-prompt
1671 'org-read-date-popup-calendar))
1673 (defcustom org-extend-today-until 0
1674 "The hour when your day really ends. Must be an integer.
1675 This has influence for the following applications:
1676 - When switching the agenda to \"today\". It it is still earlier than
1677 the time given here, the day recognized as TODAY is actually yesterday.
1678 - When a date is read from the user and it is still before the time given
1679 here, the current date and time will be assumed to be yesterday, 23:59.
1680 Also, timestamps inserted in remember templates follow this rule.
1682 IMPORTANT: This is a feature whose implementation is and likely will
1683 remain incomplete. Really, it is only here because past midnight seems to
1684 ne the favorite working time of John Wiegley :-)"
1685 :group 'org-time
1686 :type 'number)
1688 (defcustom org-edit-timestamp-down-means-later nil
1689 "Non-nil means, S-down will increase the time in a time stamp.
1690 When nil, S-up will increase."
1691 :group 'org-time
1692 :type 'boolean)
1694 (defcustom org-calendar-follow-timestamp-change t
1695 "Non-nil means, make the calendar window follow timestamp changes.
1696 When a timestamp is modified and the calendar window is visible, it will be
1697 moved to the new date."
1698 :group 'org-time
1699 :type 'boolean)
1701 (defgroup org-tags nil
1702 "Options concerning tags in Org-mode."
1703 :tag "Org Tags"
1704 :group 'org)
1706 (defcustom org-tag-alist nil
1707 "List of tags allowed in Org-mode files.
1708 When this list is nil, Org-mode will base TAG input on what is already in the
1709 buffer.
1710 The value of this variable is an alist, the car of each entry must be a
1711 keyword as a string, the cdr may be a character that is used to select
1712 that tag through the fast-tag-selection interface.
1713 See the manual for details."
1714 :group 'org-tags
1715 :type '(repeat
1716 (choice
1717 (cons (string :tag "Tag name")
1718 (character :tag "Access char"))
1719 (const :tag "Start radio group" (:startgroup))
1720 (const :tag "End radio group" (:endgroup)))))
1722 (defvar org-file-tags nil
1723 "List of tags that can be inherited by all entries in the file.
1724 The tags will be inherited if the variable `org-use-tag-inheritance'
1725 says they should be.
1726 This variable is populated from #+TAG lines.")
1728 (defcustom org-use-fast-tag-selection 'auto
1729 "Non-nil means, use fast tag selection scheme.
1730 This is a special interface to select and deselect tags with single keys.
1731 When nil, fast selection is never used.
1732 When the symbol `auto', fast selection is used if and only if selection
1733 characters for tags have been configured, either through the variable
1734 `org-tag-alist' or through a #+TAGS line in the buffer.
1735 When t, fast selection is always used and selection keys are assigned
1736 automatically if necessary."
1737 :group 'org-tags
1738 :type '(choice
1739 (const :tag "Always" t)
1740 (const :tag "Never" nil)
1741 (const :tag "When selection characters are configured" 'auto)))
1743 (defcustom org-fast-tag-selection-single-key nil
1744 "Non-nil means, fast tag selection exits after first change.
1745 When nil, you have to press RET to exit it.
1746 During fast tag selection, you can toggle this flag with `C-c'.
1747 This variable can also have the value `expert'. In this case, the window
1748 displaying the tags menu is not even shown, until you press C-c again."
1749 :group 'org-tags
1750 :type '(choice
1751 (const :tag "No" nil)
1752 (const :tag "Yes" t)
1753 (const :tag "Expert" expert)))
1755 (defvar org-fast-tag-selection-include-todo nil
1756 "Non-nil means, fast tags selection interface will also offer TODO states.
1757 This is an undocumented feature, you should not rely on it.")
1759 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1760 "The column to which tags should be indented in a headline.
1761 If this number is positive, it specifies the column. If it is negative,
1762 it means that the tags should be flushright to that column. For example,
1763 -80 works well for a normal 80 character screen."
1764 :group 'org-tags
1765 :type 'integer)
1767 (defcustom org-auto-align-tags t
1768 "Non-nil means, realign tags after pro/demotion of TODO state change.
1769 These operations change the length of a headline and therefore shift
1770 the tags around. With this options turned on, after each such operation
1771 the tags are again aligned to `org-tags-column'."
1772 :group 'org-tags
1773 :type 'boolean)
1775 (defcustom org-use-tag-inheritance t
1776 "Non-nil means, tags in levels apply also for sublevels.
1777 When nil, only the tags directly given in a specific line apply there.
1778 If this option is t, a match early-on in a tree can lead to a large
1779 number of matches in the subtree. If you only want to see the first
1780 match in a tree during a search, check out the variable
1781 `org-tags-match-list-sublevels'.
1783 This may also be a list of tags that should be inherited, or a regexp that
1784 matches tags that should be inherited."
1785 :group 'org-tags
1786 :type '(choice
1787 (const :tag "Not" nil)
1788 (const :tag "Always" t)
1789 (repeat :tag "Specific tags" (string :tag "Tag"))
1790 (regexp :tag "Tags matched by regexp")))
1792 (defun org-tag-inherit-p (tag)
1793 "Check if TAG is one that should be inherited."
1794 (cond
1795 ((eq org-use-tag-inheritance t) t)
1796 ((not org-use-tag-inheritance) nil)
1797 ((stringp org-use-tag-inheritance)
1798 (string-match org-use-tag-inheritance tag))
1799 ((listp org-use-tag-inheritance)
1800 (member tag org-use-tag-inheritance))
1801 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1803 (defcustom org-tags-match-list-sublevels t
1804 "Non-nil means list also sublevels of headlines matching tag search.
1805 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1806 the sublevels of a headline matching a tag search often also match
1807 the same search. Listing all of them can create very long lists.
1808 Setting this variable to nil causes subtrees of a match to be skipped.
1809 This option is off by default, because inheritance in on. If you turn
1810 inheritance off, you very likely want to turn this option on.
1812 As a special case, if the tag search is restricted to TODO items, the
1813 value of this variable is ignored and sublevels are always checked, to
1814 make sure all corresponding TODO items find their way into the list."
1815 :group 'org-tags
1816 :type 'boolean)
1818 (defvar org-tags-history nil
1819 "History of minibuffer reads for tags.")
1820 (defvar org-last-tags-completion-table nil
1821 "The last used completion table for tags.")
1822 (defvar org-after-tags-change-hook nil
1823 "Hook that is run after the tags in a line have changed.")
1825 (defgroup org-properties nil
1826 "Options concerning properties in Org-mode."
1827 :tag "Org Properties"
1828 :group 'org)
1830 (defcustom org-property-format "%-10s %s"
1831 "How property key/value pairs should be formatted by `indent-line'.
1832 When `indent-line' hits a property definition, it will format the line
1833 according to this format, mainly to make sure that the values are
1834 lined-up with respect to each other."
1835 :group 'org-properties
1836 :type 'string)
1838 (defcustom org-use-property-inheritance nil
1839 "Non-nil means, properties apply also for sublevels.
1841 This setting is chiefly used during property searches. Turning it on can
1842 cause significant overhead when doing a search, which is why it is not
1843 on by default.
1845 When nil, only the properties directly given in the current entry count.
1846 When t, every property is inherited. The value may also be a list of
1847 properties that should have inheritance, or a regular expression matching
1848 properties that should be inherited.
1850 However, note that some special properties use inheritance under special
1851 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1852 and the properties ending in \"_ALL\" when they are used as descriptor
1853 for valid values of a property.
1855 Note for programmers:
1856 When querying an entry with `org-entry-get', you can control if inheritance
1857 should be used. By default, `org-entry-get' looks only at the local
1858 properties. You can request inheritance by setting the inherit argument
1859 to t (to force inheritance) or to `selective' (to respect the setting
1860 in this variable)."
1861 :group 'org-properties
1862 :type '(choice
1863 (const :tag "Not" nil)
1864 (const :tag "Always" t)
1865 (repeat :tag "Specific properties" (string :tag "Property"))
1866 (regexp :tag "Properties matched by regexp")))
1868 (defun org-property-inherit-p (property)
1869 "Check if PROPERTY is one that should be inherited."
1870 (cond
1871 ((eq org-use-property-inheritance t) t)
1872 ((not org-use-property-inheritance) nil)
1873 ((stringp org-use-property-inheritance)
1874 (string-match org-use-property-inheritance property))
1875 ((listp org-use-property-inheritance)
1876 (member property org-use-property-inheritance))
1877 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1879 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1880 "The default column format, if no other format has been defined.
1881 This variable can be set on the per-file basis by inserting a line
1883 #+COLUMNS: %25ITEM ....."
1884 :group 'org-properties
1885 :type 'string)
1887 (defcustom org-columns-ellipses ".."
1888 "The ellipses to be used when a field in column view is truncated.
1889 When this is the empty string, as many characters as possible are shown,
1890 but then there will be no visual indication that the field has been truncated.
1891 When this is a string of length N, the last N characters of a truncated
1892 field are replaced by this string. If the column is narrower than the
1893 ellipses string, only part of the ellipses string will be shown."
1894 :group 'org-properties
1895 :type 'string)
1897 (defcustom org-columns-modify-value-for-display-function nil
1898 "Function that modifies values for display in column view.
1899 For example, it can be used to cut out a certain part from a time stamp.
1900 The function must take 2 argments:
1902 column-title The tite of the column (*not* the property name)
1903 value The value that should be modified.
1905 The function should return the value that should be displayed,
1906 or nil if the normal value should be used."
1907 :group 'org-properties
1908 :type 'function)
1910 (defcustom org-effort-property "Effort"
1911 "The property that is being used to keep track of effort estimates.
1912 Effort estimates given in this property need to have the format H:MM."
1913 :group 'org-properties
1914 :group 'org-progress
1915 :type '(string :tag "Property"))
1917 (defconst org-global-properties-fixed
1918 '(("VISIBILITY_ALL" . "folded children content all"))
1919 "List of property/value pairs that can be inherited by any entry.
1920 These are fixed values, for the preset properties.")
1923 (defcustom org-global-properties nil
1924 "List of property/value pairs that can be inherited by any entry.
1925 You can set buffer-local values for this by adding lines like
1927 #+PROPERTY: NAME VALUE"
1928 :group 'org-properties
1929 :type '(repeat
1930 (cons (string :tag "Property")
1931 (string :tag "Value"))))
1933 (defvar org-file-properties nil
1934 "List of property/value pairs that can be inherited by any entry.
1935 Valid for the current buffer.
1936 This variable is populated from #+PROPERTY lines.")
1937 (make-variable-buffer-local 'org-file-properties)
1939 (defgroup org-agenda nil
1940 "Options concerning agenda views in Org-mode."
1941 :tag "Org Agenda"
1942 :group 'org)
1944 (defvar org-category nil
1945 "Variable used by org files to set a category for agenda display.
1946 Such files should use a file variable to set it, for example
1948 # -*- mode: org; org-category: \"ELisp\"
1950 or contain a special line
1952 #+CATEGORY: ELisp
1954 If the file does not specify a category, then file's base name
1955 is used instead.")
1956 (make-variable-buffer-local 'org-category)
1957 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
1959 (defcustom org-agenda-files nil
1960 "The files to be used for agenda display.
1961 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1962 \\[org-remove-file]. You can also use customize to edit the list.
1964 If an entry is a directory, all files in that directory that are matched by
1965 `org-agenda-file-regexp' will be part of the file list.
1967 If the value of the variable is not a list but a single file name, then
1968 the list of agenda files is actually stored and maintained in that file, one
1969 agenda file per line."
1970 :group 'org-agenda
1971 :type '(choice
1972 (repeat :tag "List of files and directories" file)
1973 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1975 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1976 "Regular expression to match files for `org-agenda-files'.
1977 If any element in the list in that variable contains a directory instead
1978 of a normal file, all files in that directory that are matched by this
1979 regular expression will be included."
1980 :group 'org-agenda
1981 :type 'regexp)
1983 (defcustom org-agenda-text-search-extra-files nil
1984 "List of extra files to be searched by text search commands.
1985 These files will be search in addition to the agenda files by the
1986 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1987 Note that these files will only be searched for text search commands,
1988 not for the other agenda views like todo lists, tag searches or the weekly
1989 agenda. This variable is intended to list notes and possibly archive files
1990 that should also be searched by these two commands.
1991 In fact, if the first element in the list is the symbol `agenda-archives',
1992 than all archive files of all agenda files will be added to the search
1993 scope."
1994 :group 'org-agenda
1995 :type '(set :greedy t
1996 (const :tag "Agenda Archives" agenda-archives)
1997 (repeat :inline t (file))))
1999 (if (fboundp 'defvaralias)
2000 (defvaralias 'org-agenda-multi-occur-extra-files
2001 'org-agenda-text-search-extra-files))
2003 (defcustom org-agenda-skip-unavailable-files nil
2004 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2005 A nil value means to remove them, after a query, from the list."
2006 :group 'org-agenda
2007 :type 'boolean)
2009 (defcustom org-calendar-to-agenda-key [?c]
2010 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2011 The command `org-calendar-goto-agenda' will be bound to this key. The
2012 default is the character `c' because then `c' can be used to switch back and
2013 forth between agenda and calendar."
2014 :group 'org-agenda
2015 :type 'sexp)
2017 (defcustom org-calendar-agenda-action-key [?k]
2018 "The key to be installed in `calendar-mode-map' for agenda-action.
2019 The command `org-agenda-action' will be bound to this key. The
2020 default is the character `k' because we use the same key in the agenda."
2021 :group 'org-agenda
2022 :type 'sexp)
2024 (eval-after-load "calendar"
2025 '(progn
2026 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2027 'org-calendar-goto-agenda)
2028 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2029 'org-agenda-action)))
2031 (defgroup org-latex nil
2032 "Options for embedding LaTeX code into Org-mode."
2033 :tag "Org LaTeX"
2034 :group 'org)
2036 (defcustom org-format-latex-options
2037 '(:foreground default :background default :scale 1.0
2038 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2039 :matchers ("begin" "$" "$$" "\\(" "\\["))
2040 "Options for creating images from LaTeX fragments.
2041 This is a property list with the following properties:
2042 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2043 `default' means use the foreground of the default face.
2044 :background the background color, or \"Transparent\".
2045 `default' means use the background of the default face.
2046 :scale a scaling factor for the size of the images.
2047 :html-foreground, :html-background, :html-scale
2048 the same numbers for HTML export.
2049 :matchers a list indicating which matchers should be used to
2050 find LaTeX fragments. Valid members of this list are:
2051 \"begin\" find environments
2052 \"$\" find math expressions surrounded by $...$
2053 \"$$\" find math expressions surrounded by $$....$$
2054 \"\\(\" find math expressions surrounded by \\(...\\)
2055 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2056 :group 'org-latex
2057 :type 'plist)
2059 (defcustom org-format-latex-header "\\documentclass{article}
2060 \\usepackage{fullpage} % do not remove
2061 \\usepackage{amssymb}
2062 \\usepackage[usenames]{color}
2063 \\usepackage{amsmath}
2064 \\usepackage{latexsym}
2065 \\usepackage[mathscr]{eucal}
2066 \\pagestyle{empty} % do not remove"
2067 "The document header used for processing LaTeX fragments."
2068 :group 'org-latex
2069 :type 'string)
2072 (defgroup org-font-lock nil
2073 "Font-lock settings for highlighting in Org-mode."
2074 :tag "Org Font Lock"
2075 :group 'org)
2077 (defcustom org-level-color-stars-only nil
2078 "Non-nil means fontify only the stars in each headline.
2079 When nil, the entire headline is fontified.
2080 Changing it requires restart of `font-lock-mode' to become effective
2081 also in regions already fontified."
2082 :group 'org-font-lock
2083 :type 'boolean)
2085 (defcustom org-hide-leading-stars nil
2086 "Non-nil means, hide the first N-1 stars in a headline.
2087 This works by using the face `org-hide' for these stars. This
2088 face is white for a light background, and black for a dark
2089 background. You may have to customize the face `org-hide' to
2090 make this work.
2091 Changing it requires restart of `font-lock-mode' to become effective
2092 also in regions already fontified.
2093 You may also set this on a per-file basis by adding one of the following
2094 lines to the buffer:
2096 #+STARTUP: hidestars
2097 #+STARTUP: showstars"
2098 :group 'org-font-lock
2099 :type 'boolean)
2101 (defcustom org-fontify-done-headline nil
2102 "Non-nil means, change the face of a headline if it is marked DONE.
2103 Normally, only the TODO/DONE keyword indicates the state of a headline.
2104 When this is non-nil, the headline after the keyword is set to the
2105 `org-headline-done' as an additional indication."
2106 :group 'org-font-lock
2107 :type 'boolean)
2109 (defcustom org-fontify-emphasized-text t
2110 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2111 Changing this variable requires a restart of Emacs to take effect."
2112 :group 'org-font-lock
2113 :type 'boolean)
2115 (defcustom org-highlight-latex-fragments-and-specials nil
2116 "Non-nil means, fontify what is treated specially by the exporters."
2117 :group 'org-font-lock
2118 :type 'boolean)
2120 (defcustom org-hide-emphasis-markers nil
2121 "Non-nil mean font-lock should hide the emphasis marker characters."
2122 :group 'org-font-lock
2123 :type 'boolean)
2125 (defvar org-emph-re nil
2126 "Regular expression for matching emphasis.")
2127 (defvar org-verbatim-re nil
2128 "Regular expression for matching verbatim text.")
2129 (defvar org-emphasis-regexp-components) ; defined just below
2130 (defvar org-emphasis-alist) ; defined just below
2131 (defun org-set-emph-re (var val)
2132 "Set variable and compute the emphasis regular expression."
2133 (set var val)
2134 (when (and (boundp 'org-emphasis-alist)
2135 (boundp 'org-emphasis-regexp-components)
2136 org-emphasis-alist org-emphasis-regexp-components)
2137 (let* ((e org-emphasis-regexp-components)
2138 (pre (car e))
2139 (post (nth 1 e))
2140 (border (nth 2 e))
2141 (body (nth 3 e))
2142 (nl (nth 4 e))
2143 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2144 (body1 (concat body "*?"))
2145 (markers (mapconcat 'car org-emphasis-alist ""))
2146 (vmarkers (mapconcat
2147 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2148 org-emphasis-alist "")))
2149 ;; make sure special characters appear at the right position in the class
2150 (if (string-match "\\^" markers)
2151 (setq markers (concat (replace-match "" t t markers) "^")))
2152 (if (string-match "-" markers)
2153 (setq markers (concat (replace-match "" t t markers) "-")))
2154 (if (string-match "\\^" vmarkers)
2155 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2156 (if (string-match "-" vmarkers)
2157 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2158 (if (> nl 0)
2159 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2160 (int-to-string nl) "\\}")))
2161 ;; Make the regexp
2162 (setq org-emph-re
2163 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2164 "\\("
2165 "\\([" markers "]\\)"
2166 "\\("
2167 "[^" border "]\\|"
2168 "[^" border (if (and nil stacked) markers) "]"
2169 body1
2170 "[^" border (if (and nil stacked) markers) "]"
2171 "\\)"
2172 "\\3\\)"
2173 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2174 (setq org-verbatim-re
2175 (concat "\\([" pre "]\\|^\\)"
2176 "\\("
2177 "\\([" vmarkers "]\\)"
2178 "\\("
2179 "[^" border "]\\|"
2180 "[^" border "]"
2181 body1
2182 "[^" border "]"
2183 "\\)"
2184 "\\3\\)"
2185 "\\([" post "]\\|$\\)")))))
2187 (defcustom org-emphasis-regexp-components
2188 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2189 "Components used to build the regular expression for emphasis.
2190 This is a list with 6 entries. Terminology: In an emphasis string
2191 like \" *strong word* \", we call the initial space PREMATCH, the final
2192 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2193 and \"trong wor\" is the body. The different components in this variable
2194 specify what is allowed/forbidden in each part:
2196 pre Chars allowed as prematch. Beginning of line will be allowed too.
2197 post Chars allowed as postmatch. End of line will be allowed too.
2198 border The chars *forbidden* as border characters.
2199 body-regexp A regexp like \".\" to match a body character. Don't use
2200 non-shy groups here, and don't allow newline here.
2201 newline The maximum number of newlines allowed in an emphasis exp.
2203 Use customize to modify this, or restart Emacs after changing it."
2204 :group 'org-font-lock
2205 :set 'org-set-emph-re
2206 :type '(list
2207 (sexp :tag "Allowed chars in pre ")
2208 (sexp :tag "Allowed chars in post ")
2209 (sexp :tag "Forbidden chars in border ")
2210 (sexp :tag "Regexp for body ")
2211 (integer :tag "number of newlines allowed")
2212 (option (boolean :tag "Please ignore this button"))))
2214 (defcustom org-emphasis-alist
2215 `(("*" bold "<b>" "</b>")
2216 ("/" italic "<i>" "</i>")
2217 ("_" underline "<u>" "</u>")
2218 ("=" org-code "<code>" "</code>" verbatim)
2219 ("~" org-verbatim "" "" verbatim)
2220 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2221 "<del>" "</del>")
2223 "Special syntax for emphasized text.
2224 Text starting and ending with a special character will be emphasized, for
2225 example *bold*, _underlined_ and /italic/. This variable sets the marker
2226 characters, the face to be used by font-lock for highlighting in Org-mode
2227 Emacs buffers, and the HTML tags to be used for this.
2228 Use customize to modify this, or restart Emacs after changing it."
2229 :group 'org-font-lock
2230 :set 'org-set-emph-re
2231 :type '(repeat
2232 (list
2233 (string :tag "Marker character")
2234 (choice
2235 (face :tag "Font-lock-face")
2236 (plist :tag "Face property list"))
2237 (string :tag "HTML start tag")
2238 (string :tag "HTML end tag")
2239 (option (const verbatim)))))
2241 ;;; Miscellaneous options
2243 (defgroup org-completion nil
2244 "Completion in Org-mode."
2245 :tag "Org Completion"
2246 :group 'org)
2248 (defcustom org-completion-fallback-command 'hippie-expand
2249 "The expansion command called by \\[org-complete] in normal context.
2250 Normal means, no org-mode-specific context."
2251 :group 'org-completion
2252 :type 'function)
2254 ;;; Functions and variables from ther packages
2255 ;; Declared here to avoid compiler warnings
2257 ;; XEmacs only
2258 (defvar outline-mode-menu-heading)
2259 (defvar outline-mode-menu-show)
2260 (defvar outline-mode-menu-hide)
2261 (defvar zmacs-regions) ; XEmacs regions
2263 ;; Emacs only
2264 (defvar mark-active)
2266 ;; Various packages
2267 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2268 (declare-function calendar-forward-day "cal-move" (arg))
2269 (declare-function calendar-goto-date "cal-move" (date))
2270 (declare-function calendar-goto-today "cal-move" ())
2271 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2272 (defvar calc-embedded-close-formula)
2273 (defvar calc-embedded-open-formula)
2274 (declare-function cdlatex-tab "ext:cdlatex" ())
2275 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2276 (defvar font-lock-unfontify-region-function)
2277 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2278 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2279 (defvar iswitchb-temp-buflist)
2280 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2281 (declare-function org-agenda-skip "org-agenda" ())
2282 (declare-function org-format-agenda-item "org-agenda"
2283 (extra txt &optional category tags dotime noprefix remove-re))
2284 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2285 (declare-function org-agenda-change-all-lines "org-agenda"
2286 (newhead hdmarker &optional fixface))
2287 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2288 (declare-function org-agenda-maybe-redo "org-agenda" ())
2289 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2290 (beg end))
2291 (declare-function parse-time-string "parse-time" (string))
2292 (declare-function remember "remember" (&optional initial))
2293 (declare-function remember-buffer-desc "remember" ())
2294 (declare-function remember-finalize "remember" ())
2295 (defvar remember-save-after-remembering)
2296 (defvar remember-data-file)
2297 (defvar remember-register)
2298 (defvar remember-buffer)
2299 (defvar remember-handler-functions)
2300 (defvar remember-annotation-functions)
2301 (defvar texmathp-why)
2302 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2303 (declare-function table--at-cell-p "table" (position &optional object at-column))
2305 (defvar w3m-current-url)
2306 (defvar w3m-current-title)
2308 (defvar org-latex-regexps)
2310 ;;; Autoload and prepare some org modules
2312 ;; Some table stuff that needs to be defined here, because it is used
2313 ;; by the functions setting up org-mode or checking for table context.
2315 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2316 "Detects an org-type or table-type table.")
2317 (defconst org-table-line-regexp "^[ \t]*|"
2318 "Detects an org-type table line.")
2319 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2320 "Detects an org-type table line.")
2321 (defconst org-table-hline-regexp "^[ \t]*|-"
2322 "Detects an org-type table hline.")
2323 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2324 "Detects a table-type table hline.")
2325 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2326 "Searching from within a table (any type) this finds the first line
2327 outside the table.")
2329 ;; Autoload the functions in org-table.el that are needed by functions here.
2331 (eval-and-compile
2332 (org-autoload "org-table"
2333 '(org-table-align org-table-begin org-table-blank-field
2334 org-table-convert org-table-convert-region org-table-copy-down
2335 org-table-copy-region org-table-create
2336 org-table-create-or-convert-from-region
2337 org-table-create-with-table.el org-table-current-dline
2338 org-table-cut-region org-table-delete-column org-table-edit-field
2339 org-table-edit-formulas org-table-end org-table-eval-formula
2340 org-table-export org-table-field-info
2341 org-table-get-stored-formulas org-table-goto-column
2342 org-table-hline-and-move org-table-import org-table-insert-column
2343 org-table-insert-hline org-table-insert-row org-table-iterate
2344 org-table-justify-field-maybe org-table-kill-row
2345 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2346 org-table-move-column org-table-move-column-left
2347 org-table-move-column-right org-table-move-row
2348 org-table-move-row-down org-table-move-row-up
2349 org-table-next-field org-table-next-row org-table-paste-rectangle
2350 org-table-previous-field org-table-recalculate
2351 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2352 org-table-toggle-coordinate-overlays
2353 org-table-toggle-formula-debugger org-table-wrap-region
2354 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2356 (defun org-at-table-p (&optional table-type)
2357 "Return t if the cursor is inside an org-type table.
2358 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2359 (if org-enable-table-editor
2360 (save-excursion
2361 (beginning-of-line 1)
2362 (looking-at (if table-type org-table-any-line-regexp
2363 org-table-line-regexp)))
2364 nil))
2365 (defsubst org-table-p () (org-at-table-p))
2367 (defun org-at-table.el-p ()
2368 "Return t if and only if we are at a table.el table."
2369 (and (org-at-table-p 'any)
2370 (save-excursion
2371 (goto-char (org-table-begin 'any))
2372 (looking-at org-table1-hline-regexp))))
2373 (defun org-table-recognize-table.el ()
2374 "If there is a table.el table nearby, recognize it and move into it."
2375 (if org-table-tab-recognizes-table.el
2376 (if (org-at-table.el-p)
2377 (progn
2378 (beginning-of-line 1)
2379 (if (looking-at org-table-dataline-regexp)
2381 (if (looking-at org-table1-hline-regexp)
2382 (progn
2383 (beginning-of-line 2)
2384 (if (looking-at org-table-any-border-regexp)
2385 (beginning-of-line -1)))))
2386 (if (re-search-forward "|" (org-table-end t) t)
2387 (progn
2388 (require 'table)
2389 (if (table--at-cell-p (point))
2391 (message "recognizing table.el table...")
2392 (table-recognize-table)
2393 (message "recognizing table.el table...done")))
2394 (error "This should not happen..."))
2396 nil)
2397 nil))
2399 (defun org-at-table-hline-p ()
2400 "Return t if the cursor is inside a hline in a table."
2401 (if org-enable-table-editor
2402 (save-excursion
2403 (beginning-of-line 1)
2404 (looking-at org-table-hline-regexp))
2405 nil))
2407 (defvar org-table-clean-did-remove-column nil)
2409 (defun org-table-map-tables (function)
2410 "Apply FUNCTION to the start of all tables in the buffer."
2411 (save-excursion
2412 (save-restriction
2413 (widen)
2414 (goto-char (point-min))
2415 (while (re-search-forward org-table-any-line-regexp nil t)
2416 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2417 (beginning-of-line 1)
2418 (if (looking-at org-table-line-regexp)
2419 (save-excursion (funcall function)))
2420 (re-search-forward org-table-any-border-regexp nil 1))))
2421 (message "Mapping tables: done"))
2423 ;; Declare and autoload functions from org-exp.el
2425 (declare-function org-default-export-plist "org-exp")
2426 (declare-function org-infile-export-plist "org-exp")
2427 (declare-function org-get-current-options "org-exp")
2428 (eval-and-compile
2429 (org-autoload "org-exp"
2430 '(org-export org-export-as-ascii org-export-visible
2431 org-insert-export-options-template org-export-as-html-and-open
2432 org-export-as-html-batch org-export-as-html-to-buffer
2433 org-replace-region-by-html org-export-region-as-html
2434 org-export-as-html org-export-icalendar-this-file
2435 org-export-icalendar-all-agenda-files
2436 org-table-clean-before-export
2437 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2439 ;; Declare and autoload functions from org-agenda.el
2441 (eval-and-compile
2442 (org-autoload "org-agenda"
2443 '(org-agenda org-agenda-list org-search-view
2444 org-todo-list org-tags-view org-agenda-list-stuck-projects
2445 org-diary org-agenda-to-appt)))
2447 ;; Autoload org-remember
2449 (eval-and-compile
2450 (org-autoload "org-remember"
2451 '(org-remember-insinuate org-remember-annotation
2452 org-remember-apply-template org-remember org-remember-handler)))
2454 ;; Autoload org-clock.el
2457 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2458 (beg end))
2459 (declare-function org-update-mode-line "org-clock" ())
2460 (defvar org-clock-start-time)
2461 (defvar org-clock-marker (make-marker)
2462 "Marker recording the last clock-in.")
2464 (eval-and-compile
2465 (org-autoload
2466 "org-clock"
2467 '(org-clock-in org-clock-out org-clock-cancel
2468 org-clock-goto org-clock-sum org-clock-display
2469 org-remove-clock-overlays org-clock-report
2470 org-clocktable-shift org-dblock-write:clocktable
2471 org-get-clocktable)))
2473 (defun org-clock-update-time-maybe ()
2474 "If this is a CLOCK line, update it and return t.
2475 Otherwise, return nil."
2476 (interactive)
2477 (save-excursion
2478 (beginning-of-line 1)
2479 (skip-chars-forward " \t")
2480 (when (looking-at org-clock-string)
2481 (let ((re (concat "[ \t]*" org-clock-string
2482 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2483 "\\([ \t]*=>.*\\)?\\)?"))
2484 ts te h m s)
2485 (cond
2486 ((not (looking-at re))
2487 nil)
2488 ((not (match-end 2))
2489 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2490 (> org-clock-marker (point))
2491 (<= org-clock-marker (point-at-eol)))
2492 ;; The clock is running here
2493 (setq org-clock-start-time
2494 (apply 'encode-time
2495 (org-parse-time-string (match-string 1))))
2496 (org-update-mode-line)))
2498 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2499 (end-of-line 1)
2500 (setq ts (match-string 1)
2501 te (match-string 3))
2502 (setq s (- (time-to-seconds
2503 (apply 'encode-time (org-parse-time-string te)))
2504 (time-to-seconds
2505 (apply 'encode-time (org-parse-time-string ts))))
2506 h (floor (/ s 3600))
2507 s (- s (* 3600 h))
2508 m (floor (/ s 60))
2509 s (- s (* 60 s)))
2510 (insert " => " (format "%2d:%02d" h m))
2511 t))))))
2513 (defun org-check-running-clock ()
2514 "Check if the current buffer contains the running clock.
2515 If yes, offer to stop it and to save the buffer with the changes."
2516 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2517 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2518 (buffer-name))))
2519 (org-clock-out)
2520 (when (y-or-n-p "Save changed buffer?")
2521 (save-buffer))))
2523 (defun org-clocktable-try-shift (dir n)
2524 "Check if this line starts a clock table, if yes, shift the time block."
2525 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2526 (org-clocktable-shift dir n)))
2528 ;; Autoload archiving code
2529 ;; The stuff that is needed for cycling and tags has to be defined here.
2531 (defgroup org-archive nil
2532 "Options concerning archiving in Org-mode."
2533 :tag "Org Archive"
2534 :group 'org-structure)
2536 (defcustom org-archive-location "%s_archive::"
2537 "The location where subtrees should be archived.
2539 Otherwise, the value of this variable is a string, consisting of two
2540 parts, separated by a double-colon.
2542 The first part is a file name - when omitted, archiving happens in the same
2543 file. %s will be replaced by the current file name (without directory part).
2544 Archiving to a different file is useful to keep archived entries from
2545 contributing to the Org-mode Agenda.
2547 The part after the double colon is a headline. The archived entries will be
2548 filed under that headline. When omitted, the subtrees are simply filed away
2549 at the end of the file, as top-level entries.
2551 Here are a few examples:
2552 \"%s_archive::\"
2553 If the current file is Projects.org, archive in file
2554 Projects.org_archive, as top-level trees. This is the default.
2556 \"::* Archived Tasks\"
2557 Archive in the current file, under the top-level headline
2558 \"* Archived Tasks\".
2560 \"~/org/archive.org::\"
2561 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2563 \"basement::** Finished Tasks\"
2564 Archive in file ./basement (relative path), as level 3 trees
2565 below the level 2 heading \"** Finished Tasks\".
2567 You may set this option on a per-file basis by adding to the buffer a
2568 line like
2570 #+ARCHIVE: basement::** Finished Tasks
2572 You may also define it locally for a subtree by setting an ARCHIVE property
2573 in the entry. If such a property is found in an entry, or anywhere up
2574 the hierarchy, it will be used."
2575 :group 'org-archive
2576 :type 'string)
2578 (defcustom org-archive-tag "ARCHIVE"
2579 "The tag that marks a subtree as archived.
2580 An archived subtree does not open during visibility cycling, and does
2581 not contribute to the agenda listings.
2582 After changing this, font-lock must be restarted in the relevant buffers to
2583 get the proper fontification."
2584 :group 'org-archive
2585 :group 'org-keywords
2586 :type 'string)
2588 (defcustom org-agenda-skip-archived-trees t
2589 "Non-nil means, the agenda will skip any items located in archived trees.
2590 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2591 variable is no longer recommended, you should leave it at the value t.
2592 Instead, use the key `v' to cycle the archives-mode in the agenda."
2593 :group 'org-archive
2594 :group 'org-agenda-skip
2595 :type 'boolean)
2597 (defcustom org-cycle-open-archived-trees nil
2598 "Non-nil means, `org-cycle' will open archived trees.
2599 An archived tree is a tree marked with the tag ARCHIVE.
2600 When nil, archived trees will stay folded. You can still open them with
2601 normal outline commands like `show-all', but not with the cycling commands."
2602 :group 'org-archive
2603 :group 'org-cycle
2604 :type 'boolean)
2606 (defcustom org-sparse-tree-open-archived-trees nil
2607 "Non-nil means sparse tree construction shows matches in archived trees.
2608 When nil, matches in these trees are highlighted, but the trees are kept in
2609 collapsed state."
2610 :group 'org-archive
2611 :group 'org-sparse-trees
2612 :type 'boolean)
2614 (defun org-cycle-hide-archived-subtrees (state)
2615 "Re-hide all archived subtrees after a visibility state change."
2616 (when (and (not org-cycle-open-archived-trees)
2617 (not (memq state '(overview folded))))
2618 (save-excursion
2619 (let* ((globalp (memq state '(contents all)))
2620 (beg (if globalp (point-min) (point)))
2621 (end (if globalp (point-max) (org-end-of-subtree t))))
2622 (org-hide-archived-subtrees beg end)
2623 (goto-char beg)
2624 (if (looking-at (concat ".*:" org-archive-tag ":"))
2625 (message "%s" (substitute-command-keys
2626 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2628 (defun org-force-cycle-archived ()
2629 "Cycle subtree even if it is archived."
2630 (interactive)
2631 (setq this-command 'org-cycle)
2632 (let ((org-cycle-open-archived-trees t))
2633 (call-interactively 'org-cycle)))
2635 (defun org-hide-archived-subtrees (beg end)
2636 "Re-hide all archived subtrees after a visibility state change."
2637 (save-excursion
2638 (let* ((re (concat ":" org-archive-tag ":")))
2639 (goto-char beg)
2640 (while (re-search-forward re end t)
2641 (and (org-on-heading-p) (hide-subtree))
2642 (org-end-of-subtree t)))))
2644 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2646 (eval-and-compile
2647 (org-autoload "org-archive"
2648 '(org-add-archive-files org-archive-subtree
2649 org-archive-to-archive-sibling org-toggle-archive-tag)))
2651 ;; Autoload Column View Code
2653 (declare-function org-columns-number-to-string "org-colview")
2654 (declare-function org-columns-get-format-and-top-level "org-colview")
2655 (declare-function org-columns-compute "org-colview")
2657 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2658 '(org-columns-number-to-string org-columns-get-format-and-top-level
2659 org-columns-compute org-agenda-columns org-columns-remove-overlays
2660 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2662 ;; Autoload ID code
2664 (org-autoload "org-id"
2665 '(org-id-get-create org-id-new org-id-copy org-id-get
2666 org-id-get-with-outline-path-completion
2667 org-id-get-with-outline-drilling
2668 org-id-goto org-id-find))
2670 ;;; Variables for pre-computed regular expressions, all buffer local
2672 (defvar org-drawer-regexp nil
2673 "Matches first line of a hidden block.")
2674 (make-variable-buffer-local 'org-drawer-regexp)
2675 (defvar org-todo-regexp nil
2676 "Matches any of the TODO state keywords.")
2677 (make-variable-buffer-local 'org-todo-regexp)
2678 (defvar org-not-done-regexp nil
2679 "Matches any of the TODO state keywords except the last one.")
2680 (make-variable-buffer-local 'org-not-done-regexp)
2681 (defvar org-todo-line-regexp nil
2682 "Matches a headline and puts TODO state into group 2 if present.")
2683 (make-variable-buffer-local 'org-todo-line-regexp)
2684 (defvar org-complex-heading-regexp nil
2685 "Matches a headline and puts everything into groups:
2686 group 1: the stars
2687 group 2: The todo keyword, maybe
2688 group 3: Priority cookie
2689 group 4: True headline
2690 group 5: Tags")
2691 (make-variable-buffer-local 'org-complex-heading-regexp)
2692 (defvar org-todo-line-tags-regexp nil
2693 "Matches a headline and puts TODO state into group 2 if present.
2694 Also put tags into group 4 if tags are present.")
2695 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2696 (defvar org-nl-done-regexp nil
2697 "Matches newline followed by a headline with the DONE keyword.")
2698 (make-variable-buffer-local 'org-nl-done-regexp)
2699 (defvar org-looking-at-done-regexp nil
2700 "Matches the DONE keyword a point.")
2701 (make-variable-buffer-local 'org-looking-at-done-regexp)
2702 (defvar org-ds-keyword-length 12
2703 "Maximum length of the Deadline and SCHEDULED keywords.")
2704 (make-variable-buffer-local 'org-ds-keyword-length)
2705 (defvar org-deadline-regexp nil
2706 "Matches the DEADLINE keyword.")
2707 (make-variable-buffer-local 'org-deadline-regexp)
2708 (defvar org-deadline-time-regexp nil
2709 "Matches the DEADLINE keyword together with a time stamp.")
2710 (make-variable-buffer-local 'org-deadline-time-regexp)
2711 (defvar org-deadline-line-regexp nil
2712 "Matches the DEADLINE keyword and the rest of the line.")
2713 (make-variable-buffer-local 'org-deadline-line-regexp)
2714 (defvar org-scheduled-regexp nil
2715 "Matches the SCHEDULED keyword.")
2716 (make-variable-buffer-local 'org-scheduled-regexp)
2717 (defvar org-scheduled-time-regexp nil
2718 "Matches the SCHEDULED keyword together with a time stamp.")
2719 (make-variable-buffer-local 'org-scheduled-time-regexp)
2720 (defvar org-closed-time-regexp nil
2721 "Matches the CLOSED keyword together with a time stamp.")
2722 (make-variable-buffer-local 'org-closed-time-regexp)
2724 (defvar org-keyword-time-regexp nil
2725 "Matches any of the 4 keywords, together with the time stamp.")
2726 (make-variable-buffer-local 'org-keyword-time-regexp)
2727 (defvar org-keyword-time-not-clock-regexp nil
2728 "Matches any of the 3 keywords, together with the time stamp.")
2729 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2730 (defvar org-maybe-keyword-time-regexp nil
2731 "Matches a timestamp, possibly preceeded by a keyword.")
2732 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2733 (defvar org-planning-or-clock-line-re nil
2734 "Matches a line with planning or clock info.")
2735 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2737 (defconst org-plain-time-of-day-regexp
2738 (concat
2739 "\\(\\<[012]?[0-9]"
2740 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2741 "\\(--?"
2742 "\\(\\<[012]?[0-9]"
2743 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2744 "\\)?")
2745 "Regular expression to match a plain time or time range.
2746 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2747 groups carry important information:
2748 0 the full match
2749 1 the first time, range or not
2750 8 the second time, if it is a range.")
2752 (defconst org-plain-time-extension-regexp
2753 (concat
2754 "\\(\\<[012]?[0-9]"
2755 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2756 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2757 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2758 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2759 groups carry important information:
2760 0 the full match
2761 7 hours of duration
2762 9 minutes of duration")
2764 (defconst org-stamp-time-of-day-regexp
2765 (concat
2766 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2767 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2768 "\\(--?"
2769 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2770 "Regular expression to match a timestamp time or time range.
2771 After a match, the following groups carry important information:
2772 0 the full match
2773 1 date plus weekday, for backreferencing to make sure both times on same day
2774 2 the first time, range or not
2775 4 the second time, if it is a range.")
2777 (defconst org-startup-options
2778 '(("fold" org-startup-folded t)
2779 ("overview" org-startup-folded t)
2780 ("nofold" org-startup-folded nil)
2781 ("showall" org-startup-folded nil)
2782 ("content" org-startup-folded content)
2783 ("hidestars" org-hide-leading-stars t)
2784 ("showstars" org-hide-leading-stars nil)
2785 ("odd" org-odd-levels-only t)
2786 ("oddeven" org-odd-levels-only nil)
2787 ("align" org-startup-align-all-tables t)
2788 ("noalign" org-startup-align-all-tables nil)
2789 ("customtime" org-display-custom-times t)
2790 ("logdone" org-log-done time)
2791 ("lognotedone" org-log-done note)
2792 ("nologdone" org-log-done nil)
2793 ("lognoteclock-out" org-log-note-clock-out t)
2794 ("nolognoteclock-out" org-log-note-clock-out nil)
2795 ("logrepeat" org-log-repeat state)
2796 ("lognoterepeat" org-log-repeat note)
2797 ("nologrepeat" org-log-repeat nil)
2798 ("constcgs" constants-unit-system cgs)
2799 ("constSI" constants-unit-system SI))
2800 "Variable associated with STARTUP options for org-mode.
2801 Each element is a list of three items: The startup options as written
2802 in the #+STARTUP line, the corresponding variable, and the value to
2803 set this variable to if the option is found. An optional forth element PUSH
2804 means to push this value onto the list in the variable.")
2806 (defun org-set-regexps-and-options ()
2807 "Precompute regular expressions for current buffer."
2808 (when (org-mode-p)
2809 (org-set-local 'org-todo-kwd-alist nil)
2810 (org-set-local 'org-todo-key-alist nil)
2811 (org-set-local 'org-todo-key-trigger nil)
2812 (org-set-local 'org-todo-keywords-1 nil)
2813 (org-set-local 'org-done-keywords nil)
2814 (org-set-local 'org-todo-heads nil)
2815 (org-set-local 'org-todo-sets nil)
2816 (org-set-local 'org-todo-log-states nil)
2817 (org-set-local 'org-file-properties nil)
2818 (org-set-local 'org-file-tags nil)
2819 (let ((re (org-make-options-regexp
2820 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2821 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2822 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2823 (splitre "[ \t]+")
2824 kwds kws0 kwsa key log value cat arch tags const links hw dws
2825 tail sep kws1 prio props ftags drawers
2826 ext-setup-or-nil setup-contents (start 0))
2827 (save-excursion
2828 (save-restriction
2829 (widen)
2830 (goto-char (point-min))
2831 (while (or (and ext-setup-or-nil
2832 (string-match re ext-setup-or-nil start)
2833 (setq start (match-end 0)))
2834 (and (setq ext-setup-or-nil nil start 0)
2835 (re-search-forward re nil t)))
2836 (setq key (upcase (match-string 1 ext-setup-or-nil))
2837 value (org-match-string-no-properties 2 ext-setup-or-nil))
2838 (cond
2839 ((equal key "CATEGORY")
2840 (if (string-match "[ \t]+$" value)
2841 (setq value (replace-match "" t t value)))
2842 (setq cat value))
2843 ((member key '("SEQ_TODO" "TODO"))
2844 (push (cons 'sequence (org-split-string value splitre)) kwds))
2845 ((equal key "TYP_TODO")
2846 (push (cons 'type (org-split-string value splitre)) kwds))
2847 ((equal key "TAGS")
2848 (setq tags (append tags (org-split-string value splitre))))
2849 ((equal key "COLUMNS")
2850 (org-set-local 'org-columns-default-format value))
2851 ((equal key "LINK")
2852 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2853 (push (cons (match-string 1 value)
2854 (org-trim (match-string 2 value)))
2855 links)))
2856 ((equal key "PRIORITIES")
2857 (setq prio (org-split-string value " +")))
2858 ((equal key "PROPERTY")
2859 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2860 (push (cons (match-string 1 value) (match-string 2 value))
2861 props)))
2862 ((equal key "FILETAGS")
2863 (when (string-match "\\S-" value)
2864 (setq ftags
2865 (append
2866 ftags
2867 (apply 'append
2868 (mapcar (lambda (x) (org-split-string x ":"))
2869 (org-split-string value)))))))
2870 ((equal key "DRAWERS")
2871 (setq drawers (org-split-string value splitre)))
2872 ((equal key "CONSTANTS")
2873 (setq const (append const (org-split-string value splitre))))
2874 ((equal key "STARTUP")
2875 (let ((opts (org-split-string value splitre))
2876 l var val)
2877 (while (setq l (pop opts))
2878 (when (setq l (assoc l org-startup-options))
2879 (setq var (nth 1 l) val (nth 2 l))
2880 (if (not (nth 3 l))
2881 (set (make-local-variable var) val)
2882 (if (not (listp (symbol-value var)))
2883 (set (make-local-variable var) nil))
2884 (set (make-local-variable var) (symbol-value var))
2885 (add-to-list var val))))))
2886 ((equal key "ARCHIVE")
2887 (string-match " *$" value)
2888 (setq arch (replace-match "" t t value))
2889 (remove-text-properties 0 (length arch)
2890 '(face t fontified t) arch))
2891 ((equal key "SETUPFILE")
2892 (setq setup-contents (org-file-contents
2893 (expand-file-name
2894 (org-remove-double-quotes value))
2895 'noerror))
2896 (if (not ext-setup-or-nil)
2897 (setq ext-setup-or-nil setup-contents start 0)
2898 (setq ext-setup-or-nil
2899 (concat (substring ext-setup-or-nil 0 start)
2900 "\n" setup-contents "\n"
2901 (substring ext-setup-or-nil start)))))
2902 ))))
2903 (when cat
2904 (org-set-local 'org-category (intern cat))
2905 (push (cons "CATEGORY" cat) props))
2906 (when prio
2907 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2908 (setq prio (mapcar 'string-to-char prio))
2909 (org-set-local 'org-highest-priority (nth 0 prio))
2910 (org-set-local 'org-lowest-priority (nth 1 prio))
2911 (org-set-local 'org-default-priority (nth 2 prio)))
2912 (and props (org-set-local 'org-file-properties (nreverse props)))
2913 (and ftags (org-set-local 'org-file-tags ftags))
2914 (and drawers (org-set-local 'org-drawers drawers))
2915 (and arch (org-set-local 'org-archive-location arch))
2916 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2917 ;; Process the TODO keywords
2918 (unless kwds
2919 ;; Use the global values as if they had been given locally.
2920 (setq kwds (default-value 'org-todo-keywords))
2921 (if (stringp (car kwds))
2922 (setq kwds (list (cons org-todo-interpretation
2923 (default-value 'org-todo-keywords)))))
2924 (setq kwds (reverse kwds)))
2925 (setq kwds (nreverse kwds))
2926 (let (inter kws kw)
2927 (while (setq kws (pop kwds))
2928 (setq inter (pop kws) sep (member "|" kws)
2929 kws0 (delete "|" (copy-sequence kws))
2930 kwsa nil
2931 kws1 (mapcar
2932 (lambda (x)
2933 ;; 1 2
2934 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2935 (progn
2936 (setq kw (match-string 1 x)
2937 key (and (match-end 2) (match-string 2 x))
2938 log (org-extract-log-state-settings x))
2939 (push (cons kw (and key (string-to-char key))) kwsa)
2940 (and log (push log org-todo-log-states))
2942 (error "Invalid TODO keyword %s" x)))
2943 kws0)
2944 kwsa (if kwsa (append '((:startgroup))
2945 (nreverse kwsa)
2946 '((:endgroup))))
2947 hw (car kws1)
2948 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2949 tail (list inter hw (car dws) (org-last dws)))
2950 (add-to-list 'org-todo-heads hw 'append)
2951 (push kws1 org-todo-sets)
2952 (setq org-done-keywords (append org-done-keywords dws nil))
2953 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2954 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2955 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2956 (setq org-todo-sets (nreverse org-todo-sets)
2957 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2958 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2959 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2960 ;; Process the constants
2961 (when const
2962 (let (e cst)
2963 (while (setq e (pop const))
2964 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2965 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2966 (setq org-table-formula-constants-local cst)))
2968 ;; Process the tags.
2969 (when tags
2970 (let (e tgs)
2971 (while (setq e (pop tags))
2972 (cond
2973 ((equal e "{") (push '(:startgroup) tgs))
2974 ((equal e "}") (push '(:endgroup) tgs))
2975 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2976 (push (cons (match-string 1 e)
2977 (string-to-char (match-string 2 e)))
2978 tgs))
2979 (t (push (list e) tgs))))
2980 (org-set-local 'org-tag-alist nil)
2981 (while (setq e (pop tgs))
2982 (or (and (stringp (car e))
2983 (assoc (car e) org-tag-alist))
2984 (push e org-tag-alist)))))
2986 ;; Compute the regular expressions and other local variables
2987 (if (not org-done-keywords)
2988 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2989 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2990 (length org-scheduled-string)
2991 (length org-clock-string)
2992 (length org-closed-string)))
2993 org-drawer-regexp
2994 (concat "^[ \t]*:\\("
2995 (mapconcat 'regexp-quote org-drawers "\\|")
2996 "\\):[ \t]*$")
2997 org-not-done-keywords
2998 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2999 org-todo-regexp
3000 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3001 "\\|") "\\)\\>")
3002 org-not-done-regexp
3003 (concat "\\<\\("
3004 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3005 "\\)\\>")
3006 org-todo-line-regexp
3007 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3008 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3009 "\\)\\>\\)?[ \t]*\\(.*\\)")
3010 org-complex-heading-regexp
3011 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3012 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3013 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3014 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3015 org-nl-done-regexp
3016 (concat "\n\\*+[ \t]+"
3017 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3018 "\\)" "\\>")
3019 org-todo-line-tags-regexp
3020 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3021 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3022 (org-re
3023 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3024 org-looking-at-done-regexp
3025 (concat "^" "\\(?:"
3026 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3027 "\\>")
3028 org-deadline-regexp (concat "\\<" org-deadline-string)
3029 org-deadline-time-regexp
3030 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3031 org-deadline-line-regexp
3032 (concat "\\<\\(" org-deadline-string "\\).*")
3033 org-scheduled-regexp
3034 (concat "\\<" org-scheduled-string)
3035 org-scheduled-time-regexp
3036 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3037 org-closed-time-regexp
3038 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3039 org-keyword-time-regexp
3040 (concat "\\<\\(" org-scheduled-string
3041 "\\|" org-deadline-string
3042 "\\|" org-closed-string
3043 "\\|" org-clock-string "\\)"
3044 " *[[<]\\([^]>]+\\)[]>]")
3045 org-keyword-time-not-clock-regexp
3046 (concat "\\<\\(" org-scheduled-string
3047 "\\|" org-deadline-string
3048 "\\|" org-closed-string
3049 "\\)"
3050 " *[[<]\\([^]>]+\\)[]>]")
3051 org-maybe-keyword-time-regexp
3052 (concat "\\(\\<\\(" org-scheduled-string
3053 "\\|" org-deadline-string
3054 "\\|" org-closed-string
3055 "\\|" org-clock-string "\\)\\)?"
3056 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3057 org-planning-or-clock-line-re
3058 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3059 "\\|" org-deadline-string
3060 "\\|" org-closed-string "\\|" org-clock-string
3061 "\\)\\>\\)")
3063 (org-compute-latex-and-specials-regexp)
3064 (org-set-font-lock-defaults))))
3066 (defun org-file-contents (file &optional noerror)
3067 "Return the contents of FILE, as a string."
3068 (if (or (not file)
3069 (not (file-readable-p file)))
3070 (if noerror
3071 (progn
3072 (message "Cannot read file %s" file)
3073 (ding) (sit-for 2)
3075 (error "Cannot read file %s" file))
3076 (with-temp-buffer
3077 (insert-file-contents file)
3078 (buffer-string))))
3080 (defun org-extract-log-state-settings (x)
3081 "Extract the log state setting from a TODO keyword string.
3082 This will extract info from a string like \"WAIT(w@/!)\"."
3083 (let (kw key log1 log2)
3084 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3085 (setq kw (match-string 1 x)
3086 key (and (match-end 2) (match-string 2 x))
3087 log1 (and (match-end 3) (match-string 3 x))
3088 log2 (and (match-end 4) (match-string 4 x)))
3089 (and (or log1 log2)
3090 (list kw
3091 (and log1 (if (equal log1 "!") 'time 'note))
3092 (and log2 (if (equal log2 "!") 'time 'note)))))))
3094 (defun org-remove-keyword-keys (list)
3095 "Remove a pair of parenthesis at the end of each string in LIST."
3096 (mapcar (lambda (x)
3097 (if (string-match "(.*)$" x)
3098 (substring x 0 (match-beginning 0))
3100 list))
3102 ;; FIXME: this could be done much better, using second characters etc.
3103 (defun org-assign-fast-keys (alist)
3104 "Assign fast keys to a keyword-key alist.
3105 Respect keys that are already there."
3106 (let (new e k c c1 c2 (char ?a))
3107 (while (setq e (pop alist))
3108 (cond
3109 ((equal e '(:startgroup)) (push e new))
3110 ((equal e '(:endgroup)) (push e new))
3112 (setq k (car e) c2 nil)
3113 (if (cdr e)
3114 (setq c (cdr e))
3115 ;; automatically assign a character.
3116 (setq c1 (string-to-char
3117 (downcase (substring
3118 k (if (= (string-to-char k) ?@) 1 0)))))
3119 (if (or (rassoc c1 new) (rassoc c1 alist))
3120 (while (or (rassoc char new) (rassoc char alist))
3121 (setq char (1+ char)))
3122 (setq c2 c1))
3123 (setq c (or c2 char)))
3124 (push (cons k c) new))))
3125 (nreverse new)))
3127 ;;; Some variables used in various places
3129 (defvar org-window-configuration nil
3130 "Used in various places to store a window configuration.")
3131 (defvar org-finish-function nil
3132 "Function to be called when `C-c C-c' is used.
3133 This is for getting out of special buffers like remember.")
3136 ;; FIXME: Occasionally check by commenting these, to make sure
3137 ;; no other functions uses these, forgetting to let-bind them.
3138 (defvar entry)
3139 (defvar state)
3140 (defvar last-state)
3141 (defvar date)
3142 (defvar description)
3144 ;; Defined somewhere in this file, but used before definition.
3145 (defvar org-html-entities)
3146 (defvar org-struct-menu)
3147 (defvar org-org-menu)
3148 (defvar org-tbl-menu)
3149 (defvar org-agenda-keymap)
3151 ;;;; Define the Org-mode
3153 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3154 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
3157 ;; We use a before-change function to check if a table might need
3158 ;; an update.
3159 (defvar org-table-may-need-update t
3160 "Indicates that a table might need an update.
3161 This variable is set by `org-before-change-function'.
3162 `org-table-align' sets it back to nil.")
3163 (defun org-before-change-function (beg end)
3164 "Every change indicates that a table might need an update."
3165 (setq org-table-may-need-update t))
3166 (defvar org-mode-map)
3167 (defvar org-mode-hook nil)
3168 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3169 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3170 (defvar org-table-buffer-is-an nil)
3171 (defconst org-outline-regexp "\\*+ ")
3173 ;;;###autoload
3174 (define-derived-mode org-mode outline-mode "Org"
3175 "Outline-based notes management and organizer, alias
3176 \"Carsten's outline-mode for keeping track of everything.\"
3178 Org-mode develops organizational tasks around a NOTES file which
3179 contains information about projects as plain text. Org-mode is
3180 implemented on top of outline-mode, which is ideal to keep the content
3181 of large files well structured. It supports ToDo items, deadlines and
3182 time stamps, which magically appear in the diary listing of the Emacs
3183 calendar. Tables are easily created with a built-in table editor.
3184 Plain text URL-like links connect to websites, emails (VM), Usenet
3185 messages (Gnus), BBDB entries, and any files related to the project.
3186 For printing and sharing of notes, an Org-mode file (or a part of it)
3187 can be exported as a structured ASCII or HTML file.
3189 The following commands are available:
3191 \\{org-mode-map}"
3193 ;; Get rid of Outline menus, they are not needed
3194 ;; Need to do this here because define-derived-mode sets up
3195 ;; the keymap so late. Still, it is a waste to call this each time
3196 ;; we switch another buffer into org-mode.
3197 (if (featurep 'xemacs)
3198 (when (boundp 'outline-mode-menu-heading)
3199 ;; Assume this is Greg's port, it used easymenu
3200 (easy-menu-remove outline-mode-menu-heading)
3201 (easy-menu-remove outline-mode-menu-show)
3202 (easy-menu-remove outline-mode-menu-hide))
3203 (define-key org-mode-map [menu-bar headings] 'undefined)
3204 (define-key org-mode-map [menu-bar hide] 'undefined)
3205 (define-key org-mode-map [menu-bar show] 'undefined))
3207 (org-load-modules-maybe)
3208 (easy-menu-add org-org-menu)
3209 (easy-menu-add org-tbl-menu)
3210 (org-install-agenda-files-menu)
3211 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3212 (org-add-to-invisibility-spec '(org-cwidth))
3213 (when (featurep 'xemacs)
3214 (org-set-local 'line-move-ignore-invisible t))
3215 (org-set-local 'outline-regexp org-outline-regexp)
3216 (org-set-local 'outline-level 'org-outline-level)
3217 (when (and org-ellipsis
3218 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3219 (fboundp 'make-glyph-code))
3220 (unless org-display-table
3221 (setq org-display-table (make-display-table)))
3222 (set-display-table-slot
3223 org-display-table 4
3224 (vconcat (mapcar
3225 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3226 org-ellipsis)))
3227 (if (stringp org-ellipsis) org-ellipsis "..."))))
3228 (setq buffer-display-table org-display-table))
3229 (org-set-regexps-and-options)
3230 ;; Calc embedded
3231 (org-set-local 'calc-embedded-open-mode "# ")
3232 (modify-syntax-entry ?# "<")
3233 (modify-syntax-entry ?@ "w")
3234 (if org-startup-truncated (setq truncate-lines t))
3235 (org-set-local 'font-lock-unfontify-region-function
3236 'org-unfontify-region)
3237 ;; Activate before-change-function
3238 (org-set-local 'org-table-may-need-update t)
3239 (org-add-hook 'before-change-functions 'org-before-change-function nil
3240 'local)
3241 ;; Check for running clock before killing a buffer
3242 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3243 ;; Paragraphs and auto-filling
3244 (org-set-autofill-regexps)
3245 (setq indent-line-function 'org-indent-line-function)
3246 (org-update-radio-target-regexp)
3248 ;; Comment characters
3249 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3250 (org-set-local 'comment-padding " ")
3252 ;; Align options lines
3253 (org-set-local
3254 'align-mode-rules-list
3255 '((org-in-buffer-settings
3256 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3257 (modes . '(org-mode)))))
3259 ;; Imenu
3260 (org-set-local 'imenu-create-index-function
3261 'org-imenu-get-tree)
3263 ;; Make isearch reveal context
3264 (if (or (featurep 'xemacs)
3265 (not (boundp 'outline-isearch-open-invisible-function)))
3266 ;; Emacs 21 and XEmacs make use of the hook
3267 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3268 ;; Emacs 22 deals with this through a special variable
3269 (org-set-local 'outline-isearch-open-invisible-function
3270 (lambda (&rest ignore) (org-show-context 'isearch))))
3272 ;; If empty file that did not turn on org-mode automatically, make it to.
3273 (if (and org-insert-mode-line-in-empty-file
3274 (interactive-p)
3275 (= (point-min) (point-max)))
3276 (insert "# -*- mode: org -*-\n\n"))
3278 (unless org-inhibit-startup
3279 (when org-startup-align-all-tables
3280 (let ((bmp (buffer-modified-p)))
3281 (org-table-map-tables 'org-table-align)
3282 (set-buffer-modified-p bmp)))
3283 (org-set-startup-visibility)))
3285 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3287 (defun org-current-time ()
3288 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3289 (if (> (car org-time-stamp-rounding-minutes) 1)
3290 (let ((r (car org-time-stamp-rounding-minutes))
3291 (time (decode-time)))
3292 (apply 'encode-time
3293 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3294 (nthcdr 2 time))))
3295 (current-time)))
3297 ;;;; Font-Lock stuff, including the activators
3299 (defvar org-mouse-map (make-sparse-keymap))
3300 (org-defkey org-mouse-map
3301 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3302 (org-defkey org-mouse-map
3303 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3304 (when org-mouse-1-follows-link
3305 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3306 (when org-tab-follows-link
3307 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3308 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3309 (when org-return-follows-link
3310 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3311 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3313 (require 'font-lock)
3315 (defconst org-non-link-chars "]\t\n\r<>")
3316 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3317 "shell" "elisp"))
3318 (defvar org-link-types-re nil
3319 "Matches a link that has a url-like prefix like \"http:\"")
3320 (defvar org-link-re-with-space nil
3321 "Matches a link with spaces, optional angular brackets around it.")
3322 (defvar org-link-re-with-space2 nil
3323 "Matches a link with spaces, optional angular brackets around it.")
3324 (defvar org-angle-link-re nil
3325 "Matches link with angular brackets, spaces are allowed.")
3326 (defvar org-plain-link-re nil
3327 "Matches plain link, without spaces.")
3328 (defvar org-bracket-link-regexp nil
3329 "Matches a link in double brackets.")
3330 (defvar org-bracket-link-analytic-regexp nil
3331 "Regular expression used to analyze links.
3332 Here is what the match groups contain after a match:
3333 1: http:
3334 2: http
3335 3: path
3336 4: [desc]
3337 5: desc")
3338 (defvar org-any-link-re nil
3339 "Regular expression matching any link.")
3341 (defun org-make-link-regexps ()
3342 "Update the link regular expressions.
3343 This should be called after the variable `org-link-types' has changed."
3344 (setq org-link-types-re
3345 (concat
3346 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3347 org-link-re-with-space
3348 (concat
3349 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3350 "\\([^" org-non-link-chars " ]"
3351 "[^" org-non-link-chars "]*"
3352 "[^" org-non-link-chars " ]\\)>?")
3353 org-link-re-with-space2
3354 (concat
3355 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3356 "\\([^" org-non-link-chars " ]"
3357 "[^]\t\n\r]*"
3358 "[^" org-non-link-chars " ]\\)>?")
3359 org-angle-link-re
3360 (concat
3361 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3362 "\\([^" org-non-link-chars " ]"
3363 "[^" org-non-link-chars "]*"
3364 "\\)>")
3365 org-plain-link-re
3366 (concat
3367 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3368 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3369 org-bracket-link-regexp
3370 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3371 org-bracket-link-analytic-regexp
3372 (concat
3373 "\\[\\["
3374 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3375 "\\([^]]+\\)"
3376 "\\]"
3377 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3378 "\\]")
3379 org-any-link-re
3380 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3381 org-angle-link-re "\\)\\|\\("
3382 org-plain-link-re "\\)")))
3384 (org-make-link-regexps)
3386 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3387 "Regular expression for fast time stamp matching.")
3388 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3389 "Regular expression for fast time stamp matching.")
3390 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3391 "Regular expression matching time strings for analysis.
3392 This one does not require the space after the date, so it can be used
3393 on a string that terminates immediately after the date.")
3394 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3395 "Regular expression matching time strings for analysis.")
3396 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3397 "Regular expression matching time stamps, with groups.")
3398 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3399 "Regular expression matching time stamps (also [..]), with groups.")
3400 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3401 "Regular expression matching a time stamp range.")
3402 (defconst org-tr-regexp-both
3403 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3404 "Regular expression matching a time stamp range.")
3405 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3406 org-ts-regexp "\\)?")
3407 "Regular expression matching a time stamp or time stamp range.")
3408 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3409 org-ts-regexp-both "\\)?")
3410 "Regular expression matching a time stamp or time stamp range.
3411 The time stamps may be either active or inactive.")
3413 (defvar org-emph-face nil)
3415 (defun org-do-emphasis-faces (limit)
3416 "Run through the buffer and add overlays to links."
3417 (let (rtn)
3418 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3419 (if (not (= (char-after (match-beginning 3))
3420 (char-after (match-beginning 4))))
3421 (progn
3422 (setq rtn t)
3423 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3424 'face
3425 (nth 1 (assoc (match-string 3)
3426 org-emphasis-alist)))
3427 (add-text-properties (match-beginning 2) (match-end 2)
3428 '(font-lock-multiline t))
3429 (when org-hide-emphasis-markers
3430 (add-text-properties (match-end 4) (match-beginning 5)
3431 '(invisible org-link))
3432 (add-text-properties (match-beginning 3) (match-end 3)
3433 '(invisible org-link)))))
3434 (backward-char 1))
3435 rtn))
3437 (defun org-emphasize (&optional char)
3438 "Insert or change an emphasis, i.e. a font like bold or italic.
3439 If there is an active region, change that region to a new emphasis.
3440 If there is no region, just insert the marker characters and position
3441 the cursor between them.
3442 CHAR should be either the marker character, or the first character of the
3443 HTML tag associated with that emphasis. If CHAR is a space, the means
3444 to remove the emphasis of the selected region.
3445 If char is not given (for example in an interactive call) it
3446 will be prompted for."
3447 (interactive)
3448 (let ((eal org-emphasis-alist) e det
3449 (erc org-emphasis-regexp-components)
3450 (prompt "")
3451 (string "") beg end move tag c s)
3452 (if (org-region-active-p)
3453 (setq beg (region-beginning) end (region-end)
3454 string (buffer-substring beg end))
3455 (setq move t))
3457 (while (setq e (pop eal))
3458 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3459 c (aref tag 0))
3460 (push (cons c (string-to-char (car e))) det)
3461 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3462 (substring tag 1)))))
3463 (unless char
3464 (message "%s" (concat "Emphasis marker or tag:" prompt))
3465 (setq char (read-char-exclusive)))
3466 (setq char (or (cdr (assoc char det)) char))
3467 (if (equal char ?\ )
3468 (setq s "" move nil)
3469 (unless (assoc (char-to-string char) org-emphasis-alist)
3470 (error "No such emphasis marker: \"%c\"" char))
3471 (setq s (char-to-string char)))
3472 (while (and (> (length string) 1)
3473 (equal (substring string 0 1) (substring string -1))
3474 (assoc (substring string 0 1) org-emphasis-alist))
3475 (setq string (substring string 1 -1)))
3476 (setq string (concat s string s))
3477 (if beg (delete-region beg end))
3478 (unless (or (bolp)
3479 (string-match (concat "[" (nth 0 erc) "\n]")
3480 (char-to-string (char-before (point)))))
3481 (insert " "))
3482 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3483 (char-to-string (char-after (point))))
3484 (insert " ") (backward-char 1))
3485 (insert string)
3486 (and move (backward-char 1))))
3488 (defconst org-nonsticky-props
3489 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3492 (defun org-activate-plain-links (limit)
3493 "Run through the buffer and add overlays to links."
3494 (catch 'exit
3495 (let (f)
3496 (while (re-search-forward org-plain-link-re limit t)
3497 (setq f (get-text-property (match-beginning 0) 'face))
3498 (if (or (eq f 'org-tag)
3499 (and (listp f) (memq 'org-tag f)))
3501 (add-text-properties (match-beginning 0) (match-end 0)
3502 (list 'mouse-face 'highlight
3503 'rear-nonsticky org-nonsticky-props
3504 'keymap org-mouse-map
3506 (throw 'exit t))))))
3508 (defun org-activate-code (limit)
3509 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3510 (progn
3511 (remove-text-properties (match-beginning 0) (match-end 0)
3512 '(display t invisible t intangible t))
3513 t)))
3515 (defun org-activate-angle-links (limit)
3516 "Run through the buffer and add overlays to links."
3517 (if (re-search-forward org-angle-link-re limit t)
3518 (progn
3519 (add-text-properties (match-beginning 0) (match-end 0)
3520 (list 'mouse-face 'highlight
3521 'rear-nonsticky org-nonsticky-props
3522 'keymap org-mouse-map
3524 t)))
3526 (defun org-activate-bracket-links (limit)
3527 "Run through the buffer and add overlays to bracketed links."
3528 (if (re-search-forward org-bracket-link-regexp limit t)
3529 (let* ((help (concat "LINK: "
3530 (org-match-string-no-properties 1)))
3531 ;; FIXME: above we should remove the escapes.
3532 ;; but that requires another match, protecting match data,
3533 ;; a lot of overhead for font-lock.
3534 (ip (org-maybe-intangible
3535 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3536 'keymap org-mouse-map 'mouse-face 'highlight
3537 'font-lock-multiline t 'help-echo help)))
3538 (vp (list 'rear-nonsticky org-nonsticky-props
3539 'keymap org-mouse-map 'mouse-face 'highlight
3540 ' font-lock-multiline t 'help-echo help)))
3541 ;; We need to remove the invisible property here. Table narrowing
3542 ;; may have made some of this invisible.
3543 (remove-text-properties (match-beginning 0) (match-end 0)
3544 '(invisible nil))
3545 (if (match-end 3)
3546 (progn
3547 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3548 (add-text-properties (match-beginning 3) (match-end 3) vp)
3549 (add-text-properties (match-end 3) (match-end 0) ip))
3550 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3551 (add-text-properties (match-beginning 1) (match-end 1) vp)
3552 (add-text-properties (match-end 1) (match-end 0) ip))
3553 t)))
3555 (defun org-activate-dates (limit)
3556 "Run through the buffer and add overlays to dates."
3557 (if (re-search-forward org-tsr-regexp-both limit t)
3558 (progn
3559 (add-text-properties (match-beginning 0) (match-end 0)
3560 (list 'mouse-face 'highlight
3561 'rear-nonsticky org-nonsticky-props
3562 'keymap org-mouse-map))
3563 (when org-display-custom-times
3564 (if (match-end 3)
3565 (org-display-custom-time (match-beginning 3) (match-end 3)))
3566 (org-display-custom-time (match-beginning 1) (match-end 1)))
3567 t)))
3569 (defvar org-target-link-regexp nil
3570 "Regular expression matching radio targets in plain text.")
3571 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3572 "Regular expression matching a link target.")
3573 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3574 "Regular expression matching a radio target.")
3575 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3576 "Regular expression matching any target.")
3578 (defun org-activate-target-links (limit)
3579 "Run through the buffer and add overlays to target matches."
3580 (when org-target-link-regexp
3581 (let ((case-fold-search t))
3582 (if (re-search-forward org-target-link-regexp limit t)
3583 (progn
3584 (add-text-properties (match-beginning 0) (match-end 0)
3585 (list 'mouse-face 'highlight
3586 'rear-nonsticky org-nonsticky-props
3587 'keymap org-mouse-map
3588 'help-echo "Radio target link"
3589 'org-linked-text t))
3590 t)))))
3592 (defun org-update-radio-target-regexp ()
3593 "Find all radio targets in this file and update the regular expression."
3594 (interactive)
3595 (when (memq 'radio org-activate-links)
3596 (setq org-target-link-regexp
3597 (org-make-target-link-regexp (org-all-targets 'radio)))
3598 (org-restart-font-lock)))
3600 (defun org-hide-wide-columns (limit)
3601 (let (s e)
3602 (setq s (text-property-any (point) (or limit (point-max))
3603 'org-cwidth t))
3604 (when s
3605 (setq e (next-single-property-change s 'org-cwidth))
3606 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3607 (goto-char e)
3608 t)))
3610 (defvar org-latex-and-specials-regexp nil
3611 "Regular expression for highlighting export special stuff.")
3612 (defvar org-match-substring-regexp)
3613 (defvar org-match-substring-with-braces-regexp)
3614 (defvar org-export-html-special-string-regexps)
3616 (defun org-compute-latex-and-specials-regexp ()
3617 "Compute regular expression for stuff treated specially by exporters."
3618 (if (not org-highlight-latex-fragments-and-specials)
3619 (org-set-local 'org-latex-and-specials-regexp nil)
3620 (require 'org-exp)
3621 (let*
3622 ((matchers (plist-get org-format-latex-options :matchers))
3623 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3624 org-latex-regexps)))
3625 (options (org-combine-plists (org-default-export-plist)
3626 (org-infile-export-plist)))
3627 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3628 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3629 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3630 (org-export-html-expand (plist-get options :expand-quoted-html))
3631 (org-export-with-special-strings (plist-get options :special-strings))
3632 (re-sub
3633 (cond
3634 ((equal org-export-with-sub-superscripts '{})
3635 (list org-match-substring-with-braces-regexp))
3636 (org-export-with-sub-superscripts
3637 (list org-match-substring-regexp))
3638 (t nil)))
3639 (re-latex
3640 (if org-export-with-LaTeX-fragments
3641 (mapcar (lambda (x) (nth 1 x)) latexs)))
3642 (re-macros
3643 (if org-export-with-TeX-macros
3644 (list (concat "\\\\"
3645 (regexp-opt
3646 (append (mapcar 'car org-html-entities)
3647 (if (boundp 'org-latex-entities)
3648 org-latex-entities nil))
3649 'words))) ; FIXME
3651 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3652 (re-special (if org-export-with-special-strings
3653 (mapcar (lambda (x) (car x))
3654 org-export-html-special-string-regexps)))
3655 (re-rest
3656 (delq nil
3657 (list
3658 (if org-export-html-expand "@<[^>\n]+>")
3659 ))))
3660 (org-set-local
3661 'org-latex-and-specials-regexp
3662 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3663 re-rest) "\\|")))))
3665 (defun org-do-latex-and-special-faces (limit)
3666 "Run through the buffer and add overlays to links."
3667 (when org-latex-and-specials-regexp
3668 (let (rtn d)
3669 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3670 limit t))
3671 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3672 'face))
3673 '(org-code org-verbatim underline)))
3674 (progn
3675 (setq rtn t
3676 d (cond ((member (char-after (1+ (match-beginning 0)))
3677 '(?_ ?^)) 1)
3678 (t 0)))
3679 (font-lock-prepend-text-property
3680 (+ d (match-beginning 0)) (match-end 0)
3681 'face 'org-latex-and-export-specials)
3682 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3683 '(font-lock-multiline t)))))
3684 rtn)))
3686 (defun org-restart-font-lock ()
3687 "Restart font-lock-mode, to force refontification."
3688 (when (and (boundp 'font-lock-mode) font-lock-mode)
3689 (font-lock-mode -1)
3690 (font-lock-mode 1)))
3692 (defun org-all-targets (&optional radio)
3693 "Return a list of all targets in this file.
3694 With optional argument RADIO, only find radio targets."
3695 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3696 rtn)
3697 (save-excursion
3698 (goto-char (point-min))
3699 (while (re-search-forward re nil t)
3700 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3701 rtn)))
3703 (defun org-make-target-link-regexp (targets)
3704 "Make regular expression matching all strings in TARGETS.
3705 The regular expression finds the targets also if there is a line break
3706 between words."
3707 (and targets
3708 (concat
3709 "\\<\\("
3710 (mapconcat
3711 (lambda (x)
3712 (while (string-match " +" x)
3713 (setq x (replace-match "\\s-+" t t x)))
3715 targets
3716 "\\|")
3717 "\\)\\>")))
3719 (defun org-activate-tags (limit)
3720 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3721 (progn
3722 (add-text-properties (match-beginning 1) (match-end 1)
3723 (list 'mouse-face 'highlight
3724 'rear-nonsticky org-nonsticky-props
3725 'keymap org-mouse-map))
3726 t)))
3728 (defun org-outline-level ()
3729 (save-excursion
3730 (looking-at outline-regexp)
3731 (if (match-beginning 1)
3732 (+ (org-get-string-indentation (match-string 1)) 1000)
3733 (1- (- (match-end 0) (match-beginning 0))))))
3735 (defvar org-font-lock-keywords nil)
3737 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3738 "Regular expression matching a property line.")
3740 (defvar org-font-lock-hook nil
3741 "Functions to be called for special font lock stuff.")
3743 (defun org-font-lock-hook (limit)
3744 (run-hook-with-args 'org-font-lock-hook limit))
3746 (defun org-set-font-lock-defaults ()
3747 (let* ((em org-fontify-emphasized-text)
3748 (lk org-activate-links)
3749 (org-font-lock-extra-keywords
3750 (list
3751 ;; Call the hook
3752 '(org-font-lock-hook)
3753 ;; Headlines
3754 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3755 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3756 ;; Table lines
3757 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3758 (1 'org-table t))
3759 ;; Table internals
3760 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3761 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3762 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3763 ;; Drawers
3764 (list org-drawer-regexp '(0 'org-special-keyword t))
3765 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3766 ;; Properties
3767 (list org-property-re
3768 '(1 'org-special-keyword t)
3769 '(3 'org-property-value t))
3770 (if org-format-transports-properties-p
3771 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3772 ;; Links
3773 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3774 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3775 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3776 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3777 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3778 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3779 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3780 '(org-hide-wide-columns (0 nil append))
3781 ;; TODO lines
3782 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3783 '(1 (org-get-todo-face 1) t))
3784 ;; DONE
3785 (if org-fontify-done-headline
3786 (list (concat "^[*]+ +\\<\\("
3787 (mapconcat 'regexp-quote org-done-keywords "\\|")
3788 "\\)\\(.*\\)")
3789 '(2 'org-headline-done t))
3790 nil)
3791 ;; Priorities
3792 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3793 ;; Special keywords
3794 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3795 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3796 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3797 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3798 ;; Emphasis
3799 (if em
3800 (if (featurep 'xemacs)
3801 '(org-do-emphasis-faces (0 nil append))
3802 '(org-do-emphasis-faces)))
3803 ;; Checkboxes
3804 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3805 2 'bold prepend)
3806 (if org-provide-checkbox-statistics
3807 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3808 (0 (org-get-checkbox-statistics-face) t)))
3809 ;; Description list items
3810 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3811 2 'bold prepend)
3812 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3813 '(1 'org-archived prepend))
3814 ;; Specials
3815 '(org-do-latex-and-special-faces)
3816 ;; Code
3817 '(org-activate-code (1 'org-code t))
3818 ;; COMMENT
3819 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3820 "\\|" org-quote-string "\\)\\>")
3821 '(1 'org-special-keyword t))
3822 '("^#.*" (0 'font-lock-comment-face t))
3824 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3825 ;; Now set the full font-lock-keywords
3826 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3827 (org-set-local 'font-lock-defaults
3828 '(org-font-lock-keywords t nil nil backward-paragraph))
3829 (kill-local-variable 'font-lock-keywords) nil))
3831 (defvar org-m nil)
3832 (defvar org-l nil)
3833 (defvar org-f nil)
3834 (defun org-get-level-face (n)
3835 "Get the right face for match N in font-lock matching of healdines."
3836 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3837 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3838 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3839 (cond
3840 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3841 ((eq n 2) org-f)
3842 (t (if org-level-color-stars-only nil org-f))))
3844 (defun org-get-todo-face (kwd)
3845 "Get the right face for a TODO keyword KWD.
3846 If KWD is a number, get the corresponding match group."
3847 (if (numberp kwd) (setq kwd (match-string kwd)))
3848 (or (cdr (assoc kwd org-todo-keyword-faces))
3849 (and (member kwd org-done-keywords) 'org-done)
3850 'org-todo))
3852 (defun org-unfontify-region (beg end &optional maybe_loudly)
3853 "Remove fontification and activation overlays from links."
3854 (font-lock-default-unfontify-region beg end)
3855 (let* ((buffer-undo-list t)
3856 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3857 (inhibit-modification-hooks t)
3858 deactivate-mark buffer-file-name buffer-file-truename)
3859 (remove-text-properties beg end
3860 '(mouse-face t keymap t org-linked-text t
3861 invisible t intangible t))))
3863 ;;;; Visibility cycling, including org-goto and indirect buffer
3865 ;;; Cycling
3867 (defvar org-cycle-global-status nil)
3868 (make-variable-buffer-local 'org-cycle-global-status)
3869 (defvar org-cycle-subtree-status nil)
3870 (make-variable-buffer-local 'org-cycle-subtree-status)
3872 ;;;###autoload
3873 (defun org-cycle (&optional arg)
3874 "Visibility cycling for Org-mode.
3876 - When this function is called with a prefix argument, rotate the entire
3877 buffer through 3 states (global cycling)
3878 1. OVERVIEW: Show only top-level headlines.
3879 2. CONTENTS: Show all headlines of all levels, but no body text.
3880 3. SHOW ALL: Show everything.
3881 When called with two C-u C-u prefixes, switch to the startup visibility,
3882 determined by the variable `org-startup-folded', and by any VISIBILITY
3883 properties in the buffer.
3884 When called with three C-u C-u C-u prefixed, show the entire buffer,
3885 including drawers.
3887 - When point is at the beginning of a headline, rotate the subtree started
3888 by this line through 3 different states (local cycling)
3889 1. FOLDED: Only the main headline is shown.
3890 2. CHILDREN: The main headline and the direct children are shown.
3891 From this state, you can move to one of the children
3892 and zoom in further.
3893 3. SUBTREE: Show the entire subtree, including body text.
3895 - When there is a numeric prefix, go up to a heading with level ARG, do
3896 a `show-subtree' and return to the previous cursor position. If ARG
3897 is negative, go up that many levels.
3899 - When point is not at the beginning of a headline, execute the global
3900 binding for TAB, which is re-indenting the line. See the option
3901 `org-cycle-emulate-tab' for details.
3903 - Special case: if point is at the beginning of the buffer and there is
3904 no headline in line 1, this function will act as if called with prefix arg.
3905 But only if also the variable `org-cycle-global-at-bob' is t."
3906 (interactive "P")
3907 (org-load-modules-maybe)
3908 (let* ((outline-regexp
3909 (if (and (org-mode-p) org-cycle-include-plain-lists)
3910 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3911 outline-regexp))
3912 (bob-special (and org-cycle-global-at-bob (bobp)
3913 (not (looking-at outline-regexp))))
3914 (org-cycle-hook
3915 (if bob-special
3916 (delq 'org-optimize-window-after-visibility-change
3917 (copy-sequence org-cycle-hook))
3918 org-cycle-hook))
3919 (pos (point)))
3921 (if (or bob-special (equal arg '(4)))
3922 ;; special case: use global cycling
3923 (setq arg t))
3925 (cond
3927 ((equal arg '(16))
3928 (org-set-startup-visibility)
3929 (message "Startup visibility, plus VISIBILITY properties"))
3931 ((equal arg '(64))
3932 (show-all)
3933 (message "Entire buffer visible, including drawers"))
3935 ((org-at-table-p 'any)
3936 ;; Enter the table or move to the next field in the table
3937 (or (org-table-recognize-table.el)
3938 (progn
3939 (if arg (org-table-edit-field t)
3940 (org-table-justify-field-maybe)
3941 (call-interactively 'org-table-next-field)))))
3943 ((eq arg t) ;; Global cycling
3945 (cond
3946 ((and (eq last-command this-command)
3947 (eq org-cycle-global-status 'overview))
3948 ;; We just created the overview - now do table of contents
3949 ;; This can be slow in very large buffers, so indicate action
3950 (message "CONTENTS...")
3951 (org-content)
3952 (message "CONTENTS...done")
3953 (setq org-cycle-global-status 'contents)
3954 (run-hook-with-args 'org-cycle-hook 'contents))
3956 ((and (eq last-command this-command)
3957 (eq org-cycle-global-status 'contents))
3958 ;; We just showed the table of contents - now show everything
3959 (show-all)
3960 (message "SHOW ALL")
3961 (setq org-cycle-global-status 'all)
3962 (run-hook-with-args 'org-cycle-hook 'all))
3965 ;; Default action: go to overview
3966 (org-overview)
3967 (message "OVERVIEW")
3968 (setq org-cycle-global-status 'overview)
3969 (run-hook-with-args 'org-cycle-hook 'overview))))
3971 ((and org-drawers org-drawer-regexp
3972 (save-excursion
3973 (beginning-of-line 1)
3974 (looking-at org-drawer-regexp)))
3975 ;; Toggle block visibility
3976 (org-flag-drawer
3977 (not (get-char-property (match-end 0) 'invisible))))
3979 ((integerp arg)
3980 ;; Show-subtree, ARG levels up from here.
3981 (save-excursion
3982 (org-back-to-heading)
3983 (outline-up-heading (if (< arg 0) (- arg)
3984 (- (funcall outline-level) arg)))
3985 (org-show-subtree)))
3987 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3988 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3989 ;; At a heading: rotate between three different views
3990 (org-back-to-heading)
3991 (let ((goal-column 0) eoh eol eos)
3992 ;; First, some boundaries
3993 (save-excursion
3994 (org-back-to-heading)
3995 (save-excursion
3996 (beginning-of-line 2)
3997 (while (and (not (eobp)) ;; this is like `next-line'
3998 (get-char-property (1- (point)) 'invisible))
3999 (beginning-of-line 2)) (setq eol (point)))
4000 (outline-end-of-heading) (setq eoh (point))
4001 (org-end-of-subtree t)
4002 (unless (eobp)
4003 (skip-chars-forward " \t\n")
4004 (beginning-of-line 1) ; in case this is an item
4006 (setq eos (1- (point))))
4007 ;; Find out what to do next and set `this-command'
4008 (cond
4009 ((= eos eoh)
4010 ;; Nothing is hidden behind this heading
4011 (message "EMPTY ENTRY")
4012 (setq org-cycle-subtree-status nil)
4013 (save-excursion
4014 (goto-char eos)
4015 (outline-next-heading)
4016 (if (org-invisible-p) (org-flag-heading nil))))
4017 ((or (>= eol eos)
4018 (not (string-match "\\S-" (buffer-substring eol eos))))
4019 ;; Entire subtree is hidden in one line: open it
4020 (org-show-entry)
4021 (show-children)
4022 (message "CHILDREN")
4023 (save-excursion
4024 (goto-char eos)
4025 (outline-next-heading)
4026 (if (org-invisible-p) (org-flag-heading nil)))
4027 (setq org-cycle-subtree-status 'children)
4028 (run-hook-with-args 'org-cycle-hook 'children))
4029 ((and (eq last-command this-command)
4030 (eq org-cycle-subtree-status 'children))
4031 ;; We just showed the children, now show everything.
4032 (org-show-subtree)
4033 (message "SUBTREE")
4034 (setq org-cycle-subtree-status 'subtree)
4035 (run-hook-with-args 'org-cycle-hook 'subtree))
4037 ;; Default action: hide the subtree.
4038 (hide-subtree)
4039 (message "FOLDED")
4040 (setq org-cycle-subtree-status 'folded)
4041 (run-hook-with-args 'org-cycle-hook 'folded)))))
4043 ;; TAB emulation and template completion
4044 (buffer-read-only (org-back-to-heading))
4046 ((org-try-structure-completion))
4048 ((org-try-cdlatex-tab))
4050 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4051 (or (not (bolp))
4052 (not (looking-at outline-regexp))))
4053 (call-interactively (global-key-binding "\t")))
4055 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4056 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4057 (or (and (eq org-cycle-emulate-tab 'white)
4058 (= (match-end 0) (point-at-eol)))
4059 (and (eq org-cycle-emulate-tab 'whitestart)
4060 (>= (match-end 0) pos))))
4062 (eq org-cycle-emulate-tab t))
4063 (call-interactively (global-key-binding "\t")))
4065 (t (save-excursion
4066 (org-back-to-heading)
4067 (org-cycle))))))
4069 ;;;###autoload
4070 (defun org-global-cycle (&optional arg)
4071 "Cycle the global visibility. For details see `org-cycle'.
4072 With C-u prefix arg, switch to startup visibility.
4073 With a numeric prefix, show all headlines up to that level."
4074 (interactive "P")
4075 (let ((org-cycle-include-plain-lists
4076 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4077 (cond
4078 ((integerp arg)
4079 (show-all)
4080 (hide-sublevels arg)
4081 (setq org-cycle-global-status 'contents))
4082 ((equal arg '(4))
4083 (org-set-startup-visibility)
4084 (message "Startup visibility, plus VISIBILITY properties."))
4086 (org-cycle '(4))))))
4088 (defun org-set-startup-visibility ()
4089 "Set the visibility required by startup options and properties."
4090 (cond
4091 ((eq org-startup-folded t)
4092 (org-cycle '(4)))
4093 ((eq org-startup-folded 'content)
4094 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4095 (org-cycle '(4)) (org-cycle '(4)))))
4096 (org-set-visibility-according-to-property 'no-cleanup)
4097 (org-cycle-hide-archived-subtrees 'all)
4098 (org-cycle-hide-drawers 'all)
4099 (org-cycle-show-empty-lines 'all))
4101 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4102 "Switch subtree visibilities according to :VISIBILITY: property."
4103 (interactive)
4104 (let (state)
4105 (save-excursion
4106 (goto-char (point-min))
4107 (while (re-search-forward
4108 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4109 nil t)
4110 (setq state (match-string 1))
4111 (save-excursion
4112 (org-back-to-heading t)
4113 (hide-subtree)
4114 (org-reveal)
4115 (cond
4116 ((equal state '("fold" "folded"))
4117 (hide-subtree))
4118 ((equal state "children")
4119 (org-show-hidden-entry)
4120 (show-children))
4121 ((equal state "content")
4122 (save-excursion
4123 (save-restriction
4124 (org-narrow-to-subtree)
4125 (org-content))))
4126 ((member state '("all" "showall"))
4127 (show-subtree)))))
4128 (unless no-cleanup
4129 (org-cycle-hide-archived-subtrees 'all)
4130 (org-cycle-hide-drawers 'all)
4131 (org-cycle-show-empty-lines 'all)))))
4133 (defun org-overview ()
4134 "Switch to overview mode, shoing only top-level headlines.
4135 Really, this shows all headlines with level equal or greater than the level
4136 of the first headline in the buffer. This is important, because if the
4137 first headline is not level one, then (hide-sublevels 1) gives confusing
4138 results."
4139 (interactive)
4140 (let ((level (save-excursion
4141 (goto-char (point-min))
4142 (if (re-search-forward (concat "^" outline-regexp) nil t)
4143 (progn
4144 (goto-char (match-beginning 0))
4145 (funcall outline-level))))))
4146 (and level (hide-sublevels level))))
4148 (defun org-content (&optional arg)
4149 "Show all headlines in the buffer, like a table of contents.
4150 With numerical argument N, show content up to level N."
4151 (interactive "P")
4152 (save-excursion
4153 ;; Visit all headings and show their offspring
4154 (and (integerp arg) (org-overview))
4155 (goto-char (point-max))
4156 (catch 'exit
4157 (while (and (progn (condition-case nil
4158 (outline-previous-visible-heading 1)
4159 (error (goto-char (point-min))))
4161 (looking-at outline-regexp))
4162 (if (integerp arg)
4163 (show-children (1- arg))
4164 (show-branches))
4165 (if (bobp) (throw 'exit nil))))))
4168 (defun org-optimize-window-after-visibility-change (state)
4169 "Adjust the window after a change in outline visibility.
4170 This function is the default value of the hook `org-cycle-hook'."
4171 (when (get-buffer-window (current-buffer))
4172 (cond
4173 ; ((eq state 'overview) (org-first-headline-recenter 1))
4174 ; ((eq state 'overview) (org-beginning-of-line))
4175 ((eq state 'content) nil)
4176 ((eq state 'all) nil)
4177 ((eq state 'folded) nil)
4178 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4179 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4181 (defun org-compact-display-after-subtree-move ()
4182 (let (beg end)
4183 (save-excursion
4184 (if (org-up-heading-safe)
4185 (progn
4186 (hide-subtree)
4187 (show-entry)
4188 (show-children)
4189 (org-cycle-show-empty-lines 'children)
4190 (org-cycle-hide-drawers 'children))
4191 (org-overview)))))
4193 (defun org-cycle-show-empty-lines (state)
4194 "Show empty lines above all visible headlines.
4195 The region to be covered depends on STATE when called through
4196 `org-cycle-hook'. Lisp program can use t for STATE to get the
4197 entire buffer covered. Note that an empty line is only shown if there
4198 are at least `org-cycle-separator-lines' empty lines before the headeline."
4199 (when (> org-cycle-separator-lines 0)
4200 (save-excursion
4201 (let* ((n org-cycle-separator-lines)
4202 (re (cond
4203 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4204 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4205 (t (let ((ns (number-to-string (- n 2))))
4206 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4207 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4208 beg end)
4209 (cond
4210 ((memq state '(overview contents t))
4211 (setq beg (point-min) end (point-max)))
4212 ((memq state '(children folded))
4213 (setq beg (point) end (progn (org-end-of-subtree t t)
4214 (beginning-of-line 2)
4215 (point)))))
4216 (when beg
4217 (goto-char beg)
4218 (while (re-search-forward re end t)
4219 (if (not (get-char-property (match-end 1) 'invisible))
4220 (outline-flag-region
4221 (match-beginning 1) (match-end 1) nil)))))))
4222 ;; Never hide empty lines at the end of the file.
4223 (save-excursion
4224 (goto-char (point-max))
4225 (outline-previous-heading)
4226 (outline-end-of-heading)
4227 (if (and (looking-at "[ \t\n]+")
4228 (= (match-end 0) (point-max)))
4229 (outline-flag-region (point) (match-end 0) nil))))
4231 (defun org-show-empty-lines-in-parent ()
4232 "Move to the parent and re-show empty lines before visible headlines."
4233 (save-excursion
4234 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4235 (org-cycle-show-empty-lines context))))
4237 (defun org-cycle-hide-drawers (state)
4238 "Re-hide all drawers after a visibility state change."
4239 (when (and (org-mode-p)
4240 (not (memq state '(overview folded))))
4241 (save-excursion
4242 (let* ((globalp (memq state '(contents all)))
4243 (beg (if globalp (point-min) (point)))
4244 (end (if globalp (point-max) (org-end-of-subtree t))))
4245 (goto-char beg)
4246 (while (re-search-forward org-drawer-regexp end t)
4247 (org-flag-drawer t))))))
4249 (defun org-flag-drawer (flag)
4250 (save-excursion
4251 (beginning-of-line 1)
4252 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4253 (let ((b (match-end 0))
4254 (outline-regexp org-outline-regexp))
4255 (if (re-search-forward
4256 "^[ \t]*:END:"
4257 (save-excursion (outline-next-heading) (point)) t)
4258 (outline-flag-region b (point-at-eol) flag)
4259 (error ":END: line missing"))))))
4261 (defun org-subtree-end-visible-p ()
4262 "Is the end of the current subtree visible?"
4263 (pos-visible-in-window-p
4264 (save-excursion (org-end-of-subtree t) (point))))
4266 (defun org-first-headline-recenter (&optional N)
4267 "Move cursor to the first headline and recenter the headline.
4268 Optional argument N means, put the headline into the Nth line of the window."
4269 (goto-char (point-min))
4270 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4271 (beginning-of-line)
4272 (recenter (prefix-numeric-value N))))
4274 ;;; Org-goto
4276 (defvar org-goto-window-configuration nil)
4277 (defvar org-goto-marker nil)
4278 (defvar org-goto-map
4279 (let ((map (make-sparse-keymap)))
4280 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4281 (while (setq cmd (pop cmds))
4282 (substitute-key-definition cmd cmd map global-map)))
4283 (suppress-keymap map)
4284 (org-defkey map "\C-m" 'org-goto-ret)
4285 (org-defkey map [(return)] 'org-goto-ret)
4286 (org-defkey map [(left)] 'org-goto-left)
4287 (org-defkey map [(right)] 'org-goto-right)
4288 (org-defkey map [(control ?g)] 'org-goto-quit)
4289 (org-defkey map "\C-i" 'org-cycle)
4290 (org-defkey map [(tab)] 'org-cycle)
4291 (org-defkey map [(down)] 'outline-next-visible-heading)
4292 (org-defkey map [(up)] 'outline-previous-visible-heading)
4293 (if org-goto-auto-isearch
4294 (if (fboundp 'define-key-after)
4295 (define-key-after map [t] 'org-goto-local-auto-isearch)
4296 nil)
4297 (org-defkey map "q" 'org-goto-quit)
4298 (org-defkey map "n" 'outline-next-visible-heading)
4299 (org-defkey map "p" 'outline-previous-visible-heading)
4300 (org-defkey map "f" 'outline-forward-same-level)
4301 (org-defkey map "b" 'outline-backward-same-level)
4302 (org-defkey map "u" 'outline-up-heading))
4303 (org-defkey map "/" 'org-occur)
4304 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4305 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4306 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4307 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4308 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4309 map))
4311 (defconst org-goto-help
4312 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4313 RET=jump to location [Q]uit and return to previous location
4314 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4316 (defvar org-goto-start-pos) ; dynamically scoped parameter
4318 ;; FIXME: Docstring doe not mention both interfaces
4319 (defun org-goto (&optional alternative-interface)
4320 "Look up a different location in the current file, keeping current visibility.
4322 When you want look-up or go to a different location in a document, the
4323 fastest way is often to fold the entire buffer and then dive into the tree.
4324 This method has the disadvantage, that the previous location will be folded,
4325 which may not be what you want.
4327 This command works around this by showing a copy of the current buffer
4328 in an indirect buffer, in overview mode. You can dive into the tree in
4329 that copy, use org-occur and incremental search to find a location.
4330 When pressing RET or `Q', the command returns to the original buffer in
4331 which the visibility is still unchanged. After RET is will also jump to
4332 the location selected in the indirect buffer and expose the
4333 the headline hierarchy above."
4334 (interactive "P")
4335 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4336 (org-refile-use-outline-path t)
4337 (interface
4338 (if (not alternative-interface)
4339 org-goto-interface
4340 (if (eq org-goto-interface 'outline)
4341 'outline-path-completion
4342 'outline)))
4343 (org-goto-start-pos (point))
4344 (selected-point
4345 (if (eq interface 'outline)
4346 (car (org-get-location (current-buffer) org-goto-help))
4347 (nth 3 (org-refile-get-location "Goto: ")))))
4348 (if selected-point
4349 (progn
4350 (org-mark-ring-push org-goto-start-pos)
4351 (goto-char selected-point)
4352 (if (or (org-invisible-p) (org-invisible-p2))
4353 (org-show-context 'org-goto)))
4354 (message "Quit"))))
4356 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4357 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4358 (defvar org-goto-local-auto-isearch-map) ; defined below
4360 (defun org-get-location (buf help)
4361 "Let the user select a location in the Org-mode buffer BUF.
4362 This function uses a recursive edit. It returns the selected position
4363 or nil."
4364 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4365 (isearch-hide-immediately nil)
4366 (isearch-search-fun-function
4367 (lambda () 'org-goto-local-search-headings))
4368 (org-goto-selected-point org-goto-exit-command))
4369 (save-excursion
4370 (save-window-excursion
4371 (delete-other-windows)
4372 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4373 (switch-to-buffer
4374 (condition-case nil
4375 (make-indirect-buffer (current-buffer) "*org-goto*")
4376 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4377 (with-output-to-temp-buffer "*Help*"
4378 (princ help))
4379 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4380 (setq buffer-read-only nil)
4381 (let ((org-startup-truncated t)
4382 (org-startup-folded nil)
4383 (org-startup-align-all-tables nil))
4384 (org-mode)
4385 (org-overview))
4386 (setq buffer-read-only t)
4387 (if (and (boundp 'org-goto-start-pos)
4388 (integer-or-marker-p org-goto-start-pos))
4389 (let ((org-show-hierarchy-above t)
4390 (org-show-siblings t)
4391 (org-show-following-heading t))
4392 (goto-char org-goto-start-pos)
4393 (and (org-invisible-p) (org-show-context)))
4394 (goto-char (point-min)))
4395 (org-beginning-of-line)
4396 (message "Select location and press RET")
4397 (use-local-map org-goto-map)
4398 (recursive-edit)
4400 (kill-buffer "*org-goto*")
4401 (cons org-goto-selected-point org-goto-exit-command)))
4403 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4404 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4405 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4406 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4408 (defun org-goto-local-search-headings (string bound noerror)
4409 "Search and make sure that any matches are in headlines."
4410 (catch 'return
4411 (while (if isearch-forward
4412 (search-forward string bound noerror)
4413 (search-backward string bound noerror))
4414 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4415 (and (member :headline context)
4416 (not (member :tags context))))
4417 (throw 'return (point))))))
4419 (defun org-goto-local-auto-isearch ()
4420 "Start isearch."
4421 (interactive)
4422 (goto-char (point-min))
4423 (let ((keys (this-command-keys)))
4424 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4425 (isearch-mode t)
4426 (isearch-process-search-char (string-to-char keys)))))
4428 (defun org-goto-ret (&optional arg)
4429 "Finish `org-goto' by going to the new location."
4430 (interactive "P")
4431 (setq org-goto-selected-point (point)
4432 org-goto-exit-command 'return)
4433 (throw 'exit nil))
4435 (defun org-goto-left ()
4436 "Finish `org-goto' by going to the new location."
4437 (interactive)
4438 (if (org-on-heading-p)
4439 (progn
4440 (beginning-of-line 1)
4441 (setq org-goto-selected-point (point)
4442 org-goto-exit-command 'left)
4443 (throw 'exit nil))
4444 (error "Not on a heading")))
4446 (defun org-goto-right ()
4447 "Finish `org-goto' by going to the new location."
4448 (interactive)
4449 (if (org-on-heading-p)
4450 (progn
4451 (setq org-goto-selected-point (point)
4452 org-goto-exit-command 'right)
4453 (throw 'exit nil))
4454 (error "Not on a heading")))
4456 (defun org-goto-quit ()
4457 "Finish `org-goto' without cursor motion."
4458 (interactive)
4459 (setq org-goto-selected-point nil)
4460 (setq org-goto-exit-command 'quit)
4461 (throw 'exit nil))
4463 ;;; Indirect buffer display of subtrees
4465 (defvar org-indirect-dedicated-frame nil
4466 "This is the frame being used for indirect tree display.")
4467 (defvar org-last-indirect-buffer nil)
4469 (defun org-tree-to-indirect-buffer (&optional arg)
4470 "Create indirect buffer and narrow it to current subtree.
4471 With numerical prefix ARG, go up to this level and then take that tree.
4472 If ARG is negative, go up that many levels.
4473 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4474 indirect buffer previously made with this command, to avoid proliferation of
4475 indirect buffers. However, when you call the command with a `C-u' prefix, or
4476 when `org-indirect-buffer-display' is `new-frame', the last buffer
4477 is kept so that you can work with several indirect buffers at the same time.
4478 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4479 requests that a new frame be made for the new buffer, so that the dedicated
4480 frame is not changed."
4481 (interactive "P")
4482 (let ((cbuf (current-buffer))
4483 (cwin (selected-window))
4484 (pos (point))
4485 beg end level heading ibuf)
4486 (save-excursion
4487 (org-back-to-heading t)
4488 (when (numberp arg)
4489 (setq level (org-outline-level))
4490 (if (< arg 0) (setq arg (+ level arg)))
4491 (while (> (setq level (org-outline-level)) arg)
4492 (outline-up-heading 1 t)))
4493 (setq beg (point)
4494 heading (org-get-heading))
4495 (org-end-of-subtree t) (setq end (point)))
4496 (if (and (buffer-live-p org-last-indirect-buffer)
4497 (not (eq org-indirect-buffer-display 'new-frame))
4498 (not arg))
4499 (kill-buffer org-last-indirect-buffer))
4500 (setq ibuf (org-get-indirect-buffer cbuf)
4501 org-last-indirect-buffer ibuf)
4502 (cond
4503 ((or (eq org-indirect-buffer-display 'new-frame)
4504 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4505 (select-frame (make-frame))
4506 (delete-other-windows)
4507 (switch-to-buffer ibuf)
4508 (org-set-frame-title heading))
4509 ((eq org-indirect-buffer-display 'dedicated-frame)
4510 (raise-frame
4511 (select-frame (or (and org-indirect-dedicated-frame
4512 (frame-live-p org-indirect-dedicated-frame)
4513 org-indirect-dedicated-frame)
4514 (setq org-indirect-dedicated-frame (make-frame)))))
4515 (delete-other-windows)
4516 (switch-to-buffer ibuf)
4517 (org-set-frame-title (concat "Indirect: " heading)))
4518 ((eq org-indirect-buffer-display 'current-window)
4519 (switch-to-buffer ibuf))
4520 ((eq org-indirect-buffer-display 'other-window)
4521 (pop-to-buffer ibuf))
4522 (t (error "Invalid value.")))
4523 (if (featurep 'xemacs)
4524 (save-excursion (org-mode) (turn-on-font-lock)))
4525 (narrow-to-region beg end)
4526 (show-all)
4527 (goto-char pos)
4528 (and (window-live-p cwin) (select-window cwin))))
4530 (defun org-get-indirect-buffer (&optional buffer)
4531 (setq buffer (or buffer (current-buffer)))
4532 (let ((n 1) (base (buffer-name buffer)) bname)
4533 (while (buffer-live-p
4534 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4535 (setq n (1+ n)))
4536 (condition-case nil
4537 (make-indirect-buffer buffer bname 'clone)
4538 (error (make-indirect-buffer buffer bname)))))
4540 (defun org-set-frame-title (title)
4541 "Set the title of the current frame to the string TITLE."
4542 ;; FIXME: how to name a single frame in XEmacs???
4543 (unless (featurep 'xemacs)
4544 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4546 ;;;; Structure editing
4548 ;;; Inserting headlines
4550 (defun org-insert-heading (&optional force-heading)
4551 "Insert a new heading or item with same depth at point.
4552 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4553 If point is at the beginning of a headline, insert a sibling before the
4554 current headline. If point is not at the beginning, do not split the line,
4555 but create the new hedline after the current line."
4556 (interactive "P")
4557 (if (= (buffer-size) 0)
4558 (insert "\n* ")
4559 (when (or force-heading (not (org-insert-item)))
4560 (let* ((head (save-excursion
4561 (condition-case nil
4562 (progn
4563 (org-back-to-heading)
4564 (match-string 0))
4565 (error "*"))))
4566 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4567 pos)
4568 (cond
4569 ((and (org-on-heading-p) (bolp)
4570 (or (bobp)
4571 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4572 ;; insert before the current line
4573 (open-line (if blank 2 1)))
4574 ((and (bolp)
4575 (or (bobp)
4576 (save-excursion
4577 (backward-char 1) (not (org-invisible-p)))))
4578 ;; insert right here
4579 nil)
4581 ;; in the middle of the line
4582 (org-show-entry)
4583 (let ((split
4584 (org-get-alist-option org-M-RET-may-split-line 'headline))
4585 tags pos)
4586 (cond
4587 (org-insert-heading-respect-content
4588 (org-end-of-subtree nil t)
4589 (open-line 1))
4590 ((org-on-heading-p)
4591 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4592 (setq tags (and (match-end 2) (match-string 2)))
4593 (and (match-end 1)
4594 (delete-region (match-beginning 1) (match-end 1)))
4595 (setq pos (point-at-bol))
4596 (or split (end-of-line 1))
4597 (delete-horizontal-space)
4598 (newline (if blank 2 1))
4599 (when tags
4600 (save-excursion
4601 (goto-char pos)
4602 (end-of-line 1)
4603 (insert " " tags)
4604 (org-set-tags nil 'align))))
4606 (or split (end-of-line 1))
4607 (newline (if blank 2 1)))))))
4608 (insert head) (just-one-space)
4609 (setq pos (point))
4610 (end-of-line 1)
4611 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4612 (run-hooks 'org-insert-heading-hook)))))
4614 (defun org-get-heading (&optional no-tags)
4615 "Return the heading of the current entry, without the stars."
4616 (save-excursion
4617 (org-back-to-heading t)
4618 (if (looking-at
4619 (if no-tags
4620 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4621 "\\*+[ \t]+\\([^\r\n]*\\)"))
4622 (match-string 1) "")))
4624 (defun org-insert-heading-after-current ()
4625 "Insert a new heading with same level as current, after current subtree."
4626 (interactive)
4627 (org-back-to-heading)
4628 (org-insert-heading)
4629 (org-move-subtree-down)
4630 (end-of-line 1))
4632 (defun org-insert-heading-respect-content ()
4633 (interactive)
4634 (let ((org-insert-heading-respect-content t))
4635 (call-interactively 'org-insert-heading)))
4637 (defun org-insert-todo-heading-respect-content ()
4638 (interactive)
4639 (let ((org-insert-heading-respect-content t))
4640 (call-interactively 'org-insert-todo-todo-heading)))
4642 (defun org-insert-todo-heading (arg)
4643 "Insert a new heading with the same level and TODO state as current heading.
4644 If the heading has no TODO state, or if the state is DONE, use the first
4645 state (TODO by default). Also with prefix arg, force first state."
4646 (interactive "P")
4647 (when (not (org-insert-item 'checkbox))
4648 (org-insert-heading)
4649 (save-excursion
4650 (org-back-to-heading)
4651 (outline-previous-heading)
4652 (looking-at org-todo-line-regexp))
4653 (if (or arg
4654 (not (match-beginning 2))
4655 (member (match-string 2) org-done-keywords))
4656 (insert (car org-todo-keywords-1) " ")
4657 (insert (match-string 2) " "))
4658 (when org-provide-todo-statistics
4659 (org-update-parent-todo-statistics))))
4661 (defun org-insert-subheading (arg)
4662 "Insert a new subheading and demote it.
4663 Works for outline headings and for plain lists alike."
4664 (interactive "P")
4665 (org-insert-heading arg)
4666 (cond
4667 ((org-on-heading-p) (org-do-demote))
4668 ((org-at-item-p) (org-indent-item 1))))
4670 (defun org-insert-todo-subheading (arg)
4671 "Insert a new subheading with TODO keyword or checkbox and demote it.
4672 Works for outline headings and for plain lists alike."
4673 (interactive "P")
4674 (org-insert-todo-heading arg)
4675 (cond
4676 ((org-on-heading-p) (org-do-demote))
4677 ((org-at-item-p) (org-indent-item 1))))
4679 ;;; Promotion and Demotion
4681 (defun org-promote-subtree ()
4682 "Promote the entire subtree.
4683 See also `org-promote'."
4684 (interactive)
4685 (save-excursion
4686 (org-map-tree 'org-promote))
4687 (org-fix-position-after-promote))
4689 (defun org-demote-subtree ()
4690 "Demote the entire subtree. See `org-demote'.
4691 See also `org-promote'."
4692 (interactive)
4693 (save-excursion
4694 (org-map-tree 'org-demote))
4695 (org-fix-position-after-promote))
4698 (defun org-do-promote ()
4699 "Promote the current heading higher up the tree.
4700 If the region is active in `transient-mark-mode', promote all headings
4701 in the region."
4702 (interactive)
4703 (save-excursion
4704 (if (org-region-active-p)
4705 (org-map-region 'org-promote (region-beginning) (region-end))
4706 (org-promote)))
4707 (org-fix-position-after-promote))
4709 (defun org-do-demote ()
4710 "Demote the current heading lower down the tree.
4711 If the region is active in `transient-mark-mode', demote all headings
4712 in the region."
4713 (interactive)
4714 (save-excursion
4715 (if (org-region-active-p)
4716 (org-map-region 'org-demote (region-beginning) (region-end))
4717 (org-demote)))
4718 (org-fix-position-after-promote))
4720 (defun org-fix-position-after-promote ()
4721 "Make sure that after pro/demotion cursor position is right."
4722 (let ((pos (point)))
4723 (when (save-excursion
4724 (beginning-of-line 1)
4725 (looking-at org-todo-line-regexp)
4726 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4727 (cond ((eobp) (insert " "))
4728 ((eolp) (insert " "))
4729 ((equal (char-after) ?\ ) (forward-char 1))))))
4731 (defun org-reduced-level (l)
4732 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4734 (defun org-get-valid-level (level &optional change)
4735 "Rectify a level change under the influence of `org-odd-levels-only'
4736 LEVEL is a current level, CHANGE is by how much the level should be
4737 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4738 even level numbers will become the next higher odd number."
4739 (if org-odd-levels-only
4740 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4741 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4742 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4743 (max 1 (+ level change))))
4745 (if (boundp 'define-obsolete-function-alias)
4746 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4747 (define-obsolete-function-alias 'org-get-legal-level
4748 'org-get-valid-level)
4749 (define-obsolete-function-alias 'org-get-legal-level
4750 'org-get-valid-level "23.1")))
4752 (defun org-promote ()
4753 "Promote the current heading higher up the tree.
4754 If the region is active in `transient-mark-mode', promote all headings
4755 in the region."
4756 (org-back-to-heading t)
4757 (let* ((level (save-match-data (funcall outline-level)))
4758 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4759 (diff (abs (- level (length up-head) -1))))
4760 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4761 (replace-match up-head nil t)
4762 ;; Fixup tag positioning
4763 (and org-auto-align-tags (org-set-tags nil t))
4764 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4766 (defun org-demote ()
4767 "Demote the current heading lower down the tree.
4768 If the region is active in `transient-mark-mode', demote all headings
4769 in the region."
4770 (org-back-to-heading t)
4771 (let* ((level (save-match-data (funcall outline-level)))
4772 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4773 (diff (abs (- level (length down-head) -1))))
4774 (replace-match down-head nil t)
4775 ;; Fixup tag positioning
4776 (and org-auto-align-tags (org-set-tags nil t))
4777 (if org-adapt-indentation (org-fixup-indentation diff))))
4779 (defun org-map-tree (fun)
4780 "Call FUN for every heading underneath the current one."
4781 (org-back-to-heading)
4782 (let ((level (funcall outline-level)))
4783 (save-excursion
4784 (funcall fun)
4785 (while (and (progn
4786 (outline-next-heading)
4787 (> (funcall outline-level) level))
4788 (not (eobp)))
4789 (funcall fun)))))
4791 (defun org-map-region (fun beg end)
4792 "Call FUN for every heading between BEG and END."
4793 (let ((org-ignore-region t))
4794 (save-excursion
4795 (setq end (copy-marker end))
4796 (goto-char beg)
4797 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4798 (< (point) end))
4799 (funcall fun))
4800 (while (and (progn
4801 (outline-next-heading)
4802 (< (point) end))
4803 (not (eobp)))
4804 (funcall fun)))))
4806 (defun org-fixup-indentation (diff)
4807 "Change the indentation in the current entry by DIFF
4808 However, if any line in the current entry has no indentation, or if it
4809 would end up with no indentation after the change, nothing at all is done."
4810 (save-excursion
4811 (let ((end (save-excursion (outline-next-heading)
4812 (point-marker)))
4813 (prohibit (if (> diff 0)
4814 "^\\S-"
4815 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4816 col)
4817 (unless (save-excursion (end-of-line 1)
4818 (re-search-forward prohibit end t))
4819 (while (and (< (point) end)
4820 (re-search-forward "^[ \t]+" end t))
4821 (goto-char (match-end 0))
4822 (setq col (current-column))
4823 (if (< diff 0) (replace-match ""))
4824 (indent-to (+ diff col))))
4825 (move-marker end nil))))
4827 (defun org-convert-to-odd-levels ()
4828 "Convert an org-mode file with all levels allowed to one with odd levels.
4829 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4830 level 5 etc."
4831 (interactive)
4832 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4833 (let ((org-odd-levels-only nil) n)
4834 (save-excursion
4835 (goto-char (point-min))
4836 (while (re-search-forward "^\\*\\*+ " nil t)
4837 (setq n (- (length (match-string 0)) 2))
4838 (while (>= (setq n (1- n)) 0)
4839 (org-demote))
4840 (end-of-line 1))))))
4843 (defun org-convert-to-oddeven-levels ()
4844 "Convert an org-mode file with only odd levels to one with odd and even levels.
4845 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4846 section with an even level, conversion would destroy the structure of the file. An error
4847 is signaled in this case."
4848 (interactive)
4849 (goto-char (point-min))
4850 ;; First check if there are no even levels
4851 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4852 (org-show-context t)
4853 (error "Not all levels are odd in this file. Conversion not possible."))
4854 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4855 (let ((org-odd-levels-only nil) n)
4856 (save-excursion
4857 (goto-char (point-min))
4858 (while (re-search-forward "^\\*\\*+ " nil t)
4859 (setq n (/ (1- (length (match-string 0))) 2))
4860 (while (>= (setq n (1- n)) 0)
4861 (org-promote))
4862 (end-of-line 1))))))
4864 (defun org-tr-level (n)
4865 "Make N odd if required."
4866 (if org-odd-levels-only (1+ (/ n 2)) n))
4868 ;;; Vertical tree motion, cutting and pasting of subtrees
4870 (defun org-move-subtree-up (&optional arg)
4871 "Move the current subtree up past ARG headlines of the same level."
4872 (interactive "p")
4873 (org-move-subtree-down (- (prefix-numeric-value arg))))
4875 (defun org-move-subtree-down (&optional arg)
4876 "Move the current subtree down past ARG headlines of the same level."
4877 (interactive "p")
4878 (setq arg (prefix-numeric-value arg))
4879 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4880 'outline-get-last-sibling))
4881 (ins-point (make-marker))
4882 (cnt (abs arg))
4883 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4884 ;; Select the tree
4885 (org-back-to-heading)
4886 (setq beg0 (point))
4887 (save-excursion
4888 (setq ne-beg (org-back-over-empty-lines))
4889 (setq beg (point)))
4890 (save-match-data
4891 (save-excursion (outline-end-of-heading)
4892 (setq folded (org-invisible-p)))
4893 (outline-end-of-subtree))
4894 (outline-next-heading)
4895 (setq ne-end (org-back-over-empty-lines))
4896 (setq end (point))
4897 (goto-char beg0)
4898 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4899 ;; include less whitespace
4900 (save-excursion
4901 (goto-char beg)
4902 (forward-line (- ne-beg ne-end))
4903 (setq beg (point))))
4904 ;; Find insertion point, with error handling
4905 (while (> cnt 0)
4906 (or (and (funcall movfunc) (looking-at outline-regexp))
4907 (progn (goto-char beg0)
4908 (error "Cannot move past superior level or buffer limit")))
4909 (setq cnt (1- cnt)))
4910 (if (> arg 0)
4911 ;; Moving forward - still need to move over subtree
4912 (progn (org-end-of-subtree t t)
4913 (save-excursion
4914 (org-back-over-empty-lines)
4915 (or (bolp) (newline)))))
4916 (setq ne-ins (org-back-over-empty-lines))
4917 (move-marker ins-point (point))
4918 (setq txt (buffer-substring beg end))
4919 (org-save-markers-in-region beg end)
4920 (delete-region beg end)
4921 (outline-flag-region (1- beg) beg nil)
4922 (outline-flag-region (1- (point)) (point) nil)
4923 (let ((bbb (point)))
4924 (insert-before-markers txt)
4925 (org-reinstall-markers-in-region bbb)
4926 (move-marker ins-point bbb))
4927 (or (bolp) (insert "\n"))
4928 (setq ins-end (point))
4929 (goto-char ins-point)
4930 (org-skip-whitespace)
4931 (when (and (< arg 0)
4932 (org-first-sibling-p)
4933 (> ne-ins ne-beg))
4934 ;; Move whitespace back to beginning
4935 (save-excursion
4936 (goto-char ins-end)
4937 (let ((kill-whole-line t))
4938 (kill-line (- ne-ins ne-beg)) (point)))
4939 (insert (make-string (- ne-ins ne-beg) ?\n)))
4940 (move-marker ins-point nil)
4941 (org-compact-display-after-subtree-move)
4942 (org-show-empty-lines-in-parent)
4943 (unless folded
4944 (org-show-entry)
4945 (show-children)
4946 (org-cycle-hide-drawers 'children))))
4948 (defvar org-subtree-clip ""
4949 "Clipboard for cut and paste of subtrees.
4950 This is actually only a copy of the kill, because we use the normal kill
4951 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4953 (defvar org-subtree-clip-folded nil
4954 "Was the last copied subtree folded?
4955 This is used to fold the tree back after pasting.")
4957 (defun org-cut-subtree (&optional n)
4958 "Cut the current subtree into the clipboard.
4959 With prefix arg N, cut this many sequential subtrees.
4960 This is a short-hand for marking the subtree and then cutting it."
4961 (interactive "p")
4962 (org-copy-subtree n 'cut))
4964 (defun org-copy-subtree (&optional n cut force-store-markers)
4965 "Cut the current subtree into the clipboard.
4966 With prefix arg N, cut this many sequential subtrees.
4967 This is a short-hand for marking the subtree and then copying it.
4968 If CUT is non-nil, actually cut the subtree.
4969 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4970 of some markers in the region, even if CUT is non-nil. This is
4971 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4972 (interactive "p")
4973 (let (beg end folded (beg0 (point)))
4974 (if (interactive-p)
4975 (org-back-to-heading nil) ; take what looks like a subtree
4976 (org-back-to-heading t)) ; take what is really there
4977 (org-back-over-empty-lines)
4978 (setq beg (point))
4979 (skip-chars-forward " \t\r\n")
4980 (save-match-data
4981 (save-excursion (outline-end-of-heading)
4982 (setq folded (org-invisible-p)))
4983 (condition-case nil
4984 (outline-forward-same-level (1- n))
4985 (error nil))
4986 (org-end-of-subtree t t))
4987 (org-back-over-empty-lines)
4988 (setq end (point))
4989 (goto-char beg0)
4990 (when (> end beg)
4991 (setq org-subtree-clip-folded folded)
4992 (when (or cut force-store-markers)
4993 (org-save-markers-in-region beg end))
4994 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4995 (setq org-subtree-clip (current-kill 0))
4996 (message "%s: Subtree(s) with %d characters"
4997 (if cut "Cut" "Copied")
4998 (length org-subtree-clip)))))
5000 (defun org-paste-subtree (&optional level tree)
5001 "Paste the clipboard as a subtree, with modification of headline level.
5002 The entire subtree is promoted or demoted in order to match a new headline
5003 level. By default, the new level is derived from the visible headings
5004 before and after the insertion point, and taken to be the inferior headline
5005 level of the two. So if the previous visible heading is level 3 and the
5006 next is level 4 (or vice versa), level 4 will be used for insertion.
5007 This makes sure that the subtree remains an independent subtree and does
5008 not swallow low level entries.
5010 You can also force a different level, either by using a numeric prefix
5011 argument, or by inserting the heading marker by hand. For example, if the
5012 cursor is after \"*****\", then the tree will be shifted to level 5.
5014 If you want to insert the tree as is, just use \\[yank].
5016 If optional TREE is given, use this text instead of the kill ring."
5017 (interactive "P")
5018 (unless (org-kill-is-subtree-p tree)
5019 (error "%s"
5020 (substitute-command-keys
5021 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5022 (let* ((visp (not (org-invisible-p)))
5023 (txt (or tree (and kill-ring (current-kill 0))))
5024 (^re (concat "^\\(" outline-regexp "\\)"))
5025 (re (concat "\\(" outline-regexp "\\)"))
5026 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5028 (old-level (if (string-match ^re txt)
5029 (- (match-end 0) (match-beginning 0) 1)
5030 -1))
5031 (force-level (cond (level (prefix-numeric-value level))
5032 ((string-match
5033 ^re_ (buffer-substring (point-at-bol) (point)))
5034 (- (match-end 1) (match-beginning 1)))
5035 (t nil)))
5036 (previous-level (save-excursion
5037 (condition-case nil
5038 (progn
5039 (outline-previous-visible-heading 1)
5040 (if (looking-at re)
5041 (- (match-end 0) (match-beginning 0) 1)
5043 (error 1))))
5044 (next-level (save-excursion
5045 (condition-case nil
5046 (progn
5047 (or (looking-at outline-regexp)
5048 (outline-next-visible-heading 1))
5049 (if (looking-at re)
5050 (- (match-end 0) (match-beginning 0) 1)
5052 (error 1))))
5053 (new-level (or force-level (max previous-level next-level)))
5054 (shift (if (or (= old-level -1)
5055 (= new-level -1)
5056 (= old-level new-level))
5058 (- new-level old-level)))
5059 (delta (if (> shift 0) -1 1))
5060 (func (if (> shift 0) 'org-demote 'org-promote))
5061 (org-odd-levels-only nil)
5062 beg end)
5063 ;; Remove the forced level indicator
5064 (if force-level
5065 (delete-region (point-at-bol) (point)))
5066 ;; Paste
5067 (beginning-of-line 1)
5068 (org-back-over-empty-lines)
5069 (setq beg (point))
5070 (insert-before-markers txt)
5071 (unless (string-match "\n\\'" txt) (insert "\n"))
5072 (org-reinstall-markers-in-region beg)
5073 (setq end (point))
5074 (goto-char beg)
5075 (skip-chars-forward " \t\n\r")
5076 (setq beg (point))
5077 (if (and (org-invisible-p) visp)
5078 (save-excursion (outline-show-heading)))
5079 ;; Shift if necessary
5080 (unless (= shift 0)
5081 (save-restriction
5082 (narrow-to-region beg end)
5083 (while (not (= shift 0))
5084 (org-map-region func (point-min) (point-max))
5085 (setq shift (+ delta shift)))
5086 (goto-char (point-min))))
5087 (when (interactive-p)
5088 (message "Clipboard pasted as level %d subtree" new-level))
5089 (if (and kill-ring
5090 (eq org-subtree-clip (current-kill 0))
5091 org-subtree-clip-folded)
5092 ;; The tree was folded before it was killed/copied
5093 (hide-subtree))))
5095 (defun org-kill-is-subtree-p (&optional txt)
5096 "Check if the current kill is an outline subtree, or a set of trees.
5097 Returns nil if kill does not start with a headline, or if the first
5098 headline level is not the largest headline level in the tree.
5099 So this will actually accept several entries of equal levels as well,
5100 which is OK for `org-paste-subtree'.
5101 If optional TXT is given, check this string instead of the current kill."
5102 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5103 (start-level (and kill
5104 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5105 org-outline-regexp "\\)")
5106 kill)
5107 (- (match-end 2) (match-beginning 2) 1)))
5108 (re (concat "^" org-outline-regexp))
5109 (start (1+ (or (match-beginning 2) -1))))
5110 (if (not start-level)
5111 (progn
5112 nil) ;; does not even start with a heading
5113 (catch 'exit
5114 (while (setq start (string-match re kill (1+ start)))
5115 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5116 (throw 'exit nil)))
5117 t))))
5119 (defvar org-markers-to-move nil
5120 "Markers that should be moved with a cut-and-paste operation.
5121 Those markers are stored together with their positions relative to
5122 the start of the region.")
5124 (defun org-save-markers-in-region (beg end)
5125 "Check markers in region.
5126 If these markers are between BEG and END, record their position relative
5127 to BEG, so that after moving the block of text, we can put the markers back
5128 into place.
5129 This function gets called just before an entry or tree gets cut from the
5130 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5131 called immediately, to move the markers with the entries."
5132 (setq org-markers-to-move nil)
5133 (when (featurep 'org-clock)
5134 (org-clock-save-markers-for-cut-and-paste beg end))
5135 (when (featurep 'org-agenda)
5136 (org-agenda-save-markers-for-cut-and-paste beg end)))
5138 (defun org-check-and-save-marker (marker beg end)
5139 "Check if MARKER is between BEG and END.
5140 If yes, remember the marker and the distance to BEG."
5141 (when (and (marker-buffer marker)
5142 (equal (marker-buffer marker) (current-buffer)))
5143 (if (and (>= marker beg) (< marker end))
5144 (push (cons marker (- marker beg)) org-markers-to-move))))
5146 (defun org-reinstall-markers-in-region (beg)
5147 "Move all remembered markers to their position relative to BEG."
5148 (mapc (lambda (x)
5149 (move-marker (car x) (+ beg (cdr x))))
5150 org-markers-to-move)
5151 (setq org-markers-to-move nil))
5153 (defun org-narrow-to-subtree ()
5154 "Narrow buffer to the current subtree."
5155 (interactive)
5156 (save-excursion
5157 (save-match-data
5158 (narrow-to-region
5159 (progn (org-back-to-heading) (point))
5160 (progn (org-end-of-subtree t) (point))))))
5163 ;;; Outline Sorting
5165 (defun org-sort (with-case)
5166 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5167 Optional argument WITH-CASE means sort case-sensitively."
5168 (interactive "P")
5169 (if (org-at-table-p)
5170 (org-call-with-arg 'org-table-sort-lines with-case)
5171 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5173 (defun org-sort-remove-invisible (s)
5174 (remove-text-properties 0 (length s) org-rm-props s)
5175 (while (string-match org-bracket-link-regexp s)
5176 (setq s (replace-match (if (match-end 2)
5177 (match-string 3 s)
5178 (match-string 1 s)) t t s)))
5181 (defvar org-priority-regexp) ; defined later in the file
5183 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5184 "Sort entries on a certain level of an outline tree.
5185 If there is an active region, the entries in the region are sorted.
5186 Else, if the cursor is before the first entry, sort the top-level items.
5187 Else, the children of the entry at point are sorted.
5189 Sorting can be alphabetically, numerically, and by date/time as given by
5190 the first time stamp in the entry. The command prompts for the sorting
5191 type unless it has been given to the function through the SORTING-TYPE
5192 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5193 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5194 called with point at the beginning of the record. It must return either
5195 a string or a number that should serve as the sorting key for that record.
5197 Comparing entries ignores case by default. However, with an optional argument
5198 WITH-CASE, the sorting considers case as well."
5199 (interactive "P")
5200 (let ((case-func (if with-case 'identity 'downcase))
5201 start beg end stars re re2
5202 txt what tmp plain-list-p)
5203 ;; Find beginning and end of region to sort
5204 (cond
5205 ((org-region-active-p)
5206 ;; we will sort the region
5207 (setq end (region-end)
5208 what "region")
5209 (goto-char (region-beginning))
5210 (if (not (org-on-heading-p)) (outline-next-heading))
5211 (setq start (point)))
5212 ((org-at-item-p)
5213 ;; we will sort this plain list
5214 (org-beginning-of-item-list) (setq start (point))
5215 (org-end-of-item-list) (setq end (point))
5216 (goto-char start)
5217 (setq plain-list-p t
5218 what "plain list"))
5219 ((or (org-on-heading-p)
5220 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5221 ;; we will sort the children of the current headline
5222 (org-back-to-heading)
5223 (setq start (point)
5224 end (progn (org-end-of-subtree t t)
5225 (org-back-over-empty-lines)
5226 (point))
5227 what "children")
5228 (goto-char start)
5229 (show-subtree)
5230 (outline-next-heading))
5232 ;; we will sort the top-level entries in this file
5233 (goto-char (point-min))
5234 (or (org-on-heading-p) (outline-next-heading))
5235 (setq start (point) end (point-max) what "top-level")
5236 (goto-char start)
5237 (show-all)))
5239 (setq beg (point))
5240 (if (>= beg end) (error "Nothing to sort"))
5242 (unless plain-list-p
5243 (looking-at "\\(\\*+\\)")
5244 (setq stars (match-string 1)
5245 re (concat "^" (regexp-quote stars) " +")
5246 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5247 txt (buffer-substring beg end))
5248 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5249 (if (and (not (equal stars "*")) (string-match re2 txt))
5250 (error "Region to sort contains a level above the first entry")))
5252 (unless sorting-type
5253 (message
5254 (if plain-list-p
5255 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5256 "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:")
5257 what)
5258 (setq sorting-type (read-char-exclusive))
5260 (and (= (downcase sorting-type) ?f)
5261 (setq getkey-func
5262 (completing-read "Sort using function: "
5263 obarray 'fboundp t nil nil))
5264 (setq getkey-func (intern getkey-func)))
5266 (and (= (downcase sorting-type) ?r)
5267 (setq property
5268 (completing-read "Property: "
5269 (mapcar 'list (org-buffer-property-keys t))
5270 nil t))))
5272 (message "Sorting entries...")
5274 (save-restriction
5275 (narrow-to-region start end)
5277 (let ((dcst (downcase sorting-type))
5278 (now (current-time)))
5279 (sort-subr
5280 (/= dcst sorting-type)
5281 ;; This function moves to the beginning character of the "record" to
5282 ;; be sorted.
5283 (if plain-list-p
5284 (lambda nil
5285 (if (org-at-item-p) t (goto-char (point-max))))
5286 (lambda nil
5287 (if (re-search-forward re nil t)
5288 (goto-char (match-beginning 0))
5289 (goto-char (point-max)))))
5290 ;; This function moves to the last character of the "record" being
5291 ;; sorted.
5292 (if plain-list-p
5293 'org-end-of-item
5294 (lambda nil
5295 (save-match-data
5296 (condition-case nil
5297 (outline-forward-same-level 1)
5298 (error
5299 (goto-char (point-max)))))))
5301 ;; This function returns the value that gets sorted against.
5302 (if plain-list-p
5303 (lambda nil
5304 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5305 (cond
5306 ((= dcst ?n)
5307 (string-to-number (buffer-substring (match-end 0)
5308 (point-at-eol))))
5309 ((= dcst ?a)
5310 (buffer-substring (match-end 0) (point-at-eol)))
5311 ((= dcst ?t)
5312 (if (re-search-forward org-ts-regexp
5313 (point-at-eol) t)
5314 (org-time-string-to-time (match-string 0))
5315 now))
5316 ((= dcst ?f)
5317 (if getkey-func
5318 (progn
5319 (setq tmp (funcall getkey-func))
5320 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5321 tmp)
5322 (error "Invalid key function `%s'" getkey-func)))
5323 (t (error "Invalid sorting type `%c'" sorting-type)))))
5324 (lambda nil
5325 (cond
5326 ((= dcst ?n)
5327 (if (looking-at org-complex-heading-regexp)
5328 (string-to-number (match-string 4))
5329 nil))
5330 ((= dcst ?a)
5331 (if (looking-at org-complex-heading-regexp)
5332 (funcall case-func (match-string 4))
5333 nil))
5334 ((= dcst ?t)
5335 (if (re-search-forward org-ts-regexp
5336 (save-excursion
5337 (forward-line 2)
5338 (point)) t)
5339 (org-time-string-to-time (match-string 0))
5340 now))
5341 ((= dcst ?p)
5342 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5343 (string-to-char (match-string 2))
5344 org-default-priority))
5345 ((= dcst ?r)
5346 (or (org-entry-get nil property) ""))
5347 ((= dcst ?o)
5348 (if (looking-at org-complex-heading-regexp)
5349 (- 9999 (length (member (match-string 2)
5350 org-todo-keywords-1)))))
5351 ((= dcst ?f)
5352 (if getkey-func
5353 (progn
5354 (setq tmp (funcall getkey-func))
5355 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5356 tmp)
5357 (error "Invalid key function `%s'" getkey-func)))
5358 (t (error "Invalid sorting type `%c'" sorting-type)))))
5360 (cond
5361 ((= dcst ?a) 'string<)
5362 ((= dcst ?t) 'time-less-p)
5363 (t nil)))))
5364 (message "Sorting entries...done")))
5366 (defun org-do-sort (table what &optional with-case sorting-type)
5367 "Sort TABLE of WHAT according to SORTING-TYPE.
5368 The user will be prompted for the SORTING-TYPE if the call to this
5369 function does not specify it. WHAT is only for the prompt, to indicate
5370 what is being sorted. The sorting key will be extracted from
5371 the car of the elements of the table.
5372 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5373 (unless sorting-type
5374 (message
5375 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5376 what)
5377 (setq sorting-type (read-char-exclusive)))
5378 (let ((dcst (downcase sorting-type))
5379 extractfun comparefun)
5380 ;; Define the appropriate functions
5381 (cond
5382 ((= dcst ?n)
5383 (setq extractfun 'string-to-number
5384 comparefun (if (= dcst sorting-type) '< '>)))
5385 ((= dcst ?a)
5386 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5387 (lambda(x) (downcase (org-sort-remove-invisible x))))
5388 comparefun (if (= dcst sorting-type)
5389 'string<
5390 (lambda (a b) (and (not (string< a b))
5391 (not (string= a b)))))))
5392 ((= dcst ?t)
5393 (setq extractfun
5394 (lambda (x)
5395 (if (string-match org-ts-regexp x)
5396 (time-to-seconds
5397 (org-time-string-to-time (match-string 0 x)))
5399 comparefun (if (= dcst sorting-type) '< '>)))
5400 (t (error "Invalid sorting type `%c'" sorting-type)))
5402 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5403 table)
5404 (lambda (a b) (funcall comparefun (car a) (car b))))))
5406 ;;; Editing source examples
5408 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5409 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5410 (defvar org-edit-src-force-single-line nil)
5411 (defvar org-edit-src-from-org-mode nil)
5412 (defvar org-edit-src-picture nil)
5414 (define-minor-mode org-exit-edit-mode
5415 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5417 (defun org-edit-src-code ()
5418 "Edit the source code example at point.
5419 An indirect buffer is created, and that buffer is then narrowed to the
5420 example at point and switched to the correct language mode. When done,
5421 exit by killing the buffer with \\[org-edit-src-exit]."
5422 (interactive)
5423 (let ((line (org-current-line))
5424 (case-fold-search t)
5425 (msg (substitute-command-keys
5426 "Edit, then exit with C-c ' (C-c and single quote)"))
5427 (info (org-edit-src-find-region-and-lang))
5428 (org-mode-p (eq major-mode 'org-mode))
5429 beg end lang lang-f single)
5430 (if (not info)
5432 (setq beg (nth 0 info)
5433 end (nth 1 info)
5434 lang (nth 2 info)
5435 single (nth 3 info)
5436 lang-f (intern (concat lang "-mode")))
5437 (unless (functionp lang-f)
5438 (error "No such language mode: %s" lang-f))
5439 (goto-line line)
5440 (if (get-buffer "*Org Edit Src Example*")
5441 (kill-buffer "*Org Edit Src Example*"))
5442 (switch-to-buffer (make-indirect-buffer (current-buffer)
5443 "*Org Edit Src Example*"))
5444 (narrow-to-region beg end)
5445 (remove-text-properties beg end '(display nil invisible nil
5446 intangible nil))
5447 (let ((org-inhibit-startup t))
5448 (funcall lang-f))
5449 (set (make-local-variable 'org-edit-src-force-single-line) single)
5450 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5451 (when org-mode-p
5452 (goto-char (point-min))
5453 (while (re-search-forward "^," nil t)
5454 (replace-match "")))
5455 (goto-line line)
5456 (org-exit-edit-mode)
5457 (org-set-local 'header-line-format msg)
5458 (message "%s" msg)
5459 t)))
5461 (defun org-edit-fixed-width-region ()
5462 "Edit the fixed-width ascii drawing at point.
5463 This must be a region where each line starts with ca colon followed by
5464 a space character.
5465 An indirect buffer is created, and that buffer is then narrowed to the
5466 example at point and switched to artist-mode. When done,
5467 exit by killing the buffer with \\[org-edit-src-exit]."
5468 (interactive)
5469 (let ((line (org-current-line))
5470 (case-fold-search t)
5471 (msg (substitute-command-keys
5472 "Edit, then exit with C-c ' (C-c and single quote)"))
5473 (org-mode-p (eq major-mode 'org-mode))
5474 beg end lang lang-f)
5475 (beginning-of-line 1)
5476 (if (looking-at "[ \t]*[^:\n \t]")
5478 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5479 (setq beg (point) end (match-end 0))
5480 (save-excursion
5481 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5482 (setq beg (point-at-bol 2))
5483 (setq beg (point))))
5484 (save-excursion
5485 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5486 (setq end (match-beginning 0))
5487 (setq end (point))))
5488 (goto-line line)
5489 (if (get-buffer "*Org Edit Picture*")
5490 (kill-buffer "*Org Edit Picture*"))
5491 (switch-to-buffer (make-indirect-buffer (current-buffer)
5492 "*Org Edit Picture*"))
5493 (narrow-to-region beg end)
5494 (remove-text-properties beg end '(display nil invisible nil
5495 intangible nil))
5496 (when (fboundp 'font-lock-unfontify-region)
5497 (font-lock-unfontify-region (point-min) (point-max)))
5498 (cond
5499 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5500 (fundamental-mode)
5501 (artist-mode 1))
5502 (t (funcall org-edit-fixed-width-region-mode)))
5503 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5504 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5505 (set (make-local-variable 'org-edit-src-picture) t)
5506 (goto-char (point-min))
5507 (while (re-search-forward "^[ \t]*: " nil t)
5508 (replace-match ""))
5509 (goto-line line)
5510 (org-exit-edit-mode)
5511 (org-set-local 'header-line-format msg)
5512 (message "%s" msg)
5513 t))))
5516 (defun org-edit-src-find-region-and-lang ()
5517 "Find the region and language for a local edit.
5518 Return a list with beginning and end of the region, a string representing
5519 the language, a switch telling of the content should be in a single line."
5520 (let ((re-list
5521 (append
5522 org-edit-src-region-extra
5524 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5525 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5526 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5527 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5528 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5529 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5530 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5531 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5532 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5533 ("^#\\+html:" "\n" "html" single-line)
5534 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5535 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5536 ("^#\\+latex:" "\n" "latex" single-line)
5537 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5538 ("^#\\+ascii:" "\n" "ascii" single-line)
5540 (pos (point))
5541 re re1 re2 single beg end lang)
5542 (catch 'exit
5543 (while (setq entry (pop re-list))
5544 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5545 single (nth 3 entry))
5546 (save-excursion
5547 (if (or (looking-at re1)
5548 (re-search-backward re1 nil t))
5549 (progn
5550 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5551 (if (and (re-search-forward re2 nil t)
5552 (>= (match-end 0) pos))
5553 (throw 'exit (list beg (match-beginning 0) lang single))))
5554 (if (or (looking-at re2)
5555 (re-search-forward re2 nil t))
5556 (progn
5557 (setq end (match-beginning 0))
5558 (if (and (re-search-backward re1 nil t)
5559 (<= (match-beginning 0) pos))
5560 (throw 'exit
5561 (list (match-end 0) end
5562 (org-edit-src-get-lang lang) single)))))))))))
5564 (defun org-edit-src-get-lang (lang)
5565 "Extract the src language."
5566 (let ((m (match-string 0)))
5567 (cond
5568 ((stringp lang) lang)
5569 ((integerp lang) (match-string lang))
5570 ((and (eq lang 'lang)
5571 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5572 (match-string 1 m))
5573 ((and (eq lang 'style)
5574 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5575 (match-string 1 m))
5576 (t "fundamental"))))
5578 (defun org-edit-src-exit ()
5579 "Exit special edit and protect problematic lines."
5580 (interactive)
5581 (unless (buffer-base-buffer (current-buffer))
5582 (error "This is not an indirect buffer, something is wrong..."))
5583 (unless (> (point-min) 1)
5584 (error "This buffer is not narrowed, something is wrong..."))
5585 (goto-char (point-min))
5586 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5587 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5588 (when (org-bound-and-true-p org-edit-src-force-single-line)
5589 (goto-char (point-min))
5590 (while (re-search-forward "\n" nil t)
5591 (replace-match " "))
5592 (goto-char (point-min))
5593 (if (looking-at "\\s-*") (replace-match " "))
5594 (if (re-search-forward "\\s-+\\'" nil t)
5595 (replace-match "")))
5596 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5597 (goto-char (point-min))
5598 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5599 (replace-match ",\\1"))
5600 (when font-lock-mode
5601 (font-lock-unfontify-region (point-min) (point-max)))
5602 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5603 (when (org-bound-and-true-p org-edit-src-picture)
5604 (goto-char (point-min))
5605 (while (re-search-forward "^" nil t)
5606 (replace-match ": "))
5607 (when font-lock-mode
5608 (font-lock-unfontify-region (point-min) (point-max)))
5609 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5610 (kill-buffer (current-buffer))
5611 (and (org-mode-p) (org-restart-font-lock)))
5614 ;;; The orgstruct minor mode
5616 ;; Define a minor mode which can be used in other modes in order to
5617 ;; integrate the org-mode structure editing commands.
5619 ;; This is really a hack, because the org-mode structure commands use
5620 ;; keys which normally belong to the major mode. Here is how it
5621 ;; works: The minor mode defines all the keys necessary to operate the
5622 ;; structure commands, but wraps the commands into a function which
5623 ;; tests if the cursor is currently at a headline or a plain list
5624 ;; item. If that is the case, the structure command is used,
5625 ;; temporarily setting many Org-mode variables like regular
5626 ;; expressions for filling etc. However, when any of those keys is
5627 ;; used at a different location, function uses `key-binding' to look
5628 ;; up if the key has an associated command in another currently active
5629 ;; keymap (minor modes, major mode, global), and executes that
5630 ;; command. There might be problems if any of the keys is otherwise
5631 ;; used as a prefix key.
5633 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5634 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5635 ;; addresses this by checking explicitly for both bindings.
5637 (defvar orgstruct-mode-map (make-sparse-keymap)
5638 "Keymap for the minor `orgstruct-mode'.")
5640 (defvar org-local-vars nil
5641 "List of local variables, for use by `orgstruct-mode'")
5643 ;;;###autoload
5644 (define-minor-mode orgstruct-mode
5645 "Toggle the minor more `orgstruct-mode'.
5646 This mode is for using Org-mode structure commands in other modes.
5647 The following key behave as if Org-mode was active, if the cursor
5648 is on a headline, or on a plain list item (both in the definition
5649 of Org-mode).
5651 M-up Move entry/item up
5652 M-down Move entry/item down
5653 M-left Promote
5654 M-right Demote
5655 M-S-up Move entry/item up
5656 M-S-down Move entry/item down
5657 M-S-left Promote subtree
5658 M-S-right Demote subtree
5659 M-q Fill paragraph and items like in Org-mode
5660 C-c ^ Sort entries
5661 C-c - Cycle list bullet
5662 TAB Cycle item visibility
5663 M-RET Insert new heading/item
5664 S-M-RET Insert new TODO heading / Chekbox item
5665 C-c C-c Set tags / toggle checkbox"
5666 nil " OrgStruct" nil
5667 (org-load-modules-maybe)
5668 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5670 ;;;###autoload
5671 (defun turn-on-orgstruct ()
5672 "Unconditionally turn on `orgstruct-mode'."
5673 (orgstruct-mode 1))
5675 ;;;###autoload
5676 (defun turn-on-orgstruct++ ()
5677 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5678 In addition to setting orgstruct-mode, this also exports all indentation and
5679 autofilling variables from org-mode into the buffer. Note that turning
5680 off orgstruct-mode will *not* remove these additional settings."
5681 (orgstruct-mode 1)
5682 (let (var val)
5683 (mapc
5684 (lambda (x)
5685 (when (string-match
5686 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5687 (symbol-name (car x)))
5688 (setq var (car x) val (nth 1 x))
5689 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5690 org-local-vars)))
5692 (defun orgstruct-error ()
5693 "Error when there is no default binding for a structure key."
5694 (interactive)
5695 (error "This key has no function outside structure elements"))
5697 (defun orgstruct-setup ()
5698 "Setup orgstruct keymaps."
5699 (let ((nfunc 0)
5700 (bindings
5701 (list
5702 '([(meta up)] org-metaup)
5703 '([(meta down)] org-metadown)
5704 '([(meta left)] org-metaleft)
5705 '([(meta right)] org-metaright)
5706 '([(meta shift up)] org-shiftmetaup)
5707 '([(meta shift down)] org-shiftmetadown)
5708 '([(meta shift left)] org-shiftmetaleft)
5709 '([(meta shift right)] org-shiftmetaright)
5710 '([(shift up)] org-shiftup)
5711 '([(shift down)] org-shiftdown)
5712 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5713 '("\M-q" fill-paragraph)
5714 '("\C-c^" org-sort)
5715 '("\C-c-" org-cycle-list-bullet)))
5716 elt key fun cmd)
5717 (while (setq elt (pop bindings))
5718 (setq nfunc (1+ nfunc))
5719 (setq key (org-key (car elt))
5720 fun (nth 1 elt)
5721 cmd (orgstruct-make-binding fun nfunc key))
5722 (org-defkey orgstruct-mode-map key cmd))
5724 ;; Special treatment needed for TAB and RET
5725 (org-defkey orgstruct-mode-map [(tab)]
5726 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5727 (org-defkey orgstruct-mode-map "\C-i"
5728 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5730 (org-defkey orgstruct-mode-map "\M-\C-m"
5731 (orgstruct-make-binding 'org-insert-heading 105
5732 "\M-\C-m" [(meta return)]))
5733 (org-defkey orgstruct-mode-map [(meta return)]
5734 (orgstruct-make-binding 'org-insert-heading 106
5735 [(meta return)] "\M-\C-m"))
5737 (org-defkey orgstruct-mode-map [(shift meta return)]
5738 (orgstruct-make-binding 'org-insert-todo-heading 107
5739 [(meta return)] "\M-\C-m"))
5741 (unless org-local-vars
5742 (setq org-local-vars (org-get-local-variables)))
5746 (defun orgstruct-make-binding (fun n &rest keys)
5747 "Create a function for binding in the structure minor mode.
5748 FUN is the command to call inside a table. N is used to create a unique
5749 command name. KEYS are keys that should be checked in for a command
5750 to execute outside of tables."
5751 (eval
5752 (list 'defun
5753 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5754 '(arg)
5755 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5756 "Outside of structure, run the binding of `"
5757 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5758 "'.")
5759 '(interactive "p")
5760 (list 'if
5761 '(org-context-p 'headline 'item)
5762 (list 'org-run-like-in-org-mode (list 'quote fun))
5763 (list 'let '(orgstruct-mode)
5764 (list 'call-interactively
5765 (append '(or)
5766 (mapcar (lambda (k)
5767 (list 'key-binding k))
5768 keys)
5769 '('orgstruct-error))))))))
5771 (defun org-context-p (&rest contexts)
5772 "Check if local context is any of CONTEXTS.
5773 Possible values in the list of contexts are `table', `headline', and `item'."
5774 (let ((pos (point)))
5775 (goto-char (point-at-bol))
5776 (prog1 (or (and (memq 'table contexts)
5777 (looking-at "[ \t]*|"))
5778 (and (memq 'headline contexts)
5779 ;;????????? (looking-at "\\*+"))
5780 (looking-at outline-regexp))
5781 (and (memq 'item contexts)
5782 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5783 (goto-char pos))))
5785 (defun org-get-local-variables ()
5786 "Return a list of all local variables in an org-mode buffer."
5787 (let (varlist)
5788 (with-current-buffer (get-buffer-create "*Org tmp*")
5789 (erase-buffer)
5790 (org-mode)
5791 (setq varlist (buffer-local-variables)))
5792 (kill-buffer "*Org tmp*")
5793 (delq nil
5794 (mapcar
5795 (lambda (x)
5796 (setq x
5797 (if (symbolp x)
5798 (list x)
5799 (list (car x) (list 'quote (cdr x)))))
5800 (if (string-match
5801 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5802 (symbol-name (car x)))
5803 x nil))
5804 varlist))))
5806 ;;;###autoload
5807 (defun org-run-like-in-org-mode (cmd)
5808 (org-load-modules-maybe)
5809 (unless org-local-vars
5810 (setq org-local-vars (org-get-local-variables)))
5811 (eval (list 'let org-local-vars
5812 (list 'call-interactively (list 'quote cmd)))))
5814 ;;;; Archiving
5816 (defun org-get-category (&optional pos)
5817 "Get the category applying to position POS."
5818 (get-text-property (or pos (point)) 'org-category))
5820 (defun org-refresh-category-properties ()
5821 "Refresh category text properties in the buffer."
5822 (let ((def-cat (cond
5823 ((null org-category)
5824 (if buffer-file-name
5825 (file-name-sans-extension
5826 (file-name-nondirectory buffer-file-name))
5827 "???"))
5828 ((symbolp org-category) (symbol-name org-category))
5829 (t org-category)))
5830 beg end cat pos optionp)
5831 (org-unmodified
5832 (save-excursion
5833 (save-restriction
5834 (widen)
5835 (goto-char (point-min))
5836 (put-text-property (point) (point-max) 'org-category def-cat)
5837 (while (re-search-forward
5838 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5839 (setq pos (match-end 0)
5840 optionp (equal (char-after (match-beginning 0)) ?#)
5841 cat (org-trim (match-string 2)))
5842 (if optionp
5843 (setq beg (point-at-bol) end (point-max))
5844 (org-back-to-heading t)
5845 (setq beg (point) end (org-end-of-subtree t t)))
5846 (put-text-property beg end 'org-category cat)
5847 (goto-char pos)))))))
5850 ;;;; Link Stuff
5852 ;;; Link abbreviations
5854 (defun org-link-expand-abbrev (link)
5855 "Apply replacements as defined in `org-link-abbrev-alist."
5856 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5857 (let* ((key (match-string 1 link))
5858 (as (or (assoc key org-link-abbrev-alist-local)
5859 (assoc key org-link-abbrev-alist)))
5860 (tag (and (match-end 2) (match-string 3 link)))
5861 rpl)
5862 (if (not as)
5863 link
5864 (setq rpl (cdr as))
5865 (cond
5866 ((symbolp rpl) (funcall rpl tag))
5867 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5868 (t (concat rpl tag)))))
5869 link))
5871 ;;; Storing and inserting links
5873 (defvar org-insert-link-history nil
5874 "Minibuffer history for links inserted with `org-insert-link'.")
5876 (defvar org-stored-links nil
5877 "Contains the links stored with `org-store-link'.")
5879 (defvar org-store-link-plist nil
5880 "Plist with info about the most recently link created with `org-store-link'.")
5882 (defvar org-link-protocols nil
5883 "Link protocols added to Org-mode using `org-add-link-type'.")
5885 (defvar org-store-link-functions nil
5886 "List of functions that are called to create and store a link.
5887 Each function will be called in turn until one returns a non-nil
5888 value. Each function should check if it is responsible for creating
5889 this link (for example by looking at the major mode).
5890 If not, it must exit and return nil.
5891 If yes, it should return a non-nil value after a calling
5892 `org-store-link-props' with a list of properties and values.
5893 Special properties are:
5895 :type The link prefix. like \"http\". This must be given.
5896 :link The link, like \"http://www.astro.uva.nl/~dominik\".
5897 This is obligatory as well.
5898 :description Optional default description for the second pair
5899 of brackets in an Org-mode link. The user can still change
5900 this when inserting this link into an Org-mode buffer.
5902 In addition to these, any additional properties can be specified
5903 and then used in remember templates.")
5905 (defun org-add-link-type (type &optional follow export)
5906 "Add TYPE to the list of `org-link-types'.
5907 Re-compute all regular expressions depending on `org-link-types'
5909 FOLLOW and EXPORT are two functions.
5911 FOLLOW should take the link path as the single argument and do whatever
5912 is necessary to follow the link, for example find a file or display
5913 a mail message.
5915 EXPORT should format the link path for export to one of the export formats.
5916 It should be a function accepting three arguments:
5918 path the path of the link, the text after the prefix (like \"http:\")
5919 desc the description of the link, if any, nil if there was no descripton
5920 format the export format, a symbol like `html' or `latex'.
5922 The function may use the FORMAT information to return different values
5923 depending on the format. The return value will be put literally into
5924 the exported file.
5925 Org-mode has a built-in default for exporting links. If you are happy with
5926 this default, there is no need to define an export function for the link
5927 type. For a simple example of an export function, see `org-bbdb.el'."
5928 (add-to-list 'org-link-types type t)
5929 (org-make-link-regexps)
5930 (if (assoc type org-link-protocols)
5931 (setcdr (assoc type org-link-protocols) (list follow export))
5932 (push (list type follow export) org-link-protocols)))
5935 ;;;###autoload
5936 (defun org-store-link (arg)
5937 "\\<org-mode-map>Store an org-link to the current location.
5938 This link is added to `org-stored-links' and can later be inserted
5939 into an org-buffer with \\[org-insert-link].
5941 For some link types, a prefix arg is interpreted:
5942 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5943 For file links, arg negates `org-context-in-file-links'."
5944 (interactive "P")
5945 (org-load-modules-maybe)
5946 (setq org-store-link-plist nil) ; reset
5947 (let (link cpltxt desc description search txt)
5948 (cond
5950 ((run-hook-with-args-until-success 'org-store-link-functions)
5951 (setq link (plist-get org-store-link-plist :link)
5952 desc (or (plist-get org-store-link-plist :description) link)))
5954 ((eq major-mode 'calendar-mode)
5955 (let ((cd (calendar-cursor-to-date)))
5956 (setq link
5957 (format-time-string
5958 (car org-time-stamp-formats)
5959 (apply 'encode-time
5960 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5961 nil nil nil))))
5962 (org-store-link-props :type "calendar" :date cd)))
5964 ((eq major-mode 'w3-mode)
5965 (setq cpltxt (url-view-url t)
5966 link (org-make-link cpltxt))
5967 (org-store-link-props :type "w3" :url (url-view-url t)))
5969 ((eq major-mode 'w3m-mode)
5970 (setq cpltxt (or w3m-current-title w3m-current-url)
5971 link (org-make-link w3m-current-url))
5972 (org-store-link-props :type "w3m" :url (url-view-url t)))
5974 ((setq search (run-hook-with-args-until-success
5975 'org-create-file-search-functions))
5976 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
5977 "::" search))
5978 (setq cpltxt (or description link)))
5980 ((eq major-mode 'image-mode)
5981 (setq cpltxt (concat "file:"
5982 (abbreviate-file-name buffer-file-name))
5983 link (org-make-link cpltxt))
5984 (org-store-link-props :type "image" :file buffer-file-name))
5986 ((eq major-mode 'dired-mode)
5987 ;; link to the file in the current line
5988 (setq cpltxt (concat "file:"
5989 (abbreviate-file-name
5990 (expand-file-name
5991 (dired-get-filename nil t))))
5992 link (org-make-link cpltxt)))
5994 ((and buffer-file-name (org-mode-p))
5995 ;; Just link to current headline
5996 (setq cpltxt (concat "file:"
5997 (abbreviate-file-name buffer-file-name)))
5998 ;; Add a context search string
5999 (when (org-xor org-context-in-file-links arg)
6000 ;; Check if we are on a target
6001 (if (org-in-regexp "<<\\(.*?\\)>>")
6002 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6003 (setq txt (cond
6004 ((org-on-heading-p) nil)
6005 ((org-region-active-p)
6006 (buffer-substring (region-beginning) (region-end)))
6007 (t nil)))
6008 (when (or (null txt) (string-match "\\S-" txt))
6009 (setq cpltxt
6010 (concat cpltxt "::"
6011 (condition-case nil
6012 (org-make-org-heading-search-string txt)
6013 (error "")))
6014 desc "NONE"))))
6015 (if (string-match "::\\'" cpltxt)
6016 (setq cpltxt (substring cpltxt 0 -2)))
6017 (setq link (org-make-link cpltxt)))
6019 ((buffer-file-name (buffer-base-buffer))
6020 ;; Just link to this file here.
6021 (setq cpltxt (concat "file:"
6022 (abbreviate-file-name
6023 (buffer-file-name (buffer-base-buffer)))))
6024 ;; Add a context string
6025 (when (org-xor org-context-in-file-links arg)
6026 (setq txt (if (org-region-active-p)
6027 (buffer-substring (region-beginning) (region-end))
6028 (buffer-substring (point-at-bol) (point-at-eol))))
6029 ;; Only use search option if there is some text.
6030 (when (string-match "\\S-" txt)
6031 (setq cpltxt
6032 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6033 desc "NONE")))
6034 (setq link (org-make-link cpltxt)))
6036 ((interactive-p)
6037 (error "Cannot link to a buffer which is not visiting a file"))
6039 (t (setq link nil)))
6041 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6042 (setq link (or link cpltxt)
6043 desc (or desc cpltxt))
6044 (if (equal desc "NONE") (setq desc nil))
6046 (if (and (interactive-p) link)
6047 (progn
6048 (setq org-stored-links
6049 (cons (list link desc) org-stored-links))
6050 (message "Stored: %s" (or desc link)))
6051 (and link (org-make-link-string link desc)))))
6053 (defun org-store-link-props (&rest plist)
6054 "Store link properties, extract names and addresses."
6055 (let (x adr)
6056 (when (setq x (plist-get plist :from))
6057 (setq adr (mail-extract-address-components x))
6058 (plist-put plist :fromname (car adr))
6059 (plist-put plist :fromaddress (nth 1 adr)))
6060 (when (setq x (plist-get plist :to))
6061 (setq adr (mail-extract-address-components x))
6062 (plist-put plist :toname (car adr))
6063 (plist-put plist :toaddress (nth 1 adr))))
6064 (let ((from (plist-get plist :from))
6065 (to (plist-get plist :to)))
6066 (when (and from to org-from-is-user-regexp)
6067 (plist-put plist :fromto
6068 (if (string-match org-from-is-user-regexp from)
6069 (concat "to %t")
6070 (concat "from %f")))))
6071 (setq org-store-link-plist plist))
6073 (defun org-add-link-props (&rest plist)
6074 "Add these properties to the link property list."
6075 (let (key value)
6076 (while plist
6077 (setq key (pop plist) value (pop plist))
6078 (setq org-store-link-plist
6079 (plist-put org-store-link-plist key value)))))
6081 (defun org-email-link-description (&optional fmt)
6082 "Return the description part of an email link.
6083 This takes information from `org-store-link-plist' and formats it
6084 according to FMT (default from `org-email-link-description-format')."
6085 (setq fmt (or fmt org-email-link-description-format))
6086 (let* ((p org-store-link-plist)
6087 (to (plist-get p :toaddress))
6088 (from (plist-get p :fromaddress))
6089 (table
6090 (list
6091 (cons "%c" (plist-get p :fromto))
6092 (cons "%F" (plist-get p :from))
6093 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6094 (cons "%T" (plist-get p :to))
6095 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6096 (cons "%s" (plist-get p :subject))
6097 (cons "%m" (plist-get p :message-id)))))
6098 (when (string-match "%c" fmt)
6099 ;; Check if the user wrote this message
6100 (if (and org-from-is-user-regexp from to
6101 (save-match-data (string-match org-from-is-user-regexp from)))
6102 (setq fmt (replace-match "to %t" t t fmt))
6103 (setq fmt (replace-match "from %f" t t fmt))))
6104 (org-replace-escapes fmt table)))
6106 (defun org-make-org-heading-search-string (&optional string heading)
6107 "Make search string for STRING or current headline."
6108 (interactive)
6109 (let ((s (or string (org-get-heading))))
6110 (unless (and string (not heading))
6111 ;; We are using a headline, clean up garbage in there.
6112 (if (string-match org-todo-regexp s)
6113 (setq s (replace-match "" t t s)))
6114 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6115 (setq s (replace-match "" t t s)))
6116 (setq s (org-trim s))
6117 (if (string-match (concat "^\\(" org-quote-string "\\|"
6118 org-comment-string "\\)") s)
6119 (setq s (replace-match "" t t s)))
6120 (while (string-match org-ts-regexp s)
6121 (setq s (replace-match "" t t s))))
6122 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6123 (setq s (replace-match " " t t s)))
6124 (or string (setq s (concat "*" s))) ; Add * for headlines
6125 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6127 (defun org-make-link (&rest strings)
6128 "Concatenate STRINGS."
6129 (apply 'concat strings))
6131 (defun org-make-link-string (link &optional description)
6132 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6133 (unless (string-match "\\S-" link)
6134 (error "Empty link"))
6135 (when (stringp description)
6136 ;; Remove brackets from the description, they are fatal.
6137 (while (string-match "\\[" description)
6138 (setq description (replace-match "{" t t description)))
6139 (while (string-match "\\]" description)
6140 (setq description (replace-match "}" t t description))))
6141 (when (equal (org-link-escape link) description)
6142 ;; No description needed, it is identical
6143 (setq description nil))
6144 (when (and (not description)
6145 (not (equal link (org-link-escape link))))
6146 (setq description (org-extract-attributes link)))
6147 (concat "[[" (org-link-escape link) "]"
6148 (if description (concat "[" description "]") "")
6149 "]"))
6151 (defconst org-link-escape-chars
6152 '((?\ . "%20")
6153 (?\[ . "%5B")
6154 (?\] . "%5D")
6155 (?\340 . "%E0") ; `a
6156 (?\342 . "%E2") ; ^a
6157 (?\347 . "%E7") ; ,c
6158 (?\350 . "%E8") ; `e
6159 (?\351 . "%E9") ; 'e
6160 (?\352 . "%EA") ; ^e
6161 (?\356 . "%EE") ; ^i
6162 (?\364 . "%F4") ; ^o
6163 (?\371 . "%F9") ; `u
6164 (?\373 . "%FB") ; ^u
6165 (?\; . "%3B")
6166 (?? . "%3F")
6167 (?= . "%3D")
6168 (?+ . "%2B")
6170 "Association list of escapes for some characters problematic in links.
6171 This is the list that is used for internal purposes.")
6173 (defconst org-link-escape-chars-browser
6174 '((?\ . "%20")) ; 32 for the SPC char
6175 "Association list of escapes for some characters problematic in links.
6176 This is the list that is used before handing over to the browser.")
6178 (defun org-link-escape (text &optional table)
6179 "Escape charaters in TEXT that are problematic for links."
6180 (setq table (or table org-link-escape-chars))
6181 (when text
6182 (let ((re (mapconcat (lambda (x) (regexp-quote
6183 (char-to-string (car x))))
6184 table "\\|")))
6185 (while (string-match re text)
6186 (setq text
6187 (replace-match
6188 (cdr (assoc (string-to-char (match-string 0 text))
6189 table))
6190 t t text)))
6191 text)))
6193 (defun org-link-unescape (text &optional table)
6194 "Reverse the action of `org-link-escape'."
6195 (setq table (or table org-link-escape-chars))
6196 (when text
6197 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6198 table "\\|")))
6199 (while (string-match re text)
6200 (setq text
6201 (replace-match
6202 (char-to-string (car (rassoc (match-string 0 text) table)))
6203 t t text)))
6204 text)))
6206 (defun org-xor (a b)
6207 "Exclusive or."
6208 (if a (not b) b))
6210 (defun org-get-header (header)
6211 "Find a header field in the current buffer."
6212 (save-excursion
6213 (goto-char (point-min))
6214 (let ((case-fold-search t) s)
6215 (cond
6216 ((eq header 'from)
6217 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6218 (setq s (match-string 1)))
6219 (while (string-match "\"" s)
6220 (setq s (replace-match "" t t s)))
6221 (if (string-match "[<(].*" s)
6222 (setq s (replace-match "" t t s))))
6223 ((eq header 'message-id)
6224 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6225 (setq s (match-string 1))))
6226 ((eq header 'subject)
6227 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6228 (setq s (match-string 1)))))
6229 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6230 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6231 s)))
6234 (defun org-fixup-message-id-for-http (s)
6235 "Replace special characters in a message id, so it can be used in an http query."
6236 (while (string-match "<" s)
6237 (setq s (replace-match "%3C" t t s)))
6238 (while (string-match ">" s)
6239 (setq s (replace-match "%3E" t t s)))
6240 (while (string-match "@" s)
6241 (setq s (replace-match "%40" t t s)))
6244 ;;;###autoload
6245 (defun org-insert-link-global ()
6246 "Insert a link like Org-mode does.
6247 This command can be called in any mode to insert a link in Org-mode syntax."
6248 (interactive)
6249 (org-load-modules-maybe)
6250 (org-run-like-in-org-mode 'org-insert-link))
6252 (defun org-insert-link (&optional complete-file link-location)
6253 "Insert a link. At the prompt, enter the link.
6255 Completion can be used to select a link previously stored with
6256 `org-store-link'. When the empty string is entered (i.e. if you just
6257 press RET at the prompt), the link defaults to the most recently
6258 stored link. As SPC triggers completion in the minibuffer, you need to
6259 use M-SPC or C-q SPC to force the insertion of a space character.
6261 You will also be prompted for a description, and if one is given, it will
6262 be displayed in the buffer instead of the link.
6264 If there is already a link at point, this command will allow you to edit link
6265 and description parts.
6267 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6268 be selected using completion. The path to the file will be relative to the
6269 current directory if the file is in the current directory or a subdirectory.
6270 Otherwise, the link will be the absolute path as completed in the minibuffer
6271 \(i.e. normally ~/path/to/file).
6273 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6274 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6275 of `org-keep-stored-link-after-insertion'.
6277 If `org-make-link-description-function' is non-nil, this function will be
6278 called with the link target, and the result will be the default
6279 link description.
6281 If the LINK-LOCATION parameter is non-nil, this value will be
6282 used as the link location instead of reading one interactively."
6283 (interactive "P")
6284 (let* ((wcf (current-window-configuration))
6285 (region (if (org-region-active-p)
6286 (buffer-substring (region-beginning) (region-end))))
6287 (remove (and region (list (region-beginning) (region-end))))
6288 (desc region)
6289 tmphist ; byte-compile incorrectly complains about this
6290 (link link-location)
6291 entry file)
6292 (cond
6293 (link-location) ; specified by arg, just use it.
6294 ((org-in-regexp org-bracket-link-regexp 1)
6295 ;; We do have a link at point, and we are going to edit it.
6296 (setq remove (list (match-beginning 0) (match-end 0)))
6297 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6298 (setq link (read-string "Link: "
6299 (org-link-unescape
6300 (org-match-string-no-properties 1)))))
6301 ((or (org-in-regexp org-angle-link-re)
6302 (org-in-regexp org-plain-link-re))
6303 ;; Convert to bracket link
6304 (setq remove (list (match-beginning 0) (match-end 0))
6305 link (read-string "Link: "
6306 (org-remove-angle-brackets (match-string 0)))))
6307 ((equal complete-file '(4))
6308 ;; Completing read for file names.
6309 (setq file (read-file-name "File: "))
6310 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6311 (pwd1 (file-name-as-directory (abbreviate-file-name
6312 (expand-file-name ".")))))
6313 (cond
6314 ((equal complete-file '(16))
6315 (setq link (org-make-link
6316 "file:"
6317 (abbreviate-file-name (expand-file-name file)))))
6318 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6319 (setq link (org-make-link "file:" (match-string 1 file))))
6320 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6321 (expand-file-name file))
6322 (setq link (org-make-link
6323 "file:" (match-string 1 (expand-file-name file)))))
6324 (t (setq link (org-make-link "file:" file))))))
6326 ;; Read link, with completion for stored links.
6327 (with-output-to-temp-buffer "*Org Links*"
6328 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6329 (when org-stored-links
6330 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6331 (princ (mapconcat
6332 (lambda (x)
6333 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6334 (reverse org-stored-links) "\n"))))
6335 (let ((cw (selected-window)))
6336 (select-window (get-buffer-window "*Org Links*"))
6337 (shrink-window-if-larger-than-buffer)
6338 (setq truncate-lines t)
6339 (select-window cw))
6340 ;; Fake a link history, containing the stored links.
6341 (setq tmphist (append (mapcar 'car org-stored-links)
6342 org-insert-link-history))
6343 (unwind-protect
6344 (setq link (org-completing-read
6345 "Link: "
6346 (append
6347 (mapcar (lambda (x) (list (concat (car x) ":")))
6348 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6349 (mapcar (lambda (x) (list (concat x ":")))
6350 org-link-types))
6351 nil nil nil
6352 'tmphist
6353 (or (car (car org-stored-links)))))
6354 (set-window-configuration wcf)
6355 (kill-buffer "*Org Links*"))
6356 (setq entry (assoc link org-stored-links))
6357 (or entry (push link org-insert-link-history))
6358 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6359 (not org-keep-stored-link-after-insertion))
6360 (setq org-stored-links (delq (assoc link org-stored-links)
6361 org-stored-links)))
6362 (setq desc (or desc (nth 1 entry)))))
6364 (if (string-match org-plain-link-re link)
6365 ;; URL-like link, normalize the use of angular brackets.
6366 (setq link (org-make-link (org-remove-angle-brackets link))))
6368 ;; Check if we are linking to the current file with a search option
6369 ;; If yes, simplify the link by using only the search option.
6370 (when (and buffer-file-name
6371 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6372 (let* ((path (match-string 1 link))
6373 (case-fold-search nil)
6374 (search (match-string 2 link)))
6375 (save-match-data
6376 (if (equal (file-truename buffer-file-name) (file-truename path))
6377 ;; We are linking to this same file, with a search option
6378 (setq link search)))))
6380 ;; Check if we can/should use a relative path. If yes, simplify the link
6381 (when (string-match "\\<file:\\(.*\\)" link)
6382 (let* ((path (match-string 1 link))
6383 (origpath path)
6384 (case-fold-search nil))
6385 (cond
6386 ((eq org-link-file-path-type 'absolute)
6387 (setq path (abbreviate-file-name (expand-file-name path))))
6388 ((eq org-link-file-path-type 'noabbrev)
6389 (setq path (expand-file-name path)))
6390 ((eq org-link-file-path-type 'relative)
6391 (setq path (file-relative-name path)))
6393 (save-match-data
6394 (if (string-match (concat "^" (regexp-quote
6395 (file-name-as-directory
6396 (expand-file-name "."))))
6397 (expand-file-name path))
6398 ;; We are linking a file with relative path name.
6399 (setq path (substring (expand-file-name path)
6400 (match-end 0)))))))
6401 (setq link (concat "file:" path))
6402 (if (equal desc origpath)
6403 (setq desc path))))
6405 (if org-make-link-description-function
6406 (setq desc (funcall org-make-link-description-function link desc)))
6408 (setq desc (read-string "Description: " desc))
6409 (unless (string-match "\\S-" desc) (setq desc nil))
6410 (if remove (apply 'delete-region remove))
6411 (insert (org-make-link-string link desc))))
6413 (defun org-completing-read (&rest args)
6414 (let ((minibuffer-local-completion-map
6415 (copy-keymap minibuffer-local-completion-map)))
6416 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6417 (apply 'completing-read args)))
6419 (defun org-extract-attributes (s)
6420 "Extract the attributes cookie from a string and set as text property."
6421 (let (a attr (start 0) key value)
6422 (save-match-data
6423 (when (string-match "{{\\([^}]+\\)}}$" s)
6424 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6425 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6426 (setq key (match-string 1 a) value (match-string 2 a)
6427 start (match-end 0)
6428 attr (plist-put attr (intern key) value))))
6429 (org-add-props s nil 'org-attributes attr))
6432 (defun org-attributes-to-string (plist)
6433 "Format a property list into an HTML attribute list."
6434 (let ((s "") key value)
6435 (while plist
6436 (setq key (pop plist) value (pop plist))
6437 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6440 ;;; Opening/following a link
6442 (defvar org-link-search-failed nil)
6444 (defun org-next-link ()
6445 "Move forward to the next link.
6446 If the link is in hidden text, expose it."
6447 (interactive)
6448 (when (and org-link-search-failed (eq this-command last-command))
6449 (goto-char (point-min))
6450 (message "Link search wrapped back to beginning of buffer"))
6451 (setq org-link-search-failed nil)
6452 (let* ((pos (point))
6453 (ct (org-context))
6454 (a (assoc :link ct)))
6455 (if a (goto-char (nth 2 a)))
6456 (if (re-search-forward org-any-link-re nil t)
6457 (progn
6458 (goto-char (match-beginning 0))
6459 (if (org-invisible-p) (org-show-context)))
6460 (goto-char pos)
6461 (setq org-link-search-failed t)
6462 (error "No further link found"))))
6464 (defun org-previous-link ()
6465 "Move backward to the previous link.
6466 If the link is in hidden text, expose it."
6467 (interactive)
6468 (when (and org-link-search-failed (eq this-command last-command))
6469 (goto-char (point-max))
6470 (message "Link search wrapped back to end of buffer"))
6471 (setq org-link-search-failed nil)
6472 (let* ((pos (point))
6473 (ct (org-context))
6474 (a (assoc :link ct)))
6475 (if a (goto-char (nth 1 a)))
6476 (if (re-search-backward org-any-link-re nil t)
6477 (progn
6478 (goto-char (match-beginning 0))
6479 (if (org-invisible-p) (org-show-context)))
6480 (goto-char pos)
6481 (setq org-link-search-failed t)
6482 (error "No further link found"))))
6484 (defun org-find-file-at-mouse (ev)
6485 "Open file link or URL at mouse."
6486 (interactive "e")
6487 (mouse-set-point ev)
6488 (org-open-at-point 'in-emacs))
6490 (defun org-open-at-mouse (ev)
6491 "Open file link or URL at mouse."
6492 (interactive "e")
6493 (mouse-set-point ev)
6494 (org-open-at-point))
6496 (defvar org-window-config-before-follow-link nil
6497 "The window configuration before following a link.
6498 This is saved in case the need arises to restore it.")
6500 (defvar org-open-link-marker (make-marker)
6501 "Marker pointing to the location where `org-open-at-point; was called.")
6503 ;;;###autoload
6504 (defun org-open-at-point-global ()
6505 "Follow a link like Org-mode does.
6506 This command can be called in any mode to follow a link that has
6507 Org-mode syntax."
6508 (interactive)
6509 (org-run-like-in-org-mode 'org-open-at-point))
6511 ;;;###autoload
6512 (defun org-open-link-from-string (s &optional arg)
6513 "Open a link in the string S, as if it was in Org-mode."
6514 (interactive "sLink: \nP")
6515 (with-temp-buffer
6516 (let ((org-inhibit-startup t))
6517 (org-mode)
6518 (insert s)
6519 (goto-char (point-min))
6520 (org-open-at-point arg))))
6522 (defun org-open-at-point (&optional in-emacs)
6523 "Open link at or after point.
6524 If there is no link at point, this function will search forward up to
6525 the end of the current subtree.
6526 Normally, files will be opened by an appropriate application. If the
6527 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6528 (interactive "P")
6529 (org-load-modules-maybe)
6530 (move-marker org-open-link-marker (point))
6531 (setq org-window-config-before-follow-link (current-window-configuration))
6532 (org-remove-occur-highlights nil nil t)
6533 (if (org-at-timestamp-p t)
6534 (org-follow-timestamp-link)
6535 (let (type path link line search (pos (point)))
6536 (catch 'match
6537 (save-excursion
6538 (skip-chars-forward "^]\n\r")
6539 (when (org-in-regexp org-bracket-link-regexp)
6540 (setq link (org-extract-attributes
6541 (org-link-unescape (org-match-string-no-properties 1))))
6542 (while (string-match " *\n *" link)
6543 (setq link (replace-match " " t t link)))
6544 (setq link (org-link-expand-abbrev link))
6545 (cond
6546 ((or (file-name-absolute-p link)
6547 (string-match "^\\.\\.?/" link))
6548 (setq type "file" path link))
6549 ((string-match org-link-re-with-space2 link)
6550 (setq type (match-string 1 link) path (match-string 2 link)))
6551 (t (setq type "thisfile" path link)))
6552 (throw 'match t)))
6554 (when (get-text-property (point) 'org-linked-text)
6555 (setq type "thisfile"
6556 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6557 (1+ (point)) (point))
6558 path (buffer-substring
6559 (previous-single-property-change pos 'org-linked-text)
6560 (next-single-property-change pos 'org-linked-text)))
6561 (throw 'match t))
6563 (save-excursion
6564 (when (or (org-in-regexp org-angle-link-re)
6565 (org-in-regexp org-plain-link-re))
6566 (setq type (match-string 1) path (match-string 2))
6567 (throw 'match t)))
6568 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6569 (setq type "tree-match"
6570 path (match-string 1))
6571 (throw 'match t))
6572 (save-excursion
6573 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6574 (setq type "tags"
6575 path (match-string 1))
6576 (while (string-match ":" path)
6577 (setq path (replace-match "+" t t path)))
6578 (throw 'match t))))
6579 (unless path
6580 (error "No link found"))
6581 ;; Remove any trailing spaces in path
6582 (if (string-match " +\\'" path)
6583 (setq path (replace-match "" t t path)))
6585 (cond
6587 ((assoc type org-link-protocols)
6588 (funcall (nth 1 (assoc type org-link-protocols)) path))
6590 ((equal type "mailto")
6591 (let ((cmd (car org-link-mailto-program))
6592 (args (cdr org-link-mailto-program)) args1
6593 (address path) (subject "") a)
6594 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6595 (setq address (match-string 1 path)
6596 subject (org-link-escape (match-string 2 path))))
6597 (while args
6598 (cond
6599 ((not (stringp (car args))) (push (pop args) args1))
6600 (t (setq a (pop args))
6601 (if (string-match "%a" a)
6602 (setq a (replace-match address t t a)))
6603 (if (string-match "%s" a)
6604 (setq a (replace-match subject t t a)))
6605 (push a args1))))
6606 (apply cmd (nreverse args1))))
6608 ((member type '("http" "https" "ftp" "news"))
6609 (browse-url (concat type ":" (org-link-escape
6610 path org-link-escape-chars-browser))))
6612 ((member type '("message"))
6613 (browse-url (concat type ":" path)))
6615 ((string= type "tags")
6616 (org-tags-view in-emacs path))
6617 ((string= type "thisfile")
6618 (if in-emacs
6619 (switch-to-buffer-other-window
6620 (org-get-buffer-for-internal-link (current-buffer)))
6621 (org-mark-ring-push))
6622 (let ((cmd `(org-link-search
6623 ,path
6624 ,(cond ((equal in-emacs '(4)) 'occur)
6625 ((equal in-emacs '(16)) 'org-occur)
6626 (t nil))
6627 ,pos)))
6628 (condition-case nil (eval cmd)
6629 (error (progn (widen) (eval cmd))))))
6631 ((string= type "tree-match")
6632 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6634 ((string= type "file")
6635 (if (string-match "::\\([0-9]+\\)\\'" path)
6636 (setq line (string-to-number (match-string 1 path))
6637 path (substring path 0 (match-beginning 0)))
6638 (if (string-match "::\\(.+\\)\\'" path)
6639 (setq search (match-string 1 path)
6640 path (substring path 0 (match-beginning 0)))))
6641 (if (string-match "[*?{]" (file-name-nondirectory path))
6642 (dired path)
6643 (org-open-file path in-emacs line search)))
6645 ((string= type "news")
6646 (require 'org-gnus)
6647 (org-gnus-follow-link path))
6649 ((string= type "shell")
6650 (let ((cmd path))
6651 (if (or (not org-confirm-shell-link-function)
6652 (funcall org-confirm-shell-link-function
6653 (format "Execute \"%s\" in shell? "
6654 (org-add-props cmd nil
6655 'face 'org-warning))))
6656 (progn
6657 (message "Executing %s" cmd)
6658 (shell-command cmd))
6659 (error "Abort"))))
6661 ((string= type "elisp")
6662 (let ((cmd path))
6663 (if (or (not org-confirm-elisp-link-function)
6664 (funcall org-confirm-elisp-link-function
6665 (format "Execute \"%s\" as elisp? "
6666 (org-add-props cmd nil
6667 'face 'org-warning))))
6668 (message "%s => %s" cmd (eval (read cmd)))
6669 (error "Abort"))))
6672 (browse-url-at-point)))))
6673 (move-marker org-open-link-marker nil)
6674 (run-hook-with-args 'org-follow-link-hook))
6676 ;;;; Time estimates
6678 (defun org-get-effort (&optional pom)
6679 "Get the effort estimate for the current entry."
6680 (org-entry-get pom org-effort-property))
6682 ;;; File search
6684 (defvar org-create-file-search-functions nil
6685 "List of functions to construct the right search string for a file link.
6686 These functions are called in turn with point at the location to
6687 which the link should point.
6689 A function in the hook should first test if it would like to
6690 handle this file type, for example by checking the major-mode or
6691 the file extension. If it decides not to handle this file, it
6692 should just return nil to give other functions a chance. If it
6693 does handle the file, it must return the search string to be used
6694 when following the link. The search string will be part of the
6695 file link, given after a double colon, and `org-open-at-point'
6696 will automatically search for it. If special measures must be
6697 taken to make the search successful, another function should be
6698 added to the companion hook `org-execute-file-search-functions',
6699 which see.
6701 A function in this hook may also use `setq' to set the variable
6702 `description' to provide a suggestion for the descriptive text to
6703 be used for this link when it gets inserted into an Org-mode
6704 buffer with \\[org-insert-link].")
6706 (defvar org-execute-file-search-functions nil
6707 "List of functions to execute a file search triggered by a link.
6709 Functions added to this hook must accept a single argument, the
6710 search string that was part of the file link, the part after the
6711 double colon. The function must first check if it would like to
6712 handle this search, for example by checking the major-mode or the
6713 file extension. If it decides not to handle this search, it
6714 should just return nil to give other functions a chance. If it
6715 does handle the search, it must return a non-nil value to keep
6716 other functions from trying.
6718 Each function can access the current prefix argument through the
6719 variable `current-prefix-argument'. Note that a single prefix is
6720 used to force opening a link in Emacs, so it may be good to only
6721 use a numeric or double prefix to guide the search function.
6723 In case this is needed, a function in this hook can also restore
6724 the window configuration before `org-open-at-point' was called using:
6726 (set-window-configuration org-window-config-before-follow-link)")
6728 (defun org-link-search (s &optional type avoid-pos)
6729 "Search for a link search option.
6730 If S is surrounded by forward slashes, it is interpreted as a
6731 regular expression. In org-mode files, this will create an `org-occur'
6732 sparse tree. In ordinary files, `occur' will be used to list matches.
6733 If the current buffer is in `dired-mode', grep will be used to search
6734 in all files. If AVOID-POS is given, ignore matches near that position."
6735 (let ((case-fold-search t)
6736 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6737 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6738 (append '(("") (" ") ("\t") ("\n"))
6739 org-emphasis-alist)
6740 "\\|") "\\)"))
6741 (pos (point))
6742 (pre nil) (post nil)
6743 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6744 (cond
6745 ;; First check if there are any special
6746 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6747 ;; Now try the builtin stuff
6748 ((save-excursion
6749 (goto-char (point-min))
6750 (and
6751 (re-search-forward
6752 (concat "<<" (regexp-quote s0) ">>") nil t)
6753 (setq type 'dedicated
6754 pos (match-beginning 0))))
6755 ;; There is an exact target for this
6756 (goto-char pos))
6757 ((string-match "^/\\(.*\\)/$" s)
6758 ;; A regular expression
6759 (cond
6760 ((org-mode-p)
6761 (org-occur (match-string 1 s)))
6762 ;;((eq major-mode 'dired-mode)
6763 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6764 (t (org-do-occur (match-string 1 s)))))
6766 ;; A normal search strings
6767 (when (equal (string-to-char s) ?*)
6768 ;; Anchor on headlines, post may include tags.
6769 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6770 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6771 s (substring s 1)))
6772 (remove-text-properties
6773 0 (length s)
6774 '(face nil mouse-face nil keymap nil fontified nil) s)
6775 ;; Make a series of regular expressions to find a match
6776 (setq words (org-split-string s "[ \n\r\t]+")
6778 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6779 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6780 "\\)" markers)
6781 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6782 re2a (concat "[ \t\r\n]" re2a_)
6783 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6784 re4 (concat "[^a-zA-Z_]" re4_)
6786 re1 (concat pre re2 post)
6787 re3 (concat pre (if pre re4_ re4) post)
6788 re5 (concat pre ".*" re4)
6789 re2 (concat pre re2)
6790 re2a (concat pre (if pre re2a_ re2a))
6791 re4 (concat pre (if pre re4_ re4))
6792 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6793 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6794 re5 "\\)"
6796 (cond
6797 ((eq type 'org-occur) (org-occur reall))
6798 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6799 (t (goto-char (point-min))
6800 (setq type 'fuzzy)
6801 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6802 (org-search-not-self 1 re1 nil t)
6803 (org-search-not-self 1 re2 nil t)
6804 (org-search-not-self 1 re2a nil t)
6805 (org-search-not-self 1 re3 nil t)
6806 (org-search-not-self 1 re4 nil t)
6807 (org-search-not-self 1 re5 nil t)
6809 (goto-char (match-beginning 1))
6810 (goto-char pos)
6811 (error "No match")))))
6813 ;; Normal string-search
6814 (goto-char (point-min))
6815 (if (search-forward s nil t)
6816 (goto-char (match-beginning 0))
6817 (error "No match"))))
6818 (and (org-mode-p) (org-show-context 'link-search))
6819 type))
6821 (defun org-search-not-self (group &rest args)
6822 "Execute `re-search-forward', but only accept matches that do not
6823 enclose the position of `org-open-link-marker'."
6824 (let ((m org-open-link-marker))
6825 (catch 'exit
6826 (while (apply 're-search-forward args)
6827 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6828 (goto-char (match-end group))
6829 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6830 (> (match-beginning 0) (marker-position m))
6831 (< (match-end 0) (marker-position m)))
6832 (save-match-data
6833 (or (not (org-in-regexp
6834 org-bracket-link-analytic-regexp 1))
6835 (not (match-end 4)) ; no description
6836 (and (<= (match-beginning 4) (point))
6837 (>= (match-end 4) (point))))))
6838 (throw 'exit (point))))))))
6840 (defun org-get-buffer-for-internal-link (buffer)
6841 "Return a buffer to be used for displaying the link target of internal links."
6842 (cond
6843 ((not org-display-internal-link-with-indirect-buffer)
6844 buffer)
6845 ((string-match "(Clone)$" (buffer-name buffer))
6846 (message "Buffer is already a clone, not making another one")
6847 ;; we also do not modify visibility in this case
6848 buffer)
6849 (t ; make a new indirect buffer for displaying the link
6850 (let* ((bn (buffer-name buffer))
6851 (ibn (concat bn "(Clone)"))
6852 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6853 (with-current-buffer ib (org-overview))
6854 ib))))
6856 (defun org-do-occur (regexp &optional cleanup)
6857 "Call the Emacs command `occur'.
6858 If CLEANUP is non-nil, remove the printout of the regular expression
6859 in the *Occur* buffer. This is useful if the regex is long and not useful
6860 to read."
6861 (occur regexp)
6862 (when cleanup
6863 (let ((cwin (selected-window)) win beg end)
6864 (when (setq win (get-buffer-window "*Occur*"))
6865 (select-window win))
6866 (goto-char (point-min))
6867 (when (re-search-forward "match[a-z]+" nil t)
6868 (setq beg (match-end 0))
6869 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6870 (setq end (1- (match-beginning 0)))))
6871 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6872 (goto-char (point-min))
6873 (select-window cwin))))
6875 ;;; The mark ring for links jumps
6877 (defvar org-mark-ring nil
6878 "Mark ring for positions before jumps in Org-mode.")
6879 (defvar org-mark-ring-last-goto nil
6880 "Last position in the mark ring used to go back.")
6881 ;; Fill and close the ring
6882 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6883 (loop for i from 1 to org-mark-ring-length do
6884 (push (make-marker) org-mark-ring))
6885 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6886 org-mark-ring)
6888 (defun org-mark-ring-push (&optional pos buffer)
6889 "Put the current position or POS into the mark ring and rotate it."
6890 (interactive)
6891 (setq pos (or pos (point)))
6892 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6893 (move-marker (car org-mark-ring)
6894 (or pos (point))
6895 (or buffer (current-buffer)))
6896 (message "%s"
6897 (substitute-command-keys
6898 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6900 (defun org-mark-ring-goto (&optional n)
6901 "Jump to the previous position in the mark ring.
6902 With prefix arg N, jump back that many stored positions. When
6903 called several times in succession, walk through the entire ring.
6904 Org-mode commands jumping to a different position in the current file,
6905 or to another Org-mode file, automatically push the old position
6906 onto the ring."
6907 (interactive "p")
6908 (let (p m)
6909 (if (eq last-command this-command)
6910 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6911 (setq p org-mark-ring))
6912 (setq org-mark-ring-last-goto p)
6913 (setq m (car p))
6914 (switch-to-buffer (marker-buffer m))
6915 (goto-char m)
6916 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
6918 (defun org-remove-angle-brackets (s)
6919 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
6920 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
6922 (defun org-add-angle-brackets (s)
6923 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
6924 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
6926 (defun org-remove-double-quotes (s)
6927 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
6928 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
6931 ;;; Following specific links
6933 (defun org-follow-timestamp-link ()
6934 (cond
6935 ((org-at-date-range-p t)
6936 (let ((org-agenda-start-on-weekday)
6937 (t1 (match-string 1))
6938 (t2 (match-string 2)))
6939 (setq t1 (time-to-days (org-time-string-to-time t1))
6940 t2 (time-to-days (org-time-string-to-time t2)))
6941 (org-agenda-list nil t1 (1+ (- t2 t1)))))
6942 ((org-at-timestamp-p t)
6943 (org-agenda-list nil (time-to-days (org-time-string-to-time
6944 (substring (match-string 1) 0 10)))
6946 (t (error "This should not happen"))))
6949 ;;; Following file links
6950 (defvar org-wait nil)
6951 (defun org-open-file (path &optional in-emacs line search)
6952 "Open the file at PATH.
6953 First, this expands any special file name abbreviations. Then the
6954 configuration variable `org-file-apps' is checked if it contains an
6955 entry for this file type, and if yes, the corresponding command is launched.
6956 If no application is found, Emacs simply visits the file.
6957 With optional argument IN-EMACS, Emacs will visit the file.
6958 Optional LINE specifies a line to go to, optional SEARCH a string to
6959 search for. If LINE or SEARCH is given, the file will always be
6960 opened in Emacs.
6961 If the file does not exist, an error is thrown."
6962 (setq in-emacs (or in-emacs line search))
6963 (let* ((file (if (equal path "")
6964 buffer-file-name
6965 (substitute-in-file-name (expand-file-name path))))
6966 (apps (append org-file-apps (org-default-apps)))
6967 (remp (and (assq 'remote apps) (org-file-remote-p file)))
6968 (dirp (if remp nil (file-directory-p file)))
6969 (file (if (and dirp org-open-directory-means-index-dot-org)
6970 (concat (file-name-as-directory file) "index.org")
6971 file))
6972 (dfile (downcase file))
6973 (old-buffer (current-buffer))
6974 (old-pos (point))
6975 (old-mode major-mode)
6976 ext cmd)
6977 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6978 (setq ext (match-string 1 dfile))
6979 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6980 (setq ext (match-string 1 dfile))))
6981 (if in-emacs
6982 (setq cmd 'emacs)
6983 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
6984 (and dirp (cdr (assoc 'directory apps)))
6985 (cdr (assoc ext apps))
6986 (cdr (assoc t apps)))))
6987 (when (eq cmd 'default)
6988 (setq cmd (cdr (assoc t apps))))
6989 (when (eq cmd 'mailcap)
6990 (require 'mailcap)
6991 (mailcap-parse-mailcaps)
6992 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
6993 (command (mailcap-mime-info mime-type)))
6994 (if (stringp command)
6995 (setq cmd command)
6996 (setq cmd 'emacs))))
6997 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
6998 (not (file-exists-p file))
6999 (not org-open-non-existing-files))
7000 (error "No such file: %s" file))
7001 (cond
7002 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7003 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7004 (while (string-match "['\"]%s['\"]" cmd)
7005 (setq cmd (replace-match "%s" t t cmd)))
7006 (while (string-match "%s" cmd)
7007 (setq cmd (replace-match
7008 (save-match-data
7009 (shell-quote-argument
7010 (convert-standard-filename file)))
7011 t t cmd)))
7012 (save-window-excursion
7013 (start-process-shell-command cmd nil cmd)
7014 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7016 ((or (stringp cmd)
7017 (eq cmd 'emacs))
7018 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7019 (widen)
7020 (if line (goto-line line)
7021 (if search (org-link-search search))))
7022 ((consp cmd)
7023 (let ((file (convert-standard-filename file)))
7024 (eval cmd)))
7025 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7026 (and (org-mode-p) (eq old-mode 'org-mode)
7027 (or (not (equal old-buffer (current-buffer)))
7028 (not (equal old-pos (point))))
7029 (org-mark-ring-push old-pos old-buffer))))
7031 (defun org-default-apps ()
7032 "Return the default applications for this operating system."
7033 (cond
7034 ((eq system-type 'darwin)
7035 org-file-apps-defaults-macosx)
7036 ((eq system-type 'windows-nt)
7037 org-file-apps-defaults-windowsnt)
7038 (t org-file-apps-defaults-gnu)))
7040 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7041 (defun org-file-remote-p (file)
7042 "Test whether FILE specifies a location on a remote system.
7043 Return non-nil if the location is indeed remote.
7045 For example, the filename \"/user@host:/foo\" specifies a location
7046 on the system \"/user@host:\"."
7047 (cond ((fboundp 'file-remote-p)
7048 (file-remote-p file))
7049 ((fboundp 'tramp-handle-file-remote-p)
7050 (tramp-handle-file-remote-p file))
7051 ((and (boundp 'ange-ftp-name-format)
7052 (string-match (car ange-ftp-name-format) file))
7054 (t nil)))
7057 ;;;; Refiling
7059 (defun org-get-org-file ()
7060 "Read a filename, with default directory `org-directory'."
7061 (let ((default (or org-default-notes-file remember-data-file)))
7062 (read-file-name (format "File name [%s]: " default)
7063 (file-name-as-directory org-directory)
7064 default)))
7066 (defun org-notes-order-reversed-p ()
7067 "Check if the current file should receive notes in reversed order."
7068 (cond
7069 ((not org-reverse-note-order) nil)
7070 ((eq t org-reverse-note-order) t)
7071 ((not (listp org-reverse-note-order)) nil)
7072 (t (catch 'exit
7073 (let ((all org-reverse-note-order)
7074 entry)
7075 (while (setq entry (pop all))
7076 (if (string-match (car entry) buffer-file-name)
7077 (throw 'exit (cdr entry))))
7078 nil)))))
7080 (defvar org-refile-target-table nil
7081 "The list of refile targets, created by `org-refile'.")
7083 (defvar org-agenda-new-buffers nil
7084 "Buffers created to visit agenda files.")
7086 (defun org-get-refile-targets (&optional default-buffer)
7087 "Produce a table with refile targets."
7088 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7089 targets txt re files f desc descre)
7090 (with-current-buffer (or default-buffer (current-buffer))
7091 (while (setq entry (pop entries))
7092 (setq files (car entry) desc (cdr entry))
7093 (cond
7094 ((null files) (setq files (list (current-buffer))))
7095 ((eq files 'org-agenda-files)
7096 (setq files (org-agenda-files 'unrestricted)))
7097 ((and (symbolp files) (fboundp files))
7098 (setq files (funcall files)))
7099 ((and (symbolp files) (boundp files))
7100 (setq files (symbol-value files))))
7101 (if (stringp files) (setq files (list files)))
7102 (cond
7103 ((eq (car desc) :tag)
7104 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7105 ((eq (car desc) :todo)
7106 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7107 ((eq (car desc) :regexp)
7108 (setq descre (cdr desc)))
7109 ((eq (car desc) :level)
7110 (setq descre (concat "^\\*\\{" (number-to-string
7111 (if org-odd-levels-only
7112 (1- (* 2 (cdr desc)))
7113 (cdr desc)))
7114 "\\}[ \t]")))
7115 ((eq (car desc) :maxlevel)
7116 (setq descre (concat "^\\*\\{1," (number-to-string
7117 (if org-odd-levels-only
7118 (1- (* 2 (cdr desc)))
7119 (cdr desc)))
7120 "\\}[ \t]")))
7121 (t (error "Bad refiling target description %s" desc)))
7122 (while (setq f (pop files))
7123 (save-excursion
7124 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7125 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7126 (save-excursion
7127 (save-restriction
7128 (widen)
7129 (goto-char (point-min))
7130 (while (re-search-forward descre nil t)
7131 (goto-char (point-at-bol))
7132 (when (looking-at org-complex-heading-regexp)
7133 (setq txt (org-link-display-format (match-string 4))
7134 re (concat "^" (regexp-quote
7135 (buffer-substring (match-beginning 1)
7136 (match-end 4)))))
7137 (if (match-end 5) (setq re (concat re "[ \t]+"
7138 (regexp-quote
7139 (match-string 5)))))
7140 (setq re (concat re "[ \t]*$"))
7141 (when org-refile-use-outline-path
7142 (setq txt (mapconcat 'org-protect-slash
7143 (append
7144 (if (eq org-refile-use-outline-path 'file)
7145 (list (file-name-nondirectory
7146 (buffer-file-name (buffer-base-buffer))))
7147 (if (eq org-refile-use-outline-path 'full-file-path)
7148 (list (buffer-file-name (buffer-base-buffer)))))
7149 (org-get-outline-path)
7150 (list txt))
7151 "/")))
7152 (push (list txt f re (point)) targets))
7153 (goto-char (point-at-eol))))))))
7154 (nreverse targets))))
7156 (defun org-protect-slash (s)
7157 (while (string-match "/" s)
7158 (setq s (replace-match "\\" t t s)))
7161 (defun org-get-outline-path ()
7162 "Return the outline path to the current entry, as a list."
7163 (let (rtn)
7164 (save-excursion
7165 (while (org-up-heading-safe)
7166 (when (looking-at org-complex-heading-regexp)
7167 (push (org-match-string-no-properties 4) rtn)))
7168 rtn)))
7170 (defvar org-refile-history nil
7171 "History for refiling operations.")
7173 (defun org-refile (&optional goto default-buffer)
7174 "Move the entry at point to another heading.
7175 The list of target headings is compiled using the information in
7176 `org-refile-targets', which see. This list is created before each use
7177 and will therefore always be up-to-date.
7179 At the target location, the entry is filed as a subitem of the target heading.
7180 Depending on `org-reverse-note-order', the new subitem will either be the
7181 first of the last subitem.
7183 With prefix arg GOTO, the command will only visit the target location,
7184 not actually move anything.
7185 With a double prefix `C-u C-u', go to the location where the last refiling
7186 operation has put the subtree."
7187 (interactive "P")
7188 (let* ((cbuf (current-buffer))
7189 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7190 pos it nbuf file re level reversed)
7191 (if (equal goto '(16))
7192 (org-refile-goto-last-stored)
7193 (when (setq it (org-refile-get-location
7194 (if goto "Goto: " "Refile to: ") default-buffer))
7195 (setq file (nth 1 it)
7196 re (nth 2 it)
7197 pos (nth 3 it))
7198 (setq nbuf (or (find-buffer-visiting file)
7199 (find-file-noselect file)))
7200 (if goto
7201 (progn
7202 (switch-to-buffer nbuf)
7203 (goto-char pos)
7204 (org-show-context 'org-goto))
7205 (org-copy-subtree 1 nil t)
7206 (save-excursion
7207 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7208 (find-file-noselect file))))
7209 (setq reversed (org-notes-order-reversed-p))
7210 (save-excursion
7211 (save-restriction
7212 (widen)
7213 (goto-char pos)
7214 (looking-at outline-regexp)
7215 (setq level (org-get-valid-level (funcall outline-level) 1))
7216 (goto-char
7217 (if reversed
7218 (or (outline-next-heading) (point-max))
7219 (or (save-excursion (outline-get-next-sibling))
7220 (org-end-of-subtree t t)
7221 (point-max))))
7222 (if (not (bolp)) (newline))
7223 (bookmark-set "org-refile-last-stored")
7224 (org-paste-subtree level))))
7225 (org-cut-subtree)
7226 (setq org-markers-to-move nil)
7227 (message "Entry refiled to \"%s\"" (car it)))))))
7229 (defun org-refile-goto-last-stored ()
7230 "Go to the location where the last refile was stored."
7231 (interactive)
7232 (bookmark-jump "org-refile-last-stored")
7233 (message "This is the location of the last refile"))
7235 (defun org-refile-get-location (&optional prompt default-buffer)
7236 "Prompt the user for a refile location, using PROMPT."
7237 (let ((org-refile-targets org-refile-targets)
7238 (org-refile-use-outline-path org-refile-use-outline-path))
7239 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7240 (unless org-refile-target-table
7241 (error "No refile targets"))
7242 (let* ((cbuf (current-buffer))
7243 (cfunc (if org-refile-use-outline-path
7244 'org-olpath-completing-read
7245 'completing-read))
7246 (extra (if org-refile-use-outline-path "/" ""))
7247 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7248 (fname (and filename (file-truename filename)))
7249 (tbl (mapcar
7250 (lambda (x)
7251 (if (not (equal fname (file-truename (nth 1 x))))
7252 (cons (concat (car x) extra " ("
7253 (file-name-nondirectory (nth 1 x)) ")")
7254 (cdr x))
7255 (cons (concat (car x) extra) (cdr x))))
7256 org-refile-target-table))
7257 (completion-ignore-case t))
7258 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7259 tbl)))
7261 (defun org-olpath-completing-read (prompt collection &rest args)
7262 "Read an outline path like a file name."
7263 (let ((thetable collection))
7264 (apply
7265 'completing-read prompt
7266 (lambda (string predicate &optional flag)
7267 (let (rtn r s f (l (length string)))
7268 (cond
7269 ((eq flag nil)
7270 ;; try completion
7271 (try-completion string thetable))
7272 ((eq flag t)
7273 ;; all-completions
7274 (setq rtn (all-completions string thetable predicate))
7275 (mapcar
7276 (lambda (x)
7277 (setq r (substring x l))
7278 (if (string-match " ([^)]*)$" x)
7279 (setq f (match-string 0 x))
7280 (setq f ""))
7281 (if (string-match "/" r)
7282 (concat string (substring r 0 (match-end 0)) f)
7284 rtn))
7285 ((eq flag 'lambda)
7286 ;; exact match?
7287 (assoc string thetable)))
7289 args)))
7291 ;;;; Dynamic blocks
7293 (defun org-find-dblock (name)
7294 "Find the first dynamic block with name NAME in the buffer.
7295 If not found, stay at current position and return nil."
7296 (let (pos)
7297 (save-excursion
7298 (goto-char (point-min))
7299 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7300 nil t)
7301 (match-beginning 0))))
7302 (if pos (goto-char pos))
7303 pos))
7305 (defconst org-dblock-start-re
7306 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7307 "Matches the startline of a dynamic block, with parameters.")
7309 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7310 "Matches the end of a dyhamic block.")
7312 (defun org-create-dblock (plist)
7313 "Create a dynamic block section, with parameters taken from PLIST.
7314 PLIST must containe a :name entry which is used as name of the block."
7315 (unless (bolp) (newline))
7316 (let ((name (plist-get plist :name)))
7317 (insert "#+BEGIN: " name)
7318 (while plist
7319 (if (eq (car plist) :name)
7320 (setq plist (cddr plist))
7321 (insert " " (prin1-to-string (pop plist)))))
7322 (insert "\n\n#+END:\n")
7323 (beginning-of-line -2)))
7325 (defun org-prepare-dblock ()
7326 "Prepare dynamic block for refresh.
7327 This empties the block, puts the cursor at the insert position and returns
7328 the property list including an extra property :name with the block name."
7329 (unless (looking-at org-dblock-start-re)
7330 (error "Not at a dynamic block"))
7331 (let* ((begdel (1+ (match-end 0)))
7332 (name (org-no-properties (match-string 1)))
7333 (params (append (list :name name)
7334 (read (concat "(" (match-string 3) ")")))))
7335 (unless (re-search-forward org-dblock-end-re nil t)
7336 (error "Dynamic block not terminated"))
7337 (setq params
7338 (append params
7339 (list :content (buffer-substring
7340 begdel (match-beginning 0)))))
7341 (delete-region begdel (match-beginning 0))
7342 (goto-char begdel)
7343 (open-line 1)
7344 params))
7346 (defun org-map-dblocks (&optional command)
7347 "Apply COMMAND to all dynamic blocks in the current buffer.
7348 If COMMAND is not given, use `org-update-dblock'."
7349 (let ((cmd (or command 'org-update-dblock))
7350 pos)
7351 (save-excursion
7352 (goto-char (point-min))
7353 (while (re-search-forward org-dblock-start-re nil t)
7354 (goto-char (setq pos (match-beginning 0)))
7355 (condition-case nil
7356 (funcall cmd)
7357 (error (message "Error during update of dynamic block")))
7358 (goto-char pos)
7359 (unless (re-search-forward org-dblock-end-re nil t)
7360 (error "Dynamic block not terminated"))))))
7362 (defun org-dblock-update (&optional arg)
7363 "User command for updating dynamic blocks.
7364 Update the dynamic block at point. With prefix ARG, update all dynamic
7365 blocks in the buffer."
7366 (interactive "P")
7367 (if arg
7368 (org-update-all-dblocks)
7369 (or (looking-at org-dblock-start-re)
7370 (org-beginning-of-dblock))
7371 (org-update-dblock)))
7373 (defun org-update-dblock ()
7374 "Update the dynamic block at point
7375 This means to empty the block, parse for parameters and then call
7376 the correct writing function."
7377 (save-window-excursion
7378 (let* ((pos (point))
7379 (line (org-current-line))
7380 (params (org-prepare-dblock))
7381 (name (plist-get params :name))
7382 (cmd (intern (concat "org-dblock-write:" name))))
7383 (message "Updating dynamic block `%s' at line %d..." name line)
7384 (funcall cmd params)
7385 (message "Updating dynamic block `%s' at line %d...done" name line)
7386 (goto-char pos))))
7388 (defun org-beginning-of-dblock ()
7389 "Find the beginning of the dynamic block at point.
7390 Error if there is no scuh block at point."
7391 (let ((pos (point))
7392 beg)
7393 (end-of-line 1)
7394 (if (and (re-search-backward org-dblock-start-re nil t)
7395 (setq beg (match-beginning 0))
7396 (re-search-forward org-dblock-end-re nil t)
7397 (> (match-end 0) pos))
7398 (goto-char beg)
7399 (goto-char pos)
7400 (error "Not in a dynamic block"))))
7402 (defun org-update-all-dblocks ()
7403 "Update all dynamic blocks in the buffer.
7404 This function can be used in a hook."
7405 (when (org-mode-p)
7406 (org-map-dblocks 'org-update-dblock)))
7409 ;;;; Completion
7411 (defconst org-additional-option-like-keywords
7412 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7413 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7414 "BEGIN_EXAMPLE" "END_EXAMPLE"
7415 "BEGIN_QUOTE" "END_QUOTE"
7416 "BEGIN_VERSE" "END_VERSE"
7417 "BEGIN_SRC" "END_SRC"))
7419 (defcustom org-structure-template-alist
7421 ("s" "#+begin_src ?\n\n#+end_src"
7422 "<src lang=\"?\">\n\n</src>")
7423 ("e" "#+begin_example\n?\n#+end_example"
7424 "<example>\n?\n</example>")
7425 ("q" "#+begin_quote\n?\n#+end_quote"
7426 "<quote>\n?\n</quote>")
7427 ("v" "#+begin_verse\n?\n#+end_verse"
7428 "<verse>\n?\n/verse>")
7429 ("l" "#+begin_latex\n?\n#+end_latex"
7430 "<literal style=\"latex\">\n?\n</literal>")
7431 ("L" "#+latex: "
7432 "<literal style=\"latex\">?</literal>")
7433 ("h" "#+begin_html\n?\n#+end_html"
7434 "<literal style=\"html\">\n?\n</literal>")
7435 ("H" "#+html: "
7436 "<literal style=\"html\">?</literal>")
7437 ("a" "#+begin_ascii\n?\n#+end_ascii")
7438 ("A" "#+ascii: ")
7439 ("i" "#+include %file ?"
7440 "<include file=%file markup=\"?\">")
7442 "Structure completion elements.
7443 This is a list of abbreviation keys and values. The value gets inserted
7444 it you type @samp{.} followed by the key and then the completion key,
7445 usually `M-TAB'. %file will be replaced by a file name after prompting
7446 for the file uning completion.
7447 There are two templates for each key, the first uses the original Org syntax,
7448 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7449 the default when the /org-mtags.el/ module has been loaded. See also the
7450 variable `org-mtags-prefere-muse-templates'.
7451 This is an experimental feature, it is undecided if it is going to stay in."
7452 :group 'org-completion
7453 :type '(repeat
7454 (string :tag "Key")
7455 (string :tag "Template")
7456 (string :tag "Muse Template")))
7458 (defun org-try-structure-completion ()
7459 "Try to complete a structure template before point.
7460 This looks for strings like \"<e\" on an otherwise empty line and
7461 expands them."
7462 (let ((l (buffer-substring (point-at-bol) (point)))
7464 (when (and (looking-at "[ \t]*$")
7465 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7466 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7467 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7468 (match-beginning 1)) a)
7469 t)))
7471 (defun org-complete-expand-structure-template (start cell)
7472 "Expand a structure template."
7473 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7474 (rpl (nth (if musep 2 1) cell)))
7475 (delete-region start (point))
7476 (when (string-match "\\`#\\+" rpl)
7477 (cond
7478 ((bolp))
7479 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7480 (delete-region (point-at-bol) (point)))
7481 (t (newline))))
7482 (setq start (point))
7483 (if (string-match "%file" rpl)
7484 (setq rpl (replace-match
7485 (concat
7486 "\""
7487 (save-match-data
7488 (abbreviate-file-name (read-file-name "Include file: ")))
7489 "\"")
7490 t t rpl)))
7491 (insert rpl)
7492 (if (re-search-backward "\\?" start t) (delete-char 1))))
7495 (defun org-complete (&optional arg)
7496 "Perform completion on word at point.
7497 At the beginning of a headline, this completes TODO keywords as given in
7498 `org-todo-keywords'.
7499 If the current word is preceded by a backslash, completes the TeX symbols
7500 that are supported for HTML support.
7501 If the current word is preceded by \"#+\", completes special words for
7502 setting file options.
7503 In the line after \"#+STARTUP:, complete valid keywords.\"
7504 At all other locations, this simply calls the value of
7505 `org-completion-fallback-command'."
7506 (interactive "P")
7507 (org-without-partial-completion
7508 (catch 'exit
7509 (let* ((a nil)
7510 (end (point))
7511 (beg1 (save-excursion
7512 (skip-chars-backward (org-re "[:alnum:]_@"))
7513 (point)))
7514 (beg (save-excursion
7515 (skip-chars-backward "a-zA-Z0-9_:$")
7516 (point)))
7517 (confirm (lambda (x) (stringp (car x))))
7518 (searchhead (equal (char-before beg) ?*))
7519 (struct
7520 (when (and (member (char-before beg1) '(?. ?<))
7521 (setq a (assoc (buffer-substring beg1 (point))
7522 org-structure-template-alist)))
7523 (org-complete-expand-structure-template (1- beg1) a)
7524 (throw 'exit t)))
7525 (tag (and (equal (char-before beg1) ?:)
7526 (equal (char-after (point-at-bol)) ?*)))
7527 (prop (and (equal (char-before beg1) ?:)
7528 (not (equal (char-after (point-at-bol)) ?*))))
7529 (texp (equal (char-before beg) ?\\))
7530 (link (equal (char-before beg) ?\[))
7531 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7532 beg)
7533 "#+"))
7534 (startup (string-match "^#\\+STARTUP:.*"
7535 (buffer-substring (point-at-bol) (point))))
7536 (completion-ignore-case opt)
7537 (type nil)
7538 (tbl nil)
7539 (table (cond
7540 (opt
7541 (setq type :opt)
7542 (require 'org-exp)
7543 (append
7544 (mapcar
7545 (lambda (x)
7546 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7547 (cons (match-string 2 x) (match-string 1 x)))
7548 (org-split-string (org-get-current-options) "\n"))
7549 (mapcar 'list org-additional-option-like-keywords)))
7550 (startup
7551 (setq type :startup)
7552 org-startup-options)
7553 (link (append org-link-abbrev-alist-local
7554 org-link-abbrev-alist))
7555 (texp
7556 (setq type :tex)
7557 org-html-entities)
7558 ((string-match "\\`\\*+[ \t]+\\'"
7559 (buffer-substring (point-at-bol) beg))
7560 (setq type :todo)
7561 (mapcar 'list org-todo-keywords-1))
7562 (searchhead
7563 (setq type :searchhead)
7564 (save-excursion
7565 (goto-char (point-min))
7566 (while (re-search-forward org-todo-line-regexp nil t)
7567 (push (list
7568 (org-make-org-heading-search-string
7569 (match-string 3) t))
7570 tbl)))
7571 tbl)
7572 (tag (setq type :tag beg beg1)
7573 (or org-tag-alist (org-get-buffer-tags)))
7574 (prop (setq type :prop beg beg1)
7575 (mapcar 'list (org-buffer-property-keys nil t t)))
7576 (t (progn
7577 (call-interactively org-completion-fallback-command)
7578 (throw 'exit nil)))))
7579 (pattern (buffer-substring-no-properties beg end))
7580 (completion (try-completion pattern table confirm)))
7581 (cond ((eq completion t)
7582 (if (not (assoc (upcase pattern) table))
7583 (message "Already complete")
7584 (if (and (equal type :opt)
7585 (not (member (car (assoc (upcase pattern) table))
7586 org-additional-option-like-keywords)))
7587 (insert (substring (cdr (assoc (upcase pattern) table))
7588 (length pattern)))
7589 (if (memq type '(:tag :prop)) (insert ":")))))
7590 ((null completion)
7591 (message "Can't find completion for \"%s\"" pattern)
7592 (ding))
7593 ((not (string= pattern completion))
7594 (delete-region beg end)
7595 (if (string-match " +$" completion)
7596 (setq completion (replace-match "" t t completion)))
7597 (insert completion)
7598 (if (get-buffer-window "*Completions*")
7599 (delete-window (get-buffer-window "*Completions*")))
7600 (if (assoc completion table)
7601 (if (eq type :todo) (insert " ")
7602 (if (memq type '(:tag :prop)) (insert ":"))))
7603 (if (and (equal type :opt) (assoc completion table))
7604 (message "%s" (substitute-command-keys
7605 "Press \\[org-complete] again to insert example settings"))))
7607 (message "Making completion list...")
7608 (let ((list (sort (all-completions pattern table confirm)
7609 'string<)))
7610 (with-output-to-temp-buffer "*Completions*"
7611 (condition-case nil
7612 ;; Protection needed for XEmacs and emacs 21
7613 (display-completion-list list pattern)
7614 (error (display-completion-list list)))))
7615 (message "Making completion list...%s" "done")))))))
7617 ;;;; TODO, DEADLINE, Comments
7619 (defun org-toggle-comment ()
7620 "Change the COMMENT state of an entry."
7621 (interactive)
7622 (save-excursion
7623 (org-back-to-heading)
7624 (let (case-fold-search)
7625 (if (looking-at (concat outline-regexp
7626 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7627 (replace-match "" t t nil 1)
7628 (if (looking-at outline-regexp)
7629 (progn
7630 (goto-char (match-end 0))
7631 (insert org-comment-string " ")))))))
7633 (defvar org-last-todo-state-is-todo nil
7634 "This is non-nil when the last TODO state change led to a TODO state.
7635 If the last change removed the TODO tag or switched to DONE, then
7636 this is nil.")
7638 (defvar org-setting-tags nil) ; dynamically skiped
7640 (defun org-parse-local-options (string var)
7641 "Parse STRING for startup setting relevant for variable VAR."
7642 (let ((rtn (symbol-value var))
7643 e opts)
7644 (save-match-data
7645 (if (or (not string) (not (string-match "\\S-" string)))
7647 (setq opts (delq nil (mapcar (lambda (x)
7648 (setq e (assoc x org-startup-options))
7649 (if (eq (nth 1 e) var) e nil))
7650 (org-split-string string "[ \t]+"))))
7651 (if (not opts)
7653 (setq rtn nil)
7654 (while (setq e (pop opts))
7655 (if (not (nth 3 e))
7656 (setq rtn (nth 2 e))
7657 (if (not (listp rtn)) (setq rtn nil))
7658 (push (nth 2 e) rtn)))
7659 rtn)))))
7661 (defvar org-blocker-hook nil
7662 "Hook for functions that are allowed to block a state change.
7664 Each function gets as its single argument a property list, see
7665 `org-trigger-hook' for more information about this list.
7667 If any of the functions in this hook returns nil, the state change
7668 is blocked.")
7670 (defvar org-trigger-hook nil
7671 "Hook for functions that are triggered by a state change.
7673 Each function gets as its single argument a property list with at least
7674 the following elements:
7676 (:type type-of-change :position pos-at-entry-start
7677 :from old-state :to new-state)
7679 Depending on the type, more properties may be present.
7681 This mechanism is currently implemented for:
7683 TODO state changes
7684 ------------------
7685 :type todo-state-change
7686 :from previous state (keyword as a string), or nil
7687 :to new state (keyword as a string), or nil")
7690 (defun org-todo (&optional arg)
7691 "Change the TODO state of an item.
7692 The state of an item is given by a keyword at the start of the heading,
7693 like
7694 *** TODO Write paper
7695 *** DONE Call mom
7697 The different keywords are specified in the variable `org-todo-keywords'.
7698 By default the available states are \"TODO\" and \"DONE\".
7699 So for this example: when the item starts with TODO, it is changed to DONE.
7700 When it starts with DONE, the DONE is removed. And when neither TODO nor
7701 DONE are present, add TODO at the beginning of the heading.
7703 With C-u prefix arg, use completion to determine the new state.
7704 With numeric prefix arg, switch to that state.
7706 For calling through lisp, arg is also interpreted in the following way:
7707 'none -> empty state
7708 \"\"(empty string) -> switch to empty state
7709 'done -> switch to DONE
7710 'nextset -> switch to the next set of keywords
7711 'previousset -> switch to the previous set of keywords
7712 \"WAITING\" -> switch to the specified keyword, but only if it
7713 really is a member of `org-todo-keywords'."
7714 (interactive "P")
7715 (save-excursion
7716 (catch 'exit
7717 (org-back-to-heading)
7718 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7719 (or (looking-at (concat " +" org-todo-regexp " *"))
7720 (looking-at " *"))
7721 (let* ((match-data (match-data))
7722 (startpos (point-at-bol))
7723 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7724 (org-log-done org-log-done)
7725 (org-log-repeat org-log-repeat)
7726 (org-todo-log-states org-todo-log-states)
7727 (this (match-string 1))
7728 (hl-pos (match-beginning 0))
7729 (head (org-get-todo-sequence-head this))
7730 (ass (assoc head org-todo-kwd-alist))
7731 (interpret (nth 1 ass))
7732 (done-word (nth 3 ass))
7733 (final-done-word (nth 4 ass))
7734 (last-state (or this ""))
7735 (completion-ignore-case t)
7736 (member (member this org-todo-keywords-1))
7737 (tail (cdr member))
7738 (state (cond
7739 ((and org-todo-key-trigger
7740 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7741 (and (not arg) org-use-fast-todo-selection
7742 (not (eq org-use-fast-todo-selection 'prefix)))))
7743 ;; Use fast selection
7744 (org-fast-todo-selection))
7745 ((and (equal arg '(4))
7746 (or (not org-use-fast-todo-selection)
7747 (not org-todo-key-trigger)))
7748 ;; Read a state with completion
7749 (completing-read "State: " (mapcar (lambda(x) (list x))
7750 org-todo-keywords-1)
7751 nil t))
7752 ((eq arg 'right)
7753 (if this
7754 (if tail (car tail) nil)
7755 (car org-todo-keywords-1)))
7756 ((eq arg 'left)
7757 (if (equal member org-todo-keywords-1)
7759 (if this
7760 (nth (- (length org-todo-keywords-1) (length tail) 2)
7761 org-todo-keywords-1)
7762 (org-last org-todo-keywords-1))))
7763 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7764 (setq arg nil))) ; hack to fall back to cycling
7765 (arg
7766 ;; user or caller requests a specific state
7767 (cond
7768 ((equal arg "") nil)
7769 ((eq arg 'none) nil)
7770 ((eq arg 'done) (or done-word (car org-done-keywords)))
7771 ((eq arg 'nextset)
7772 (or (car (cdr (member head org-todo-heads)))
7773 (car org-todo-heads)))
7774 ((eq arg 'previousset)
7775 (let ((org-todo-heads (reverse org-todo-heads)))
7776 (or (car (cdr (member head org-todo-heads)))
7777 (car org-todo-heads))))
7778 ((car (member arg org-todo-keywords-1)))
7779 ((nth (1- (prefix-numeric-value arg))
7780 org-todo-keywords-1))))
7781 ((null member) (or head (car org-todo-keywords-1)))
7782 ((equal this final-done-word) nil) ;; -> make empty
7783 ((null tail) nil) ;; -> first entry
7784 ((eq interpret 'sequence)
7785 (car tail))
7786 ((memq interpret '(type priority))
7787 (if (eq this-command last-command)
7788 (car tail)
7789 (if (> (length tail) 0)
7790 (or done-word (car org-done-keywords))
7791 nil)))
7792 (t nil)))
7793 (next (if state (concat " " state " ") " "))
7794 (change-plist (list :type 'todo-state-change :from this :to state
7795 :position startpos))
7796 dolog now-done-p)
7797 (when org-blocker-hook
7798 (unless (save-excursion
7799 (save-match-data
7800 (run-hook-with-args-until-failure
7801 'org-blocker-hook change-plist)))
7802 (if (interactive-p)
7803 (error "TODO state change from %s to %s blocked" this state)
7804 ;; fail silently
7805 (message "TODO state change from %s to %s blocked" this state)
7806 (throw 'exit nil))))
7807 (store-match-data match-data)
7808 (replace-match next t t)
7809 (unless (pos-visible-in-window-p hl-pos)
7810 (message "TODO state changed to %s" (org-trim next)))
7811 (unless head
7812 (setq head (org-get-todo-sequence-head state)
7813 ass (assoc head org-todo-kwd-alist)
7814 interpret (nth 1 ass)
7815 done-word (nth 3 ass)
7816 final-done-word (nth 4 ass)))
7817 (when (memq arg '(nextset previousset))
7818 (message "Keyword-Set %d/%d: %s"
7819 (- (length org-todo-sets) -1
7820 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7821 (length org-todo-sets)
7822 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7823 (setq org-last-todo-state-is-todo
7824 (not (member state org-done-keywords)))
7825 (setq now-done-p (and (member state org-done-keywords)
7826 (not (member this org-done-keywords))))
7827 (and logging (org-local-logging logging))
7828 (when (and (or org-todo-log-states org-log-done)
7829 (not (memq arg '(nextset previousset))))
7830 ;; we need to look at recording a time and note
7831 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7832 (nth 2 (assoc this org-todo-log-states))))
7833 (when (and state
7834 (member state org-not-done-keywords)
7835 (not (member this org-not-done-keywords)))
7836 ;; This is now a todo state and was not one before
7837 ;; If there was a CLOSED time stamp, get rid of it.
7838 (org-add-planning-info nil nil 'closed))
7839 (when (and now-done-p org-log-done)
7840 ;; It is now done, and it was not done before
7841 (org-add-planning-info 'closed (org-current-time))
7842 (if (and (not dolog) (eq 'note org-log-done))
7843 (org-add-log-setup 'done state 'findpos 'note)))
7844 (when (and state dolog)
7845 ;; This is a non-nil state, and we need to log it
7846 (org-add-log-setup 'state state 'findpos dolog)))
7847 ;; Fixup tag positioning
7848 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7849 (when org-provide-todo-statistics
7850 (org-update-parent-todo-statistics))
7851 (run-hooks 'org-after-todo-state-change-hook)
7852 (if (and arg (not (member state org-done-keywords)))
7853 (setq head (org-get-todo-sequence-head state)))
7854 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7855 ;; Do we need to trigger a repeat?
7856 (when now-done-p (org-auto-repeat-maybe state))
7857 ;; Fixup cursor location if close to the keyword
7858 (if (and (outline-on-heading-p)
7859 (not (bolp))
7860 (save-excursion (beginning-of-line 1)
7861 (looking-at org-todo-line-regexp))
7862 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7863 (progn
7864 (goto-char (or (match-end 2) (match-end 1)))
7865 (just-one-space)))
7866 (when org-trigger-hook
7867 (save-excursion
7868 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7870 (defun org-update-parent-todo-statistics ()
7871 "Update any statistics cookie in the parent of the current headline."
7872 (interactive)
7873 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7874 level (cnt-all 0) (cnt-done 0) is-percent kwd)
7875 (catch 'exit
7876 (save-excursion
7877 (setq level (org-up-heading-safe))
7878 (unless (and level
7879 (re-search-forward box-re (point-at-eol) t))
7880 (throw 'exit nil))
7881 (setq is-percent (match-end 2))
7882 (save-match-data
7883 (unless (outline-next-heading) (throw 'exit nil))
7884 (while (looking-at org-todo-line-regexp)
7885 (setq kwd (match-string 2))
7886 (and kwd (setq cnt-all (1+ cnt-all)))
7887 (and (member kwd org-done-keywords)
7888 (setq cnt-done (1+ cnt-done)))
7889 (condition-case nil
7890 (org-forward-same-level 1)
7891 (error (end-of-line 1)))))
7892 (replace-match
7893 (if is-percent
7894 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
7895 (format "[%d/%d]" cnt-done cnt-all)))
7896 (run-hook-with-args 'org-after-todo-statistics-hook
7897 cnt-done (- cnt-all cnt-done))))))
7899 (defvar org-after-todo-statistics-hook nil
7900 "Hook that is called after a TODO statistics cookie has been updated.
7901 Each function is called with two arguments: the number of not-done entries
7902 and the number of done entries.
7904 For example, the following function, when added to this hook, will switch
7905 an entry to DONE when all children are done, and back to TODO when new
7906 entries are set to a TODO status. Note that this hook is only called
7907 when there is a statistics cookie in the headline!
7909 (defun org-summary-todo (n-done n-not-done)
7910 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
7911 (let (org-log-done org-log-states) ; turn off logging
7912 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
7915 (defun org-local-logging (value)
7916 "Get logging settings from a property VALUE."
7917 (let* (words w a)
7918 ;; directly set the variables, they are already local.
7919 (setq org-log-done nil
7920 org-log-repeat nil
7921 org-todo-log-states nil)
7922 (setq words (org-split-string value))
7923 (while (setq w (pop words))
7924 (cond
7925 ((setq a (assoc w org-startup-options))
7926 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7927 (set (nth 1 a) (nth 2 a))))
7928 ((setq a (org-extract-log-state-settings w))
7929 (and (member (car a) org-todo-keywords-1)
7930 (push a org-todo-log-states)))))))
7932 (defun org-get-todo-sequence-head (kwd)
7933 "Return the head of the TODO sequence to which KWD belongs.
7934 If KWD is not set, check if there is a text property remembering the
7935 right sequence."
7936 (let (p)
7937 (cond
7938 ((not kwd)
7939 (or (get-text-property (point-at-bol) 'org-todo-head)
7940 (progn
7941 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7942 nil (point-at-eol)))
7943 (get-text-property p 'org-todo-head))))
7944 ((not (member kwd org-todo-keywords-1))
7945 (car org-todo-keywords-1))
7946 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7948 (defun org-fast-todo-selection ()
7949 "Fast TODO keyword selection with single keys.
7950 Returns the new TODO keyword, or nil if no state change should occur."
7951 (let* ((fulltable org-todo-key-alist)
7952 (done-keywords org-done-keywords) ;; needed for the faces.
7953 (maxlen (apply 'max (mapcar
7954 (lambda (x)
7955 (if (stringp (car x)) (string-width (car x)) 0))
7956 fulltable)))
7957 (expert nil)
7958 (fwidth (+ maxlen 3 1 3))
7959 (ncol (/ (- (window-width) 4) fwidth))
7960 tg cnt e c tbl
7961 groups ingroup)
7962 (save-window-excursion
7963 (if expert
7964 (set-buffer (get-buffer-create " *Org todo*"))
7965 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7966 (erase-buffer)
7967 (org-set-local 'org-done-keywords done-keywords)
7968 (setq tbl fulltable cnt 0)
7969 (while (setq e (pop tbl))
7970 (cond
7971 ((equal e '(:startgroup))
7972 (push '() groups) (setq ingroup t)
7973 (when (not (= cnt 0))
7974 (setq cnt 0)
7975 (insert "\n"))
7976 (insert "{ "))
7977 ((equal e '(:endgroup))
7978 (setq ingroup nil cnt 0)
7979 (insert "}\n"))
7981 (setq tg (car e) c (cdr e))
7982 (if ingroup (push tg (car groups)))
7983 (setq tg (org-add-props tg nil 'face
7984 (org-get-todo-face tg)))
7985 (if (and (= cnt 0) (not ingroup)) (insert " "))
7986 (insert "[" c "] " tg (make-string
7987 (- fwidth 4 (length tg)) ?\ ))
7988 (when (= (setq cnt (1+ cnt)) ncol)
7989 (insert "\n")
7990 (if ingroup (insert " "))
7991 (setq cnt 0)))))
7992 (insert "\n")
7993 (goto-char (point-min))
7994 (if (and (not expert) (fboundp 'fit-window-to-buffer))
7995 (fit-window-to-buffer))
7996 (message "[a-z..]:Set [SPC]:clear")
7997 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
7998 (cond
7999 ((or (= c ?\C-g)
8000 (and (= c ?q) (not (rassoc c fulltable))))
8001 (setq quit-flag t))
8002 ((= c ?\ ) nil)
8003 ((setq e (rassoc c fulltable) tg (car e))
8005 (t (setq quit-flag t))))))
8007 (defun org-entry-is-todo-p ()
8008 (member (org-get-todo-state) org-not-done-keywords))
8010 (defun org-entry-is-done-p ()
8011 (member (org-get-todo-state) org-done-keywords))
8013 (defun org-get-todo-state ()
8014 (save-excursion
8015 (org-back-to-heading t)
8016 (and (looking-at org-todo-line-regexp)
8017 (match-end 2)
8018 (match-string 2))))
8020 (defun org-at-date-range-p (&optional inactive-ok)
8021 "Is the cursor inside a date range?"
8022 (interactive)
8023 (save-excursion
8024 (catch 'exit
8025 (let ((pos (point)))
8026 (skip-chars-backward "^[<\r\n")
8027 (skip-chars-backward "<[")
8028 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8029 (>= (match-end 0) pos)
8030 (throw 'exit t))
8031 (skip-chars-backward "^<[\r\n")
8032 (skip-chars-backward "<[")
8033 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8034 (>= (match-end 0) pos)
8035 (throw 'exit t)))
8036 nil)))
8038 (defun org-get-repeat ()
8039 "Check if there is a deadline/schedule with repeater in this entry."
8040 (save-match-data
8041 (save-excursion
8042 (org-back-to-heading t)
8043 (if (re-search-forward
8044 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8045 (match-string 1)))))
8047 (defvar org-last-changed-timestamp)
8048 (defvar org-last-inserted-timestamp)
8049 (defvar org-log-post-message)
8050 (defvar org-log-note-purpose)
8051 (defvar org-log-note-how)
8052 (defvar org-log-note-extra)
8053 (defun org-auto-repeat-maybe (done-word)
8054 "Check if the current headline contains a repeated deadline/schedule.
8055 If yes, set TODO state back to what it was and change the base date
8056 of repeating deadline/scheduled time stamps to new date.
8057 This function is run automatically after each state change to a DONE state."
8058 ;; last-state is dynamically scoped into this function
8059 (let* ((repeat (org-get-repeat))
8060 (aa (assoc last-state org-todo-kwd-alist))
8061 (interpret (nth 1 aa))
8062 (head (nth 2 aa))
8063 (whata '(("d" . day) ("m" . month) ("y" . year)))
8064 (msg "Entry repeats: ")
8065 (org-log-done nil)
8066 (org-todo-log-states nil)
8067 (nshiftmax 10) (nshift 0)
8068 re type n what ts mb0 time)
8069 (when repeat
8070 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8071 (org-todo (if (eq interpret 'type) last-state head))
8072 (when org-log-repeat
8073 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8074 (memq 'org-add-log-note post-command-hook))
8075 ;; OK, we are already setup for some record
8076 (if (eq org-log-repeat 'note)
8077 ;; make sure we take a note, not only a time stamp
8078 (setq org-log-note-how 'note))
8079 ;; Set up for taking a record
8080 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8081 'findpos org-log-repeat)))
8082 (org-back-to-heading t)
8083 (org-add-planning-info nil nil 'closed)
8084 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8085 org-deadline-time-regexp "\\)\\|\\("
8086 org-ts-regexp "\\)"))
8087 (while (re-search-forward
8088 re (save-excursion (outline-next-heading) (point)) t)
8089 (setq type (if (match-end 1) org-scheduled-string
8090 (if (match-end 3) org-deadline-string "Plain:"))
8091 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8092 mb0 (match-beginning 0))
8093 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8094 (setq n (string-to-number (match-string 2 ts))
8095 what (match-string 3 ts))
8096 (if (equal what "w") (setq n (* n 7) what "d"))
8097 ;; Preparation, see if we need to modify the start date for the change
8098 (when (match-end 1)
8099 (setq time (save-match-data (org-time-string-to-time ts)))
8100 (cond
8101 ((equal (match-string 1 ts) ".")
8102 ;; Shift starting date to today
8103 (org-timestamp-change
8104 (- (time-to-days (current-time)) (time-to-days time))
8105 'day))
8106 ((equal (match-string 1 ts) "+")
8107 (while (or (= nshift 0)
8108 (<= (time-to-days time) (time-to-days (current-time))))
8109 (when (= (incf nshift) nshiftmax)
8110 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8111 (error "Abort")))
8112 (org-timestamp-change n (cdr (assoc what whata)))
8113 (org-at-timestamp-p t)
8114 (setq ts (match-string 1))
8115 (setq time (save-match-data (org-time-string-to-time ts))))
8116 (org-timestamp-change (- n) (cdr (assoc what whata)))
8117 ;; rematch, so that we have everything in place for the real shift
8118 (org-at-timestamp-p t)
8119 (setq ts (match-string 1))
8120 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8121 (org-timestamp-change n (cdr (assoc what whata)))
8122 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8123 (setq org-log-post-message msg)
8124 (message "%s" msg))))
8126 (defun org-show-todo-tree (arg)
8127 "Make a compact tree which shows all headlines marked with TODO.
8128 The tree will show the lines where the regexp matches, and all higher
8129 headlines above the match.
8130 With a \\[universal-argument] prefix, also show the DONE entries.
8131 With a numeric prefix N, construct a sparse tree for the Nth element
8132 of `org-todo-keywords-1'."
8133 (interactive "P")
8134 (let ((case-fold-search nil)
8135 (kwd-re
8136 (cond ((null arg) org-not-done-regexp)
8137 ((equal arg '(4))
8138 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8139 (mapcar 'list org-todo-keywords-1))))
8140 (concat "\\("
8141 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8142 "\\)\\>")))
8143 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8144 (regexp-quote (nth (1- (prefix-numeric-value arg))
8145 org-todo-keywords-1)))
8146 (t (error "Invalid prefix argument: %s" arg)))))
8147 (message "%d TODO entries found"
8148 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8150 (defun org-deadline (&optional remove time)
8151 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8152 With argument REMOVE, remove any deadline from the item.
8153 When TIME is set, it should be an internal time specification, and the
8154 scheduling will use the corresponding date."
8155 (interactive "P")
8156 (if remove
8157 (progn
8158 (org-remove-timestamp-with-keyword org-deadline-string)
8159 (message "Item no longer has a deadline."))
8160 (if (org-get-repeat)
8161 (error "Cannot change deadline on task with repeater, please do that by hand")
8162 (org-add-planning-info 'deadline time 'closed)
8163 (message "Deadline on %s" org-last-inserted-timestamp))))
8165 (defun org-schedule (&optional remove time)
8166 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8167 With argument REMOVE, remove any scheduling date from the item.
8168 When TIME is set, it should be an internal time specification, and the
8169 scheduling will use the corresponding date."
8170 (interactive "P")
8171 (if remove
8172 (progn
8173 (org-remove-timestamp-with-keyword org-scheduled-string)
8174 (message "Item is no longer scheduled."))
8175 (if (org-get-repeat)
8176 (error "Cannot reschedule task with repeater, please do that by hand")
8177 (org-add-planning-info 'scheduled time 'closed)
8178 (message "Scheduled to %s" org-last-inserted-timestamp))))
8180 (defun org-remove-timestamp-with-keyword (keyword)
8181 "Remove all time stamps with KEYWORD in the current entry."
8182 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8183 beg)
8184 (save-excursion
8185 (org-back-to-heading t)
8186 (setq beg (point))
8187 (org-end-of-subtree t t)
8188 (while (re-search-backward re beg t)
8189 (replace-match "")
8190 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8191 (equal (char-before) ?\ ))
8192 (backward-delete-char 1)
8193 (if (string-match "^[ \t]*$" (buffer-substring
8194 (point-at-bol) (point-at-eol)))
8195 (delete-region (point-at-bol)
8196 (min (point-max) (1+ (point-at-eol))))))))))
8198 (defun org-add-planning-info (what &optional time &rest remove)
8199 "Insert new timestamp with keyword in the line directly after the headline.
8200 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8201 If non is given, the user is prompted for a date.
8202 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8203 be removed."
8204 (interactive)
8205 (let (org-time-was-given org-end-time-was-given ts
8206 end default-time default-input)
8208 (when (and (not time) (memq what '(scheduled deadline)))
8209 ;; Try to get a default date/time from existing timestamp
8210 (save-excursion
8211 (org-back-to-heading t)
8212 (setq end (save-excursion (outline-next-heading) (point)))
8213 (when (re-search-forward (if (eq what 'scheduled)
8214 org-scheduled-time-regexp
8215 org-deadline-time-regexp)
8216 end t)
8217 (setq ts (match-string 1)
8218 default-time
8219 (apply 'encode-time (org-parse-time-string ts))
8220 default-input (and ts (org-get-compact-tod ts))))))
8221 (when what
8222 ;; If necessary, get the time from the user
8223 (setq time (or time (org-read-date nil 'to-time nil nil
8224 default-time default-input))))
8226 (when (and org-insert-labeled-timestamps-at-point
8227 (member what '(scheduled deadline)))
8228 (insert
8229 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8230 (org-insert-time-stamp time org-time-was-given
8231 nil nil nil (list org-end-time-was-given))
8232 (setq what nil))
8233 (save-excursion
8234 (save-restriction
8235 (let (col list elt ts buffer-invisibility-spec)
8236 (org-back-to-heading t)
8237 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8238 (goto-char (match-end 1))
8239 (setq col (current-column))
8240 (goto-char (match-end 0))
8241 (if (eobp) (insert "\n") (forward-char 1))
8242 (if (and (not (looking-at outline-regexp))
8243 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8244 "[^\r\n]*"))
8245 (not (equal (match-string 1) org-clock-string)))
8246 (narrow-to-region (match-beginning 0) (match-end 0))
8247 (insert-before-markers "\n")
8248 (backward-char 1)
8249 (narrow-to-region (point) (point))
8250 (and org-adapt-indentation (org-indent-to-column col)))
8251 ;; Check if we have to remove something.
8252 (setq list (cons what remove))
8253 (while list
8254 (setq elt (pop list))
8255 (goto-char (point-min))
8256 (when (or (and (eq elt 'scheduled)
8257 (re-search-forward org-scheduled-time-regexp nil t))
8258 (and (eq elt 'deadline)
8259 (re-search-forward org-deadline-time-regexp nil t))
8260 (and (eq elt 'closed)
8261 (re-search-forward org-closed-time-regexp nil t)))
8262 (replace-match "")
8263 (if (looking-at "--+<[^>]+>") (replace-match ""))
8264 (if (looking-at " +") (replace-match ""))))
8265 (goto-char (point-max))
8266 (when what
8267 (insert
8268 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8269 (cond ((eq what 'scheduled) org-scheduled-string)
8270 ((eq what 'deadline) org-deadline-string)
8271 ((eq what 'closed) org-closed-string))
8272 " ")
8273 (setq ts (org-insert-time-stamp
8274 time
8275 (or org-time-was-given
8276 (and (eq what 'closed) org-log-done-with-time))
8277 (eq what 'closed)
8278 nil nil (list org-end-time-was-given)))
8279 (end-of-line 1))
8280 (goto-char (point-min))
8281 (widen)
8282 (if (and (looking-at "[ \t]+\n")
8283 (equal (char-before) ?\n))
8284 (delete-region (1- (point)) (point-at-eol)))
8285 ts)))))
8287 (defvar org-log-note-marker (make-marker))
8288 (defvar org-log-note-purpose nil)
8289 (defvar org-log-note-state nil)
8290 (defvar org-log-note-how nil)
8291 (defvar org-log-note-extra nil)
8292 (defvar org-log-note-window-configuration nil)
8293 (defvar org-log-note-return-to (make-marker))
8294 (defvar org-log-post-message nil
8295 "Message to be displayed after a log note has been stored.
8296 The auto-repeater uses this.")
8298 (defun org-add-note ()
8299 "Add a note to the current entry.
8300 This is done in the same way as adding a state change note."
8301 (interactive)
8302 (org-add-log-setup 'note nil 'findpos nil))
8304 (defvar org-property-end-re)
8305 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8306 "Set up the post command hook to take a note.
8307 If this is about to TODO state change, the new state is expected in STATE.
8308 When FINDPOS is non-nil, find the correct position for the note in
8309 the current entry. If not, assume that it can be inserted at point.
8310 HOW is an indicator what kind of note should be created.
8311 EXTRA is additional text that will be inserted into the notes buffer."
8312 (save-restriction
8313 (save-excursion
8314 (when findpos
8315 (org-back-to-heading t)
8316 (narrow-to-region (point) (save-excursion
8317 (outline-next-heading) (point)))
8318 (while (re-search-forward
8319 (concat "\\(" org-drawer-regexp "\\|" org-property-end-re "\\)")
8320 (point-max) t) (forward-line))
8321 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8322 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8323 "[^\r\n]*\\)?"))
8324 (goto-char (match-end 0))
8325 (unless org-log-states-order-reversed
8326 (and (= (char-after) ?\n) (forward-char 1))
8327 (org-skip-over-state-notes)
8328 (skip-chars-backward " \t\n\r")))
8329 (move-marker org-log-note-marker (point))
8330 (setq org-log-note-purpose purpose
8331 org-log-note-state state
8332 org-log-note-how how
8333 org-log-note-extra extra)
8334 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8336 (defun org-skip-over-state-notes ()
8337 "Skip past the list of State notes in an entry."
8338 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8339 (while (looking-at "[ \t]*- State")
8340 (condition-case nil
8341 (org-next-item)
8342 (error (org-end-of-item)))))
8344 (defun org-add-log-note (&optional purpose)
8345 "Pop up a window for taking a note, and add this note later at point."
8346 (remove-hook 'post-command-hook 'org-add-log-note)
8347 (setq org-log-note-window-configuration (current-window-configuration))
8348 (delete-other-windows)
8349 (move-marker org-log-note-return-to (point))
8350 (switch-to-buffer (marker-buffer org-log-note-marker))
8351 (goto-char org-log-note-marker)
8352 (org-switch-to-buffer-other-window "*Org Note*")
8353 (erase-buffer)
8354 (if (memq org-log-note-how '(time state))
8355 (org-store-log-note)
8356 (let ((org-inhibit-startup t)) (org-mode))
8357 (insert (format "# Insert note for %s.
8358 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8359 (cond
8360 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8361 ((eq org-log-note-purpose 'done) "closed todo item")
8362 ((eq org-log-note-purpose 'state)
8363 (format "state change to \"%s\"" org-log-note-state))
8364 ((eq org-log-note-purpose 'note)
8365 "this entry")
8366 (t (error "This should not happen")))))
8367 (if org-log-note-extra (insert org-log-note-extra))
8368 (org-set-local 'org-finish-function 'org-store-log-note)))
8370 (defvar org-note-abort nil) ; dynamically scoped
8371 (defun org-store-log-note ()
8372 "Finish taking a log note, and insert it to where it belongs."
8373 (let ((txt (buffer-string))
8374 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8375 lines ind)
8376 (kill-buffer (current-buffer))
8377 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8378 (setq txt (replace-match "" t t txt)))
8379 (if (string-match "\\s-+\\'" txt)
8380 (setq txt (replace-match "" t t txt)))
8381 (setq lines (org-split-string txt "\n"))
8382 (when (and note (string-match "\\S-" note))
8383 (setq note
8384 (org-replace-escapes
8385 note
8386 (list (cons "%u" (user-login-name))
8387 (cons "%U" user-full-name)
8388 (cons "%t" (format-time-string
8389 (org-time-stamp-format 'long 'inactive)
8390 (current-time)))
8391 (cons "%s" (if org-log-note-state
8392 (concat "\"" org-log-note-state "\"")
8393 "")))))
8394 (if lines (setq note (concat note " \\\\")))
8395 (push note lines))
8396 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8397 (when lines
8398 (save-excursion
8399 (set-buffer (marker-buffer org-log-note-marker))
8400 (save-excursion
8401 (goto-char org-log-note-marker)
8402 (move-marker org-log-note-marker nil)
8403 (end-of-line 1)
8404 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8405 (indent-relative nil)
8406 (insert "- " (pop lines))
8407 (org-indent-line-function)
8408 (beginning-of-line 1)
8409 (looking-at "[ \t]*")
8410 (setq ind (concat (match-string 0) " "))
8411 (end-of-line 1)
8412 (while lines (insert "\n" ind (pop lines)))))))
8413 (set-window-configuration org-log-note-window-configuration)
8414 (with-current-buffer (marker-buffer org-log-note-return-to)
8415 (goto-char org-log-note-return-to))
8416 (move-marker org-log-note-return-to nil)
8417 (and org-log-post-message (message "%s" org-log-post-message)))
8419 (defun org-sparse-tree (&optional arg)
8420 "Create a sparse tree, prompt for the details.
8421 This command can create sparse trees. You first need to select the type
8422 of match used to create the tree:
8424 t Show entries with a specific TODO keyword.
8425 T Show entries selected by a tags match.
8426 p Enter a property name and its value (both with completion on existing
8427 names/values) and show entries with that property.
8428 r Show entries matching a regular expression
8429 d Show deadlines due within `org-deadline-warning-days'."
8430 (interactive "P")
8431 (let (ans kwd value)
8432 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8433 (setq ans (read-char-exclusive))
8434 (cond
8435 ((equal ans ?d)
8436 (call-interactively 'org-check-deadlines))
8437 ((equal ans ?b)
8438 (call-interactively 'org-check-before-date))
8439 ((equal ans ?t)
8440 (org-show-todo-tree '(4)))
8441 ((equal ans ?T)
8442 (call-interactively 'org-tags-sparse-tree))
8443 ((member ans '(?p ?P))
8444 (setq kwd (completing-read "Property: "
8445 (mapcar 'list (org-buffer-property-keys))))
8446 (setq value (completing-read "Value: "
8447 (mapcar 'list (org-property-values kwd))))
8448 (unless (string-match "\\`{.*}\\'" value)
8449 (setq value (concat "\"" value "\"")))
8450 (org-tags-sparse-tree arg (concat kwd "=" value)))
8451 ((member ans '(?r ?R ?/))
8452 (call-interactively 'org-occur))
8453 (t (error "No such sparse tree command \"%c\"" ans)))))
8455 (defvar org-occur-highlights nil
8456 "List of overlays used for occur matches.")
8457 (make-variable-buffer-local 'org-occur-highlights)
8458 (defvar org-occur-parameters nil
8459 "Parameters of the active org-occur calls.
8460 This is a list, each call to org-occur pushes as cons cell,
8461 containing the regular expression and the callback, onto the list.
8462 The list can contain several entries if `org-occur' has been called
8463 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8464 will only contain one set of parameters. When the highlights are
8465 removed (for example with `C-c C-c', or with the next edit (depending
8466 on `org-remove-highlights-with-change'), this variable is emptied
8467 as well.")
8468 (make-variable-buffer-local 'org-occur-parameters)
8470 (defun org-occur (regexp &optional keep-previous callback)
8471 "Make a compact tree which shows all matches of REGEXP.
8472 The tree will show the lines where the regexp matches, and all higher
8473 headlines above the match. It will also show the heading after the match,
8474 to make sure editing the matching entry is easy.
8475 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8476 call to `org-occur' will be kept, to allow stacking of calls to this
8477 command.
8478 If CALLBACK is non-nil, it is a function which is called to confirm
8479 that the match should indeed be shown."
8480 (interactive "sRegexp: \nP")
8481 (unless keep-previous
8482 (org-remove-occur-highlights nil nil t))
8483 (push (cons regexp callback) org-occur-parameters)
8484 (let ((cnt 0))
8485 (save-excursion
8486 (goto-char (point-min))
8487 (if (or (not keep-previous) ; do not want to keep
8488 (not org-occur-highlights)) ; no previous matches
8489 ;; hide everything
8490 (org-overview))
8491 (while (re-search-forward regexp nil t)
8492 (when (or (not callback)
8493 (save-match-data (funcall callback)))
8494 (setq cnt (1+ cnt))
8495 (when org-highlight-sparse-tree-matches
8496 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8497 (org-show-context 'occur-tree))))
8498 (when org-remove-highlights-with-change
8499 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8500 nil 'local))
8501 (unless org-sparse-tree-open-archived-trees
8502 (org-hide-archived-subtrees (point-min) (point-max)))
8503 (run-hooks 'org-occur-hook)
8504 (if (interactive-p)
8505 (message "%d match(es) for regexp %s" cnt regexp))
8506 cnt))
8508 (defun org-show-context (&optional key)
8509 "Make sure point and context and visible.
8510 How much context is shown depends upon the variables
8511 `org-show-hierarchy-above', `org-show-following-heading'. and
8512 `org-show-siblings'."
8513 (let ((heading-p (org-on-heading-p t))
8514 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8515 (following-p (org-get-alist-option org-show-following-heading key))
8516 (entry-p (org-get-alist-option org-show-entry-below key))
8517 (siblings-p (org-get-alist-option org-show-siblings key)))
8518 (catch 'exit
8519 ;; Show heading or entry text
8520 (if (and heading-p (not entry-p))
8521 (org-flag-heading nil) ; only show the heading
8522 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8523 (org-show-hidden-entry))) ; show entire entry
8524 (when following-p
8525 ;; Show next sibling, or heading below text
8526 (save-excursion
8527 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8528 (org-flag-heading nil))))
8529 (when siblings-p (org-show-siblings))
8530 (when hierarchy-p
8531 ;; show all higher headings, possibly with siblings
8532 (save-excursion
8533 (while (and (condition-case nil
8534 (progn (org-up-heading-all 1) t)
8535 (error nil))
8536 (not (bobp)))
8537 (org-flag-heading nil)
8538 (when siblings-p (org-show-siblings))))))))
8540 (defun org-reveal (&optional siblings)
8541 "Show current entry, hierarchy above it, and the following headline.
8542 This can be used to show a consistent set of context around locations
8543 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8544 not t for the search context.
8546 With optional argument SIBLINGS, on each level of the hierarchy all
8547 siblings are shown. This repairs the tree structure to what it would
8548 look like when opened with hierarchical calls to `org-cycle'."
8549 (interactive "P")
8550 (let ((org-show-hierarchy-above t)
8551 (org-show-following-heading t)
8552 (org-show-siblings (if siblings t org-show-siblings)))
8553 (org-show-context nil)))
8555 (defun org-highlight-new-match (beg end)
8556 "Highlight from BEG to END and mark the highlight is an occur headline."
8557 (let ((ov (org-make-overlay beg end)))
8558 (org-overlay-put ov 'face 'secondary-selection)
8559 (push ov org-occur-highlights)))
8561 (defun org-remove-occur-highlights (&optional beg end noremove)
8562 "Remove the occur highlights from the buffer.
8563 BEG and END are ignored. If NOREMOVE is nil, remove this function
8564 from the `before-change-functions' in the current buffer."
8565 (interactive)
8566 (unless org-inhibit-highlight-removal
8567 (mapc 'org-delete-overlay org-occur-highlights)
8568 (setq org-occur-highlights nil)
8569 (setq org-occur-parameters nil)
8570 (unless noremove
8571 (remove-hook 'before-change-functions
8572 'org-remove-occur-highlights 'local))))
8574 ;;;; Priorities
8576 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8577 "Regular expression matching the priority indicator.")
8579 (defvar org-remove-priority-next-time nil)
8581 (defun org-priority-up ()
8582 "Increase the priority of the current item."
8583 (interactive)
8584 (org-priority 'up))
8586 (defun org-priority-down ()
8587 "Decrease the priority of the current item."
8588 (interactive)
8589 (org-priority 'down))
8591 (defun org-priority (&optional action)
8592 "Change the priority of an item by ARG.
8593 ACTION can be `set', `up', `down', or a character."
8594 (interactive)
8595 (setq action (or action 'set))
8596 (let (current new news have remove)
8597 (save-excursion
8598 (org-back-to-heading)
8599 (if (looking-at org-priority-regexp)
8600 (setq current (string-to-char (match-string 2))
8601 have t)
8602 (setq current org-default-priority))
8603 (cond
8604 ((or (eq action 'set)
8605 (if (featurep 'xemacs) (characterp action) (integerp action)))
8606 (if (not (eq action 'set))
8607 (setq new action)
8608 (message "Priority %c-%c, SPC to remove: "
8609 org-highest-priority org-lowest-priority)
8610 (setq new (read-char-exclusive)))
8611 (if (and (= (upcase org-highest-priority) org-highest-priority)
8612 (= (upcase org-lowest-priority) org-lowest-priority))
8613 (setq new (upcase new)))
8614 (cond ((equal new ?\ ) (setq remove t))
8615 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8616 (error "Priority must be between `%c' and `%c'"
8617 org-highest-priority org-lowest-priority))))
8618 ((eq action 'up)
8619 (if (and (not have) (eq last-command this-command))
8620 (setq new org-lowest-priority)
8621 (setq new (if (and org-priority-start-cycle-with-default (not have))
8622 org-default-priority (1- current)))))
8623 ((eq action 'down)
8624 (if (and (not have) (eq last-command this-command))
8625 (setq new org-highest-priority)
8626 (setq new (if (and org-priority-start-cycle-with-default (not have))
8627 org-default-priority (1+ current)))))
8628 (t (error "Invalid action")))
8629 (if (or (< (upcase new) org-highest-priority)
8630 (> (upcase new) org-lowest-priority))
8631 (setq remove t))
8632 (setq news (format "%c" new))
8633 (if have
8634 (if remove
8635 (replace-match "" t t nil 1)
8636 (replace-match news t t nil 2))
8637 (if remove
8638 (error "No priority cookie found in line")
8639 (looking-at org-todo-line-regexp)
8640 (if (match-end 2)
8641 (progn
8642 (goto-char (match-end 2))
8643 (insert " [#" news "]"))
8644 (goto-char (match-beginning 3))
8645 (insert "[#" news "] ")))))
8646 (org-preserve-lc (org-set-tags nil 'align))
8647 (if remove
8648 (message "Priority removed")
8649 (message "Priority of current item set to %s" news))))
8652 (defun org-get-priority (s)
8653 "Find priority cookie and return priority."
8654 (save-match-data
8655 (if (not (string-match org-priority-regexp s))
8656 (* 1000 (- org-lowest-priority org-default-priority))
8657 (* 1000 (- org-lowest-priority
8658 (string-to-char (match-string 2 s)))))))
8660 ;;;; Tags
8662 (defvar org-agenda-archives-mode)
8663 (defun org-scan-tags (action matcher &optional todo-only)
8664 "Scan headline tags with inheritance and produce output ACTION.
8666 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8667 or `agenda' to produce an entry list for an agenda view. It can also be
8668 a Lisp form or a function that should be called at each matched headline, in
8669 this case the return value is a list of all return values from these calls.
8671 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8672 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8673 only lines with a TODO keyword are included in the output."
8674 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8675 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8676 (org-re
8677 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8678 (props (list 'face 'default
8679 'done-face 'org-done
8680 'undone-face 'default
8681 'mouse-face 'highlight
8682 'org-not-done-regexp org-not-done-regexp
8683 'org-todo-regexp org-todo-regexp
8684 'keymap org-agenda-keymap
8685 'help-echo
8686 (format "mouse-2 or RET jump to org file %s"
8687 (abbreviate-file-name
8688 (or (buffer-file-name (buffer-base-buffer))
8689 (buffer-name (buffer-base-buffer)))))))
8690 (case-fold-search nil)
8691 lspos tags tags-list
8692 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8693 (llast 0) rtn rtn1 level category i txt
8694 todo marker entry priority)
8695 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8696 (setq action (list 'lambda nil action)))
8697 (save-excursion
8698 (goto-char (point-min))
8699 (when (eq action 'sparse-tree)
8700 (org-overview)
8701 (org-remove-occur-highlights))
8702 (while (re-search-forward re nil t)
8703 (catch :skip
8704 (setq todo (if (match-end 1) (match-string 2))
8705 tags (if (match-end 4) (match-string 4)))
8706 (goto-char (setq lspos (1+ (match-beginning 0))))
8707 (setq level (org-reduced-level (funcall outline-level))
8708 category (org-get-category))
8709 (setq i llast llast level)
8710 ;; remove tag lists from same and sublevels
8711 (while (>= i level)
8712 (when (setq entry (assoc i tags-alist))
8713 (setq tags-alist (delete entry tags-alist)))
8714 (setq i (1- i)))
8715 ;; add the next tags
8716 (when tags
8717 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8718 tags-alist
8719 (cons (cons level tags) tags-alist)))
8720 ;; compile tags for current headline
8721 (setq tags-list
8722 (if org-use-tag-inheritance
8723 (apply 'append (mapcar 'cdr tags-alist))
8724 tags))
8725 (when (and tags org-use-tag-inheritance
8726 (not (eq t org-use-tag-inheritance)))
8727 ;; selective inheritance, remove uninherited ones
8728 (setcdr (car tags-alist)
8729 (org-remove-uniherited-tags (cdar tags-alist))))
8730 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8731 (let ((case-fold-search t)) (eval matcher))
8733 (not (member org-archive-tag tags-list))
8734 ;; we have an archive tag, should we use this anyway?
8735 (or (not org-agenda-skip-archived-trees)
8736 (and (eq action 'agenda) org-agenda-archives-mode))))
8737 (unless (eq action 'sparse-tree) (org-agenda-skip))
8739 ;; select this headline
8741 (cond
8742 ((eq action 'sparse-tree)
8743 (and org-highlight-sparse-tree-matches
8744 (org-get-heading) (match-end 0)
8745 (org-highlight-new-match
8746 (match-beginning 0) (match-beginning 1)))
8747 (org-show-context 'tags-tree))
8748 ((eq action 'agenda)
8749 (setq txt (org-format-agenda-item
8751 (concat
8752 (if org-tags-match-list-sublevels
8753 (make-string (1- level) ?.) "")
8754 (org-get-heading))
8755 category tags-list)
8756 priority (org-get-priority txt))
8757 (goto-char lspos)
8758 (setq marker (org-agenda-new-marker))
8759 (org-add-props txt props
8760 'org-marker marker 'org-hd-marker marker 'org-category category
8761 'priority priority 'type "tagsmatch")
8762 (push txt rtn))
8763 ((functionp action)
8764 (save-excursion
8765 (setq rtn1 (funcall action))
8766 (push rtn1 rtn))
8767 (goto-char (point-at-eol)))
8768 (t (error "Invalid action")))
8770 ;; if we are to skip sublevels, jump to end of subtree
8771 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8772 (when (and (eq action 'sparse-tree)
8773 (not org-sparse-tree-open-archived-trees))
8774 (org-hide-archived-subtrees (point-min) (point-max)))
8775 (nreverse rtn)))
8777 (defun org-remove-uniherited-tags (tags)
8778 "Remove all tags that are not inherited from the list TAGS."
8779 (cond
8780 ((eq org-use-tag-inheritance t) tags)
8781 ((not org-use-tag-inheritance) nil)
8782 ((stringp org-use-tag-inheritance)
8783 (delq nil (mapcar
8784 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8785 tags)))
8786 ((listp org-use-tag-inheritance)
8787 (org-delete-all org-use-tag-inheritance tags))))
8789 (defvar todo-only) ;; dynamically scoped
8791 (defun org-tags-sparse-tree (&optional todo-only match)
8792 "Create a sparse tree according to tags string MATCH.
8793 MATCH can contain positive and negative selection of tags, like
8794 \"+WORK+URGENT-WITHBOSS\".
8795 If optional argument TODO_ONLY is non-nil, only select lines that are
8796 also TODO lines."
8797 (interactive "P")
8798 (org-prepare-agenda-buffers (list (current-buffer)))
8799 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8801 (defvar org-cached-props nil)
8802 (defun org-cached-entry-get (pom property)
8803 (if (or (eq t org-use-property-inheritance)
8804 (and (stringp org-use-property-inheritance)
8805 (string-match org-use-property-inheritance property))
8806 (and (listp org-use-property-inheritance)
8807 (member property org-use-property-inheritance)))
8808 ;; Caching is not possible, check it directly
8809 (org-entry-get pom property 'inherit)
8810 ;; Get all properties, so that we can do complicated checks easily
8811 (cdr (assoc property (or org-cached-props
8812 (setq org-cached-props
8813 (org-entry-properties pom)))))))
8815 (defun org-global-tags-completion-table (&optional files)
8816 "Return the list of all tags in all agenda buffer/files."
8817 (save-excursion
8818 (org-uniquify
8819 (delq nil
8820 (apply 'append
8821 (mapcar
8822 (lambda (file)
8823 (set-buffer (find-file-noselect file))
8824 (append (org-get-buffer-tags)
8825 (mapcar (lambda (x) (if (stringp (car-safe x))
8826 (list (car-safe x)) nil))
8827 org-tag-alist)))
8828 (if (and files (car files))
8829 files
8830 (org-agenda-files))))))))
8832 (defun org-make-tags-matcher (match)
8833 "Create the TAGS//TODO matcher form for the selection string MATCH."
8834 ;; todo-only is scoped dynamically into this function, and the function
8835 ;; may change it it the matcher asksk for it.
8836 (unless match
8837 ;; Get a new match request, with completion
8838 (let ((org-last-tags-completion-table
8839 (org-global-tags-completion-table)))
8840 (setq match (completing-read
8841 "Match: " 'org-tags-completion-function nil nil nil
8842 'org-tags-history))))
8844 ;; Parse the string and create a lisp form
8845 (let ((match0 match)
8846 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8847 minus tag mm
8848 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8849 orterms term orlist re-p str-p level-p level-op time-p
8850 prop-p pn pv po cat-p gv)
8851 (if (string-match "/+" match)
8852 ;; match contains also a todo-matching request
8853 (progn
8854 (setq tagsmatch (substring match 0 (match-beginning 0))
8855 todomatch (substring match (match-end 0)))
8856 (if (string-match "^!" todomatch)
8857 (setq todo-only t todomatch (substring todomatch 1)))
8858 (if (string-match "^\\s-*$" todomatch)
8859 (setq todomatch nil)))
8860 ;; only matching tags
8861 (setq tagsmatch match todomatch nil))
8863 ;; Make the tags matcher
8864 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8865 (setq tagsmatcher t)
8866 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8867 (while (setq term (pop orterms))
8868 (while (and (equal (substring term -1) "\\") orterms)
8869 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8870 (while (string-match re term)
8871 (setq minus (and (match-end 1)
8872 (equal (match-string 1 term) "-"))
8873 tag (match-string 2 term)
8874 re-p (equal (string-to-char tag) ?{)
8875 level-p (match-end 4)
8876 prop-p (match-end 5)
8877 mm (cond
8878 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8879 (level-p
8880 (setq level-op (org-op-to-function (match-string 3 term)))
8881 `(,level-op level ,(string-to-number
8882 (match-string 4 term))))
8883 (prop-p
8884 (setq pn (match-string 5 term)
8885 po (match-string 6 term)
8886 pv (match-string 7 term)
8887 cat-p (equal pn "CATEGORY")
8888 re-p (equal (string-to-char pv) ?{)
8889 str-p (equal (string-to-char pv) ?\")
8890 time-p (save-match-data (string-match "^\"<.*>\"$" pv))
8891 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8892 (if time-p (setq pv (org-matcher-time pv)))
8893 (setq po (org-op-to-function po (if time-p 'time str-p)))
8894 (if (equal pn "CATEGORY")
8895 (setq gv '(get-text-property (point) 'org-category))
8896 (setq gv `(org-cached-entry-get nil ,pn)))
8897 (if re-p
8898 (if (eq po 'org<>)
8899 `(not (string-match ,pv (or ,gv "")))
8900 `(string-match ,pv (or ,gv "")))
8901 (if str-p
8902 `(,po (or ,gv "") ,pv)
8903 `(,po (string-to-number (or ,gv ""))
8904 ,(string-to-number pv) ))))
8905 (t `(member ,(downcase tag) tags-list)))
8906 mm (if minus (list 'not mm) mm)
8907 term (substring term (match-end 0)))
8908 (push mm tagsmatcher))
8909 (push (if (> (length tagsmatcher) 1)
8910 (cons 'and tagsmatcher)
8911 (car tagsmatcher))
8912 orlist)
8913 (setq tagsmatcher nil))
8914 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8915 (setq tagsmatcher
8916 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8917 ;; Make the todo matcher
8918 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8919 (setq todomatcher t)
8920 (setq orterms (org-split-string todomatch "|") orlist nil)
8921 (while (setq term (pop orterms))
8922 (while (string-match re term)
8923 (setq minus (and (match-end 1)
8924 (equal (match-string 1 term) "-"))
8925 kwd (match-string 2 term)
8926 re-p (equal (string-to-char kwd) ?{)
8927 term (substring term (match-end 0))
8928 mm (if re-p
8929 `(string-match ,(substring kwd 1 -1) todo)
8930 (list 'equal 'todo kwd))
8931 mm (if minus (list 'not mm) mm))
8932 (push mm todomatcher))
8933 (push (if (> (length todomatcher) 1)
8934 (cons 'and todomatcher)
8935 (car todomatcher))
8936 orlist)
8937 (setq todomatcher nil))
8938 (setq todomatcher (if (> (length orlist) 1)
8939 (cons 'or orlist) (car orlist))))
8941 ;; Return the string and lisp forms of the matcher
8942 (setq matcher (if todomatcher
8943 (list 'and tagsmatcher todomatcher)
8944 tagsmatcher))
8945 (cons match0 matcher)))
8947 (defun org-op-to-function (op &optional stringp)
8948 "Turn an operator into the appropriate function."
8949 (setq op
8950 (cond
8951 ((equal op "<" ) '(< string< org-time<))
8952 ((equal op ">" ) '(> org-string> org-time>))
8953 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
8954 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
8955 ((member op '("=" "==")) '(= string= org-time=))
8956 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
8957 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
8959 (defun org<> (a b) (not (= a b)))
8960 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8961 (defun org-string>= (a b) (not (string< a b)))
8962 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
8963 (defun org-string<> (a b) (not (string= a b)))
8964 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
8965 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
8966 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
8967 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
8968 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
8969 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
8970 (defun org-2ft (s)
8971 "Convert S to a floating point time.
8972 If S is already a number, just return it. If it is a string, parse
8973 it as a time string and apply `float-time' to it. f S is nil, just return 0."
8974 (cond
8975 ((numberp s) s)
8976 ((stringp s)
8977 (condition-case nil
8978 (float-time (apply 'encode-time (org-parse-time-string s)))
8979 (error 0.)))
8980 (t 0.)))
8982 (defun org-matcher-time (s)
8983 (cond
8984 ((equal s "<now>") (float-time))
8985 ((equal s "<today>")
8986 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
8987 (t (org-2ft s))))
8989 (defun org-match-any-p (re list)
8990 "Does re match any element of list?"
8991 (setq list (mapcar (lambda (x) (string-match re x)) list))
8992 (delq nil list))
8994 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8995 (defvar org-tags-overlay (org-make-overlay 1 1))
8996 (org-detach-overlay org-tags-overlay)
8998 (defun org-get-local-tags-at (&optional pos)
8999 "Get a list of tags defined in the current headline."
9000 (org-get-tags-at pos 'local))
9002 (defun org-get-local-tags ()
9003 "Get a list of tags defined in the current headline."
9004 (org-get-tags-at nil 'local))
9006 (defun org-get-tags-at (&optional pos local)
9007 "Get a list of all headline tags applicable at POS.
9008 POS defaults to point. If tags are inherited, the list contains
9009 the targets in the same sequence as the headlines appear, i.e.
9010 the tags of the current headline come last.
9011 When LOCAL is non-nil, only return tags from the current headline,
9012 ignore inherited ones."
9013 (interactive)
9014 (let (tags ltags lastpos parent)
9015 (save-excursion
9016 (save-restriction
9017 (widen)
9018 (goto-char (or pos (point)))
9019 (save-match-data
9020 (catch 'done
9021 (condition-case nil
9022 (progn
9023 (org-back-to-heading t)
9024 (while (not (equal lastpos (point)))
9025 (setq lastpos (point))
9026 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9027 (setq ltags (org-split-string
9028 (org-match-string-no-properties 1) ":"))
9029 (setq tags (append
9030 (if parent
9031 (org-remove-uniherited-tags ltags)
9032 ltags)
9033 tags)))
9034 (or org-use-tag-inheritance (throw 'done t))
9035 (if local (throw 'done t))
9036 (org-up-heading-all 1)
9037 (setq parent t)))
9038 (error nil)))))
9039 (append (org-remove-uniherited-tags org-file-tags) tags))))
9041 (defun org-toggle-tag (tag &optional onoff)
9042 "Toggle the tag TAG for the current line.
9043 If ONOFF is `on' or `off', don't toggle but set to this state."
9044 (unless (org-on-heading-p t) (error "Not on headling"))
9045 (let (res current)
9046 (save-excursion
9047 (beginning-of-line)
9048 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9049 (point-at-eol) t)
9050 (progn
9051 (setq current (match-string 1))
9052 (replace-match ""))
9053 (setq current ""))
9054 (setq current (nreverse (org-split-string current ":")))
9055 (cond
9056 ((eq onoff 'on)
9057 (setq res t)
9058 (or (member tag current) (push tag current)))
9059 ((eq onoff 'off)
9060 (or (not (member tag current)) (setq current (delete tag current))))
9061 (t (if (member tag current)
9062 (setq current (delete tag current))
9063 (setq res t)
9064 (push tag current))))
9065 (end-of-line 1)
9066 (if current
9067 (progn
9068 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9069 (org-set-tags nil t))
9070 (delete-horizontal-space))
9071 (run-hooks 'org-after-tags-change-hook))
9072 res))
9074 (defun org-align-tags-here (to-col)
9075 ;; Assumes that this is a headline
9076 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9077 (beginning-of-line 1)
9078 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9079 (< pos (match-beginning 2)))
9080 (progn
9081 (setq tags-l (- (match-end 2) (match-beginning 2)))
9082 (goto-char (match-beginning 1))
9083 (insert " ")
9084 (delete-region (point) (1+ (match-beginning 2)))
9085 (setq ncol (max (1+ (current-column))
9086 (1+ col)
9087 (if (> to-col 0)
9088 to-col
9089 (- (abs to-col) tags-l))))
9090 (setq p (point))
9091 (insert (make-string (- ncol (current-column)) ?\ ))
9092 (setq ncol (current-column))
9093 (when indent-tabs-mode (tabify p (point-at-eol)))
9094 (org-move-to-column (min ncol col) t))
9095 (goto-char pos))))
9097 (defun org-set-tags (&optional arg just-align)
9098 "Set the tags for the current headline.
9099 With prefix ARG, realign all tags in headings in the current buffer."
9100 (interactive "P")
9101 (let* ((re (concat "^" outline-regexp))
9102 (current (org-get-tags-string))
9103 (col (current-column))
9104 (org-setting-tags t)
9105 table current-tags inherited-tags ; computed below when needed
9106 tags p0 c0 c1 rpl)
9107 (if arg
9108 (save-excursion
9109 (goto-char (point-min))
9110 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9111 (while (re-search-forward re nil t)
9112 (org-set-tags nil t)
9113 (end-of-line 1)))
9114 (message "All tags realigned to column %d" org-tags-column))
9115 (if just-align
9116 (setq tags current)
9117 ;; Get a new set of tags from the user
9118 (save-excursion
9119 (setq table (or org-tag-alist (org-get-buffer-tags))
9120 org-last-tags-completion-table table
9121 current-tags (org-split-string current ":")
9122 inherited-tags (nreverse
9123 (nthcdr (length current-tags)
9124 (nreverse (org-get-tags-at))))
9125 tags
9126 (if (or (eq t org-use-fast-tag-selection)
9127 (and org-use-fast-tag-selection
9128 (delq nil (mapcar 'cdr table))))
9129 (org-fast-tag-selection
9130 current-tags inherited-tags table
9131 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9132 (let ((org-add-colon-after-tag-completion t))
9133 (org-trim
9134 (org-without-partial-completion
9135 (completing-read "Tags: " 'org-tags-completion-function
9136 nil nil current 'org-tags-history)))))))
9137 (while (string-match "[-+&]+" tags)
9138 ;; No boolean logic, just a list
9139 (setq tags (replace-match ":" t t tags))))
9141 (if (string-match "\\`[\t ]*\\'" tags)
9142 (setq tags "")
9143 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9144 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9146 ;; Insert new tags at the correct column
9147 (beginning-of-line 1)
9148 (cond
9149 ((and (equal current "") (equal tags "")))
9150 ((re-search-forward
9151 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9152 (point-at-eol) t)
9153 (if (equal tags "")
9154 (setq rpl "")
9155 (goto-char (match-beginning 0))
9156 (setq c0 (current-column) p0 (point)
9157 c1 (max (1+ c0) (if (> org-tags-column 0)
9158 org-tags-column
9159 (- (- org-tags-column) (length tags))))
9160 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9161 (replace-match rpl t t)
9162 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9163 tags)
9164 (t (error "Tags alignment failed")))
9165 (org-move-to-column col)
9166 (unless just-align
9167 (run-hooks 'org-after-tags-change-hook)))))
9169 (defun org-change-tag-in-region (beg end tag off)
9170 "Add or remove TAG for each entry in the region.
9171 This works in the agenda, and also in an org-mode buffer."
9172 (interactive
9173 (list (region-beginning) (region-end)
9174 (let ((org-last-tags-completion-table
9175 (if (org-mode-p)
9176 (org-get-buffer-tags)
9177 (org-global-tags-completion-table))))
9178 (completing-read
9179 "Tag: " 'org-tags-completion-function nil nil nil
9180 'org-tags-history))
9181 (progn
9182 (message "[s]et or [r]emove? ")
9183 (equal (read-char-exclusive) ?r))))
9184 (if (fboundp 'deactivate-mark) (deactivate-mark))
9185 (let ((agendap (equal major-mode 'org-agenda-mode))
9186 l1 l2 m buf pos newhead (cnt 0))
9187 (goto-char end)
9188 (setq l2 (1- (org-current-line)))
9189 (goto-char beg)
9190 (setq l1 (org-current-line))
9191 (loop for l from l1 to l2 do
9192 (goto-line l)
9193 (setq m (get-text-property (point) 'org-hd-marker))
9194 (when (or (and (org-mode-p) (org-on-heading-p))
9195 (and agendap m))
9196 (setq buf (if agendap (marker-buffer m) (current-buffer))
9197 pos (if agendap m (point)))
9198 (with-current-buffer buf
9199 (save-excursion
9200 (save-restriction
9201 (goto-char pos)
9202 (setq cnt (1+ cnt))
9203 (org-toggle-tag tag (if off 'off 'on))
9204 (setq newhead (org-get-heading)))))
9205 (and agendap (org-agenda-change-all-lines newhead m))))
9206 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9208 (defun org-tags-completion-function (string predicate &optional flag)
9209 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9210 (confirm (lambda (x) (stringp (car x)))))
9211 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9212 (setq s1 (match-string 1 string)
9213 s2 (match-string 2 string))
9214 (setq s1 "" s2 string))
9215 (cond
9216 ((eq flag nil)
9217 ;; try completion
9218 (setq rtn (try-completion s2 ctable confirm))
9219 (if (stringp rtn)
9220 (setq rtn
9221 (concat s1 s2 (substring rtn (length s2))
9222 (if (and org-add-colon-after-tag-completion
9223 (assoc rtn ctable))
9224 ":" ""))))
9225 rtn)
9226 ((eq flag t)
9227 ;; all-completions
9228 (all-completions s2 ctable confirm)
9230 ((eq flag 'lambda)
9231 ;; exact match?
9232 (assoc s2 ctable)))
9235 (defun org-fast-tag-insert (kwd tags face &optional end)
9236 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9237 (insert (format "%-12s" (concat kwd ":"))
9238 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9239 (or end "")))
9241 (defun org-fast-tag-show-exit (flag)
9242 (save-excursion
9243 (goto-line 3)
9244 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9245 (replace-match ""))
9246 (when flag
9247 (end-of-line 1)
9248 (org-move-to-column (- (window-width) 19) t)
9249 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9251 (defun org-set-current-tags-overlay (current prefix)
9252 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9253 (if (featurep 'xemacs)
9254 (org-overlay-display org-tags-overlay (concat prefix s)
9255 'secondary-selection)
9256 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9257 (org-overlay-display org-tags-overlay (concat prefix s)))))
9259 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9260 "Fast tag selection with single keys.
9261 CURRENT is the current list of tags in the headline, INHERITED is the
9262 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9263 possibly with grouping information. TODO-TABLE is a similar table with
9264 TODO keywords, should these have keys assigned to them.
9265 If the keys are nil, a-z are automatically assigned.
9266 Returns the new tags string, or nil to not change the current settings."
9267 (let* ((fulltable (append table todo-table))
9268 (maxlen (apply 'max (mapcar
9269 (lambda (x)
9270 (if (stringp (car x)) (string-width (car x)) 0))
9271 fulltable)))
9272 (buf (current-buffer))
9273 (expert (eq org-fast-tag-selection-single-key 'expert))
9274 (buffer-tags nil)
9275 (fwidth (+ maxlen 3 1 3))
9276 (ncol (/ (- (window-width) 4) fwidth))
9277 (i-face 'org-done)
9278 (c-face 'org-todo)
9279 tg cnt e c char c1 c2 ntable tbl rtn
9280 ov-start ov-end ov-prefix
9281 (exit-after-next org-fast-tag-selection-single-key)
9282 (done-keywords org-done-keywords)
9283 groups ingroup)
9284 (save-excursion
9285 (beginning-of-line 1)
9286 (if (looking-at
9287 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9288 (setq ov-start (match-beginning 1)
9289 ov-end (match-end 1)
9290 ov-prefix "")
9291 (setq ov-start (1- (point-at-eol))
9292 ov-end (1+ ov-start))
9293 (skip-chars-forward "^\n\r")
9294 (setq ov-prefix
9295 (concat
9296 (buffer-substring (1- (point)) (point))
9297 (if (> (current-column) org-tags-column)
9299 (make-string (- org-tags-column (current-column)) ?\ ))))))
9300 (org-move-overlay org-tags-overlay ov-start ov-end)
9301 (save-window-excursion
9302 (if expert
9303 (set-buffer (get-buffer-create " *Org tags*"))
9304 (delete-other-windows)
9305 (split-window-vertically)
9306 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9307 (erase-buffer)
9308 (org-set-local 'org-done-keywords done-keywords)
9309 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9310 (org-fast-tag-insert "Current" current c-face "\n\n")
9311 (org-fast-tag-show-exit exit-after-next)
9312 (org-set-current-tags-overlay current ov-prefix)
9313 (setq tbl fulltable char ?a cnt 0)
9314 (while (setq e (pop tbl))
9315 (cond
9316 ((equal e '(:startgroup))
9317 (push '() groups) (setq ingroup t)
9318 (when (not (= cnt 0))
9319 (setq cnt 0)
9320 (insert "\n"))
9321 (insert "{ "))
9322 ((equal e '(:endgroup))
9323 (setq ingroup nil cnt 0)
9324 (insert "}\n"))
9326 (setq tg (car e) c2 nil)
9327 (if (cdr e)
9328 (setq c (cdr e))
9329 ;; automatically assign a character.
9330 (setq c1 (string-to-char
9331 (downcase (substring
9332 tg (if (= (string-to-char tg) ?@) 1 0)))))
9333 (if (or (rassoc c1 ntable) (rassoc c1 table))
9334 (while (or (rassoc char ntable) (rassoc char table))
9335 (setq char (1+ char)))
9336 (setq c2 c1))
9337 (setq c (or c2 char)))
9338 (if ingroup (push tg (car groups)))
9339 (setq tg (org-add-props tg nil 'face
9340 (cond
9341 ((not (assoc tg table))
9342 (org-get-todo-face tg))
9343 ((member tg current) c-face)
9344 ((member tg inherited) i-face)
9345 (t nil))))
9346 (if (and (= cnt 0) (not ingroup)) (insert " "))
9347 (insert "[" c "] " tg (make-string
9348 (- fwidth 4 (length tg)) ?\ ))
9349 (push (cons tg c) ntable)
9350 (when (= (setq cnt (1+ cnt)) ncol)
9351 (insert "\n")
9352 (if ingroup (insert " "))
9353 (setq cnt 0)))))
9354 (setq ntable (nreverse ntable))
9355 (insert "\n")
9356 (goto-char (point-min))
9357 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9358 (fit-window-to-buffer))
9359 (setq rtn
9360 (catch 'exit
9361 (while t
9362 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9363 (if groups " [!] no groups" " [!]groups")
9364 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9365 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9366 (cond
9367 ((= c ?\r) (throw 'exit t))
9368 ((= c ?!)
9369 (setq groups (not groups))
9370 (goto-char (point-min))
9371 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9372 ((= c ?\C-c)
9373 (if (not expert)
9374 (org-fast-tag-show-exit
9375 (setq exit-after-next (not exit-after-next)))
9376 (setq expert nil)
9377 (delete-other-windows)
9378 (split-window-vertically)
9379 (org-switch-to-buffer-other-window " *Org tags*")
9380 (and (fboundp 'fit-window-to-buffer)
9381 (fit-window-to-buffer))))
9382 ((or (= c ?\C-g)
9383 (and (= c ?q) (not (rassoc c ntable))))
9384 (org-detach-overlay org-tags-overlay)
9385 (setq quit-flag t))
9386 ((= c ?\ )
9387 (setq current nil)
9388 (if exit-after-next (setq exit-after-next 'now)))
9389 ((= c ?\t)
9390 (condition-case nil
9391 (setq tg (completing-read
9392 "Tag: "
9393 (or buffer-tags
9394 (with-current-buffer buf
9395 (org-get-buffer-tags)))))
9396 (quit (setq tg "")))
9397 (when (string-match "\\S-" tg)
9398 (add-to-list 'buffer-tags (list tg))
9399 (if (member tg current)
9400 (setq current (delete tg current))
9401 (push tg current)))
9402 (if exit-after-next (setq exit-after-next 'now)))
9403 ((setq e (rassoc c todo-table) tg (car e))
9404 (with-current-buffer buf
9405 (save-excursion (org-todo tg)))
9406 (if exit-after-next (setq exit-after-next 'now)))
9407 ((setq e (rassoc c ntable) tg (car e))
9408 (if (member tg current)
9409 (setq current (delete tg current))
9410 (loop for g in groups do
9411 (if (member tg g)
9412 (mapc (lambda (x)
9413 (setq current (delete x current)))
9414 g)))
9415 (push tg current))
9416 (if exit-after-next (setq exit-after-next 'now))))
9418 ;; Create a sorted list
9419 (setq current
9420 (sort current
9421 (lambda (a b)
9422 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9423 (if (eq exit-after-next 'now) (throw 'exit t))
9424 (goto-char (point-min))
9425 (beginning-of-line 2)
9426 (delete-region (point) (point-at-eol))
9427 (org-fast-tag-insert "Current" current c-face)
9428 (org-set-current-tags-overlay current ov-prefix)
9429 (while (re-search-forward
9430 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9431 (setq tg (match-string 1))
9432 (add-text-properties
9433 (match-beginning 1) (match-end 1)
9434 (list 'face
9435 (cond
9436 ((member tg current) c-face)
9437 ((member tg inherited) i-face)
9438 (t (get-text-property (match-beginning 1) 'face))))))
9439 (goto-char (point-min)))))
9440 (org-detach-overlay org-tags-overlay)
9441 (if rtn
9442 (mapconcat 'identity current ":")
9443 nil))))
9445 (defun org-get-tags-string ()
9446 "Get the TAGS string in the current headline."
9447 (unless (org-on-heading-p t)
9448 (error "Not on a heading"))
9449 (save-excursion
9450 (beginning-of-line 1)
9451 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9452 (org-match-string-no-properties 1)
9453 "")))
9455 (defun org-get-tags ()
9456 "Get the list of tags specified in the current headline."
9457 (org-split-string (org-get-tags-string) ":"))
9459 (defun org-get-buffer-tags ()
9460 "Get a table of all tags used in the buffer, for completion."
9461 (let (tags)
9462 (save-excursion
9463 (goto-char (point-min))
9464 (while (re-search-forward
9465 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9466 (when (equal (char-after (point-at-bol 0)) ?*)
9467 (mapc (lambda (x) (add-to-list 'tags x))
9468 (org-split-string (org-match-string-no-properties 1) ":")))))
9469 (mapcar 'list tags)))
9471 ;;;; The mapping API
9473 ;;;###autoload
9474 (defun org-map-entries (func &optional match scope &rest skip)
9475 "Call FUNC at each headline selected by MATCH in SCOPE.
9477 FUNC is a function or a lisp form. The function will be called without
9478 arguments, with the cursor positioned at the beginning of the headline.
9479 The return values of all calls to the function will be collected and
9480 returned as a list.
9482 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9483 Only headlines that are matched by this query will be considered during
9484 the iteration. When MATCH is nil or t, all headlines will be
9485 visited by the iteration.
9487 SCOPE determines the scope of this command. It can be any of:
9489 nil The current buffer, respecting the restriction if any
9490 tree The subtree started with the entry at point
9491 file The current buffer, without restriction
9492 file-with-archives
9493 The current buffer, and any archives associated with it
9494 agenda All agenda files
9495 agenda-with-archives
9496 All agenda files with any archive files associated with them
9497 \(file1 file2 ...)
9498 If this is a list, all files in the list will be scanned
9500 The remaining args are treated as settings for the skipping facilities of
9501 the scanner. The following items can be given here:
9503 archive skip trees with the archive tag.
9504 comment skip trees with the COMMENT keyword
9505 function or Emacs Lisp form:
9506 will be used as value for `org-agenda-skip-function', so whenever
9507 the the function returns t, FUNC will not be called for that
9508 entry and search will continue from the point where the
9509 function leaves it."
9510 (let* ((org-agenda-archives-mode nil) ; just to make sure
9511 (org-agenda-skip-archived-trees (memq 'archive skip))
9512 (org-agenda-skip-comment-trees (memq 'comment skip))
9513 (org-agenda-skip-function
9514 (car (org-delete-all '(comment archive) skip)))
9515 (org-tags-match-list-sublevels t)
9516 matcher pos file
9517 org-todo-keywords-for-agenda
9518 org-done-keywords-for-agenda
9519 org-todo-keyword-alist-for-agenda
9520 org-tag-alist-for-agenda)
9522 (cond
9523 ((eq match t) (setq matcher t))
9524 ((eq match nil) (setq matcher t))
9525 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9527 (when (eq scope 'tree)
9528 (org-back-to-heading t)
9529 (org-narrow-to-subtree)
9530 (setq scope nil))
9532 (if (not scope)
9533 (progn
9534 (org-prepare-agenda-buffers
9535 (list (buffer-file-name (current-buffer))))
9536 (org-scan-tags func matcher))
9537 ;; Get the right scope
9538 (setq pos (point))
9539 (cond
9540 ((and scope (listp scope) (symbolp (car scope)))
9541 (setq scope (eval scope)))
9542 ((eq scope 'agenda)
9543 (setq scope (org-agenda-files t)))
9544 ((eq scope 'agenda-with-archives)
9545 (setq scope (org-agenda-files t))
9546 (setq scope (org-add-archive-files scope)))
9547 ((eq scope 'file)
9548 (setq scope (list (buffer-file-name))))
9549 ((eq scope 'file-with-archives)
9550 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9551 (org-prepare-agenda-buffers scope)
9552 (while (setq file (pop scope))
9553 (with-current-buffer (org-find-base-buffer-visiting file)
9554 (save-excursion
9555 (save-restriction
9556 (widen)
9557 (goto-char (point-min))
9558 (org-scan-tags func matcher))))))))
9560 ;;;; Properties
9562 ;;; Setting and retrieving properties
9564 (defconst org-special-properties
9565 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9566 "TIMESTAMP" "TIMESTAMP_IA")
9567 "The special properties valid in Org-mode.
9569 These are properties that are not defined in the property drawer,
9570 but in some other way.")
9572 (defconst org-default-properties
9573 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9574 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9575 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9576 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9577 "Some properties that are used by Org-mode for various purposes.
9578 Being in this list makes sure that they are offered for completion.")
9580 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9581 "Regular expression matching the first line of a property drawer.")
9583 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9584 "Regular expression matching the first line of a property drawer.")
9586 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9587 "Regular expression matching the first line of a property drawer.")
9589 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9590 "Regular expression matching the first line of a property drawer.")
9592 (defconst org-property-drawer-re
9593 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9594 org-property-end-re "\\)\n?")
9595 "Matches an entire property drawer.")
9597 (defconst org-clock-drawer-re
9598 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9599 org-property-end-re "\\)\n?")
9600 "Matches an entire clock drawer.")
9602 (defun org-property-action ()
9603 "Do an action on properties."
9604 (interactive)
9605 (let (c)
9606 (org-at-property-p)
9607 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9608 (setq c (read-char-exclusive))
9609 (cond
9610 ((equal c ?s)
9611 (call-interactively 'org-set-property))
9612 ((equal c ?d)
9613 (call-interactively 'org-delete-property))
9614 ((equal c ?D)
9615 (call-interactively 'org-delete-property-globally))
9616 ((equal c ?c)
9617 (call-interactively 'org-compute-property-at-point))
9618 (t (error "No such property action %c" c)))))
9620 (defun org-at-property-p ()
9621 "Is the cursor in a property line?"
9622 ;; FIXME: Does not check if we are actually in the drawer.
9623 ;; FIXME: also returns true on any drawers.....
9624 ;; This is used by C-c C-c for property action.
9625 (save-excursion
9626 (beginning-of-line 1)
9627 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9629 (defun org-get-property-block (&optional beg end force)
9630 "Return the (beg . end) range of the body of the property drawer.
9631 BEG and END can be beginning and end of subtree, if not given
9632 they will be found.
9633 If the drawer does not exist and FORCE is non-nil, create the drawer."
9634 (catch 'exit
9635 (save-excursion
9636 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9637 (end (or end (progn (outline-next-heading) (point)))))
9638 (goto-char beg)
9639 (if (re-search-forward org-property-start-re end t)
9640 (setq beg (1+ (match-end 0)))
9641 (if force
9642 (save-excursion
9643 (org-insert-property-drawer)
9644 (setq end (progn (outline-next-heading) (point))))
9645 (throw 'exit nil))
9646 (goto-char beg)
9647 (if (re-search-forward org-property-start-re end t)
9648 (setq beg (1+ (match-end 0)))))
9649 (if (re-search-forward org-property-end-re end t)
9650 (setq end (match-beginning 0))
9651 (or force (throw 'exit nil))
9652 (goto-char beg)
9653 (setq end beg)
9654 (org-indent-line-function)
9655 (insert ":END:\n"))
9656 (cons beg end)))))
9658 (defun org-entry-properties (&optional pom which)
9659 "Get all properties of the entry at point-or-marker POM.
9660 This includes the TODO keyword, the tags, time strings for deadline,
9661 scheduled, and clocking, and any additional properties defined in the
9662 entry. The return value is an alist, keys may occur multiple times
9663 if the property key was used several times.
9664 POM may also be nil, in which case the current entry is used.
9665 If WHICH is nil or `all', get all properties. If WHICH is
9666 `special' or `standard', only get that subclass."
9667 (setq which (or which 'all))
9668 (org-with-point-at pom
9669 (let ((clockstr (substring org-clock-string 0 -1))
9670 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9671 beg end range props sum-props key value string clocksum)
9672 (save-excursion
9673 (when (condition-case nil (org-back-to-heading t) (error nil))
9674 (setq beg (point))
9675 (setq sum-props (get-text-property (point) 'org-summaries))
9676 (setq clocksum (get-text-property (point) :org-clock-minutes))
9677 (outline-next-heading)
9678 (setq end (point))
9679 (when (memq which '(all special))
9680 ;; Get the special properties, like TODO and tags
9681 (goto-char beg)
9682 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9683 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9684 (when (looking-at org-priority-regexp)
9685 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9686 (when (and (setq value (org-get-tags-string))
9687 (string-match "\\S-" value))
9688 (push (cons "TAGS" value) props))
9689 (when (setq value (org-get-tags-at))
9690 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9691 props))
9692 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9693 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9694 string (if (equal key clockstr)
9695 (org-no-properties
9696 (org-trim
9697 (buffer-substring
9698 (match-beginning 3) (goto-char (point-at-eol)))))
9699 (substring (org-match-string-no-properties 3) 1 -1)))
9700 (unless key
9701 (if (= (char-after (match-beginning 3)) ?\[)
9702 (setq key "TIMESTAMP_IA")
9703 (setq key "TIMESTAMP")))
9704 (when (or (equal key clockstr) (not (assoc key props)))
9705 (push (cons key string) props)))
9709 (when (memq which '(all standard))
9710 ;; Get the standard properties, like :PORP: ...
9711 (setq range (org-get-property-block beg end))
9712 (when range
9713 (goto-char (car range))
9714 (while (re-search-forward
9715 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9716 (cdr range) t)
9717 (setq key (org-match-string-no-properties 1)
9718 value (org-trim (or (org-match-string-no-properties 2) "")))
9719 (unless (member key excluded)
9720 (push (cons key (or value "")) props)))))
9721 (if clocksum
9722 (push (cons "CLOCKSUM"
9723 (org-columns-number-to-string (/ (float clocksum) 60.)
9724 'add_times))
9725 props))
9726 (append sum-props (nreverse props)))))))
9728 (defun org-entry-get (pom property &optional inherit)
9729 "Get value of PROPERTY for entry at point-or-marker POM.
9730 If INHERIT is non-nil and the entry does not have the property,
9731 then also check higher levels of the hierarchy.
9732 If INHERIT is the symbol `selective', use inheritance only if the setting
9733 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9734 If the property is present but empty, the return value is the empty string.
9735 If the property is not present at all, nil is returned."
9736 (org-with-point-at pom
9737 (if (and inherit (if (eq inherit 'selective)
9738 (org-property-inherit-p property)
9740 (org-entry-get-with-inheritance property)
9741 (if (member property org-special-properties)
9742 ;; We need a special property. Use brute force, get all properties.
9743 (cdr (assoc property (org-entry-properties nil 'special)))
9744 (let ((range (org-get-property-block)))
9745 (if (and range
9746 (goto-char (car range))
9747 (re-search-forward
9748 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9749 (cdr range) t))
9750 ;; Found the property, return it.
9751 (if (match-end 1)
9752 (org-match-string-no-properties 1)
9753 "")))))))
9755 (defun org-property-or-variable-value (var &optional inherit)
9756 "Check if there is a property fixing the value of VAR.
9757 If yes, return this value. If not, return the current value of the variable."
9758 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9759 (if (and prop (stringp prop) (string-match "\\S-" prop))
9760 (read prop)
9761 (symbol-value var))))
9763 (defun org-entry-delete (pom property)
9764 "Delete the property PROPERTY from entry at point-or-marker POM."
9765 (org-with-point-at pom
9766 (if (member property org-special-properties)
9767 nil ; cannot delete these properties.
9768 (let ((range (org-get-property-block)))
9769 (if (and range
9770 (goto-char (car range))
9771 (re-search-forward
9772 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9773 (cdr range) t))
9774 (progn
9775 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9777 nil)))))
9779 ;; Multi-values properties are properties that contain multiple values
9780 ;; These values are assumed to be single words, separated by whitespace.
9781 (defun org-entry-add-to-multivalued-property (pom property value)
9782 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9783 (let* ((old (org-entry-get pom property))
9784 (values (and old (org-split-string old "[ \t]"))))
9785 (setq value (org-entry-protect-space value))
9786 (unless (member value values)
9787 (setq values (cons value values))
9788 (org-entry-put pom property
9789 (mapconcat 'identity values " ")))))
9791 (defun org-entry-remove-from-multivalued-property (pom property value)
9792 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9793 (let* ((old (org-entry-get pom property))
9794 (values (and old (org-split-string old "[ \t]"))))
9795 (setq value (org-entry-protect-space value))
9796 (when (member value values)
9797 (setq values (delete value values))
9798 (org-entry-put pom property
9799 (mapconcat 'identity values " ")))))
9801 (defun org-entry-member-in-multivalued-property (pom property value)
9802 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9803 (let* ((old (org-entry-get pom property))
9804 (values (and old (org-split-string old "[ \t]"))))
9805 (setq value (org-entry-protect-space value))
9806 (member value values)))
9808 (defun org-entry-get-multivalued-property (pom property)
9809 "Return a list of values in a multivalued property."
9810 (let* ((value (org-entry-get pom property))
9811 (values (and value (org-split-string value "[ \t]"))))
9812 (mapcar 'org-entry-restore-space values)))
9814 (defun org-entry-put-multivalued-property (pom property &rest values)
9815 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
9816 VALUES should be a list of strings. Spaces will be protected."
9817 (org-entry-put pom property
9818 (mapconcat 'org-entry-protect-space values " "))
9819 (let* ((value (org-entry-get pom property))
9820 (values (and value (org-split-string value "[ \t]"))))
9821 (mapcar 'org-entry-restore-space values)))
9823 (defun org-entry-protect-space (s)
9824 "Protect spaces and newline in string S."
9825 (while (string-match " " s)
9826 (setq s (replace-match "%20" t t s)))
9827 (while (string-match "\n" s)
9828 (setq s (replace-match "%0A" t t s)))
9831 (defun org-entry-restore-space (s)
9832 "Restore spaces and newline in string S."
9833 (while (string-match "%20" s)
9834 (setq s (replace-match " " t t s)))
9835 (while (string-match "%0A" s)
9836 (setq s (replace-match "\n" t t s)))
9839 (defvar org-entry-property-inherited-from (make-marker)
9840 "Marker pointing to the entry from where a proerty was inherited.
9841 Each call to `org-entry-get-with-inheritance' will set this marker to the
9842 location of the entry where the inheriance search matched. If there was
9843 no match, the marker will point nowhere.
9844 Note that also `org-entry-get' calls this function, if the INHERIT flag
9845 is set.")
9847 (defun org-entry-get-with-inheritance (property)
9848 "Get entry property, and search higher levels if not present."
9849 (move-marker org-entry-property-inherited-from nil)
9850 (let (tmp)
9851 (save-excursion
9852 (save-restriction
9853 (widen)
9854 (catch 'ex
9855 (while t
9856 (when (setq tmp (org-entry-get nil property))
9857 (org-back-to-heading t)
9858 (move-marker org-entry-property-inherited-from (point))
9859 (throw 'ex tmp))
9860 (or (org-up-heading-safe) (throw 'ex nil)))))
9861 (or tmp
9862 (cdr (assoc property org-file-properties))
9863 (cdr (assoc property org-global-properties))
9864 (cdr (assoc property org-global-properties-fixed))))))
9866 (defun org-entry-put (pom property value)
9867 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9868 (org-with-point-at pom
9869 (org-back-to-heading t)
9870 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9871 range)
9872 (cond
9873 ((equal property "TODO")
9874 (when (and (stringp value) (string-match "\\S-" value)
9875 (not (member value org-todo-keywords-1)))
9876 (error "\"%s\" is not a valid TODO state" value))
9877 (if (or (not value)
9878 (not (string-match "\\S-" value)))
9879 (setq value 'none))
9880 (org-todo value)
9881 (org-set-tags nil 'align))
9882 ((equal property "PRIORITY")
9883 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9884 (string-to-char value) ?\ ))
9885 (org-set-tags nil 'align))
9886 ((equal property "SCHEDULED")
9887 (if (re-search-forward org-scheduled-time-regexp end t)
9888 (cond
9889 ((eq value 'earlier) (org-timestamp-change -1 'day))
9890 ((eq value 'later) (org-timestamp-change 1 'day))
9891 (t (call-interactively 'org-schedule)))
9892 (call-interactively 'org-schedule)))
9893 ((equal property "DEADLINE")
9894 (if (re-search-forward org-deadline-time-regexp end t)
9895 (cond
9896 ((eq value 'earlier) (org-timestamp-change -1 'day))
9897 ((eq value 'later) (org-timestamp-change 1 'day))
9898 (t (call-interactively 'org-deadline)))
9899 (call-interactively 'org-deadline)))
9900 ((member property org-special-properties)
9901 (error "The %s property can not yet be set with `org-entry-put'"
9902 property))
9903 (t ; a non-special property
9904 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9905 (setq range (org-get-property-block beg end 'force))
9906 (goto-char (car range))
9907 (if (re-search-forward
9908 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9909 (progn
9910 (delete-region (match-beginning 1) (match-end 1))
9911 (goto-char (match-beginning 1)))
9912 (goto-char (cdr range))
9913 (insert "\n")
9914 (backward-char 1)
9915 (org-indent-line-function)
9916 (insert ":" property ":"))
9917 (and value (insert " " value))
9918 (org-indent-line-function)))))))
9920 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9921 "Get all property keys in the current buffer.
9922 With INCLUDE-SPECIALS, also list the special properties that relect things
9923 like tags and TODO state.
9924 With INCLUDE-DEFAULTS, also include properties that has special meaning
9925 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9926 With INCLUDE-COLUMNS, also include property names given in COLUMN
9927 formats in the current buffer."
9928 (let (rtn range cfmt cols s p)
9929 (save-excursion
9930 (save-restriction
9931 (widen)
9932 (goto-char (point-min))
9933 (while (re-search-forward org-property-start-re nil t)
9934 (setq range (org-get-property-block))
9935 (goto-char (car range))
9936 (while (re-search-forward
9937 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9938 (cdr range) t)
9939 (add-to-list 'rtn (org-match-string-no-properties 1)))
9940 (outline-next-heading))))
9942 (when include-specials
9943 (setq rtn (append org-special-properties rtn)))
9945 (when include-defaults
9946 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9948 (when include-columns
9949 (save-excursion
9950 (save-restriction
9951 (widen)
9952 (goto-char (point-min))
9953 (while (re-search-forward
9954 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9955 nil t)
9956 (setq cfmt (match-string 2) s 0)
9957 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9958 cfmt s)
9959 (setq s (match-end 0)
9960 p (match-string 1 cfmt))
9961 (unless (or (equal p "ITEM")
9962 (member p org-special-properties))
9963 (add-to-list 'rtn (match-string 1 cfmt))))))))
9965 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9967 (defun org-property-values (key)
9968 "Return a list of all values of property KEY."
9969 (save-excursion
9970 (save-restriction
9971 (widen)
9972 (goto-char (point-min))
9973 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9974 values)
9975 (while (re-search-forward re nil t)
9976 (add-to-list 'values (org-trim (match-string 1))))
9977 (delete "" values)))))
9979 (defun org-insert-property-drawer ()
9980 "Insert a property drawer into the current entry."
9981 (interactive)
9982 (org-back-to-heading t)
9983 (looking-at outline-regexp)
9984 (let ((indent (- (match-end 0)(match-beginning 0)))
9985 (beg (point))
9986 (re (concat "^[ \t]*" org-keyword-time-regexp))
9987 end hiddenp)
9988 (outline-next-heading)
9989 (setq end (point))
9990 (goto-char beg)
9991 (while (re-search-forward re end t))
9992 (setq hiddenp (org-invisible-p))
9993 (end-of-line 1)
9994 (and (equal (char-after) ?\n) (forward-char 1))
9995 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9996 (beginning-of-line 2))
9997 (org-skip-over-state-notes)
9998 (skip-chars-backward " \t\n\r")
9999 (if (eq (char-before) ?*) (forward-char 1))
10000 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10001 (beginning-of-line 0)
10002 (org-indent-to-column indent)
10003 (beginning-of-line 2)
10004 (org-indent-to-column indent)
10005 (beginning-of-line 0)
10006 (if hiddenp
10007 (save-excursion
10008 (org-back-to-heading t)
10009 (hide-entry))
10010 (org-flag-drawer t))))
10012 (defun org-set-property (property value)
10013 "In the current entry, set PROPERTY to VALUE.
10014 When called interactively, this will prompt for a property name, offering
10015 completion on existing and default properties. And then it will prompt
10016 for a value, offering competion either on allowed values (via an inherited
10017 xxx_ALL property) or on existing values in other instances of this property
10018 in the current file."
10019 (interactive
10020 (let* ((completion-ignore-case t)
10021 (keys (org-buffer-property-keys nil t t))
10022 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10023 (prop (if (member prop0 keys)
10024 prop0
10025 (or (cdr (assoc (downcase prop0)
10026 (mapcar (lambda (x) (cons (downcase x) x))
10027 keys)))
10028 prop0)))
10029 (cur (org-entry-get nil prop))
10030 (allowed (org-property-get-allowed-values nil prop 'table))
10031 (existing (mapcar 'list (org-property-values prop)))
10032 (val (if allowed
10033 (org-completing-read "Value: " allowed nil 'req-match)
10034 (org-completing-read
10035 (concat "Value" (if (and cur (string-match "\\S-" cur))
10036 (concat "[" cur "]") "")
10037 ": ")
10038 existing nil nil "" nil cur))))
10039 (list prop (if (equal val "") cur val))))
10040 (unless (equal (org-entry-get nil property) value)
10041 (org-entry-put nil property value)))
10043 (defun org-delete-property (property)
10044 "In the current entry, delete PROPERTY."
10045 (interactive
10046 (let* ((completion-ignore-case t)
10047 (prop (completing-read
10048 "Property: " (org-entry-properties nil 'standard))))
10049 (list prop)))
10050 (message "Property %s %s" property
10051 (if (org-entry-delete nil property)
10052 "deleted"
10053 "was not present in the entry")))
10055 (defun org-delete-property-globally (property)
10056 "Remove PROPERTY globally, from all entries."
10057 (interactive
10058 (let* ((completion-ignore-case t)
10059 (prop (completing-read
10060 "Globally remove property: "
10061 (mapcar 'list (org-buffer-property-keys)))))
10062 (list prop)))
10063 (save-excursion
10064 (save-restriction
10065 (widen)
10066 (goto-char (point-min))
10067 (let ((cnt 0))
10068 (while (re-search-forward
10069 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10070 nil t)
10071 (setq cnt (1+ cnt))
10072 (replace-match ""))
10073 (message "Property \"%s\" removed from %d entries" property cnt)))))
10075 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10077 (defun org-compute-property-at-point ()
10078 "Compute the property at point.
10079 This looks for an enclosing column format, extracts the operator and
10080 then applies it to the proerty in the column format's scope."
10081 (interactive)
10082 (unless (org-at-property-p)
10083 (error "Not at a property"))
10084 (let ((prop (org-match-string-no-properties 2)))
10085 (org-columns-get-format-and-top-level)
10086 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10087 (error "No operator defined for property %s" prop))
10088 (org-columns-compute prop)))
10090 (defun org-property-get-allowed-values (pom property &optional table)
10091 "Get allowed values for the property PROPERTY.
10092 When TABLE is non-nil, return an alist that can directly be used for
10093 completion."
10094 (let (vals)
10095 (cond
10096 ((equal property "TODO")
10097 (setq vals (org-with-point-at pom
10098 (append org-todo-keywords-1 '("")))))
10099 ((equal property "PRIORITY")
10100 (let ((n org-lowest-priority))
10101 (while (>= n org-highest-priority)
10102 (push (char-to-string n) vals)
10103 (setq n (1- n)))))
10104 ((member property org-special-properties))
10106 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10108 (when (and vals (string-match "\\S-" vals))
10109 (setq vals (car (read-from-string (concat "(" vals ")"))))
10110 (setq vals (mapcar (lambda (x)
10111 (cond ((stringp x) x)
10112 ((numberp x) (number-to-string x))
10113 ((symbolp x) (symbol-name x))
10114 (t "???")))
10115 vals)))))
10116 (if table (mapcar 'list vals) vals)))
10118 (defun org-property-previous-allowed-value (&optional previous)
10119 "Switch to the next allowed value for this property."
10120 (interactive)
10121 (org-property-next-allowed-value t))
10123 (defun org-property-next-allowed-value (&optional previous)
10124 "Switch to the next allowed value for this property."
10125 (interactive)
10126 (unless (org-at-property-p)
10127 (error "Not at a property"))
10128 (let* ((key (match-string 2))
10129 (value (match-string 3))
10130 (allowed (or (org-property-get-allowed-values (point) key)
10131 (and (member value '("[ ]" "[-]" "[X]"))
10132 '("[ ]" "[X]"))))
10133 nval)
10134 (unless allowed
10135 (error "Allowed values for this property have not been defined"))
10136 (if previous (setq allowed (reverse allowed)))
10137 (if (member value allowed)
10138 (setq nval (car (cdr (member value allowed)))))
10139 (setq nval (or nval (car allowed)))
10140 (if (equal nval value)
10141 (error "Only one allowed value for this property"))
10142 (org-at-property-p)
10143 (replace-match (concat " :" key ": " nval) t t)
10144 (org-indent-line-function)
10145 (beginning-of-line 1)
10146 (skip-chars-forward " \t")))
10148 (defun org-find-entry-with-id (ident)
10149 "Locate the entry that contains the ID property with exact value IDENT.
10150 IDENT can be a string, a symbol or a number, this function will search for
10151 the string representation of it.
10152 Return the position where this entry starts, or nil if there is no such entry."
10153 (let ((id (cond
10154 ((stringp ident) ident)
10155 ((symbol-name ident) (symbol-name ident))
10156 ((numberp ident) (number-to-string ident))
10157 (t (error "IDENT %s must be a string, symbol or number" ident))))
10158 (case-fold-search nil))
10159 (save-excursion
10160 (save-restriction
10161 (widen)
10162 (goto-char (point-min))
10163 (when (re-search-forward
10164 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10165 nil t)
10166 (org-back-to-heading)
10167 (point))))))
10169 ;;;; Timestamps
10171 (defvar org-last-changed-timestamp nil)
10172 (defvar org-last-inserted-timestamp nil
10173 "The last time stamp inserted with `org-insert-time-stamp'.")
10174 (defvar org-time-was-given) ; dynamically scoped parameter
10175 (defvar org-end-time-was-given) ; dynamically scoped parameter
10176 (defvar org-ts-what) ; dynamically scoped parameter
10178 (defun org-time-stamp (arg &optional inactive)
10179 "Prompt for a date/time and insert a time stamp.
10180 If the user specifies a time like HH:MM, or if this command is called
10181 with a prefix argument, the time stamp will contain date and time.
10182 Otherwise, only the date will be included. All parts of a date not
10183 specified by the user will be filled in from the current date/time.
10184 So if you press just return without typing anything, the time stamp
10185 will represent the current date/time. If there is already a timestamp
10186 at the cursor, it will be modified."
10187 (interactive "P")
10188 (let* ((ts nil)
10189 (default-time
10190 ;; Default time is either today, or, when entering a range,
10191 ;; the range start.
10192 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10193 (save-excursion
10194 (re-search-backward
10195 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10196 (- (point) 20) t)))
10197 (apply 'encode-time (org-parse-time-string (match-string 1)))
10198 (current-time)))
10199 (default-input (and ts (org-get-compact-tod ts)))
10200 org-time-was-given org-end-time-was-given time)
10201 (cond
10202 ((and (org-at-timestamp-p t)
10203 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10204 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10205 (insert "--")
10206 (setq time (let ((this-command this-command))
10207 (org-read-date arg 'totime nil nil
10208 default-time default-input)))
10209 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10210 ((org-at-timestamp-p t)
10211 (setq time (let ((this-command this-command))
10212 (org-read-date arg 'totime nil nil default-time default-input)))
10213 (when (org-at-timestamp-p t) ; just to get the match data
10214 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10215 (replace-match "")
10216 (setq org-last-changed-timestamp
10217 (org-insert-time-stamp
10218 time (or org-time-was-given arg)
10219 inactive nil nil (list org-end-time-was-given))))
10220 (message "Timestamp updated"))
10222 (setq time (let ((this-command this-command))
10223 (org-read-date arg 'totime nil nil default-time default-input)))
10224 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10225 nil nil (list org-end-time-was-given))))))
10227 ;; FIXME: can we use this for something else, like computing time differences?
10228 (defun org-get-compact-tod (s)
10229 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10230 (let* ((t1 (match-string 1 s))
10231 (h1 (string-to-number (match-string 2 s)))
10232 (m1 (string-to-number (match-string 3 s)))
10233 (t2 (and (match-end 4) (match-string 5 s)))
10234 (h2 (and t2 (string-to-number (match-string 6 s))))
10235 (m2 (and t2 (string-to-number (match-string 7 s))))
10236 dh dm)
10237 (if (not t2)
10239 (setq dh (- h2 h1) dm (- m2 m1))
10240 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10241 (concat t1 "+" (number-to-string dh)
10242 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10244 (defun org-time-stamp-inactive (&optional arg)
10245 "Insert an inactive time stamp.
10246 An inactive time stamp is enclosed in square brackets instead of angle
10247 brackets. It is inactive in the sense that it does not trigger agenda entries,
10248 does not link to the calendar and cannot be changed with the S-cursor keys.
10249 So these are more for recording a certain time/date."
10250 (interactive "P")
10251 (org-time-stamp arg 'inactive))
10253 (defvar org-date-ovl (org-make-overlay 1 1))
10254 (org-overlay-put org-date-ovl 'face 'org-warning)
10255 (org-detach-overlay org-date-ovl)
10257 (defvar org-ans1) ; dynamically scoped parameter
10258 (defvar org-ans2) ; dynamically scoped parameter
10260 (defvar org-plain-time-of-day-regexp) ; defined below
10262 (defvar org-overriding-default-time nil) ; dynamically scoped
10263 (defvar org-read-date-overlay nil)
10264 (defvar org-dcst nil) ; dynamically scoped
10266 (defun org-read-date (&optional with-time to-time from-string prompt
10267 default-time default-input)
10268 "Read a date, possibly a time, and make things smooth for the user.
10269 The prompt will suggest to enter an ISO date, but you can also enter anything
10270 which will at least partially be understood by `parse-time-string'.
10271 Unrecognized parts of the date will default to the current day, month, year,
10272 hour and minute. If this command is called to replace a timestamp at point,
10273 of to enter the second timestamp of a range, the default time is taken from the
10274 existing stamp. For example,
10275 3-2-5 --> 2003-02-05
10276 feb 15 --> currentyear-02-15
10277 sep 12 9 --> 2009-09-12
10278 12:45 --> today 12:45
10279 22 sept 0:34 --> currentyear-09-22 0:34
10280 12 --> currentyear-currentmonth-12
10281 Fri --> nearest Friday (today or later)
10282 etc.
10284 Furthermore you can specify a relative date by giving, as the *first* thing
10285 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10286 change in days weeks, months, years.
10287 With a single plus or minus, the date is relative to today. With a double
10288 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10289 +4d --> four days from today
10290 +4 --> same as above
10291 +2w --> two weeks from today
10292 ++5 --> five days from default date
10294 The function understands only English month and weekday abbreviations,
10295 but this can be configured with the variables `parse-time-months' and
10296 `parse-time-weekdays'.
10298 While prompting, a calendar is popped up - you can also select the
10299 date with the mouse (button 1). The calendar shows a period of three
10300 months. To scroll it to other months, use the keys `>' and `<'.
10301 If you don't like the calendar, turn it off with
10302 \(setq org-read-date-popup-calendar nil)
10304 With optional argument TO-TIME, the date will immediately be converted
10305 to an internal time.
10306 With an optional argument WITH-TIME, the prompt will suggest to also
10307 insert a time. Note that when WITH-TIME is not set, you can still
10308 enter a time, and this function will inform the calling routine about
10309 this change. The calling routine may then choose to change the format
10310 used to insert the time stamp into the buffer to include the time.
10311 With optional argument FROM-STRING, read from this string instead from
10312 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10313 the time/date that is used for everything that is not specified by the
10314 user."
10315 (require 'parse-time)
10316 (let* ((org-time-stamp-rounding-minutes
10317 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10318 (org-dcst org-display-custom-times)
10319 (ct (org-current-time))
10320 (def (or org-overriding-default-time default-time ct))
10321 (defdecode (decode-time def))
10322 (dummy (progn
10323 (when (< (nth 2 defdecode) org-extend-today-until)
10324 (setcar (nthcdr 2 defdecode) -1)
10325 (setcar (nthcdr 1 defdecode) 59)
10326 (setq def (apply 'encode-time defdecode)
10327 defdecode (decode-time def)))))
10328 (calendar-move-hook nil)
10329 (calendar-view-diary-initially-flag nil)
10330 (view-diary-entries-initially nil)
10331 (calendar-view-holidays-initially-flag nil)
10332 (view-calendar-holidays-initially nil)
10333 (timestr (format-time-string
10334 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10335 (prompt (concat (if prompt (concat prompt " ") "")
10336 (format "Date+time [%s]: " timestr)))
10337 ans (org-ans0 "") org-ans1 org-ans2 final)
10339 (cond
10340 (from-string (setq ans from-string))
10341 (org-read-date-popup-calendar
10342 (save-excursion
10343 (save-window-excursion
10344 (calendar)
10345 (calendar-forward-day (- (time-to-days def)
10346 (calendar-absolute-from-gregorian
10347 (calendar-current-date))))
10348 (org-eval-in-calendar nil t)
10349 (let* ((old-map (current-local-map))
10350 (map (copy-keymap calendar-mode-map))
10351 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10352 (org-defkey map (kbd "RET") 'org-calendar-select)
10353 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10354 'org-calendar-select-mouse)
10355 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10356 'org-calendar-select-mouse)
10357 (org-defkey minibuffer-local-map [(meta shift left)]
10358 (lambda () (interactive)
10359 (org-eval-in-calendar '(calendar-backward-month 1))))
10360 (org-defkey minibuffer-local-map [(meta shift right)]
10361 (lambda () (interactive)
10362 (org-eval-in-calendar '(calendar-forward-month 1))))
10363 (org-defkey minibuffer-local-map [(meta shift up)]
10364 (lambda () (interactive)
10365 (org-eval-in-calendar '(calendar-backward-year 1))))
10366 (org-defkey minibuffer-local-map [(meta shift down)]
10367 (lambda () (interactive)
10368 (org-eval-in-calendar '(calendar-forward-year 1))))
10369 (org-defkey minibuffer-local-map [(shift up)]
10370 (lambda () (interactive)
10371 (org-eval-in-calendar '(calendar-backward-week 1))))
10372 (org-defkey minibuffer-local-map [(shift down)]
10373 (lambda () (interactive)
10374 (org-eval-in-calendar '(calendar-forward-week 1))))
10375 (org-defkey minibuffer-local-map [(shift left)]
10376 (lambda () (interactive)
10377 (org-eval-in-calendar '(calendar-backward-day 1))))
10378 (org-defkey minibuffer-local-map [(shift right)]
10379 (lambda () (interactive)
10380 (org-eval-in-calendar '(calendar-forward-day 1))))
10381 (org-defkey minibuffer-local-map ">"
10382 (lambda () (interactive)
10383 (org-eval-in-calendar '(scroll-calendar-left 1))))
10384 (org-defkey minibuffer-local-map "<"
10385 (lambda () (interactive)
10386 (org-eval-in-calendar '(scroll-calendar-right 1))))
10387 (unwind-protect
10388 (progn
10389 (use-local-map map)
10390 (add-hook 'post-command-hook 'org-read-date-display)
10391 (setq org-ans0 (read-string prompt default-input nil nil))
10392 ;; org-ans0: from prompt
10393 ;; org-ans1: from mouse click
10394 ;; org-ans2: from calendar motion
10395 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10396 (remove-hook 'post-command-hook 'org-read-date-display)
10397 (use-local-map old-map)
10398 (when org-read-date-overlay
10399 (org-delete-overlay org-read-date-overlay)
10400 (setq org-read-date-overlay nil)))))))
10402 (t ; Naked prompt only
10403 (unwind-protect
10404 (setq ans (read-string prompt default-input nil timestr))
10405 (when org-read-date-overlay
10406 (org-delete-overlay org-read-date-overlay)
10407 (setq org-read-date-overlay nil)))))
10409 (setq final (org-read-date-analyze ans def defdecode))
10411 (if to-time
10412 (apply 'encode-time final)
10413 (if (and (boundp 'org-time-was-given) org-time-was-given)
10414 (format "%04d-%02d-%02d %02d:%02d"
10415 (nth 5 final) (nth 4 final) (nth 3 final)
10416 (nth 2 final) (nth 1 final))
10417 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10418 (defvar def)
10419 (defvar defdecode)
10420 (defvar with-time)
10421 (defun org-read-date-display ()
10422 "Display the currrent date prompt interpretation in the minibuffer."
10423 (when org-read-date-display-live
10424 (when org-read-date-overlay
10425 (org-delete-overlay org-read-date-overlay))
10426 (let ((p (point)))
10427 (end-of-line 1)
10428 (while (not (equal (buffer-substring
10429 (max (point-min) (- (point) 4)) (point))
10430 " "))
10431 (insert " "))
10432 (goto-char p))
10433 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10434 " " (or org-ans1 org-ans2)))
10435 (org-end-time-was-given nil)
10436 (f (org-read-date-analyze ans def defdecode))
10437 (fmts (if org-dcst
10438 org-time-stamp-custom-formats
10439 org-time-stamp-formats))
10440 (fmt (if (or with-time
10441 (and (boundp 'org-time-was-given) org-time-was-given))
10442 (cdr fmts)
10443 (car fmts)))
10444 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10445 (when (and org-end-time-was-given
10446 (string-match org-plain-time-of-day-regexp txt))
10447 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10448 org-end-time-was-given
10449 (substring txt (match-end 0)))))
10450 (setq org-read-date-overlay
10451 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10452 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10454 (defun org-read-date-analyze (ans def defdecode)
10455 "Analyze the combined answer of the date prompt."
10456 ;; FIXME: cleanup and comment
10457 (let (delta deltan deltaw deltadef year month day
10458 hour minute second wday pm h2 m2 tl wday1
10459 iso-year iso-weekday iso-week iso-year iso-date)
10461 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10462 (setq ans "+0"))
10464 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10465 (setq ans (replace-match "" t t ans)
10466 deltan (car delta)
10467 deltaw (nth 1 delta)
10468 deltadef (nth 2 delta)))
10470 ;; Check if there is an iso week date in there
10471 ;; If yes, sore the info and ostpone interpreting it until the rest
10472 ;; of the parsing is done
10473 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10474 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10475 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10476 iso-week (string-to-number (match-string 2 ans)))
10477 (setq ans (replace-match "" t t ans)))
10479 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10480 (when (string-match
10481 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10482 (setq year (if (match-end 2)
10483 (string-to-number (match-string 2 ans))
10484 (string-to-number (format-time-string "%Y")))
10485 month (string-to-number (match-string 3 ans))
10486 day (string-to-number (match-string 4 ans)))
10487 (if (< year 100) (setq year (+ 2000 year)))
10488 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10489 t nil ans)))
10490 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10491 ;; If there is a time with am/pm, and *no* time without it, we convert
10492 ;; so that matching will be successful.
10493 (loop for i from 1 to 2 do ; twice, for end time as well
10494 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10495 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10496 (setq hour (string-to-number (match-string 1 ans))
10497 minute (if (match-end 3)
10498 (string-to-number (match-string 3 ans))
10500 pm (equal ?p
10501 (string-to-char (downcase (match-string 4 ans)))))
10502 (if (and (= hour 12) (not pm))
10503 (setq hour 0)
10504 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10505 (setq ans (replace-match (format "%02d:%02d" hour minute)
10506 t t ans))))
10508 ;; Check if a time range is given as a duration
10509 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10510 (setq hour (string-to-number (match-string 1 ans))
10511 h2 (+ hour (string-to-number (match-string 3 ans)))
10512 minute (string-to-number (match-string 2 ans))
10513 m2 (+ minute (if (match-end 5) (string-to-number
10514 (match-string 5 ans))0)))
10515 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10516 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10517 t t ans)))
10519 ;; Check if there is a time range
10520 (when (boundp 'org-end-time-was-given)
10521 (setq org-time-was-given nil)
10522 (when (and (string-match org-plain-time-of-day-regexp ans)
10523 (match-end 8))
10524 (setq org-end-time-was-given (match-string 8 ans))
10525 (setq ans (concat (substring ans 0 (match-beginning 7))
10526 (substring ans (match-end 7))))))
10528 (setq tl (parse-time-string ans)
10529 day (or (nth 3 tl) (nth 3 defdecode))
10530 month (or (nth 4 tl)
10531 (if (and org-read-date-prefer-future
10532 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10533 (1+ (nth 4 defdecode))
10534 (nth 4 defdecode)))
10535 year (or (nth 5 tl)
10536 (if (and org-read-date-prefer-future
10537 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10538 (1+ (nth 5 defdecode))
10539 (nth 5 defdecode)))
10540 hour (or (nth 2 tl) (nth 2 defdecode))
10541 minute (or (nth 1 tl) (nth 1 defdecode))
10542 second (or (nth 0 tl) 0)
10543 wday (nth 6 tl))
10545 ;; Special date definitions below
10546 (cond
10547 (iso-week
10548 ;; There was an iso week
10549 (setq year (or iso-year year)
10550 day (or iso-weekday wday 1)
10551 wday nil ; to make sure that the trigger below does not match
10552 iso-date (calendar-gregorian-from-absolute
10553 (calendar-absolute-from-iso
10554 (list iso-week day year))))
10555 ; FIXME: Should we also push ISO weeks into the future?
10556 ; (when (and org-read-date-prefer-future
10557 ; (not iso-year)
10558 ; (< (calendar-absolute-from-gregorian iso-date)
10559 ; (time-to-days (current-time))))
10560 ; (setq year (1+ year)
10561 ; iso-date (calendar-gregorian-from-absolute
10562 ; (calendar-absolute-from-iso
10563 ; (list iso-week day year)))))
10564 (setq month (car iso-date)
10565 year (nth 2 iso-date)
10566 day (nth 1 iso-date)))
10567 (deltan
10568 (unless deltadef
10569 (let ((now (decode-time (current-time))))
10570 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10571 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10572 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10573 ((equal deltaw "m") (setq month (+ month deltan)))
10574 ((equal deltaw "y") (setq year (+ year deltan)))))
10575 ((and wday (not (nth 3 tl)))
10576 ;; Weekday was given, but no day, so pick that day in the week
10577 ;; on or after the derived date.
10578 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10579 (unless (equal wday wday1)
10580 (setq day (+ day (% (- wday wday1 -7) 7))))))
10581 (if (and (boundp 'org-time-was-given)
10582 (nth 2 tl))
10583 (setq org-time-was-given t))
10584 (if (< year 100) (setq year (+ 2000 year)))
10585 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10586 (list second minute hour day month year)))
10588 (defvar parse-time-weekdays)
10590 (defun org-read-date-get-relative (s today default)
10591 "Check string S for special relative date string.
10592 TODAY and DEFAULT are internal times, for today and for a default.
10593 Return shift list (N what def-flag)
10594 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10595 N is the number of WHATs to shift.
10596 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10597 the DEFAULT date rather than TODAY."
10598 (when (and
10599 (string-match
10600 (concat
10601 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10602 "\\([0-9]+\\)?"
10603 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10604 "\\([ \t]\\|$\\)") s)
10605 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10606 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10607 (string-to-char (substring (match-string 1 s) -1))
10608 ?+))
10609 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10610 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10611 (what (if (match-end 3) (match-string 3 s) "d"))
10612 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10613 (date (if rel default today))
10614 (wday (nth 6 (decode-time date)))
10615 delta)
10616 (if wday1
10617 (progn
10618 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10619 (if (= dir ?-) (setq delta (- delta 7)))
10620 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10621 (list delta "d" rel))
10622 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10624 (defun org-eval-in-calendar (form &optional keepdate)
10625 "Eval FORM in the calendar window and return to current window.
10626 Also, store the cursor date in variable org-ans2."
10627 (let ((sw (selected-window)))
10628 (select-window (get-buffer-window "*Calendar*"))
10629 (eval form)
10630 (when (and (not keepdate) (calendar-cursor-to-date))
10631 (let* ((date (calendar-cursor-to-date))
10632 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10633 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10634 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10635 (select-window sw)))
10637 (defun org-calendar-select ()
10638 "Return to `org-read-date' with the date currently selected.
10639 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10640 (interactive)
10641 (when (calendar-cursor-to-date)
10642 (let* ((date (calendar-cursor-to-date))
10643 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10644 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10645 (if (active-minibuffer-window) (exit-minibuffer))))
10647 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10648 "Insert a date stamp for the date given by the internal TIME.
10649 WITH-HM means, use the stamp format that includes the time of the day.
10650 INACTIVE means use square brackets instead of angular ones, so that the
10651 stamp will not contribute to the agenda.
10652 PRE and POST are optional strings to be inserted before and after the
10653 stamp.
10654 The command returns the inserted time stamp."
10655 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10656 stamp)
10657 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10658 (insert-before-markers (or pre ""))
10659 (insert-before-markers (setq stamp (format-time-string fmt time)))
10660 (when (listp extra)
10661 (setq extra (car extra))
10662 (if (and (stringp extra)
10663 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10664 (setq extra (format "-%02d:%02d"
10665 (string-to-number (match-string 1 extra))
10666 (string-to-number (match-string 2 extra))))
10667 (setq extra nil)))
10668 (when extra
10669 (backward-char 1)
10670 (insert-before-markers extra)
10671 (forward-char 1))
10672 (insert-before-markers (or post ""))
10673 (setq org-last-inserted-timestamp stamp)))
10675 (defun org-toggle-time-stamp-overlays ()
10676 "Toggle the use of custom time stamp formats."
10677 (interactive)
10678 (setq org-display-custom-times (not org-display-custom-times))
10679 (unless org-display-custom-times
10680 (let ((p (point-min)) (bmp (buffer-modified-p)))
10681 (while (setq p (next-single-property-change p 'display))
10682 (if (and (get-text-property p 'display)
10683 (eq (get-text-property p 'face) 'org-date))
10684 (remove-text-properties
10685 p (setq p (next-single-property-change p 'display))
10686 '(display t))))
10687 (set-buffer-modified-p bmp)))
10688 (if (featurep 'xemacs)
10689 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10690 (org-restart-font-lock)
10691 (setq org-table-may-need-update t)
10692 (if org-display-custom-times
10693 (message "Time stamps are overlayed with custom format")
10694 (message "Time stamp overlays removed")))
10696 (defun org-display-custom-time (beg end)
10697 "Overlay modified time stamp format over timestamp between BEG and END."
10698 (let* ((ts (buffer-substring beg end))
10699 t1 w1 with-hm tf time str w2 (off 0))
10700 (save-match-data
10701 (setq t1 (org-parse-time-string ts t))
10702 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10703 (setq off (- (match-end 0) (match-beginning 0)))))
10704 (setq end (- end off))
10705 (setq w1 (- end beg)
10706 with-hm (and (nth 1 t1) (nth 2 t1))
10707 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10708 time (org-fix-decoded-time t1)
10709 str (org-add-props
10710 (format-time-string
10711 (substring tf 1 -1) (apply 'encode-time time))
10712 nil 'mouse-face 'highlight)
10713 w2 (length str))
10714 (if (not (= w2 w1))
10715 (add-text-properties (1+ beg) (+ 2 beg)
10716 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10717 (if (featurep 'xemacs)
10718 (progn
10719 (put-text-property beg end 'invisible t)
10720 (put-text-property beg end 'end-glyph (make-glyph str)))
10721 (put-text-property beg end 'display str))))
10723 (defun org-translate-time (string)
10724 "Translate all timestamps in STRING to custom format.
10725 But do this only if the variable `org-display-custom-times' is set."
10726 (when org-display-custom-times
10727 (save-match-data
10728 (let* ((start 0)
10729 (re org-ts-regexp-both)
10730 t1 with-hm inactive tf time str beg end)
10731 (while (setq start (string-match re string start))
10732 (setq beg (match-beginning 0)
10733 end (match-end 0)
10734 t1 (save-match-data
10735 (org-parse-time-string (substring string beg end) t))
10736 with-hm (and (nth 1 t1) (nth 2 t1))
10737 inactive (equal (substring string beg (1+ beg)) "[")
10738 tf (funcall (if with-hm 'cdr 'car)
10739 org-time-stamp-custom-formats)
10740 time (org-fix-decoded-time t1)
10741 str (format-time-string
10742 (concat
10743 (if inactive "[" "<") (substring tf 1 -1)
10744 (if inactive "]" ">"))
10745 (apply 'encode-time time))
10746 string (replace-match str t t string)
10747 start (+ start (length str)))))))
10748 string)
10750 (defun org-fix-decoded-time (time)
10751 "Set 0 instead of nil for the first 6 elements of time.
10752 Don't touch the rest."
10753 (let ((n 0))
10754 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10756 (defun org-days-to-time (timestamp-string)
10757 "Difference between TIMESTAMP-STRING and now in days."
10758 (- (time-to-days (org-time-string-to-time timestamp-string))
10759 (time-to-days (current-time))))
10761 (defun org-deadline-close (timestamp-string &optional ndays)
10762 "Is the time in TIMESTAMP-STRING close to the current date?"
10763 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10764 (and (< (org-days-to-time timestamp-string) ndays)
10765 (not (org-entry-is-done-p))))
10767 (defun org-get-wdays (ts)
10768 "Get the deadline lead time appropriate for timestring TS."
10769 (cond
10770 ((<= org-deadline-warning-days 0)
10771 ;; 0 or negative, enforce this value no matter what
10772 (- org-deadline-warning-days))
10773 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10774 ;; lead time is specified.
10775 (floor (* (string-to-number (match-string 1 ts))
10776 (cdr (assoc (match-string 2 ts)
10777 '(("d" . 1) ("w" . 7)
10778 ("m" . 30.4) ("y" . 365.25)))))))
10779 ;; go for the default.
10780 (t org-deadline-warning-days)))
10782 (defun org-calendar-select-mouse (ev)
10783 "Return to `org-read-date' with the date currently selected.
10784 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10785 (interactive "e")
10786 (mouse-set-point ev)
10787 (when (calendar-cursor-to-date)
10788 (let* ((date (calendar-cursor-to-date))
10789 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10790 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10791 (if (active-minibuffer-window) (exit-minibuffer))))
10793 (defun org-check-deadlines (ndays)
10794 "Check if there are any deadlines due or past due.
10795 A deadline is considered due if it happens within `org-deadline-warning-days'
10796 days from today's date. If the deadline appears in an entry marked DONE,
10797 it is not shown. The prefix arg NDAYS can be used to test that many
10798 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10799 (interactive "P")
10800 (let* ((org-warn-days
10801 (cond
10802 ((equal ndays '(4)) 100000)
10803 (ndays (prefix-numeric-value ndays))
10804 (t (abs org-deadline-warning-days))))
10805 (case-fold-search nil)
10806 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10807 (callback
10808 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10810 (message "%d deadlines past-due or due within %d days"
10811 (org-occur regexp nil callback)
10812 org-warn-days)))
10814 (defun org-check-before-date (date)
10815 "Check if there are deadlines or scheduled entries before DATE."
10816 (interactive (list (org-read-date)))
10817 (let ((case-fold-search nil)
10818 (regexp (concat "\\<\\(" org-deadline-string
10819 "\\|" org-scheduled-string
10820 "\\) *<\\([^>]+\\)>"))
10821 (callback
10822 (lambda () (time-less-p
10823 (org-time-string-to-time (match-string 2))
10824 (org-time-string-to-time date)))))
10825 (message "%d entries before %s"
10826 (org-occur regexp nil callback) date)))
10828 (defun org-evaluate-time-range (&optional to-buffer)
10829 "Evaluate a time range by computing the difference between start and end.
10830 Normally the result is just printed in the echo area, but with prefix arg
10831 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10832 If the time range is actually in a table, the result is inserted into the
10833 next column.
10834 For time difference computation, a year is assumed to be exactly 365
10835 days in order to avoid rounding problems."
10836 (interactive "P")
10838 (org-clock-update-time-maybe)
10839 (save-excursion
10840 (unless (org-at-date-range-p t)
10841 (goto-char (point-at-bol))
10842 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10843 (if (not (org-at-date-range-p t))
10844 (error "Not at a time-stamp range, and none found in current line")))
10845 (let* ((ts1 (match-string 1))
10846 (ts2 (match-string 2))
10847 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10848 (match-end (match-end 0))
10849 (time1 (org-time-string-to-time ts1))
10850 (time2 (org-time-string-to-time ts2))
10851 (t1 (time-to-seconds time1))
10852 (t2 (time-to-seconds time2))
10853 (diff (abs (- t2 t1)))
10854 (negative (< (- t2 t1) 0))
10855 ;; (ys (floor (* 365 24 60 60)))
10856 (ds (* 24 60 60))
10857 (hs (* 60 60))
10858 (fy "%dy %dd %02d:%02d")
10859 (fy1 "%dy %dd")
10860 (fd "%dd %02d:%02d")
10861 (fd1 "%dd")
10862 (fh "%02d:%02d")
10863 y d h m align)
10864 (if havetime
10865 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10867 d (floor (/ diff ds)) diff (mod diff ds)
10868 h (floor (/ diff hs)) diff (mod diff hs)
10869 m (floor (/ diff 60)))
10870 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10872 d (floor (+ (/ diff ds) 0.5))
10873 h 0 m 0))
10874 (if (not to-buffer)
10875 (message "%s" (org-make-tdiff-string y d h m))
10876 (if (org-at-table-p)
10877 (progn
10878 (goto-char match-end)
10879 (setq align t)
10880 (and (looking-at " *|") (goto-char (match-end 0))))
10881 (goto-char match-end))
10882 (if (looking-at
10883 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10884 (replace-match ""))
10885 (if negative (insert " -"))
10886 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10887 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10888 (insert " " (format fh h m))))
10889 (if align (org-table-align))
10890 (message "Time difference inserted")))))
10892 (defun org-make-tdiff-string (y d h m)
10893 (let ((fmt "")
10894 (l nil))
10895 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10896 l (push y l)))
10897 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10898 l (push d l)))
10899 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10900 l (push h l)))
10901 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10902 l (push m l)))
10903 (apply 'format fmt (nreverse l))))
10905 (defun org-time-string-to-time (s)
10906 (apply 'encode-time (org-parse-time-string s)))
10908 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10909 "Convert a time stamp to an absolute day number.
10910 If there is a specifyer for a cyclic time stamp, get the closest date to
10911 DAYNR.
10912 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10913 (cond
10914 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10915 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10916 daynr
10917 (+ daynr 1000)))
10918 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10919 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10920 (time-to-days (current-time))) (match-string 0 s)
10921 prefer show-all))
10922 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10924 (defun org-days-to-iso-week (days)
10925 "Return the iso week number."
10926 (require 'cal-iso)
10927 (car (calendar-iso-from-absolute days)))
10929 (defun org-small-year-to-year (year)
10930 "Convert 2-digit years into 4-digit years.
10931 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10932 The year 2000 cannot be abbreviated. Any year lager than 99
10933 is retrned unchanged."
10934 (if (< year 38)
10935 (setq year (+ 2000 year))
10936 (if (< year 100)
10937 (setq year (+ 1900 year))))
10938 year)
10940 (defun org-time-from-absolute (d)
10941 "Return the time corresponding to date D.
10942 D may be an absolute day number, or a calendar-type list (month day year)."
10943 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10944 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10946 (defun org-calendar-holiday ()
10947 "List of holidays, for Diary display in Org-mode."
10948 (require 'holidays)
10949 (let ((hl (funcall
10950 (if (fboundp 'calendar-check-holidays)
10951 'calendar-check-holidays 'check-calendar-holidays) date)))
10952 (if hl (mapconcat 'identity hl "; "))))
10954 (defun org-diary-sexp-entry (sexp entry date)
10955 "Process a SEXP diary ENTRY for DATE."
10956 (require 'diary-lib)
10957 (let ((result (if calendar-debug-sexp
10958 (let ((stack-trace-on-error t))
10959 (eval (car (read-from-string sexp))))
10960 (condition-case nil
10961 (eval (car (read-from-string sexp)))
10962 (error
10963 (beep)
10964 (message "Bad sexp at line %d in %s: %s"
10965 (org-current-line)
10966 (buffer-file-name) sexp)
10967 (sleep-for 2))))))
10968 (cond ((stringp result) result)
10969 ((and (consp result)
10970 (stringp (cdr result))) (cdr result))
10971 (result entry)
10972 (t nil))))
10974 (defun org-diary-to-ical-string (frombuf)
10975 "Get iCalendar entries from diary entries in buffer FROMBUF.
10976 This uses the icalendar.el library."
10977 (let* ((tmpdir (if (featurep 'xemacs)
10978 (temp-directory)
10979 temporary-file-directory))
10980 (tmpfile (make-temp-name
10981 (expand-file-name "orgics" tmpdir)))
10982 buf rtn b e)
10983 (save-excursion
10984 (set-buffer frombuf)
10985 (icalendar-export-region (point-min) (point-max) tmpfile)
10986 (setq buf (find-buffer-visiting tmpfile))
10987 (set-buffer buf)
10988 (goto-char (point-min))
10989 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10990 (setq b (match-beginning 0)))
10991 (goto-char (point-max))
10992 (if (re-search-backward "^END:VEVENT" nil t)
10993 (setq e (match-end 0)))
10994 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10995 (kill-buffer buf)
10996 (delete-file tmpfile)
10997 rtn))
10999 (defun org-closest-date (start current change prefer show-all)
11000 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11001 When PREFER is `past' return a date that is either CURRENT or past.
11002 When PREFER is `future', return a date that is either CURRENT or future.
11003 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11004 ;; Make the proper lists from the dates
11005 (catch 'exit
11006 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11007 dn dw sday cday n1 n2
11008 d m y y1 y2 date1 date2 nmonths nm ny m2)
11010 (setq start (org-date-to-gregorian start)
11011 current (org-date-to-gregorian
11012 (if show-all
11013 current
11014 (time-to-days (current-time))))
11015 sday (calendar-absolute-from-gregorian start)
11016 cday (calendar-absolute-from-gregorian current))
11018 (if (<= cday sday) (throw 'exit sday))
11020 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11021 (setq dn (string-to-number (match-string 1 change))
11022 dw (cdr (assoc (match-string 2 change) a1)))
11023 (error "Invalid change specifyer: %s" change))
11024 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11025 (cond
11026 ((eq dw 'day)
11027 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11028 n2 (+ n1 dn)))
11029 ((eq dw 'year)
11030 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11031 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11032 (setq date1 (list m d y1)
11033 n1 (calendar-absolute-from-gregorian date1)
11034 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11035 n2 (calendar-absolute-from-gregorian date2)))
11036 ((eq dw 'month)
11037 ;; approx number of month between the two dates
11038 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11039 ;; How often does dn fit in there?
11040 (setq d (nth 1 start) m (car start) y (nth 2 start)
11041 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11042 m (+ m nm)
11043 ny (floor (/ m 12))
11044 y (+ y ny)
11045 m (- m (* ny 12)))
11046 (while (> m 12) (setq m (- m 12) y (1+ y)))
11047 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11048 (setq m2 (+ m dn) y2 y)
11049 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11050 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11051 (while (<= n2 cday)
11052 (setq n1 n2 m m2 y y2)
11053 (setq m2 (+ m dn) y2 y)
11054 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11055 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11056 (if show-all
11057 (cond
11058 ((eq prefer 'past) n1)
11059 ((eq prefer 'future) (if (= cday n1) n1 n2))
11060 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11061 (cond
11062 ((eq prefer 'past) n1)
11063 ((eq prefer 'future) (if (= cday n1) n1 n2))
11064 (t (if (= cday n1) n1 n2)))))))
11066 (defun org-date-to-gregorian (date)
11067 "Turn any specification of DATE into a gregorian date for the calendar."
11068 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11069 ((and (listp date) (= (length date) 3)) date)
11070 ((stringp date)
11071 (setq date (org-parse-time-string date))
11072 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11073 ((listp date)
11074 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11076 (defun org-parse-time-string (s &optional nodefault)
11077 "Parse the standard Org-mode time string.
11078 This should be a lot faster than the normal `parse-time-string'.
11079 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11080 hour and minute fields will be nil if not given."
11081 (if (string-match org-ts-regexp0 s)
11082 (list 0
11083 (if (or (match-beginning 8) (not nodefault))
11084 (string-to-number (or (match-string 8 s) "0")))
11085 (if (or (match-beginning 7) (not nodefault))
11086 (string-to-number (or (match-string 7 s) "0")))
11087 (string-to-number (match-string 4 s))
11088 (string-to-number (match-string 3 s))
11089 (string-to-number (match-string 2 s))
11090 nil nil nil)
11091 (make-list 9 0)))
11093 (defun org-timestamp-up (&optional arg)
11094 "Increase the date item at the cursor by one.
11095 If the cursor is on the year, change the year. If it is on the month or
11096 the day, change that.
11097 With prefix ARG, change by that many units."
11098 (interactive "p")
11099 (org-timestamp-change (prefix-numeric-value arg)))
11101 (defun org-timestamp-down (&optional arg)
11102 "Decrease the date item at the cursor by one.
11103 If the cursor is on the year, change the year. If it is on the month or
11104 the day, change that.
11105 With prefix ARG, change by that many units."
11106 (interactive "p")
11107 (org-timestamp-change (- (prefix-numeric-value arg))))
11109 (defun org-timestamp-up-day (&optional arg)
11110 "Increase the date in the time stamp by one day.
11111 With prefix ARG, change that many days."
11112 (interactive "p")
11113 (if (and (not (org-at-timestamp-p t))
11114 (org-on-heading-p))
11115 (org-todo 'up)
11116 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11118 (defun org-timestamp-down-day (&optional arg)
11119 "Decrease the date in the time stamp by one day.
11120 With prefix ARG, change that many days."
11121 (interactive "p")
11122 (if (and (not (org-at-timestamp-p t))
11123 (org-on-heading-p))
11124 (org-todo 'down)
11125 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11127 (defun org-at-timestamp-p (&optional inactive-ok)
11128 "Determine if the cursor is in or at a timestamp."
11129 (interactive)
11130 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11131 (pos (point))
11132 (ans (or (looking-at tsr)
11133 (save-excursion
11134 (skip-chars-backward "^[<\n\r\t")
11135 (if (> (point) (point-min)) (backward-char 1))
11136 (and (looking-at tsr)
11137 (> (- (match-end 0) pos) -1))))))
11138 (and ans
11139 (boundp 'org-ts-what)
11140 (setq org-ts-what
11141 (cond
11142 ((= pos (match-beginning 0)) 'bracket)
11143 ((= pos (1- (match-end 0))) 'bracket)
11144 ((org-pos-in-match-range pos 2) 'year)
11145 ((org-pos-in-match-range pos 3) 'month)
11146 ((org-pos-in-match-range pos 7) 'hour)
11147 ((org-pos-in-match-range pos 8) 'minute)
11148 ((or (org-pos-in-match-range pos 4)
11149 (org-pos-in-match-range pos 5)) 'day)
11150 ((and (> pos (or (match-end 8) (match-end 5)))
11151 (< pos (match-end 0)))
11152 (- pos (or (match-end 8) (match-end 5))))
11153 (t 'day))))
11154 ans))
11156 (defun org-toggle-timestamp-type ()
11157 "Toggle the type (<active> or [inactive]) of a time stamp."
11158 (interactive)
11159 (when (org-at-timestamp-p t)
11160 (save-excursion
11161 (goto-char (match-beginning 0))
11162 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11163 (goto-char (1- (match-end 0)))
11164 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11165 (message "Timestamp is now %sactive"
11166 (if (equal (char-before) ?>) "in" ""))))
11168 (defun org-timestamp-change (n &optional what)
11169 "Change the date in the time stamp at point.
11170 The date will be changed by N times WHAT. WHAT can be `day', `month',
11171 `year', `minute', `second'. If WHAT is not given, the cursor position
11172 in the timestamp determines what will be changed."
11173 (let ((pos (point))
11174 with-hm inactive
11175 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11176 org-ts-what
11177 extra rem
11178 ts time time0)
11179 (if (not (org-at-timestamp-p t))
11180 (error "Not at a timestamp"))
11181 (if (and (not what) (eq org-ts-what 'bracket))
11182 (org-toggle-timestamp-type)
11183 (if (and (not what) (not (eq org-ts-what 'day))
11184 org-display-custom-times
11185 (get-text-property (point) 'display)
11186 (not (get-text-property (1- (point)) 'display)))
11187 (setq org-ts-what 'day))
11188 (setq org-ts-what (or what org-ts-what)
11189 inactive (= (char-after (match-beginning 0)) ?\[)
11190 ts (match-string 0))
11191 (replace-match "")
11192 (if (string-match
11193 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11195 (setq extra (match-string 1 ts)))
11196 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11197 (setq with-hm t))
11198 (setq time0 (org-parse-time-string ts))
11199 (when (and (eq org-ts-what 'minute)
11200 (eq current-prefix-arg nil))
11201 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11202 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11203 (setcar (cdr time0) (+ (nth 1 time0)
11204 (if (> n 0) (- rem) (- dm rem))))))
11205 (setq time
11206 (encode-time (or (car time0) 0)
11207 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11208 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11209 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11210 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11211 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11212 (nthcdr 6 time0)))
11213 (when (integerp org-ts-what)
11214 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11215 (if (eq what 'calendar)
11216 (let ((cal-date (org-get-date-from-calendar)))
11217 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11218 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11219 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11220 (setcar time0 (or (car time0) 0))
11221 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11222 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11223 (setq time (apply 'encode-time time0))))
11224 (setq org-last-changed-timestamp
11225 (org-insert-time-stamp time with-hm inactive nil nil extra))
11226 (org-clock-update-time-maybe)
11227 (goto-char pos)
11228 ;; Try to recenter the calendar window, if any
11229 (if (and org-calendar-follow-timestamp-change
11230 (get-buffer-window "*Calendar*" t)
11231 (memq org-ts-what '(day month year)))
11232 (org-recenter-calendar (time-to-days time))))))
11234 (defun org-modify-ts-extra (s pos n dm)
11235 "Change the different parts of the lead-time and repeat fields in timestamp."
11236 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11237 ng h m new rem)
11238 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11239 (cond
11240 ((or (org-pos-in-match-range pos 2)
11241 (org-pos-in-match-range pos 3))
11242 (setq m (string-to-number (match-string 3 s))
11243 h (string-to-number (match-string 2 s)))
11244 (if (org-pos-in-match-range pos 2)
11245 (setq h (+ h n))
11246 (setq n (* dm (org-no-warnings (signum n))))
11247 (when (not (= 0 (setq rem (% m dm))))
11248 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11249 (setq m (+ m n)))
11250 (if (< m 0) (setq m (+ m 60) h (1- h)))
11251 (if (> m 59) (setq m (- m 60) h (1+ h)))
11252 (setq h (min 24 (max 0 h)))
11253 (setq ng 1 new (format "-%02d:%02d" h m)))
11254 ((org-pos-in-match-range pos 6)
11255 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11256 ((org-pos-in-match-range pos 5)
11257 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11259 ((org-pos-in-match-range pos 9)
11260 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11261 ((org-pos-in-match-range pos 8)
11262 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11264 (when ng
11265 (setq s (concat
11266 (substring s 0 (match-beginning ng))
11268 (substring s (match-end ng))))))
11271 (defun org-recenter-calendar (date)
11272 "If the calendar is visible, recenter it to DATE."
11273 (let* ((win (selected-window))
11274 (cwin (get-buffer-window "*Calendar*" t))
11275 (calendar-move-hook nil))
11276 (when cwin
11277 (select-window cwin)
11278 (calendar-goto-date (if (listp date) date
11279 (calendar-gregorian-from-absolute date)))
11280 (select-window win))))
11282 (defun org-goto-calendar (&optional arg)
11283 "Go to the Emacs calendar at the current date.
11284 If there is a time stamp in the current line, go to that date.
11285 A prefix ARG can be used to force the current date."
11286 (interactive "P")
11287 (let ((tsr org-ts-regexp) diff
11288 (calendar-move-hook nil)
11289 (calendar-view-holidays-initially-flag nil)
11290 (view-calendar-holidays-initially nil)
11291 (calendar-view-diary-initially-flag nil)
11292 (view-diary-entries-initially nil))
11293 (if (or (org-at-timestamp-p)
11294 (save-excursion
11295 (beginning-of-line 1)
11296 (looking-at (concat ".*" tsr))))
11297 (let ((d1 (time-to-days (current-time)))
11298 (d2 (time-to-days
11299 (org-time-string-to-time (match-string 1)))))
11300 (setq diff (- d2 d1))))
11301 (calendar)
11302 (calendar-goto-today)
11303 (if (and diff (not arg)) (calendar-forward-day diff))))
11305 (defun org-get-date-from-calendar ()
11306 "Return a list (month day year) of date at point in calendar."
11307 (with-current-buffer "*Calendar*"
11308 (save-match-data
11309 (calendar-cursor-to-date))))
11311 (defun org-date-from-calendar ()
11312 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11313 If there is already a time stamp at the cursor position, update it."
11314 (interactive)
11315 (if (org-at-timestamp-p t)
11316 (org-timestamp-change 0 'calendar)
11317 (let ((cal-date (org-get-date-from-calendar)))
11318 (org-insert-time-stamp
11319 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11321 (defun org-minutes-to-hh:mm-string (m)
11322 "Compute H:MM from a number of minutes."
11323 (let ((h (/ m 60)))
11324 (setq m (- m (* 60 h)))
11325 (format org-time-clocksum-format h m)))
11327 (defun org-hh:mm-string-to-minutes (s)
11328 "Convert a string H:MM to a number of minutes."
11329 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11330 (+ (* (string-to-number (match-string 1 s)) 60)
11331 (string-to-number (match-string 2 s)))
11334 ;;;; Agenda files
11336 ;;;###autoload
11337 (defun org-iswitchb (&optional arg)
11338 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11339 With a prefix argument, restrict available to files.
11340 With two prefix arguments, restrict available buffers to agenda files.
11342 Due to some yet unresolved reason, the global function
11343 `iswitchb-mode' needs to be active for this function to work."
11344 (interactive "P")
11345 (require 'iswitchb)
11346 (let ((enabled iswitchb-mode) blist)
11347 (or enabled (iswitchb-mode 1))
11348 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11349 ((equal arg '(16)) (org-buffer-list 'agenda))
11350 (t (org-buffer-list))))
11351 (unwind-protect
11352 (let ((iswitchb-make-buflist-hook
11353 (lambda ()
11354 (setq iswitchb-temp-buflist
11355 (mapcar 'buffer-name blist)))))
11356 (switch-to-buffer
11357 (iswitchb-read-buffer
11358 "Switch-to: " nil t))
11359 (or enabled (iswitchb-mode -1))))))
11361 (defun org-buffer-list (&optional predicate exclude-tmp)
11362 "Return a list of Org buffers.
11363 PREDICATE can be `export', `files' or `agenda'.
11365 export restrict the list to Export buffers.
11366 files restrict the list to buffers visiting Org files.
11367 agenda restrict the list to buffers visiting agenda files.
11369 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11370 (let* ((bfn nil)
11371 (agenda-files (and (eq predicate 'agenda)
11372 (mapcar 'file-truename (org-agenda-files t))))
11373 (filter
11374 (cond
11375 ((eq predicate 'files)
11376 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11377 ((eq predicate 'export)
11378 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11379 ((eq predicate 'agenda)
11380 (lambda (b)
11381 (with-current-buffer b
11382 (and (eq major-mode 'org-mode)
11383 (setq bfn (buffer-file-name b))
11384 (member (file-truename bfn) agenda-files)))))
11385 (t (lambda (b) (with-current-buffer b
11386 (or (eq major-mode 'org-mode)
11387 (string-match "\*Org .*Export"
11388 (buffer-name b)))))))))
11389 (delq nil
11390 (mapcar
11391 (lambda(b)
11392 (if (and (funcall filter b)
11393 (or (not exclude-tmp)
11394 (not (string-match "tmp" (buffer-name b)))))
11396 nil))
11397 (buffer-list)))))
11399 (defun org-agenda-files (&optional unrestricted archives)
11400 "Get the list of agenda files.
11401 Optional UNRESTRICTED means return the full list even if a restriction
11402 is currently in place.
11403 When ARCHIVES is t, include all archive files hat are really being
11404 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11405 `org-agenda-archives-mode' is t."
11406 (let ((files
11407 (cond
11408 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11409 ((stringp org-agenda-files) (org-read-agenda-file-list))
11410 ((listp org-agenda-files) org-agenda-files)
11411 (t (error "Invalid value of `org-agenda-files'")))))
11412 (setq files (apply 'append
11413 (mapcar (lambda (f)
11414 (if (file-directory-p f)
11415 (directory-files
11416 f t org-agenda-file-regexp)
11417 (list f)))
11418 files)))
11419 (when org-agenda-skip-unavailable-files
11420 (setq files (delq nil
11421 (mapcar (function
11422 (lambda (file)
11423 (and (file-readable-p file) file)))
11424 files))))
11425 (when (or (eq archives t)
11426 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11427 (setq files (org-add-archive-files files)))
11428 files))
11430 (defun org-edit-agenda-file-list ()
11431 "Edit the list of agenda files.
11432 Depending on setup, this either uses customize to edit the variable
11433 `org-agenda-files', or it visits the file that is holding the list. In the
11434 latter case, the buffer is set up in a way that saving it automatically kills
11435 the buffer and restores the previous window configuration."
11436 (interactive)
11437 (if (stringp org-agenda-files)
11438 (let ((cw (current-window-configuration)))
11439 (find-file org-agenda-files)
11440 (org-set-local 'org-window-configuration cw)
11441 (org-add-hook 'after-save-hook
11442 (lambda ()
11443 (set-window-configuration
11444 (prog1 org-window-configuration
11445 (kill-buffer (current-buffer))))
11446 (org-install-agenda-files-menu)
11447 (message "New agenda file list installed"))
11448 nil 'local)
11449 (message "%s" (substitute-command-keys
11450 "Edit list and finish with \\[save-buffer]")))
11451 (customize-variable 'org-agenda-files)))
11453 (defun org-store-new-agenda-file-list (list)
11454 "Set new value for the agenda file list and save it correcly."
11455 (if (stringp org-agenda-files)
11456 (let ((f org-agenda-files) b)
11457 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11458 (with-temp-file f
11459 (insert (mapconcat 'identity list "\n") "\n")))
11460 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11461 (setq org-agenda-files list)
11462 (customize-save-variable 'org-agenda-files org-agenda-files))))
11464 (defun org-read-agenda-file-list ()
11465 "Read the list of agenda files from a file."
11466 (when (file-directory-p org-agenda-files)
11467 (error "`org-agenda-files' cannot be a single directory"))
11468 (when (stringp org-agenda-files)
11469 (with-temp-buffer
11470 (insert-file-contents org-agenda-files)
11471 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11474 ;;;###autoload
11475 (defun org-cycle-agenda-files ()
11476 "Cycle through the files in `org-agenda-files'.
11477 If the current buffer visits an agenda file, find the next one in the list.
11478 If the current buffer does not, find the first agenda file."
11479 (interactive)
11480 (let* ((fs (org-agenda-files t))
11481 (files (append fs (list (car fs))))
11482 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11483 file)
11484 (unless files (error "No agenda files"))
11485 (catch 'exit
11486 (while (setq file (pop files))
11487 (if (equal (file-truename file) tcf)
11488 (when (car files)
11489 (find-file (car files))
11490 (throw 'exit t))))
11491 (find-file (car fs)))
11492 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11494 (defun org-agenda-file-to-front (&optional to-end)
11495 "Move/add the current file to the top of the agenda file list.
11496 If the file is not present in the list, it is added to the front. If it is
11497 present, it is moved there. With optional argument TO-END, add/move to the
11498 end of the list."
11499 (interactive "P")
11500 (let ((org-agenda-skip-unavailable-files nil)
11501 (file-alist (mapcar (lambda (x)
11502 (cons (file-truename x) x))
11503 (org-agenda-files t)))
11504 (ctf (file-truename buffer-file-name))
11505 x had)
11506 (setq x (assoc ctf file-alist) had x)
11508 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11509 (if to-end
11510 (setq file-alist (append (delq x file-alist) (list x)))
11511 (setq file-alist (cons x (delq x file-alist))))
11512 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11513 (org-install-agenda-files-menu)
11514 (message "File %s to %s of agenda file list"
11515 (if had "moved" "added") (if to-end "end" "front"))))
11517 (defun org-remove-file (&optional file)
11518 "Remove current file from the list of files in variable `org-agenda-files'.
11519 These are the files which are being checked for agenda entries.
11520 Optional argument FILE means, use this file instead of the current."
11521 (interactive)
11522 (let* ((org-agenda-skip-unavailable-files nil)
11523 (file (or file buffer-file-name))
11524 (true-file (file-truename file))
11525 (afile (abbreviate-file-name file))
11526 (files (delq nil (mapcar
11527 (lambda (x)
11528 (if (equal true-file
11529 (file-truename x))
11530 nil x))
11531 (org-agenda-files t)))))
11532 (if (not (= (length files) (length (org-agenda-files t))))
11533 (progn
11534 (org-store-new-agenda-file-list files)
11535 (org-install-agenda-files-menu)
11536 (message "Removed file: %s" afile))
11537 (message "File was not in list: %s (not removed)" afile))))
11539 (defun org-file-menu-entry (file)
11540 (vector file (list 'find-file file) t))
11542 (defun org-check-agenda-file (file)
11543 "Make sure FILE exists. If not, ask user what to do."
11544 (when (not (file-exists-p file))
11545 (message "non-existent file %s. [R]emove from list or [A]bort?"
11546 (abbreviate-file-name file))
11547 (let ((r (downcase (read-char-exclusive))))
11548 (cond
11549 ((equal r ?r)
11550 (org-remove-file file)
11551 (throw 'nextfile t))
11552 (t (error "Abort"))))))
11554 (defun org-get-agenda-file-buffer (file)
11555 "Get a buffer visiting FILE. If the buffer needs to be created, add
11556 it to the list of buffers which might be released later."
11557 (let ((buf (org-find-base-buffer-visiting file)))
11558 (if buf
11559 buf ; just return it
11560 ;; Make a new buffer and remember it
11561 (setq buf (find-file-noselect file))
11562 (if buf (push buf org-agenda-new-buffers))
11563 buf)))
11565 (defun org-release-buffers (blist)
11566 "Release all buffers in list, asking the user for confirmation when needed.
11567 When a buffer is unmodified, it is just killed. When modified, it is saved
11568 \(if the user agrees) and then killed."
11569 (let (buf file)
11570 (while (setq buf (pop blist))
11571 (setq file (buffer-file-name buf))
11572 (when (and (buffer-modified-p buf)
11573 file
11574 (y-or-n-p (format "Save file %s? " file)))
11575 (with-current-buffer buf (save-buffer)))
11576 (kill-buffer buf))))
11578 (defun org-prepare-agenda-buffers (files)
11579 "Create buffers for all agenda files, protect archived trees and comments."
11580 (interactive)
11581 (let ((pa '(:org-archived t))
11582 (pc '(:org-comment t))
11583 (pall '(:org-archived t :org-comment t))
11584 (inhibit-read-only t)
11585 (rea (concat ":" org-archive-tag ":"))
11586 bmp file re)
11587 (save-excursion
11588 (save-restriction
11589 (while (setq file (pop files))
11590 (if (bufferp file)
11591 (set-buffer file)
11592 (org-check-agenda-file file)
11593 (set-buffer (org-get-agenda-file-buffer file)))
11594 (widen)
11595 (setq bmp (buffer-modified-p))
11596 (org-refresh-category-properties)
11597 (setq org-todo-keywords-for-agenda
11598 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11599 (setq org-done-keywords-for-agenda
11600 (append org-done-keywords-for-agenda org-done-keywords))
11601 (setq org-todo-keyword-alist-for-agenda
11602 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11603 (setq org-tag-alist-for-agenda
11604 (append org-tag-alist-for-agenda org-tag-alist))
11606 (save-excursion
11607 (remove-text-properties (point-min) (point-max) pall)
11608 (when org-agenda-skip-archived-trees
11609 (goto-char (point-min))
11610 (while (re-search-forward rea nil t)
11611 (if (org-on-heading-p t)
11612 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11613 (goto-char (point-min))
11614 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11615 (while (re-search-forward re nil t)
11616 (add-text-properties
11617 (match-beginning 0) (org-end-of-subtree t) pc)))
11618 (set-buffer-modified-p bmp))))
11619 (setq org-todo-keyword-alist-for-agenda
11620 (org-uniquify org-todo-keyword-alist-for-agenda)
11621 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11623 ;;;; Embedded LaTeX
11625 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11626 "Keymap for the minor `org-cdlatex-mode'.")
11628 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11629 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11630 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11631 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11632 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11634 (defvar org-cdlatex-texmathp-advice-is-done nil
11635 "Flag remembering if we have applied the advice to texmathp already.")
11637 (define-minor-mode org-cdlatex-mode
11638 "Toggle the minor `org-cdlatex-mode'.
11639 This mode supports entering LaTeX environment and math in LaTeX fragments
11640 in Org-mode.
11641 \\{org-cdlatex-mode-map}"
11642 nil " OCDL" nil
11643 (when org-cdlatex-mode (require 'cdlatex))
11644 (unless org-cdlatex-texmathp-advice-is-done
11645 (setq org-cdlatex-texmathp-advice-is-done t)
11646 (defadvice texmathp (around org-math-always-on activate)
11647 "Always return t in org-mode buffers.
11648 This is because we want to insert math symbols without dollars even outside
11649 the LaTeX math segments. If Orgmode thinks that point is actually inside
11650 en embedded LaTeX fragement, let texmathp do its job.
11651 \\[org-cdlatex-mode-map]"
11652 (interactive)
11653 (let (p)
11654 (cond
11655 ((not (org-mode-p)) ad-do-it)
11656 ((eq this-command 'cdlatex-math-symbol)
11657 (setq ad-return-value t
11658 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11660 (let ((p (org-inside-LaTeX-fragment-p)))
11661 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11662 (setq ad-return-value t
11663 texmathp-why '("Org-mode embedded math" . 0))
11664 (if p ad-do-it)))))))))
11666 (defun turn-on-org-cdlatex ()
11667 "Unconditionally turn on `org-cdlatex-mode'."
11668 (org-cdlatex-mode 1))
11670 (defun org-inside-LaTeX-fragment-p ()
11671 "Test if point is inside a LaTeX fragment.
11672 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11673 sequence appearing also before point.
11674 Even though the matchers for math are configurable, this function assumes
11675 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11676 delimiters are skipped when they have been removed by customization.
11677 The return value is nil, or a cons cell with the delimiter and
11678 and the position of this delimiter.
11680 This function does a reasonably good job, but can locally be fooled by
11681 for example currency specifications. For example it will assume being in
11682 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11683 fragments that are properly closed, but during editing, we have to live
11684 with the uncertainty caused by missing closing delimiters. This function
11685 looks only before point, not after."
11686 (catch 'exit
11687 (let ((pos (point))
11688 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11689 (lim (progn
11690 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11691 (point)))
11692 dd-on str (start 0) m re)
11693 (goto-char pos)
11694 (when dodollar
11695 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11696 re (nth 1 (assoc "$" org-latex-regexps)))
11697 (while (string-match re str start)
11698 (cond
11699 ((= (match-end 0) (length str))
11700 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11701 ((= (match-end 0) (- (length str) 5))
11702 (throw 'exit nil))
11703 (t (setq start (match-end 0))))))
11704 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11705 (goto-char pos)
11706 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11707 (and (match-beginning 2) (throw 'exit nil))
11708 ;; count $$
11709 (while (re-search-backward "\\$\\$" lim t)
11710 (setq dd-on (not dd-on)))
11711 (goto-char pos)
11712 (if dd-on (cons "$$" m))))))
11715 (defun org-try-cdlatex-tab ()
11716 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11717 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11718 - inside a LaTeX fragment, or
11719 - after the first word in a line, where an abbreviation expansion could
11720 insert a LaTeX environment."
11721 (when org-cdlatex-mode
11722 (cond
11723 ((save-excursion
11724 (skip-chars-backward "a-zA-Z0-9*")
11725 (skip-chars-backward " \t")
11726 (bolp))
11727 (cdlatex-tab) t)
11728 ((org-inside-LaTeX-fragment-p)
11729 (cdlatex-tab) t)
11730 (t nil))))
11732 (defun org-cdlatex-underscore-caret (&optional arg)
11733 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11734 Revert to the normal definition outside of these fragments."
11735 (interactive "P")
11736 (if (org-inside-LaTeX-fragment-p)
11737 (call-interactively 'cdlatex-sub-superscript)
11738 (let (org-cdlatex-mode)
11739 (call-interactively (key-binding (vector last-input-event))))))
11741 (defun org-cdlatex-math-modify (&optional arg)
11742 "Execute `cdlatex-math-modify' in LaTeX fragments.
11743 Revert to the normal definition outside of these fragments."
11744 (interactive "P")
11745 (if (org-inside-LaTeX-fragment-p)
11746 (call-interactively 'cdlatex-math-modify)
11747 (let (org-cdlatex-mode)
11748 (call-interactively (key-binding (vector last-input-event))))))
11750 (defvar org-latex-fragment-image-overlays nil
11751 "List of overlays carrying the images of latex fragments.")
11752 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11754 (defun org-remove-latex-fragment-image-overlays ()
11755 "Remove all overlays with LaTeX fragment images in current buffer."
11756 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11757 (setq org-latex-fragment-image-overlays nil))
11759 (defun org-preview-latex-fragment (&optional subtree)
11760 "Preview the LaTeX fragment at point, or all locally or globally.
11761 If the cursor is in a LaTeX fragment, create the image and overlay
11762 it over the source code. If there is no fragment at point, display
11763 all fragments in the current text, from one headline to the next. With
11764 prefix SUBTREE, display all fragments in the current subtree. With a
11765 double prefix `C-u C-u', or when the cursor is before the first headline,
11766 display all fragments in the buffer.
11767 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11768 (interactive "P")
11769 (org-remove-latex-fragment-image-overlays)
11770 (save-excursion
11771 (save-restriction
11772 (let (beg end at msg)
11773 (cond
11774 ((or (equal subtree '(16))
11775 (not (save-excursion
11776 (re-search-backward (concat "^" outline-regexp) nil t))))
11777 (setq beg (point-min) end (point-max)
11778 msg "Creating images for buffer...%s"))
11779 ((equal subtree '(4))
11780 (org-back-to-heading)
11781 (setq beg (point) end (org-end-of-subtree t)
11782 msg "Creating images for subtree...%s"))
11784 (if (setq at (org-inside-LaTeX-fragment-p))
11785 (goto-char (max (point-min) (- (cdr at) 2)))
11786 (org-back-to-heading))
11787 (setq beg (point) end (progn (outline-next-heading) (point))
11788 msg (if at "Creating image...%s"
11789 "Creating images for entry...%s"))))
11790 (message msg "")
11791 (narrow-to-region beg end)
11792 (goto-char beg)
11793 (org-format-latex
11794 (concat "ltxpng/" (file-name-sans-extension
11795 (file-name-nondirectory
11796 buffer-file-name)))
11797 default-directory 'overlays msg at 'forbuffer)
11798 (message msg "done. Use `C-c C-c' to remove images.")))))
11800 (defvar org-latex-regexps
11801 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11802 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11803 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11804 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11805 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11806 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11807 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11808 "Regular expressions for matching embedded LaTeX.")
11810 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11811 "Replace LaTeX fragments with links to an image, and produce images."
11812 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11813 (let* ((prefixnodir (file-name-nondirectory prefix))
11814 (absprefix (expand-file-name prefix dir))
11815 (todir (file-name-directory absprefix))
11816 (opt org-format-latex-options)
11817 (matchers (plist-get opt :matchers))
11818 (re-list org-latex-regexps)
11819 (cnt 0) txt link beg end re e checkdir
11820 m n block linkfile movefile ov)
11821 ;; Check if there are old images files with this prefix, and remove them
11822 (when (file-directory-p todir)
11823 (mapc 'delete-file
11824 (directory-files
11825 todir 'full
11826 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11827 ;; Check the different regular expressions
11828 (while (setq e (pop re-list))
11829 (setq m (car e) re (nth 1 e) n (nth 2 e)
11830 block (if (nth 3 e) "\n\n" ""))
11831 (when (member m matchers)
11832 (goto-char (point-min))
11833 (while (re-search-forward re nil t)
11834 (when (or (not at) (equal (cdr at) (match-beginning n)))
11835 (setq txt (match-string n)
11836 beg (match-beginning n) end (match-end n)
11837 cnt (1+ cnt)
11838 linkfile (format "%s_%04d.png" prefix cnt)
11839 movefile (format "%s_%04d.png" absprefix cnt)
11840 link (concat block "[[file:" linkfile "]]" block))
11841 (if msg (message msg cnt))
11842 (goto-char beg)
11843 (unless checkdir ; make sure the directory exists
11844 (setq checkdir t)
11845 (or (file-directory-p todir) (make-directory todir)))
11846 (org-create-formula-image
11847 txt movefile opt forbuffer)
11848 (if overlays
11849 (progn
11850 (setq ov (org-make-overlay beg end))
11851 (if (featurep 'xemacs)
11852 (progn
11853 (org-overlay-put ov 'invisible t)
11854 (org-overlay-put
11855 ov 'end-glyph
11856 (make-glyph (vector 'png :file movefile))))
11857 (org-overlay-put
11858 ov 'display
11859 (list 'image :type 'png :file movefile :ascent 'center)))
11860 (push ov org-latex-fragment-image-overlays)
11861 (goto-char end))
11862 (delete-region beg end)
11863 (insert link))))))))
11865 ;; This function borrows from Ganesh Swami's latex2png.el
11866 (defun org-create-formula-image (string tofile options buffer)
11867 (let* ((tmpdir (if (featurep 'xemacs)
11868 (temp-directory)
11869 temporary-file-directory))
11870 (texfilebase (make-temp-name
11871 (expand-file-name "orgtex" tmpdir)))
11872 (texfile (concat texfilebase ".tex"))
11873 (dvifile (concat texfilebase ".dvi"))
11874 (pngfile (concat texfilebase ".png"))
11875 (fnh (if (featurep 'xemacs)
11876 (font-height (get-face-font 'default))
11877 (face-attribute 'default :height nil)))
11878 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11879 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11880 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11881 "Black"))
11882 (bg (or (plist-get options (if buffer :background :html-background))
11883 "Transparent")))
11884 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11885 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11886 (with-temp-file texfile
11887 (insert org-format-latex-header
11888 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11889 (let ((dir default-directory))
11890 (condition-case nil
11891 (progn
11892 (cd tmpdir)
11893 (call-process "latex" nil nil nil texfile))
11894 (error nil))
11895 (cd dir))
11896 (if (not (file-exists-p dvifile))
11897 (progn (message "Failed to create dvi file from %s" texfile) nil)
11898 (condition-case nil
11899 (call-process "dvipng" nil nil nil
11900 "-E" "-fg" fg "-bg" bg
11901 "-D" dpi
11902 ;;"-x" scale "-y" scale
11903 "-T" "tight"
11904 "-o" pngfile
11905 dvifile)
11906 (error nil))
11907 (if (not (file-exists-p pngfile))
11908 (progn (message "Failed to create png file from %s" texfile) nil)
11909 ;; Use the requested file name and clean up
11910 (copy-file pngfile tofile 'replace)
11911 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11912 (delete-file (concat texfilebase e)))
11913 pngfile))))
11915 (defun org-dvipng-color (attr)
11916 "Return an rgb color specification for dvipng."
11917 (apply 'format "rgb %s %s %s"
11918 (mapcar 'org-normalize-color
11919 (color-values (face-attribute 'default attr nil)))))
11921 (defun org-normalize-color (value)
11922 "Return string to be used as color value for an RGB component."
11923 (format "%g" (/ value 65535.0)))
11926 ;;;; Key bindings
11928 ;; Make `C-c C-x' a prefix key
11929 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11931 ;; TAB key with modifiers
11932 (org-defkey org-mode-map "\C-i" 'org-cycle)
11933 (org-defkey org-mode-map [(tab)] 'org-cycle)
11934 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11935 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11936 (org-defkey org-mode-map "\M-\t" 'org-complete)
11937 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11938 ;; The following line is necessary under Suse GNU/Linux
11939 (unless (featurep 'xemacs)
11940 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11941 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11942 (define-key org-mode-map [backtab] 'org-shifttab)
11944 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11945 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11946 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11948 ;; Cursor keys with modifiers
11949 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11950 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11951 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11952 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11954 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11955 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11956 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11957 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11959 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11960 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11961 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11962 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11964 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11965 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11967 ;;; Extra keys for tty access.
11968 ;; We only set them when really needed because otherwise the
11969 ;; menus don't show the simple keys
11971 (when (or org-use-extra-keys
11972 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11973 (not window-system))
11974 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11975 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11976 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11977 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11978 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11979 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11980 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11981 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11982 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11983 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11984 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11985 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11986 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11987 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11988 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11989 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11990 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11991 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11992 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11993 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11994 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11995 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11997 ;; All the other keys
11999 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12000 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12001 (if (boundp 'narrow-map)
12002 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12003 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12004 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12005 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12006 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12007 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12008 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12009 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12010 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12011 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12012 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12013 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12014 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12015 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12016 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12017 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12018 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12019 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12020 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12021 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12022 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12023 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12024 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12025 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12026 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12027 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12028 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12029 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12030 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12031 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12032 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12033 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12034 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12035 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12036 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12037 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12038 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12039 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12040 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12041 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12042 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12043 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12044 (org-defkey org-mode-map "\C-c^" 'org-sort)
12045 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12046 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12047 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12048 (org-defkey org-mode-map "\C-m" 'org-return)
12049 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12050 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12051 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12052 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12053 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12054 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12055 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12056 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12057 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12058 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12059 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12060 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12061 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12062 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12063 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12064 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12066 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12067 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12068 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12069 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12071 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12072 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12073 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12074 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12075 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12076 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12077 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12078 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12079 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12080 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12081 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12082 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12084 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12086 (when (featurep 'xemacs)
12087 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12089 (defvar org-table-auto-blank-field) ; defined in org-table.el
12090 (defun org-self-insert-command (N)
12091 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12092 If the cursor is in a table looking at whitespace, the whitespace is
12093 overwritten, and the table is not marked as requiring realignment."
12094 (interactive "p")
12095 (if (and (org-table-p)
12096 (progn
12097 ;; check if we blank the field, and if that triggers align
12098 (and (featurep 'org-table) org-table-auto-blank-field
12099 (member last-command
12100 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12101 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12102 ;; got extra space, this field does not determine column width
12103 (let (org-table-may-need-update) (org-table-blank-field))
12104 ;; no extra space, this field may determine column width
12105 (org-table-blank-field)))
12107 (eq N 1)
12108 (looking-at "[^|\n]* |"))
12109 (let (org-table-may-need-update)
12110 (goto-char (1- (match-end 0)))
12111 (delete-backward-char 1)
12112 (goto-char (match-beginning 0))
12113 (self-insert-command N))
12114 (setq org-table-may-need-update t)
12115 (self-insert-command N)
12116 (org-fix-tags-on-the-fly)))
12118 (defun org-fix-tags-on-the-fly ()
12119 (when (and (equal (char-after (point-at-bol)) ?*)
12120 (org-on-heading-p))
12121 (org-align-tags-here org-tags-column)))
12123 (defun org-delete-backward-char (N)
12124 "Like `delete-backward-char', insert whitespace at field end in tables.
12125 When deleting backwards, in tables this function will insert whitespace in
12126 front of the next \"|\" separator, to keep the table aligned. The table will
12127 still be marked for re-alignment if the field did fill the entire column,
12128 because, in this case the deletion might narrow the column."
12129 (interactive "p")
12130 (if (and (org-table-p)
12131 (eq N 1)
12132 (string-match "|" (buffer-substring (point-at-bol) (point)))
12133 (looking-at ".*?|"))
12134 (let ((pos (point))
12135 (noalign (looking-at "[^|\n\r]* |"))
12136 (c org-table-may-need-update))
12137 (backward-delete-char N)
12138 (skip-chars-forward "^|")
12139 (insert " ")
12140 (goto-char (1- pos))
12141 ;; noalign: if there were two spaces at the end, this field
12142 ;; does not determine the width of the column.
12143 (if noalign (setq org-table-may-need-update c)))
12144 (backward-delete-char N)
12145 (org-fix-tags-on-the-fly)))
12147 (defun org-delete-char (N)
12148 "Like `delete-char', but insert whitespace at field end in tables.
12149 When deleting characters, in tables this function will insert whitespace in
12150 front of the next \"|\" separator, to keep the table aligned. The table will
12151 still be marked for re-alignment if the field did fill the entire column,
12152 because, in this case the deletion might narrow the column."
12153 (interactive "p")
12154 (if (and (org-table-p)
12155 (not (bolp))
12156 (not (= (char-after) ?|))
12157 (eq N 1))
12158 (if (looking-at ".*?|")
12159 (let ((pos (point))
12160 (noalign (looking-at "[^|\n\r]* |"))
12161 (c org-table-may-need-update))
12162 (replace-match (concat
12163 (substring (match-string 0) 1 -1)
12164 " |"))
12165 (goto-char pos)
12166 ;; noalign: if there were two spaces at the end, this field
12167 ;; does not determine the width of the column.
12168 (if noalign (setq org-table-may-need-update c)))
12169 (delete-char N))
12170 (delete-char N)
12171 (org-fix-tags-on-the-fly)))
12173 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12174 (put 'org-self-insert-command 'delete-selection t)
12175 (put 'orgtbl-self-insert-command 'delete-selection t)
12176 (put 'org-delete-char 'delete-selection 'supersede)
12177 (put 'org-delete-backward-char 'delete-selection 'supersede)
12179 ;; Make `flyspell-mode' delay after some commands
12180 (put 'org-self-insert-command 'flyspell-delayed t)
12181 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12182 (put 'org-delete-char 'flyspell-delayed t)
12183 (put 'org-delete-backward-char 'flyspell-delayed t)
12185 ;; Make pabbrev-mode expand after org-mode commands
12186 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12187 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12189 ;; How to do this: Measure non-white length of current string
12190 ;; If equal to column width, we should realign.
12192 (defun org-remap (map &rest commands)
12193 "In MAP, remap the functions given in COMMANDS.
12194 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12195 (let (new old)
12196 (while commands
12197 (setq old (pop commands) new (pop commands))
12198 (if (fboundp 'command-remapping)
12199 (org-defkey map (vector 'remap old) new)
12200 (substitute-key-definition old new map global-map)))))
12202 (when (eq org-enable-table-editor 'optimized)
12203 ;; If the user wants maximum table support, we need to hijack
12204 ;; some standard editing functions
12205 (org-remap org-mode-map
12206 'self-insert-command 'org-self-insert-command
12207 'delete-char 'org-delete-char
12208 'delete-backward-char 'org-delete-backward-char)
12209 (org-defkey org-mode-map "|" 'org-force-self-insert))
12211 (defun org-shiftcursor-error ()
12212 "Throw an error because Shift-Cursor command was applied in wrong context."
12213 (error "This command is active in special context like tables, headlines or timestamps"))
12215 (defun org-shifttab (&optional arg)
12216 "Global visibility cycling or move to previous table field.
12217 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12218 on context.
12219 See the individual commands for more information."
12220 (interactive "P")
12221 (cond
12222 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12223 ((integerp arg)
12224 (message "Content view to level: %d" arg)
12225 (org-content (prefix-numeric-value arg))
12226 (setq org-cycle-global-status 'overview))
12227 (t (call-interactively 'org-global-cycle))))
12229 (defun org-shiftmetaleft ()
12230 "Promote subtree or delete table column.
12231 Calls `org-promote-subtree', `org-outdent-item',
12232 or `org-table-delete-column', depending on context.
12233 See the individual commands for more information."
12234 (interactive)
12235 (cond
12236 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12237 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12238 ((org-at-item-p) (call-interactively 'org-outdent-item))
12239 (t (org-shiftcursor-error))))
12241 (defun org-shiftmetaright ()
12242 "Demote subtree or insert table column.
12243 Calls `org-demote-subtree', `org-indent-item',
12244 or `org-table-insert-column', depending on context.
12245 See the individual commands for more information."
12246 (interactive)
12247 (cond
12248 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12249 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12250 ((org-at-item-p) (call-interactively 'org-indent-item))
12251 (t (org-shiftcursor-error))))
12253 (defun org-shiftmetaup (&optional arg)
12254 "Move subtree up or kill table row.
12255 Calls `org-move-subtree-up' or `org-table-kill-row' or
12256 `org-move-item-up' depending on context. See the individual commands
12257 for more information."
12258 (interactive "P")
12259 (cond
12260 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12261 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12262 ((org-at-item-p) (call-interactively 'org-move-item-up))
12263 (t (org-shiftcursor-error))))
12264 (defun org-shiftmetadown (&optional arg)
12265 "Move subtree down or insert table row.
12266 Calls `org-move-subtree-down' or `org-table-insert-row' or
12267 `org-move-item-down', depending on context. See the individual
12268 commands for more information."
12269 (interactive "P")
12270 (cond
12271 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12272 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12273 ((org-at-item-p) (call-interactively 'org-move-item-down))
12274 (t (org-shiftcursor-error))))
12276 (defun org-metaleft (&optional arg)
12277 "Promote heading or move table column to left.
12278 Calls `org-do-promote' or `org-table-move-column', depending on context.
12279 With no specific context, calls the Emacs default `backward-word'.
12280 See the individual commands for more information."
12281 (interactive "P")
12282 (cond
12283 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12284 ((or (org-on-heading-p) (org-region-active-p))
12285 (call-interactively 'org-do-promote))
12286 ((org-at-item-p) (call-interactively 'org-outdent-item))
12287 (t (call-interactively 'backward-word))))
12289 (defun org-metaright (&optional arg)
12290 "Demote subtree or move table column to right.
12291 Calls `org-do-demote' or `org-table-move-column', depending on context.
12292 With no specific context, calls the Emacs default `forward-word'.
12293 See the individual commands for more information."
12294 (interactive "P")
12295 (cond
12296 ((org-at-table-p) (call-interactively 'org-table-move-column))
12297 ((or (org-on-heading-p) (org-region-active-p))
12298 (call-interactively 'org-do-demote))
12299 ((org-at-item-p) (call-interactively 'org-indent-item))
12300 (t (call-interactively 'forward-word))))
12302 (defun org-metaup (&optional arg)
12303 "Move subtree up or move table row up.
12304 Calls `org-move-subtree-up' or `org-table-move-row' or
12305 `org-move-item-up', depending on context. See the individual commands
12306 for more information."
12307 (interactive "P")
12308 (cond
12309 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12310 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12311 ((org-at-item-p) (call-interactively 'org-move-item-up))
12312 (t (transpose-lines 1) (beginning-of-line -1))))
12314 (defun org-metadown (&optional arg)
12315 "Move subtree down or move table row down.
12316 Calls `org-move-subtree-down' or `org-table-move-row' or
12317 `org-move-item-down', depending on context. See the individual
12318 commands for more information."
12319 (interactive "P")
12320 (cond
12321 ((org-at-table-p) (call-interactively 'org-table-move-row))
12322 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12323 ((org-at-item-p) (call-interactively 'org-move-item-down))
12324 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12326 (defun org-shiftup (&optional arg)
12327 "Increase item in timestamp or increase priority of current headline.
12328 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12329 depending on context. See the individual commands for more information."
12330 (interactive "P")
12331 (cond
12332 ((org-at-timestamp-p t)
12333 (call-interactively (if org-edit-timestamp-down-means-later
12334 'org-timestamp-down 'org-timestamp-up)))
12335 ((org-on-heading-p) (call-interactively 'org-priority-up))
12336 ((org-at-item-p) (call-interactively 'org-previous-item))
12337 ((org-clocktable-try-shift 'up arg))
12338 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12340 (defun org-shiftdown (&optional arg)
12341 "Decrease item in timestamp or decrease priority of current headline.
12342 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12343 depending on context. See the individual commands for more information."
12344 (interactive "P")
12345 (cond
12346 ((org-at-timestamp-p t)
12347 (call-interactively (if org-edit-timestamp-down-means-later
12348 'org-timestamp-up 'org-timestamp-down)))
12349 ((org-on-heading-p) (call-interactively 'org-priority-down))
12350 ((org-clocktable-try-shift 'down arg))
12351 (t (call-interactively 'org-next-item))))
12353 (defun org-shiftright (&optional arg)
12354 "Next TODO keyword or timestamp one day later, depending on context."
12355 (interactive "P")
12356 (cond
12357 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12358 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12359 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12360 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12361 ((org-clocktable-try-shift 'right arg))
12362 (t (org-shiftcursor-error))))
12364 (defun org-shiftleft (&optional arg)
12365 "Previous TODO keyword or timestamp one day earlier, depending on context."
12366 (interactive "P")
12367 (cond
12368 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12369 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12370 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12371 ((org-at-property-p)
12372 (call-interactively 'org-property-previous-allowed-value))
12373 ((org-clocktable-try-shift 'left arg))
12374 (t (org-shiftcursor-error))))
12376 (defun org-shiftcontrolright ()
12377 "Switch to next TODO set."
12378 (interactive)
12379 (cond
12380 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12381 (t (org-shiftcursor-error))))
12383 (defun org-shiftcontrolleft ()
12384 "Switch to previous TODO set."
12385 (interactive)
12386 (cond
12387 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12388 (t (org-shiftcursor-error))))
12390 (defun org-ctrl-c-ret ()
12391 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12392 (interactive)
12393 (cond
12394 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12395 (t (call-interactively 'org-insert-heading))))
12397 (defun org-copy-special ()
12398 "Copy region in table or copy current subtree.
12399 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12400 See the individual commands for more information."
12401 (interactive)
12402 (call-interactively
12403 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12405 (defun org-cut-special ()
12406 "Cut region in table or cut current subtree.
12407 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12408 See the individual commands for more information."
12409 (interactive)
12410 (call-interactively
12411 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12413 (defun org-paste-special (arg)
12414 "Paste rectangular region into table, or past subtree relative to level.
12415 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12416 See the individual commands for more information."
12417 (interactive "P")
12418 (if (org-at-table-p)
12419 (org-table-paste-rectangle)
12420 (org-paste-subtree arg)))
12422 (defun org-edit-special ()
12423 "Call a special editor for the stuff at point.
12424 When at a table, call the formula editor with `org-table-edit-formulas'.
12425 When at the first line of an src example, call `org-edit-src-code'.
12426 When in an #+include line, visit the include file. Otherwise call
12427 `ffap' to visit the file at point."
12428 (interactive)
12429 (cond
12430 ((org-at-table-p)
12431 (call-interactively 'org-table-edit-formulas))
12432 ((save-excursion
12433 (beginning-of-line 1)
12434 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12435 (find-file (org-trim (match-string 1))))
12436 ((org-edit-src-code))
12437 ((org-edit-fixed-width-region))
12438 (t (call-interactively 'ffap))))
12440 (defun org-ctrl-c-ctrl-c (&optional arg)
12441 "Set tags in headline, or update according to changed information at point.
12443 This command does many different things, depending on context:
12445 - If the cursor is in a headline, prompt for tags and insert them
12446 into the current line, aligned to `org-tags-column'. When called
12447 with prefix arg, realign all tags in the current buffer.
12449 - If the cursor is in one of the special #+KEYWORD lines, this
12450 triggers scanning the buffer for these lines and updating the
12451 information.
12453 - If the cursor is inside a table, realign the table. This command
12454 works even if the automatic table editor has been turned off.
12456 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12457 the entire table.
12459 - If the cursor is a the beginning of a dynamic block, update it.
12461 - If the cursor is inside a table created by the table.el package,
12462 activate that table.
12464 - If the current buffer is a remember buffer, close note and file it.
12465 with a prefix argument, file it without further interaction to the default
12466 location.
12468 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12469 links in this buffer.
12471 - If the cursor is on a numbered item in a plain list, renumber the
12472 ordered list.
12474 - If the cursor is on a checkbox, toggle it."
12475 (interactive "P")
12476 (let ((org-enable-table-editor t))
12477 (cond
12478 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12479 org-occur-highlights
12480 org-latex-fragment-image-overlays)
12481 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12482 (org-remove-occur-highlights)
12483 (org-remove-latex-fragment-image-overlays)
12484 (message "Temporary highlights/overlays removed from current buffer"))
12485 ((and (local-variable-p 'org-finish-function (current-buffer))
12486 (fboundp org-finish-function))
12487 (funcall org-finish-function))
12488 ((org-at-property-p)
12489 (call-interactively 'org-property-action))
12490 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12491 ((org-on-heading-p) (call-interactively 'org-set-tags))
12492 ((org-at-table.el-p)
12493 (require 'table)
12494 (beginning-of-line 1)
12495 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12496 (call-interactively 'table-recognize-table))
12497 ((org-at-table-p)
12498 (org-table-maybe-eval-formula)
12499 (if arg
12500 (call-interactively 'org-table-recalculate)
12501 (org-table-maybe-recalculate-line))
12502 (call-interactively 'org-table-align))
12503 ((org-at-item-checkbox-p)
12504 (call-interactively 'org-toggle-checkbox))
12505 ((org-at-item-p)
12506 (call-interactively 'org-maybe-renumber-ordered-list))
12507 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12508 ;; Dynamic block
12509 (beginning-of-line 1)
12510 (save-excursion (org-update-dblock)))
12511 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12512 (cond
12513 ((equal (match-string 1) "TBLFM")
12514 ;; Recalculate the table before this line
12515 (save-excursion
12516 (beginning-of-line 1)
12517 (skip-chars-backward " \r\n\t")
12518 (if (org-at-table-p)
12519 (org-call-with-arg 'org-table-recalculate t))))
12521 ; (org-set-regexps-and-options)
12522 ; (org-restart-font-lock)
12523 (let ((org-inhibit-startup t)) (org-mode-restart))
12524 (message "Local setup has been refreshed"))))
12525 (t (error "C-c C-c can do nothing useful at this location.")))))
12527 (defun org-mode-restart ()
12528 "Restart Org-mode, to scan again for special lines.
12529 Also updates the keyword regular expressions."
12530 (interactive)
12531 (org-mode)
12532 (message "Org-mode restarted"))
12534 (defun org-kill-note-or-show-branches ()
12535 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12536 (interactive)
12537 (if (not org-finish-function)
12538 (call-interactively 'show-branches)
12539 (let ((org-note-abort t))
12540 (funcall org-finish-function))))
12542 (defun org-return (&optional indent)
12543 "Goto next table row or insert a newline.
12544 Calls `org-table-next-row' or `newline', depending on context.
12545 See the individual commands for more information."
12546 (interactive)
12547 (cond
12548 ((bobp) (if indent (newline-and-indent) (newline)))
12549 ((and (org-at-heading-p)
12550 (looking-at
12551 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12552 (org-show-entry)
12553 (end-of-line 1)
12554 (newline))
12555 ((org-at-table-p)
12556 (org-table-justify-field-maybe)
12557 (call-interactively 'org-table-next-row))
12558 (t (if indent (newline-and-indent) (newline)))))
12560 (defun org-return-indent ()
12561 "Goto next table row or insert a newline and indent.
12562 Calls `org-table-next-row' or `newline-and-indent', depending on
12563 context. See the individual commands for more information."
12564 (interactive)
12565 (org-return t))
12567 (defun org-ctrl-c-star ()
12568 "Compute table, or change heading status of lines.
12569 Calls `org-table-recalculate' or `org-toggle-region-headings',
12570 depending on context. This will also turn a plain list item or a normal
12571 line into a subheading."
12572 (interactive)
12573 (cond
12574 ((org-at-table-p)
12575 (call-interactively 'org-table-recalculate))
12576 ((org-region-active-p)
12577 ;; Convert all lines in region to list items
12578 (call-interactively 'org-toggle-region-headings))
12579 ((org-on-heading-p)
12580 (org-toggle-region-headings (point-at-bol)
12581 (min (1+ (point-at-eol)) (point-max))))
12582 ((org-at-item-p)
12583 ;; Convert to heading
12584 (let ((level (save-match-data
12585 (save-excursion
12586 (condition-case nil
12587 (progn
12588 (org-back-to-heading t)
12589 (funcall outline-level))
12590 (error 0))))))
12591 (replace-match
12592 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12593 (t (org-toggle-region-headings (point-at-bol)
12594 (min (1+ (point-at-eol)) (point-max))))))
12596 (defun org-ctrl-c-minus ()
12597 "Insert separator line in table or modify bullet status of line.
12598 Also turns a plain line or a region of lines into list items.
12599 Calls `org-table-insert-hline', `org-toggle-region-items', or
12600 `org-cycle-list-bullet', depending on context."
12601 (interactive)
12602 (cond
12603 ((org-at-table-p)
12604 (call-interactively 'org-table-insert-hline))
12605 ((org-on-heading-p)
12606 ;; Convert to item
12607 (save-excursion
12608 (beginning-of-line 1)
12609 (if (looking-at "\\*+ ")
12610 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12611 ((org-region-active-p)
12612 ;; Convert all lines in region to list items
12613 (call-interactively 'org-toggle-region-items))
12614 ((org-in-item-p)
12615 (call-interactively 'org-cycle-list-bullet))
12616 (t (org-toggle-region-items (point-at-bol)
12617 (min (1+ (point-at-eol)) (point-max))))))
12619 (defun org-toggle-region-items (beg end)
12620 "Convert all lines in region to list items.
12621 If the first line is already an item, convert all list items in the region
12622 to normal lines."
12623 (interactive "r")
12624 (let (l2 l)
12625 (save-excursion
12626 (goto-char end)
12627 (setq l2 (org-current-line))
12628 (goto-char beg)
12629 (beginning-of-line 1)
12630 (setq l (1- (org-current-line)))
12631 (if (org-at-item-p)
12632 ;; We already have items, de-itemize
12633 (while (< (setq l (1+ l)) l2)
12634 (when (org-at-item-p)
12635 (goto-char (match-beginning 2))
12636 (delete-region (match-beginning 2) (match-end 2))
12637 (and (looking-at "[ \t]+") (replace-match "")))
12638 (beginning-of-line 2))
12639 (while (< (setq l (1+ l)) l2)
12640 (unless (org-at-item-p)
12641 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12642 (replace-match "\\1- \\2")))
12643 (beginning-of-line 2))))))
12645 (defun org-toggle-region-headings (beg end)
12646 "Convert all lines in region to list items.
12647 If the first line is already an item, convert all list items in the region
12648 to normal lines."
12649 (interactive "r")
12650 (let (l2 l)
12651 (save-excursion
12652 (goto-char end)
12653 (setq l2 (org-current-line))
12654 (goto-char beg)
12655 (beginning-of-line 1)
12656 (setq l (1- (org-current-line)))
12657 (if (org-on-heading-p)
12658 ;; We already have headlines, de-star them
12659 (while (< (setq l (1+ l)) l2)
12660 (when (org-on-heading-p t)
12661 (and (looking-at outline-regexp) (replace-match "")))
12662 (beginning-of-line 2))
12663 (let* ((stars (save-excursion
12664 (re-search-backward org-complex-heading-regexp nil t)
12665 (or (match-string 1) "*")))
12666 (add-stars (if org-odd-levels-only "**" "*"))
12667 (rpl (concat stars add-stars " \\2")))
12668 (while (< (setq l (1+ l)) l2)
12669 (unless (org-on-heading-p)
12670 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12671 (replace-match rpl)))
12672 (beginning-of-line 2)))))))
12674 (defun org-meta-return (&optional arg)
12675 "Insert a new heading or wrap a region in a table.
12676 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12677 See the individual commands for more information."
12678 (interactive "P")
12679 (cond
12680 ((org-at-table-p)
12681 (call-interactively 'org-table-wrap-region))
12682 (t (call-interactively 'org-insert-heading))))
12684 ;;; Menu entries
12686 ;; Define the Org-mode menus
12687 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12688 '("Tbl"
12689 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12690 ["Next Field" org-cycle (org-at-table-p)]
12691 ["Previous Field" org-shifttab (org-at-table-p)]
12692 ["Next Row" org-return (org-at-table-p)]
12693 "--"
12694 ["Blank Field" org-table-blank-field (org-at-table-p)]
12695 ["Edit Field" org-table-edit-field (org-at-table-p)]
12696 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12697 "--"
12698 ("Column"
12699 ["Move Column Left" org-metaleft (org-at-table-p)]
12700 ["Move Column Right" org-metaright (org-at-table-p)]
12701 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12702 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12703 ("Row"
12704 ["Move Row Up" org-metaup (org-at-table-p)]
12705 ["Move Row Down" org-metadown (org-at-table-p)]
12706 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12707 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12708 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12709 "--"
12710 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12711 ("Rectangle"
12712 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12713 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12714 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12715 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12716 "--"
12717 ("Calculate"
12718 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12719 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12720 ["Edit Formulas" org-edit-special (org-at-table-p)]
12721 "--"
12722 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12723 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12724 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12725 "--"
12726 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12727 "--"
12728 ["Sum Column/Rectangle" org-table-sum
12729 (or (org-at-table-p) (org-region-active-p))]
12730 ["Which Column?" org-table-current-column (org-at-table-p)])
12731 ["Debug Formulas"
12732 org-table-toggle-formula-debugger
12733 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12734 ["Show Col/Row Numbers"
12735 org-table-toggle-coordinate-overlays
12736 :style toggle
12737 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12738 "--"
12739 ["Create" org-table-create (and (not (org-at-table-p))
12740 org-enable-table-editor)]
12741 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12742 ["Import from File" org-table-import (not (org-at-table-p))]
12743 ["Export to File" org-table-export (org-at-table-p)]
12744 "--"
12745 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12747 (easy-menu-define org-org-menu org-mode-map "Org menu"
12748 '("Org"
12749 ("Show/Hide"
12750 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12751 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12752 ["Sparse Tree..." org-sparse-tree t]
12753 ["Reveal Context" org-reveal t]
12754 ["Show All" show-all t]
12755 "--"
12756 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12757 "--"
12758 ["New Heading" org-insert-heading t]
12759 ("Navigate Headings"
12760 ["Up" outline-up-heading t]
12761 ["Next" outline-next-visible-heading t]
12762 ["Previous" outline-previous-visible-heading t]
12763 ["Next Same Level" outline-forward-same-level t]
12764 ["Previous Same Level" outline-backward-same-level t]
12765 "--"
12766 ["Jump" org-goto t])
12767 ("Edit Structure"
12768 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12769 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12770 "--"
12771 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12772 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12773 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12774 "--"
12775 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12776 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12777 ["Demote Heading" org-metaright (not (org-at-table-p))]
12778 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12779 "--"
12780 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12781 "--"
12782 ["Convert to odd levels" org-convert-to-odd-levels t]
12783 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12784 ("Editing"
12785 ["Emphasis..." org-emphasize t]
12786 ["Edit Source Example" org-edit-special t])
12787 ("Archive"
12788 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12789 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12790 ; :active t :keys "C-u C-c C-x C-a"]
12791 ["Sparse trees open ARCHIVE trees"
12792 (setq org-sparse-tree-open-archived-trees
12793 (not org-sparse-tree-open-archived-trees))
12794 :style toggle :selected org-sparse-tree-open-archived-trees]
12795 ["Cycling opens ARCHIVE trees"
12796 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12797 :style toggle :selected org-cycle-open-archived-trees]
12798 "--"
12799 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
12800 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12801 ; ["Check and Move Children" (org-archive-subtree '(4))
12802 ; :active t :keys "C-u C-c C-x C-s"]
12804 "--"
12805 ("TODO Lists"
12806 ["TODO/DONE/-" org-todo t]
12807 ("Select keyword"
12808 ["Next keyword" org-shiftright (org-on-heading-p)]
12809 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12810 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12811 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12812 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12813 ["Show TODO Tree" org-show-todo-tree t]
12814 ["Global TODO list" org-todo-list t]
12815 "--"
12816 ["Set Priority" org-priority t]
12817 ["Priority Up" org-shiftup t]
12818 ["Priority Down" org-shiftdown t])
12819 ("TAGS and Properties"
12820 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12821 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12822 "--"
12823 ["Set property" 'org-set-property t]
12824 ["Column view of properties" org-columns t]
12825 ["Insert Column View DBlock" org-insert-columns-dblock t])
12826 ("Dates and Scheduling"
12827 ["Timestamp" org-time-stamp t]
12828 ["Timestamp (inactive)" org-time-stamp-inactive t]
12829 ("Change Date"
12830 ["1 Day Later" org-shiftright t]
12831 ["1 Day Earlier" org-shiftleft t]
12832 ["1 ... Later" org-shiftup t]
12833 ["1 ... Earlier" org-shiftdown t])
12834 ["Compute Time Range" org-evaluate-time-range t]
12835 ["Schedule Item" org-schedule t]
12836 ["Deadline" org-deadline t]
12837 "--"
12838 ["Custom time format" org-toggle-time-stamp-overlays
12839 :style radio :selected org-display-custom-times]
12840 "--"
12841 ["Goto Calendar" org-goto-calendar t]
12842 ["Date from Calendar" org-date-from-calendar t])
12843 ("Logging work"
12844 ["Clock in" org-clock-in t]
12845 ["Clock out" org-clock-out t]
12846 ["Clock cancel" org-clock-cancel t]
12847 ["Goto running clock" org-clock-goto t]
12848 ["Display times" org-clock-display t]
12849 ["Create clock table" org-clock-report t]
12850 "--"
12851 ["Record DONE time"
12852 (progn (setq org-log-done (not org-log-done))
12853 (message "Switching to %s will %s record a timestamp"
12854 (car org-done-keywords)
12855 (if org-log-done "automatically" "not")))
12856 :style toggle :selected org-log-done])
12857 "--"
12858 ["Agenda Command..." org-agenda t]
12859 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12860 ("File List for Agenda")
12861 ("Special views current file"
12862 ["TODO Tree" org-show-todo-tree t]
12863 ["Check Deadlines" org-check-deadlines t]
12864 ["Timeline" org-timeline t]
12865 ["Tags Tree" org-tags-sparse-tree t])
12866 "--"
12867 ("Hyperlinks"
12868 ["Store Link (Global)" org-store-link t]
12869 ["Insert Link" org-insert-link t]
12870 ["Follow Link" org-open-at-point t]
12871 "--"
12872 ["Next link" org-next-link t]
12873 ["Previous link" org-previous-link t]
12874 "--"
12875 ["Descriptive Links"
12876 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12877 :style radio
12878 :selected (member '(org-link) buffer-invisibility-spec)]
12879 ["Literal Links"
12880 (progn
12881 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12882 :style radio
12883 :selected (not (member '(org-link) buffer-invisibility-spec))])
12884 "--"
12885 ["Export/Publish..." org-export t]
12886 ("LaTeX"
12887 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12888 :selected org-cdlatex-mode]
12889 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12890 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12891 ["Modify math symbol" org-cdlatex-math-modify
12892 (org-inside-LaTeX-fragment-p)]
12893 ["Export LaTeX fragments as images"
12894 (if (featurep 'org-exp)
12895 (setq org-export-with-LaTeX-fragments
12896 (not org-export-with-LaTeX-fragments))
12897 (require 'org-exp))
12898 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12899 org-export-with-LaTeX-fragments)])
12900 "--"
12901 ("Documentation"
12902 ["Show Version" org-version t]
12903 ["Info Documentation" org-info t])
12904 ("Customize"
12905 ["Browse Org Group" org-customize t]
12906 "--"
12907 ["Expand This Menu" org-create-customize-menu
12908 (fboundp 'customize-menu-create)])
12909 "--"
12910 ["Refresh setup" org-mode-restart t]
12913 (defun org-info (&optional node)
12914 "Read documentation for Org-mode in the info system.
12915 With optional NODE, go directly to that node."
12916 (interactive)
12917 (info (format "(org)%s" (or node ""))))
12919 (defun org-install-agenda-files-menu ()
12920 (let ((bl (buffer-list)))
12921 (save-excursion
12922 (while bl
12923 (set-buffer (pop bl))
12924 (if (org-mode-p) (setq bl nil)))
12925 (when (org-mode-p)
12926 (easy-menu-change
12927 '("Org") "File List for Agenda"
12928 (append
12929 (list
12930 ["Edit File List" (org-edit-agenda-file-list) t]
12931 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12932 ["Remove Current File from List" org-remove-file t]
12933 ["Cycle through agenda files" org-cycle-agenda-files t]
12934 ["Occur in all agenda files" org-occur-in-agenda-files t]
12935 "--")
12936 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12938 ;;;; Documentation
12940 ;;;###autoload
12941 (defun org-require-autoloaded-modules ()
12942 (interactive)
12943 (mapc 'require
12944 '(org-agenda org-archive org-clock org-colview
12945 org-exp org-id org-export-latex org-publish
12946 org-remember org-table)))
12948 ;;;###autoload
12949 (defun org-customize ()
12950 "Call the customize function with org as argument."
12951 (interactive)
12952 (org-load-modules-maybe)
12953 (org-require-autoloaded-modules)
12954 (customize-browse 'org))
12956 (defun org-create-customize-menu ()
12957 "Create a full customization menu for Org-mode, insert it into the menu."
12958 (interactive)
12959 (org-load-modules-maybe)
12960 (org-require-autoloaded-modules)
12961 (if (fboundp 'customize-menu-create)
12962 (progn
12963 (easy-menu-change
12964 '("Org") "Customize"
12965 `(["Browse Org group" org-customize t]
12966 "--"
12967 ,(customize-menu-create 'org)
12968 ["Set" Custom-set t]
12969 ["Save" Custom-save t]
12970 ["Reset to Current" Custom-reset-current t]
12971 ["Reset to Saved" Custom-reset-saved t]
12972 ["Reset to Standard Settings" Custom-reset-standard t]))
12973 (message "\"Org\"-menu now contains full customization menu"))
12974 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12976 ;;;; Miscellaneous stuff
12978 ;;; Generally useful functions
12980 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12981 "Display the given MESSAGE as a warning."
12982 (if (fboundp 'display-warning)
12983 (display-warning 'org message
12984 (if (featurep 'xemacs)
12985 'warning
12986 :warning))
12987 (let ((buf (get-buffer-create "*Org warnings*")))
12988 (with-current-buffer buf
12989 (goto-char (point-max))
12990 (insert "Warning (Org): " message)
12991 (unless (bolp)
12992 (newline)))
12993 (display-buffer buf)
12994 (sit-for 0))))
12996 (defun org-goto-marker-or-bmk (marker &optional bookmark)
12997 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
12998 (if (and marker (marker-buffer marker)
12999 (buffer-live-p (marker-buffer marker)))
13000 (progn
13001 (switch-to-buffer (marker-buffer marker))
13002 (if (or (> marker (point-max)) (< marker (point-min)))
13003 (widen))
13004 (goto-char marker))
13005 (if bookmark
13006 (bookmark-jump bookmark)
13007 (error "Cannot find location"))))
13009 (defun org-quote-csv-field (s)
13010 "Quote field for inclusion in CSV material."
13011 (if (string-match "[\",]" s)
13012 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13015 (defun org-plist-delete (plist property)
13016 "Delete PROPERTY from PLIST.
13017 This is in contrast to merely setting it to 0."
13018 (let (p)
13019 (while plist
13020 (if (not (eq property (car plist)))
13021 (setq p (plist-put p (car plist) (nth 1 plist))))
13022 (setq plist (cddr plist)))
13025 (defun org-force-self-insert (N)
13026 "Needed to enforce self-insert under remapping."
13027 (interactive "p")
13028 (self-insert-command N))
13030 (defun org-string-width (s)
13031 "Compute width of string, ignoring invisible characters.
13032 This ignores character with invisibility property `org-link', and also
13033 characters with property `org-cwidth', because these will become invisible
13034 upon the next fontification round."
13035 (let (b l)
13036 (when (or (eq t buffer-invisibility-spec)
13037 (assq 'org-link buffer-invisibility-spec))
13038 (while (setq b (text-property-any 0 (length s)
13039 'invisible 'org-link s))
13040 (setq s (concat (substring s 0 b)
13041 (substring s (or (next-single-property-change
13042 b 'invisible s) (length s)))))))
13043 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13044 (setq s (concat (substring s 0 b)
13045 (substring s (or (next-single-property-change
13046 b 'org-cwidth s) (length s))))))
13047 (setq l (string-width s) b -1)
13048 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13049 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13052 (defun org-get-indentation (&optional line)
13053 "Get the indentation of the current line, interpreting tabs.
13054 When LINE is given, assume it represents a line and compute its indentation."
13055 (if line
13056 (if (string-match "^ *" (org-remove-tabs line))
13057 (match-end 0))
13058 (save-excursion
13059 (beginning-of-line 1)
13060 (skip-chars-forward " \t")
13061 (current-column))))
13063 (defun org-remove-tabs (s &optional width)
13064 "Replace tabulators in S with spaces.
13065 Assumes that s is a single line, starting in column 0."
13066 (setq width (or width tab-width))
13067 (while (string-match "\t" s)
13068 (setq s (replace-match
13069 (make-string
13070 (- (* width (/ (+ (match-beginning 0) width) width))
13071 (match-beginning 0)) ?\ )
13072 t t s)))
13075 (defun org-fix-indentation (line ind)
13076 "Fix indentation in LINE.
13077 IND is a cons cell with target and minimum indentation.
13078 If the current indenation in LINE is smaller than the minimum,
13079 leave it alone. If it is larger than ind, set it to the target."
13080 (let* ((l (org-remove-tabs line))
13081 (i (org-get-indentation l))
13082 (i1 (car ind)) (i2 (cdr ind)))
13083 (if (>= i i2) (setq l (substring line i2)))
13084 (if (> i1 0)
13085 (concat (make-string i1 ?\ ) l)
13086 l)))
13088 (defun org-base-buffer (buffer)
13089 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13090 (if (not buffer)
13091 buffer
13092 (or (buffer-base-buffer buffer)
13093 buffer)))
13095 (defun org-trim (s)
13096 "Remove whitespace at beginning and end of string."
13097 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13098 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13101 (defun org-wrap (string &optional width lines)
13102 "Wrap string to either a number of lines, or a width in characters.
13103 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13104 that costs. If there is a word longer than WIDTH, the text is actually
13105 wrapped to the length of that word.
13106 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13107 many lines, whatever width that takes.
13108 The return value is a list of lines, without newlines at the end."
13109 (let* ((words (org-split-string string "[ \t\n]+"))
13110 (maxword (apply 'max (mapcar 'org-string-width words)))
13111 w ll)
13112 (cond (width
13113 (org-do-wrap words (max maxword width)))
13114 (lines
13115 (setq w maxword)
13116 (setq ll (org-do-wrap words maxword))
13117 (if (<= (length ll) lines)
13119 (setq ll words)
13120 (while (> (length ll) lines)
13121 (setq w (1+ w))
13122 (setq ll (org-do-wrap words w)))
13123 ll))
13124 (t (error "Cannot wrap this")))))
13126 (defun org-do-wrap (words width)
13127 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13128 (let (lines line)
13129 (while words
13130 (setq line (pop words))
13131 (while (and words (< (+ (length line) (length (car words))) width))
13132 (setq line (concat line " " (pop words))))
13133 (setq lines (push line lines)))
13134 (nreverse lines)))
13136 (defun org-split-string (string &optional separators)
13137 "Splits STRING into substrings at SEPARATORS.
13138 No empty strings are returned if there are matches at the beginning
13139 and end of string."
13140 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13141 (start 0)
13142 notfirst
13143 (list nil))
13144 (while (and (string-match rexp string
13145 (if (and notfirst
13146 (= start (match-beginning 0))
13147 (< start (length string)))
13148 (1+ start) start))
13149 (< (match-beginning 0) (length string)))
13150 (setq notfirst t)
13151 (or (eq (match-beginning 0) 0)
13152 (and (eq (match-beginning 0) (match-end 0))
13153 (eq (match-beginning 0) start))
13154 (setq list
13155 (cons (substring string start (match-beginning 0))
13156 list)))
13157 (setq start (match-end 0)))
13158 (or (eq start (length string))
13159 (setq list
13160 (cons (substring string start)
13161 list)))
13162 (nreverse list)))
13164 (defun org-context ()
13165 "Return a list of contexts of the current cursor position.
13166 If several contexts apply, all are returned.
13167 Each context entry is a list with a symbol naming the context, and
13168 two positions indicating start and end of the context. Possible
13169 contexts are:
13171 :headline anywhere in a headline
13172 :headline-stars on the leading stars in a headline
13173 :todo-keyword on a TODO keyword (including DONE) in a headline
13174 :tags on the TAGS in a headline
13175 :priority on the priority cookie in a headline
13176 :item on the first line of a plain list item
13177 :item-bullet on the bullet/number of a plain list item
13178 :checkbox on the checkbox in a plain list item
13179 :table in an org-mode table
13180 :table-special on a special filed in a table
13181 :table-table in a table.el table
13182 :link on a hyperlink
13183 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13184 :target on a <<target>>
13185 :radio-target on a <<<radio-target>>>
13186 :latex-fragment on a LaTeX fragment
13187 :latex-preview on a LaTeX fragment with overlayed preview image
13189 This function expects the position to be visible because it uses font-lock
13190 faces as a help to recognize the following contexts: :table-special, :link,
13191 and :keyword."
13192 (let* ((f (get-text-property (point) 'face))
13193 (faces (if (listp f) f (list f)))
13194 (p (point)) clist o)
13195 ;; First the large context
13196 (cond
13197 ((org-on-heading-p t)
13198 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13199 (when (progn
13200 (beginning-of-line 1)
13201 (looking-at org-todo-line-tags-regexp))
13202 (push (org-point-in-group p 1 :headline-stars) clist)
13203 (push (org-point-in-group p 2 :todo-keyword) clist)
13204 (push (org-point-in-group p 4 :tags) clist))
13205 (goto-char p)
13206 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13207 (if (looking-at "\\[#[A-Z0-9]\\]")
13208 (push (org-point-in-group p 0 :priority) clist)))
13210 ((org-at-item-p)
13211 (push (org-point-in-group p 2 :item-bullet) clist)
13212 (push (list :item (point-at-bol)
13213 (save-excursion (org-end-of-item) (point)))
13214 clist)
13215 (and (org-at-item-checkbox-p)
13216 (push (org-point-in-group p 0 :checkbox) clist)))
13218 ((org-at-table-p)
13219 (push (list :table (org-table-begin) (org-table-end)) clist)
13220 (if (memq 'org-formula faces)
13221 (push (list :table-special
13222 (previous-single-property-change p 'face)
13223 (next-single-property-change p 'face)) clist)))
13224 ((org-at-table-p 'any)
13225 (push (list :table-table) clist)))
13226 (goto-char p)
13228 ;; Now the small context
13229 (cond
13230 ((org-at-timestamp-p)
13231 (push (org-point-in-group p 0 :timestamp) clist))
13232 ((memq 'org-link faces)
13233 (push (list :link
13234 (previous-single-property-change p 'face)
13235 (next-single-property-change p 'face)) clist))
13236 ((memq 'org-special-keyword faces)
13237 (push (list :keyword
13238 (previous-single-property-change p 'face)
13239 (next-single-property-change p 'face)) clist))
13240 ((org-on-target-p)
13241 (push (org-point-in-group p 0 :target) clist)
13242 (goto-char (1- (match-beginning 0)))
13243 (if (looking-at org-radio-target-regexp)
13244 (push (org-point-in-group p 0 :radio-target) clist))
13245 (goto-char p))
13246 ((setq o (car (delq nil
13247 (mapcar
13248 (lambda (x)
13249 (if (memq x org-latex-fragment-image-overlays) x))
13250 (org-overlays-at (point))))))
13251 (push (list :latex-fragment
13252 (org-overlay-start o) (org-overlay-end o)) clist)
13253 (push (list :latex-preview
13254 (org-overlay-start o) (org-overlay-end o)) clist))
13255 ((org-inside-LaTeX-fragment-p)
13256 ;; FIXME: positions wrong.
13257 (push (list :latex-fragment (point) (point)) clist)))
13259 (setq clist (nreverse (delq nil clist)))
13260 clist))
13262 ;; FIXME: Compare with at-regexp-p Do we need both?
13263 (defun org-in-regexp (re &optional nlines visually)
13264 "Check if point is inside a match of regexp.
13265 Normally only the current line is checked, but you can include NLINES extra
13266 lines both before and after point into the search.
13267 If VISUALLY is set, require that the cursor is not after the match but
13268 really on, so that the block visually is on the match."
13269 (catch 'exit
13270 (let ((pos (point))
13271 (eol (point-at-eol (+ 1 (or nlines 0))))
13272 (inc (if visually 1 0)))
13273 (save-excursion
13274 (beginning-of-line (- 1 (or nlines 0)))
13275 (while (re-search-forward re eol t)
13276 (if (and (<= (match-beginning 0) pos)
13277 (>= (+ inc (match-end 0)) pos))
13278 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13280 (defun org-at-regexp-p (regexp)
13281 "Is point inside a match of REGEXP in the current line?"
13282 (catch 'exit
13283 (save-excursion
13284 (let ((pos (point)) (end (point-at-eol)))
13285 (beginning-of-line 1)
13286 (while (re-search-forward regexp end t)
13287 (if (and (<= (match-beginning 0) pos)
13288 (>= (match-end 0) pos))
13289 (throw 'exit t)))
13290 nil))))
13292 (defun org-occur-in-agenda-files (regexp &optional nlines)
13293 "Call `multi-occur' with buffers for all agenda files."
13294 (interactive "sOrg-files matching: \np")
13295 (let* ((files (org-agenda-files))
13296 (tnames (mapcar 'file-truename files))
13297 (extra org-agenda-text-search-extra-files)
13299 (when (eq (car extra) 'agenda-archives)
13300 (setq extra (cdr extra))
13301 (setq files (org-add-archive-files files)))
13302 (while (setq f (pop extra))
13303 (unless (member (file-truename f) tnames)
13304 (add-to-list 'files f 'append)
13305 (add-to-list 'tnames (file-truename f) 'append)))
13306 (multi-occur
13307 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13308 regexp)))
13310 (if (boundp 'occur-mode-find-occurrence-hook)
13311 ;; Emacs 23
13312 (add-hook 'occur-mode-find-occurrence-hook
13313 (lambda ()
13314 (when (org-mode-p)
13315 (org-reveal))))
13316 ;; Emacs 22
13317 (defadvice occur-mode-goto-occurrence
13318 (after org-occur-reveal activate)
13319 (and (org-mode-p) (org-reveal)))
13320 (defadvice occur-mode-goto-occurrence-other-window
13321 (after org-occur-reveal activate)
13322 (and (org-mode-p) (org-reveal)))
13323 (defadvice occur-mode-display-occurrence
13324 (after org-occur-reveal activate)
13325 (when (org-mode-p)
13326 (let ((pos (occur-mode-find-occurrence)))
13327 (with-current-buffer (marker-buffer pos)
13328 (save-excursion
13329 (goto-char pos)
13330 (org-reveal)))))))
13332 (defun org-uniquify (list)
13333 "Remove duplicate elements from LIST."
13334 (let (res)
13335 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13336 res))
13338 (defun org-delete-all (elts list)
13339 "Remove all elements in ELTS from LIST."
13340 (while elts
13341 (setq list (delete (pop elts) list)))
13342 list)
13344 (defun org-back-over-empty-lines ()
13345 "Move backwards over witespace, to the beginning of the first empty line.
13346 Returns the number of empty lines passed."
13347 (let ((pos (point)))
13348 (skip-chars-backward " \t\n\r")
13349 (beginning-of-line 2)
13350 (goto-char (min (point) pos))
13351 (count-lines (point) pos)))
13353 (defun org-skip-whitespace ()
13354 (skip-chars-forward " \t\n\r"))
13356 (defun org-point-in-group (point group &optional context)
13357 "Check if POINT is in match-group GROUP.
13358 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13359 match. If the match group does ot exist or point is not inside it,
13360 return nil."
13361 (and (match-beginning group)
13362 (>= point (match-beginning group))
13363 (<= point (match-end group))
13364 (if context
13365 (list context (match-beginning group) (match-end group))
13366 t)))
13368 (defun org-switch-to-buffer-other-window (&rest args)
13369 "Switch to buffer in a second window on the current frame.
13370 In particular, do not allow pop-up frames."
13371 (let (pop-up-frames special-display-buffer-names special-display-regexps
13372 special-display-function)
13373 (apply 'switch-to-buffer-other-window args)))
13375 (defun org-combine-plists (&rest plists)
13376 "Create a single property list from all plists in PLISTS.
13377 The process starts by copying the first list, and then setting properties
13378 from the other lists. Settings in the last list are the most significant
13379 ones and overrule settings in the other lists."
13380 (let ((rtn (copy-sequence (pop plists)))
13381 p v ls)
13382 (while plists
13383 (setq ls (pop plists))
13384 (while ls
13385 (setq p (pop ls) v (pop ls))
13386 (setq rtn (plist-put rtn p v))))
13387 rtn))
13389 (defun org-move-line-down (arg)
13390 "Move the current line down. With prefix argument, move it past ARG lines."
13391 (interactive "p")
13392 (let ((col (current-column))
13393 beg end pos)
13394 (beginning-of-line 1) (setq beg (point))
13395 (beginning-of-line 2) (setq end (point))
13396 (beginning-of-line (+ 1 arg))
13397 (setq pos (move-marker (make-marker) (point)))
13398 (insert (delete-and-extract-region beg end))
13399 (goto-char pos)
13400 (org-move-to-column col)))
13402 (defun org-move-line-up (arg)
13403 "Move the current line up. With prefix argument, move it past ARG lines."
13404 (interactive "p")
13405 (let ((col (current-column))
13406 beg end pos)
13407 (beginning-of-line 1) (setq beg (point))
13408 (beginning-of-line 2) (setq end (point))
13409 (beginning-of-line (- arg))
13410 (setq pos (move-marker (make-marker) (point)))
13411 (insert (delete-and-extract-region beg end))
13412 (goto-char pos)
13413 (org-move-to-column col)))
13415 (defun org-replace-escapes (string table)
13416 "Replace %-escapes in STRING with values in TABLE.
13417 TABLE is an association list with keys like \"%a\" and string values.
13418 The sequences in STRING may contain normal field width and padding information,
13419 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13420 so values can contain further %-escapes if they are define later in TABLE."
13421 (let ((case-fold-search nil)
13422 e re rpl)
13423 (while (setq e (pop table))
13424 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13425 (while (string-match re string)
13426 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13427 (cdr e)))
13428 (setq string (replace-match rpl t t string))))
13429 string))
13432 (defun org-sublist (list start end)
13433 "Return a section of LIST, from START to END.
13434 Counting starts at 1."
13435 (let (rtn (c start))
13436 (setq list (nthcdr (1- start) list))
13437 (while (and list (<= c end))
13438 (push (pop list) rtn)
13439 (setq c (1+ c)))
13440 (nreverse rtn)))
13442 (defun org-find-base-buffer-visiting (file)
13443 "Like `find-buffer-visiting' but alway return the base buffer and
13444 not an indirect buffer."
13445 (let ((buf (find-buffer-visiting file)))
13446 (if buf
13447 (or (buffer-base-buffer buf) buf)
13448 nil)))
13450 (defun org-image-file-name-regexp ()
13451 "Return regexp matching the file names of images."
13452 (if (fboundp 'image-file-name-regexp)
13453 (image-file-name-regexp)
13454 (let ((image-file-name-extensions
13455 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13456 "xbm" "xpm" "pbm" "pgm" "ppm")))
13457 (concat "\\."
13458 (regexp-opt (nconc (mapcar 'upcase
13459 image-file-name-extensions)
13460 image-file-name-extensions)
13462 "\\'"))))
13464 (defun org-file-image-p (file)
13465 "Return non-nil if FILE is an image."
13466 (save-match-data
13467 (string-match (org-image-file-name-regexp) file)))
13469 (defun org-get-cursor-date ()
13470 "Return the date at cursor in as a time.
13471 This works in the calendar and in the agenda, anywhere else it just
13472 returns the current time."
13473 (let (date day defd)
13474 (cond
13475 ((eq major-mode 'calendar-mode)
13476 (setq date (calendar-cursor-to-date)
13477 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13478 ((eq major-mode 'org-agenda-mode)
13479 (setq day (get-text-property (point) 'day))
13480 (if day
13481 (setq date (calendar-gregorian-from-absolute day)
13482 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13483 (nth 2 date))))))
13484 (or defd (current-time))))
13486 (defvar org-agenda-action-marker (make-marker)
13487 "Marker pointing to the entry for the next agenda action.")
13489 (defun org-mark-entry-for-agenda-action ()
13490 "Mark the current entry as target of an agenda action.
13491 Agenda actions are actions executed from the agenda with the key `k',
13492 which make use of the date at the cursor."
13493 (interactive)
13494 (move-marker org-agenda-action-marker
13495 (save-excursion (org-back-to-heading t) (point))
13496 (current-buffer))
13497 (message
13498 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13500 ;;; Paragraph filling stuff.
13501 ;; We want this to be just right, so use the full arsenal.
13503 (defun org-indent-line-function ()
13504 "Indent line like previous, but further if previous was headline or item."
13505 (interactive)
13506 (let* ((pos (point))
13507 (itemp (org-at-item-p))
13508 column bpos bcol tpos tcol bullet btype bullet-type)
13509 ;; Find the previous relevant line
13510 (beginning-of-line 1)
13511 (cond
13512 ((looking-at "#") (setq column 0))
13513 ((looking-at "\\*+ ") (setq column 0))
13515 (beginning-of-line 0)
13516 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13517 (beginning-of-line 0))
13518 (cond
13519 ((looking-at "\\*+[ \t]+")
13520 (if (not org-adapt-indentation)
13521 (setq column 0)
13522 (goto-char (match-end 0))
13523 (setq column (current-column))))
13524 ((org-in-item-p)
13525 (org-beginning-of-item)
13526 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13527 (setq bpos (match-beginning 1) tpos (match-end 0)
13528 bcol (progn (goto-char bpos) (current-column))
13529 tcol (progn (goto-char tpos) (current-column))
13530 bullet (match-string 1)
13531 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13532 (if (> tcol (+ bcol org-description-max-indent))
13533 (setq tcol (+ bcol 5)))
13534 (if (not itemp)
13535 (setq column tcol)
13536 (goto-char pos)
13537 (beginning-of-line 1)
13538 (if (looking-at "\\S-")
13539 (progn
13540 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13541 (setq bullet (match-string 1)
13542 btype (if (string-match "[0-9]" bullet) "n" bullet))
13543 (setq column (if (equal btype bullet-type) bcol tcol)))
13544 (setq column (org-get-indentation)))))
13545 (t (setq column (org-get-indentation))))))
13546 (goto-char pos)
13547 (if (<= (current-column) (current-indentation))
13548 (org-indent-line-to column)
13549 (save-excursion (org-indent-line-to column)))
13550 (setq column (current-column))
13551 (beginning-of-line 1)
13552 (if (looking-at
13553 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13554 (replace-match (concat "\\1" (format org-property-format
13555 (match-string 2) (match-string 3)))
13556 t nil))
13557 (org-move-to-column column)))
13559 (defun org-set-autofill-regexps ()
13560 (interactive)
13561 ;; In the paragraph separator we include headlines, because filling
13562 ;; text in a line directly attached to a headline would otherwise
13563 ;; fill the headline as well.
13564 (org-set-local 'comment-start-skip "^#+[ \t]*")
13565 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13566 ;; The paragraph starter includes hand-formatted lists.
13567 (org-set-local 'paragraph-start
13568 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13569 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13570 ;; But only if the user has not turned off tables or fixed-width regions
13571 (org-set-local
13572 'auto-fill-inhibit-regexp
13573 (concat "\\*+ \\|#\\+"
13574 "\\|[ \t]*" org-keyword-time-regexp
13575 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13576 (concat
13577 "\\|[ \t]*["
13578 (if org-enable-table-editor "|" "")
13579 (if org-enable-fixed-width-editor ":" "")
13580 "]"))))
13581 ;; We use our own fill-paragraph function, to make sure that tables
13582 ;; and fixed-width regions are not wrapped. That function will pass
13583 ;; through to `fill-paragraph' when appropriate.
13584 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13585 ; Adaptive filling: To get full control, first make sure that
13586 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13587 (org-set-local 'adaptive-fill-regexp "\000")
13588 (org-set-local 'adaptive-fill-function
13589 'org-adaptive-fill-function)
13590 (org-set-local
13591 'align-mode-rules-list
13592 '((org-in-buffer-settings
13593 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13594 (modes . '(org-mode))))))
13596 (defun org-fill-paragraph (&optional justify)
13597 "Re-align a table, pass through to fill-paragraph if no table."
13598 (let ((table-p (org-at-table-p))
13599 (table.el-p (org-at-table.el-p)))
13600 (cond ((and (equal (char-after (point-at-bol)) ?*)
13601 (save-excursion (goto-char (point-at-bol))
13602 (looking-at outline-regexp)))
13603 t) ; skip headlines
13604 (table.el-p t) ; skip table.el tables
13605 (table-p (org-table-align) t) ; align org-mode tables
13606 (t nil)))) ; call paragraph-fill
13608 ;; For reference, this is the default value of adaptive-fill-regexp
13609 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13611 (defun org-adaptive-fill-function ()
13612 "Return a fill prefix for org-mode files.
13613 In particular, this makes sure hanging paragraphs for hand-formatted lists
13614 work correctly."
13615 (cond ((looking-at "#[ \t]+")
13616 (match-string 0))
13617 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13618 (save-excursion
13619 (if (> (match-end 1) (+ (match-beginning 1)
13620 org-description-max-indent))
13621 (goto-char (+ (match-beginning 1) 5))
13622 (goto-char (match-end 0)))
13623 (make-string (current-column) ?\ )))
13624 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13625 (save-excursion
13626 (goto-char (match-end 0))
13627 (make-string (current-column) ?\ )))
13628 (t nil)))
13630 ;;; Other stuff.
13632 (defun org-toggle-fixed-width-section (arg)
13633 "Toggle the fixed-width export.
13634 If there is no active region, the QUOTE keyword at the current headline is
13635 inserted or removed. When present, it causes the text between this headline
13636 and the next to be exported as fixed-width text, and unmodified.
13637 If there is an active region, this command adds or removes a colon as the
13638 first character of this line. If the first character of a line is a colon,
13639 this line is also exported in fixed-width font."
13640 (interactive "P")
13641 (let* ((cc 0)
13642 (regionp (org-region-active-p))
13643 (beg (if regionp (region-beginning) (point)))
13644 (end (if regionp (region-end)))
13645 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13646 (case-fold-search nil)
13647 (re "[ \t]*\\(:\\)")
13648 off)
13649 (if regionp
13650 (save-excursion
13651 (goto-char beg)
13652 (setq cc (current-column))
13653 (beginning-of-line 1)
13654 (setq off (looking-at re))
13655 (while (> nlines 0)
13656 (setq nlines (1- nlines))
13657 (beginning-of-line 1)
13658 (cond
13659 (arg
13660 (org-move-to-column cc t)
13661 (insert ":\n")
13662 (forward-line -1))
13663 ((and off (looking-at re))
13664 (replace-match "" t t nil 1))
13665 ((not off) (org-move-to-column cc t) (insert ":")))
13666 (forward-line 1)))
13667 (save-excursion
13668 (org-back-to-heading)
13669 (if (looking-at (concat outline-regexp
13670 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13671 (replace-match "" t t nil 1)
13672 (if (looking-at outline-regexp)
13673 (progn
13674 (goto-char (match-end 0))
13675 (insert org-quote-string " "))))))))
13677 ;;;; Functions extending outline functionality
13679 (defun org-beginning-of-line (&optional arg)
13680 "Go to the beginning of the current line. If that is invisible, continue
13681 to a visible line beginning. This makes the function of C-a more intuitive.
13682 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13683 first attempt, and only move to after the tags when the cursor is already
13684 beyond the end of the headline."
13685 (interactive "P")
13686 (let ((pos (point)) refpos)
13687 (beginning-of-line 1)
13688 (if (bobp)
13690 (backward-char 1)
13691 (if (org-invisible-p)
13692 (while (and (not (bobp)) (org-invisible-p))
13693 (backward-char 1)
13694 (beginning-of-line 1))
13695 (forward-char 1)))
13696 (when org-special-ctrl-a/e
13697 (cond
13698 ((and (looking-at org-complex-heading-regexp)
13699 (= (char-after (match-end 1)) ?\ ))
13700 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13701 (point-at-eol)))
13702 (goto-char
13703 (if (eq org-special-ctrl-a/e t)
13704 (cond ((> pos refpos) refpos)
13705 ((= pos (point)) refpos)
13706 (t (point)))
13707 (cond ((> pos (point)) (point))
13708 ((not (eq last-command this-command)) (point))
13709 (t refpos)))))
13710 ((org-at-item-p)
13711 (goto-char
13712 (if (eq org-special-ctrl-a/e t)
13713 (cond ((> pos (match-end 4)) (match-end 4))
13714 ((= pos (point)) (match-end 4))
13715 (t (point)))
13716 (cond ((> pos (point)) (point))
13717 ((not (eq last-command this-command)) (point))
13718 (t (match-end 4))))))))
13719 (org-no-warnings
13720 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13722 (defun org-end-of-line (&optional arg)
13723 "Go to the end of the line.
13724 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13725 first attempt, and only move to after the tags when the cursor is already
13726 beyond the end of the headline."
13727 (interactive "P")
13728 (if (or (not org-special-ctrl-a/e)
13729 (not (org-on-heading-p)))
13730 (end-of-line arg)
13731 (let ((pos (point)))
13732 (beginning-of-line 1)
13733 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13734 (if (eq org-special-ctrl-a/e t)
13735 (if (or (< pos (match-beginning 1))
13736 (= pos (match-end 0)))
13737 (goto-char (match-beginning 1))
13738 (goto-char (match-end 0)))
13739 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13740 (goto-char (match-end 0))
13741 (goto-char (match-beginning 1))))
13742 (end-of-line arg))))
13743 (org-no-warnings
13744 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13747 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13748 (define-key org-mode-map "\C-e" 'org-end-of-line)
13750 (defun org-kill-line (&optional arg)
13751 "Kill line, to tags or end of line."
13752 (interactive "P")
13753 (cond
13754 ((or (not org-special-ctrl-k)
13755 (bolp)
13756 (not (org-on-heading-p)))
13757 (call-interactively 'kill-line))
13758 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13759 (kill-region (point) (match-beginning 1))
13760 (org-set-tags nil t))
13761 (t (kill-region (point) (point-at-eol)))))
13764 (define-key org-mode-map "\C-k" 'org-kill-line)
13766 (defun org-yank ()
13767 "Yank, and if the yanked text is a single subtree, fold it.
13768 In fact, if the yanked text is a sequence of subtrees, fold all of them."
13769 (interactive)
13770 (if org-yank-folded-subtrees
13771 (let ((beg (point)) end)
13772 (call-interactively 'yank)
13773 (setq end (point))
13774 (goto-char beg)
13775 (when (and (bolp)
13776 (org-kill-is-subtree-p))
13777 (or (looking-at outline-regexp)
13778 (re-search-forward (concat "^" outline-regexp) end t))
13779 (while (and (< (point) end) (looking-at outline-regexp))
13780 (hide-subtree)
13781 (org-cycle-show-empty-lines 'folded)
13782 (condition-case nil
13783 (outline-forward-same-level 1)
13784 (error (goto-char end)))))
13785 (goto-char end)
13786 (skip-chars-forward " \t\n\r"))
13787 (call-interactively 'yank)))
13789 (define-key org-mode-map "\C-y" 'org-yank)
13791 (defun org-invisible-p ()
13792 "Check if point is at a character currently not visible."
13793 ;; Early versions of noutline don't have `outline-invisible-p'.
13794 (if (fboundp 'outline-invisible-p)
13795 (outline-invisible-p)
13796 (get-char-property (point) 'invisible)))
13798 (defun org-invisible-p2 ()
13799 "Check if point is at a character currently not visible."
13800 (save-excursion
13801 (if (and (eolp) (not (bobp))) (backward-char 1))
13802 ;; Early versions of noutline don't have `outline-invisible-p'.
13803 (if (fboundp 'outline-invisible-p)
13804 (outline-invisible-p)
13805 (get-char-property (point) 'invisible))))
13807 (defalias 'org-back-to-heading 'outline-back-to-heading)
13808 (defalias 'org-on-heading-p 'outline-on-heading-p)
13809 (defalias 'org-at-heading-p 'outline-on-heading-p)
13810 (defun org-at-heading-or-item-p ()
13811 (or (org-on-heading-p) (org-at-item-p)))
13813 (defun org-on-target-p ()
13814 (or (org-in-regexp org-radio-target-regexp)
13815 (org-in-regexp org-target-regexp)))
13817 (defun org-up-heading-all (arg)
13818 "Move to the heading line of which the present line is a subheading.
13819 This function considers both visible and invisible heading lines.
13820 With argument, move up ARG levels."
13821 (if (fboundp 'outline-up-heading-all)
13822 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13823 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13825 (defun org-up-heading-safe ()
13826 "Move to the heading line of which the present line is a subheading.
13827 This version will not throw an error. It will return the level of the
13828 headline found, or nil if no higher level is found."
13829 (let ((pos (point)) start-level level
13830 (re (concat "^" outline-regexp)))
13831 (catch 'exit
13832 (outline-back-to-heading t)
13833 (setq start-level (funcall outline-level))
13834 (if (equal start-level 1) (throw 'exit nil))
13835 (while (re-search-backward re nil t)
13836 (setq level (funcall outline-level))
13837 (if (< level start-level) (throw 'exit level)))
13838 nil)))
13840 (defun org-first-sibling-p ()
13841 "Is this heading the first child of its parents?"
13842 (interactive)
13843 (let ((re (concat "^" outline-regexp))
13844 level l)
13845 (unless (org-at-heading-p t)
13846 (error "Not at a heading"))
13847 (setq level (funcall outline-level))
13848 (save-excursion
13849 (if (not (re-search-backward re nil t))
13851 (setq l (funcall outline-level))
13852 (< l level)))))
13854 (defun org-goto-sibling (&optional previous)
13855 "Goto the next sibling, even if it is invisible.
13856 When PREVIOUS is set, go to the previous sibling instead. Returns t
13857 when a sibling was found. When none is found, return nil and don't
13858 move point."
13859 (let ((fun (if previous 're-search-backward 're-search-forward))
13860 (pos (point))
13861 (re (concat "^" outline-regexp))
13862 level l)
13863 (when (condition-case nil (org-back-to-heading t) (error nil))
13864 (setq level (funcall outline-level))
13865 (catch 'exit
13866 (or previous (forward-char 1))
13867 (while (funcall fun re nil t)
13868 (setq l (funcall outline-level))
13869 (when (< l level) (goto-char pos) (throw 'exit nil))
13870 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13871 (goto-char pos)
13872 nil))))
13874 (defun org-show-siblings ()
13875 "Show all siblings of the current headline."
13876 (save-excursion
13877 (while (org-goto-sibling) (org-flag-heading nil)))
13878 (save-excursion
13879 (while (org-goto-sibling 'previous)
13880 (org-flag-heading nil))))
13882 (defun org-show-hidden-entry ()
13883 "Show an entry where even the heading is hidden."
13884 (save-excursion
13885 (org-show-entry)))
13887 (defun org-flag-heading (flag &optional entry)
13888 "Flag the current heading. FLAG non-nil means make invisible.
13889 When ENTRY is non-nil, show the entire entry."
13890 (save-excursion
13891 (org-back-to-heading t)
13892 ;; Check if we should show the entire entry
13893 (if entry
13894 (progn
13895 (org-show-entry)
13896 (save-excursion
13897 (and (outline-next-heading)
13898 (org-flag-heading nil))))
13899 (outline-flag-region (max (point-min) (1- (point)))
13900 (save-excursion (outline-end-of-heading) (point))
13901 flag))))
13903 (defun org-forward-same-level (arg)
13904 "Move forward to the ARG'th subheading at same level as this one.
13905 Stop at the first and last subheadings of a superior heading.
13906 This is like outline-forward-same-level, but invisible headings are ok."
13907 (interactive "p")
13908 (outline-back-to-heading t)
13909 (while (> arg 0)
13910 (let ((point-to-move-to (save-excursion
13911 (org-get-next-sibling))))
13912 (if point-to-move-to
13913 (progn
13914 (goto-char point-to-move-to)
13915 (setq arg (1- arg)))
13916 (progn
13917 (setq arg 0)
13918 (error "No following same-level heading"))))))
13920 (defun org-get-next-sibling ()
13921 "Move to next heading of the same level, and return point.
13922 If there is no such heading, return nil.
13923 This is like outline-next-sibling, but invisible headings are ok."
13924 (let ((level (funcall outline-level)))
13925 (outline-next-heading)
13926 (while (and (not (eobp)) (> (funcall outline-level) level))
13927 (outline-next-heading))
13928 (if (or (eobp) (< (funcall outline-level) level))
13930 (point))))
13932 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13933 ;; This is an exact copy of the original function, but it uses
13934 ;; `org-back-to-heading', to make it work also in invisible
13935 ;; trees. And is uses an invisible-OK argument.
13936 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13937 (org-back-to-heading invisible-OK)
13938 (let ((first t)
13939 (level (funcall outline-level)))
13940 (while (and (not (eobp))
13941 (or first (> (funcall outline-level) level)))
13942 (setq first nil)
13943 (outline-next-heading))
13944 (unless to-heading
13945 (if (memq (preceding-char) '(?\n ?\^M))
13946 (progn
13947 ;; Go to end of line before heading
13948 (forward-char -1)
13949 (if (memq (preceding-char) '(?\n ?\^M))
13950 ;; leave blank line before heading
13951 (forward-char -1))))))
13952 (point))
13954 (defun org-show-subtree ()
13955 "Show everything after this heading at deeper levels."
13956 (outline-flag-region
13957 (point)
13958 (save-excursion
13959 (outline-end-of-subtree) (outline-next-heading) (point))
13960 nil))
13962 (defun org-show-entry ()
13963 "Show the body directly following this heading.
13964 Show the heading too, if it is currently invisible."
13965 (interactive)
13966 (save-excursion
13967 (condition-case nil
13968 (progn
13969 (org-back-to-heading t)
13970 (outline-flag-region
13971 (max (point-min) (1- (point)))
13972 (save-excursion
13973 (re-search-forward
13974 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13975 (or (match-beginning 1) (point-max)))
13976 nil))
13977 (error nil))))
13979 (defun org-make-options-regexp (kwds)
13980 "Make a regular expression for keyword lines."
13981 (concat
13983 "#?[ \t]*\\+\\("
13984 (mapconcat 'regexp-quote kwds "\\|")
13985 "\\):[ \t]*"
13986 "\\(.+\\)"))
13988 ;; Make isearch reveal the necessary context
13989 (defun org-isearch-end ()
13990 "Reveal context after isearch exits."
13991 (when isearch-success ; only if search was successful
13992 (if (featurep 'xemacs)
13993 ;; Under XEmacs, the hook is run in the correct place,
13994 ;; we directly show the context.
13995 (org-show-context 'isearch)
13996 ;; In Emacs the hook runs *before* restoring the overlays.
13997 ;; So we have to use a one-time post-command-hook to do this.
13998 ;; (Emacs 22 has a special variable, see function `org-mode')
13999 (unless (and (boundp 'isearch-mode-end-hook-quit)
14000 isearch-mode-end-hook-quit)
14001 ;; Only when the isearch was not quitted.
14002 (org-add-hook 'post-command-hook 'org-isearch-post-command
14003 'append 'local)))))
14005 (defun org-isearch-post-command ()
14006 "Remove self from hook, and show context."
14007 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14008 (org-show-context 'isearch))
14011 ;;;; Integration with and fixes for other packages
14013 ;;; Imenu support
14015 (defvar org-imenu-markers nil
14016 "All markers currently used by Imenu.")
14017 (make-variable-buffer-local 'org-imenu-markers)
14019 (defun org-imenu-new-marker (&optional pos)
14020 "Return a new marker for use by Imenu, and remember the marker."
14021 (let ((m (make-marker)))
14022 (move-marker m (or pos (point)))
14023 (push m org-imenu-markers)
14026 (defun org-imenu-get-tree ()
14027 "Produce the index for Imenu."
14028 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14029 (setq org-imenu-markers nil)
14030 (let* ((n org-imenu-depth)
14031 (re (concat "^" outline-regexp))
14032 (subs (make-vector (1+ n) nil))
14033 (last-level 0)
14034 m tree level head)
14035 (save-excursion
14036 (save-restriction
14037 (widen)
14038 (goto-char (point-max))
14039 (while (re-search-backward re nil t)
14040 (setq level (org-reduced-level (funcall outline-level)))
14041 (when (<= level n)
14042 (looking-at org-complex-heading-regexp)
14043 (setq head (org-link-display-format
14044 (org-match-string-no-properties 4))
14045 m (org-imenu-new-marker))
14046 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14047 (if (>= level last-level)
14048 (push (cons head m) (aref subs level))
14049 (push (cons head (aref subs (1+ level))) (aref subs level))
14050 (loop for i from (1+ level) to n do (aset subs i nil)))
14051 (setq last-level level)))))
14052 (aref subs 1)))
14054 (eval-after-load "imenu"
14055 '(progn
14056 (add-hook 'imenu-after-jump-hook
14057 (lambda ()
14058 (if (eq major-mode 'org-mode)
14059 (org-show-context 'org-goto))))))
14061 (defun org-link-display-format (link)
14062 "Replace a link with either the description, or the link target
14063 if no description is present"
14064 (save-match-data
14065 (if (string-match org-bracket-link-analytic-regexp link)
14066 (replace-match (or (match-string 5 link)
14067 (concat (match-string 1 link)
14068 (match-string 3 link)))
14069 nil nil link)
14070 link)))
14072 ;; Speedbar support
14074 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14075 "Overlay marking the agenda restriction line in speedbar.")
14076 (org-overlay-put org-speedbar-restriction-lock-overlay
14077 'face 'org-agenda-restriction-lock)
14078 (org-overlay-put org-speedbar-restriction-lock-overlay
14079 'help-echo "Agendas are currently limited to this item.")
14080 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14082 (defun org-speedbar-set-agenda-restriction ()
14083 "Restrict future agenda commands to the location at point in speedbar.
14084 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14085 (interactive)
14086 (require 'org-agenda)
14087 (let (p m tp np dir txt w)
14088 (cond
14089 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14090 'org-imenu t))
14091 (setq m (get-text-property p 'org-imenu-marker))
14092 (save-excursion
14093 (save-restriction
14094 (set-buffer (marker-buffer m))
14095 (goto-char m)
14096 (org-agenda-set-restriction-lock 'subtree))))
14097 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14098 'speedbar-function 'speedbar-find-file))
14099 (setq tp (previous-single-property-change
14100 (1+ p) 'speedbar-function)
14101 np (next-single-property-change
14102 tp 'speedbar-function)
14103 dir (speedbar-line-directory)
14104 txt (buffer-substring-no-properties (or tp (point-min))
14105 (or np (point-max))))
14106 (save-excursion
14107 (save-restriction
14108 (set-buffer (find-file-noselect
14109 (let ((default-directory dir))
14110 (expand-file-name txt))))
14111 (unless (org-mode-p)
14112 (error "Cannot restrict to non-Org-mode file"))
14113 (org-agenda-set-restriction-lock 'file))))
14114 (t (error "Don't know how to restrict Org-mode's agenda")))
14115 (org-move-overlay org-speedbar-restriction-lock-overlay
14116 (point-at-bol) (point-at-eol))
14117 (setq current-prefix-arg nil)
14118 (org-agenda-maybe-redo)))
14120 (eval-after-load "speedbar"
14121 '(progn
14122 (speedbar-add-supported-extension ".org")
14123 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14124 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14125 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14126 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14127 (add-hook 'speedbar-visiting-tag-hook
14128 (lambda () (org-show-context 'org-goto)))))
14131 ;;; Fixes and Hacks for problems with other packages
14133 ;; Make flyspell not check words in links, to not mess up our keymap
14134 (defun org-mode-flyspell-verify ()
14135 "Don't let flyspell put overlays at active buttons."
14136 (not (get-text-property (point) 'keymap)))
14138 ;; Make `bookmark-jump' show the jump location if it was hidden.
14139 (eval-after-load "bookmark"
14140 '(if (boundp 'bookmark-after-jump-hook)
14141 ;; We can use the hook
14142 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14143 ;; Hook not available, use advice
14144 (defadvice bookmark-jump (after org-make-visible activate)
14145 "Make the position visible."
14146 (org-bookmark-jump-unhide))))
14148 (defun org-bookmark-jump-unhide ()
14149 "Unhide the current position, to show the bookmark location."
14150 (and (org-mode-p)
14151 (or (org-invisible-p)
14152 (save-excursion (goto-char (max (point-min) (1- (point))))
14153 (org-invisible-p)))
14154 (org-show-context 'bookmark-jump)))
14156 ;; Make session.el ignore our circular variable
14157 (eval-after-load "session"
14158 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14160 ;;;; Experimental code
14162 (defun org-closed-in-range ()
14163 "Sparse tree of items closed in a certain time range.
14164 Still experimental, may disappear in the future."
14165 (interactive)
14166 ;; Get the time interval from the user.
14167 (let* ((time1 (time-to-seconds
14168 (org-read-date nil 'to-time nil "Starting date: ")))
14169 (time2 (time-to-seconds
14170 (org-read-date nil 'to-time nil "End date:")))
14171 ;; callback function
14172 (callback (lambda ()
14173 (let ((time
14174 (time-to-seconds
14175 (apply 'encode-time
14176 (org-parse-time-string
14177 (match-string 1))))))
14178 ;; check if time in interval
14179 (and (>= time time1) (<= time time2))))))
14180 ;; make tree, check each match with the callback
14181 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14184 ;;;; Finish up
14186 (provide 'org)
14188 (run-hooks 'org-load-hook)
14190 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14192 ;;; org.el ends here